0

I just want to align the button to right of the bottom. This code below not working as expected.

class Frame extends JFrame {
    public Frame() {
        JButton closeButton = new JButton("Close");
        closeButton.setSize(new Dimension(75, 25));
        closeButton.setLocation(new Point(225, 275));
        add(closeButton);

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        
        setSize(300, 300);
        setLayout(null);
        setTitle("Frame");
        setVisible(true);
    }
}
Leandros
  • 3
  • 2

1 Answers1

1

In Swing, you have to plan for the whole window and put layout managers so they decide of components location and resizing when window is resized. So:

  1. Do not put null as layout
  2. Do not use size nor location

If you want to have bottom bar with buttons and button od the right, use BorderLayout to put bottom bar, and Flow layout inside:

class Frame extends JFrame {
    public Frame() {
        JPanel btPanel = new JPanel();
        btPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
        JButton closeButton = new JButton("Close");
        btPanel.add(closeButton);
        getContentPane().add(btPanel,BorderLayout.SOUTH);

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        
        setSize(300, 300);
        setTitle("Frame");
        setVisible(true);
    }
}
ePortfel
  • 119
  • 6