[英]JAVA positioning labels on JFRAME
I need to draw a horizontal histogram, and i am setting up the labels of the histogram as follows, 我需要绘制一个水平直方图,并且按如下所示设置直方图的标签,
public static void drawVertical(){
JFrame frame = new JFrame("Horizontal Histogram");
frame.setSize(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label_01=new JLabel("0-29");
label_01.setAlignmentX(-290);
label_01.setAlignmentY(290);
JLabel label_02=new JLabel("30-39");
label_02.setAlignmentX(-290);
label_02.setAlignmentY(270);
JLabel label_03=new JLabel("40-69");
label_03.setAlignmentX(-290);
label_03.setAlignmentY(250);
JLabel label_04=new JLabel("70-100");
label_04.setAlignmentX(-290);
label_04.setAlignmentY(230);
frame.add(label_01);
frame.add(label_02)
frame.add(label_03);
frame.add(label_04);
}
But this is the output i get :( 但这是我得到的输出:(
And this is my expected output (Edited with MS paint), 这是我的预期输出(使用MS paint编辑),
Can anyone figure out whats wrong here? 有人能找出这里有什么问题吗?
Why arent the other labels being displayed? 为什么不显示其他标签?
The answer to this question is that you should not use a BorderLayout
(which the JFrame
uses by default), but instead use a GridLayout
. 这个问题的答案是,您不应该使用
BorderLayout
(默认情况下, JFrame
使用BorderLayout
),而应使用GridLayout
。 This will allow you to just add the JLabels
to your JFrame
. 这将允许您仅将
JLabels
添加到JFrame
。 An example looks like this: 一个示例如下所示:
EventQueue.invokeLater(() -> {
JFrame frame = new JFrame("Stackoverflow | Question");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
// This is the important line. This will Change the layout to a GridLayout.
frame.setLayout(new GridLayout(4, 1));
frame.add(new JLabel("0-29"));
frame.add(new JLabel("30-39"));
frame.add(new JLabel("40-69"));
frame.add(new JLabel("70-100"));
frame.setVisible(true);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.