Meesh
Meesh

Reputation: 508

how do you increase panel width?

With this code I will have the following window. I created 2 panels and added the mainp one to the frame and the panel to the mainp I did this in order to make window resizing dynamic (so the panel wont resize to the frame) I tried making my default panel size wider so that the text fields and label become wider but panel.setsize doesn't seem to do anything.

enter image description here

// creates the labels
 studId = new JLabel("Student ID");
 studAvg = new JLabel("Student Average");
 studName = new JLabel("Student Name");

 // creates the text fields
 JTextField studIdText = new JTextField();
 JTextField studAvgText = new JTextField();
 JTextField studNameText = new JTextField();

 JPanel mainp = new JPanel();

 JPanel panel = new JPanel();
  panel.setLayout(new GridLayout(3, 2, 2, 2));

            panel.setSize(300, 100);

    // adds to the GridLayout
    panel.add(studId);
    panel.add(studIdText);
    panel.add(studName);
    panel.add(studNameText);
    panel.add(studAvg);
    panel.add(studAvgText);

    mainp.add(panel);
    add(BorderLayout.CENTER,mainp);

    // verifies the textfields
    studIdText.setInputVerifier(new IntVerifier());
    studAvgText.setInputVerifier(new DoubleVerifier());

    setTitle("Student Form");
    setSize(300, 200);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

enter image description here

Upvotes: 2

Views: 1289

Answers (3)

Meesh
Meesh

Reputation: 508

using Advise from @Dan and @MADprogrammer and @trashgod i came up with the following

JTextField studIdText = new JTextField(20);

JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints r1 = new GridBagConstraints();

r1.fill = GridBagConstraints.HORIZONTAL;
r1.weightx = 0.0;
r1.gridx = 0;
r1.gridy = 0;
panel.add(studId,r1);

r1.weightx = 0.5;
r1.gridx = 1;
r1.gridwidth = GridBagConstraints.REMAINDER; 
panel.add(studIdText,r1);

of course you can make GridBagConstraints for every row and just change the gridy

enter image description here

Upvotes: 2

halex
halex

Reputation: 16403

The method you are looking for is setPreferredSize. Use it instead of panel.setSize(300, 100).

panel.setPreferredSize(new Dimension(300, 100));

I would also recommend to not setting the size of your JFrame to the fixed value (300,200) but do pack() instead. This will set the size of your JFrame to fit the panels inside.

Upvotes: 3

Dan D.
Dan D.

Reputation: 32391

Set the layout for mainp as BorderLayout.

mainp.setLayout(new BorderLayout());

Then, in order to avoid having the textfields resize vertically and look strange, you can add panel to BorderLayout.NORTH, for instance.

mainp.add(panel, BorderLayout.NORTH);

Upvotes: 1

Related Questions