I need to draw a horizontal histogram, and i am setting up the labels of the histogram as follows,
CODE
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 :(
OUTPUT
And this is my expected output (Edited with MS paint),
Expected Output
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. This will allow you to just add the JLabels to your 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);
});