Can't align JKabel

11 Views Asked by At

Well, I have this code:

  static class things implements ActionListener {        
      public void actionPerformed (ActionEvent e) {     
        JFrame frame4 = new JFrame("More things");
        frame4.setVisible(true);
        frame4.setResizable(true);
        frame4.setSize(1366,730);
        JPanel panel = new JPanel();
        JLabel label = new JLabel("<html>One thing more</html>");
        label.setVerticalAlignment(SwingConstants.BOTTOM);
        label.setHorizontalAlignment(SwingConstants.RIGHT);
        panel.add(label); 
        frame4.add(panel);

      }
    }

But when I run it, the JLabel with the Vertical/horizontal alignment isn't align, why?

1

There are 1 best solutions below

0
On

That happens because of LayoutManager. Read more about using different LayoutManager's

1)JPanel use FlowLayout as default. Set to right aligning components for that with help of constructor.

2)JFrame use BorderLayout as default. Add your panel to it with parameter BorderLayout.SOUTH.

3) useframe4.setVisible(true); at the end of construction of GUI for avoiding artifacts.

4)use pack()method instead of setting size to JFrame.

JFrame frame4 = new JFrame("More things");
frame4.setResizable(true);
JPanel panel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
JLabel label = new JLabel("<html>One thing more</html>");
panel.add(label); 
frame4.add(panel,BorderLayout.SOUTH);
frame4.pack();
frame4.setVisible(true);

enter image description here