user3307020
user3307020

Reputation: 15

why the last GUI element i declare is filling the whole panel?

public class add extends JPanel { private JPanel add = new JPanel(); JFrame frame; public add(){ frame = new JFrame("Add"); frame.setBounds(550, 300, 700,500); frame.setVisible(true); JLabel nameLabel = new JLabel("Name"); final JTextField nameField = new JTextField(); frame.add(nameLabel); frame.add(nameField); nameLabel.setBounds(200, 40, 150, 30); nameField.setBounds(350, 40, 150, 30); ... JButton registerButton = new JButton("Salveaza"); frame.add(registerButton); registerButton.setBounds(200,300,300, 30); registerButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { } }); } }

and if i delete the JButton, than a label, which would be the last element, will fill the whole JPanel when i run the programm. what can i do so i can make it work properly?

Upvotes: 0

Views: 53

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

You're adding components to a container, the JFrame's contentPane, that uses a BorderLayout as its default layout manager. When you do this and don't specify constants, the component gets added BorderLayout.CENTER, covering up any components added before.

  • Good Solution: learn and use layout managers, including using nested JPanels, each using its own layout manager and components.
  • Bad Solution: use null layout with absolute positioning. While to a newbie this seems the best way to create complex GUI's, the more you deal with Swing GUI creation, the more you will find that doing this will put your GUI in a straight-jacket, painting it in a very tight corner and making it very hard to extend or enhance. Just don't do this.

Upvotes: 1

Related Questions