-6

Hello I'm a beginner in Java Swing Application Window Here I face this problem in the graphics.

  • Why this problem is appearing?
  • How to solve it?

Here's the screenshot

Here's the code

public class MainWindow {

private JFrame frame;
private JTextField textField;
private JPasswordField passwordField;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                MainWindow window = new MainWindow();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public MainWindow() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JButton btnLogin = new JButton("Login");
    btnLogin.addActionListener(new ActionListener() {
        private String txtUsername;
        private String txtPassword;

        public void actionPerformed(ActionEvent arg0) {
            txtPassword = passwordField.getText();
            txtUsername = textField.getText();
        }
    });
    btnLogin.setBounds(183, 181, 89, 23);
    frame.getContentPane().add(btnLogin);

    textField = new JTextField();
    textField.setBounds(183, 110, 150, 23);
    frame.getContentPane().add(textField);
    textField.setColumns(10);

    JLabel lblNewLabel = new JLabel("Username");
    lblNewLabel.setBounds(106, 114, 94, 14);
    frame.getContentPane().add(lblNewLabel);

    JLabel lblNewLabel_1 = new JLabel("Password");
    lblNewLabel_1.setBounds(106, 153, 67, 14);
    frame.getContentPane().add(lblNewLabel_1);

    passwordField = new JPasswordField();
    passwordField.setBounds(183, 147, 150, 23);
    frame.getContentPane().add(passwordField);

    JLabel lblNewLabel_2 = new JLabel("Bus Station");
    lblNewLabel_2.setHorizontalAlignment(SwingConstants.CENTER);
    lblNewLabel_2.setFont(new Font("Tahoma", Font.PLAIN, 25));
    lblNewLabel_2.setBounds(62, 11, 321, 51);
    frame.getContentPane().add(lblNewLabel_2);
}
}
NickJ
  • 9,380
  • 9
  • 51
  • 74
Ammar Qala
  • 63
  • 1
  • 8

1 Answers1

0

You should not directly add your Components to the JFrame. Make a nice new JPanel(), add the buttons and labels to it and then add ONLY this JPanel to the contentPane.

Edit: Of course, you should use a proper LayoutManager to position your Components.

TheBass
  • 64
  • 1
  • 3