I'm trying to make a login page for an idea I'm working on and am trying to center two buttons. When I get the screen dimensions and divide them by 2 it is not centered. Here's my code:
import javax.swing.*;
import java.awt.*;
public class ChatWindow extends JFrame {
public ChatWindow() {
JFrame frame = new JFrame("EasyChat");
JButton login = new JButton("Login");
JButton signup = new JButton("Don't have an account? Sign Up");
JPanel mainPanel = new JPanel();
Dimension ss = Toolkit.getDefaultToolkit().getScreenSize();
frame.setVisible(true);
frame.setLayout(null);
frame.setSize(800,450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.getContentPane().add(login);
frame.getContentPane().add(signup);
login.setPreferredSize(new Dimension(25,60));
login.setFont(new Font("HelveticaNeue", Font.BOLD, 20));
signup.setBounds(ss.width / 2, ss.height / 2 + 125, 200, 100);
login.setBounds(ss.width / 2, ss.height / 2, 200, 100);
mainPanel.setLayout(new BorderLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
}
}
I also want to know how to make the buttons stayed centered if the user exits fullscreen mode.
Thank you.





You need to subtract half the width and half the height of each of the buttons from the screen dimensions to center the two widgets.
Change the code where you set the bounds on the buttons to the following:
To be notified when the user exits full screen mode, add a
WindowStateListenerto the frame and reset the bounds on the buttons. Here's the complete code: