Call pack() on the JFrame after adding the components. This will cause the frame to be the smallest size needed to display the components. Finally call ( setLocation() (4) &) setVisible(true) .

import java.awt.GridLayout; import javax.swing.*; import javax.swing.border.EmptyBorder; class FrameTest { public void init() { frame_ref = new JFrame("Login"); frame_ref.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainPanel_ref = new JPanel(new GridLayout(4,2,6,3)); mainPanel_ref.setBorder(new EmptyBorder(5,5,5,5)); email_ref = new JTextField(); password_ref = new JPasswordField(); mainPanel_ref.add(new JLabel("E-Mail")); mainPanel_ref.add(email_ref); mainPanel_ref.add(new JLabel("Passwort")); mainPanel_ref.add(password_ref); mainPanel_ref.add(new JLabel("")); mainPanel_ref.add(new JLabel("")); mainPanel_ref.add(submitLogin_ref); mainPanel_ref.add(fehlerMeldung_ref); frame_ref.add(mainPanel_ref);
Other tips:
- Do not mix Swing with AWT. At least not components or not before targeting Java 7 +.
- The login component is often better suited to input
JDialog or JOptionPane rather than JFrame . - This may be better suited for a nested layout or other layout than
GridLayout setLocation() can be replaced with:- If the login has a "parent" component,
setLocationRelativeTo(Component) . - If the login is the visible first screen,
setLocationByPlatform(true) (1.6 +).
- Check the source for other tips.
- Publish SSCCE to better help.
source share