我正在使用java swing构建算法可视化工具,我想将jlabel的高度设置为某个元素
int arr[]={6,3,2,13,4};
then
JLabel1.setSize(10, arr[0]*5);
JLabel2.setSize(10, arr[1]*5);
JLabel3.setSize(10, arr[2]*5);
JLabel4.setSize(10, arr[3]*5);
JLabel5.setSize(10, arr[4]*5);
但是当我设置尺寸时,标签会扩展到底部,形成倒条形图。如何在保留jLabels底部对齐的同时增加高度?
The output after setting the values to jlabel
设置值的源代码
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
abc = new JLabel[]{one,two,three,four,five}; //JlabelArray
int p = Integer.parseInt(abc[0].getText());
int q = Integer.parseInt(abc[1].getText());
int r = Integer.parseInt(abc[2].getText());
int s = Integer.parseInt(abc[3].getText());
int t = Integer.parseInt(abc[4].getText());
one.setSize(20, p*10 );
one.setBackground(Color.decode("#03A9F4"));
two.setSize(20, q*10 );
two.setBackground(Color.decode("#03A9F4"));
three.setSize(20, r*10 );
three.setBackground(Color.decode("#03A9F4"));
four.setSize(20, s*10 );
four.setBackground(Color.decode("#03A9F4"));
five.setSize(20, t*10 );
five.setBackground(Color.decode("#03A9F4"));
arr = new int[]{p,q,r,s,t}; //number array to be sorted
}
夏日 问:当我设置jLabel的大小时,通常它会向底部增长。如何在正y方向增加高度?
答案 0 :(得分:1)
在要添加JLabel的面板上使用不同的布局管理器 - 我建议使用GridBagLayout。要做到这一点真是太痛苦了,但是一旦理解了它,就可以非常灵活地布置组件。对于你的我会尝试:
JPanel pane = new JPanel(new GridBagLayout());
GridBagConstants c = new GridBagConstants;
c.gridheight = REMAINDER;
c.gridwidth = 1;
c.fill = NONE;
c.anchor = SOUTHWEST;
c.weightx = 1;
c.weighty = 0;
pane.add(label1, c);
pane.add(label2, c);
pane.add(label3, c);
c.gridwidth = RELATIVE;
pane.add(label4, c);
c.gridwidth = REMAINDER;
pane.add(label5, c);
答案 1 :(得分:-1)
除了不同的LayoutManager之外的另一个选项是根本没有LayoutManager(JPanel.setLayout(null)
)。这样,面板的任何子组件都不会自动调整大小/移动,您必须自己定位和调整大小。这适用于固定大小的容器。这样的解决方案看起来像:
pane.setLayout(null);
pane.add(label1);
label1.setBounds(label1X, label1Y, label1Width, label1Height);
请注意,这也意味着组件不响应其容器的大小更改 - 如果需要,(可能是自定义的)LayoutManager是更好的选择。