vijay
vijay

Reputation: 1139

set JButton size in gridLayout

How to set the size of jbutton in gridlayout? otherwise the button size have lot of width and its not listening setSize or setBounds or setPreferedSize.

    addBut = new JButton("Add");

    addBut.addActionListener(this);
    deleteBut = new JButton("Delete");
    deleteBut.addActionListener(this);
    selectionPanel = new JPanel();
    selectionPanel.setLayout(new GridLayout(2,2));
    TitledBorder selectionBorder = new TitledBorder("Options");
    selectionBorder.setTitleColor(Color.BLUE);
    selectionPanel.setBorder(selectionBorder);
    selectionPanel.add(new JLabel("Department Name"));
    selectionPanel.add(new JTextField(deptName));
    selectionPanel.add(addBut);
    selectionPanel.add(deleteBut);

    selectionPanel.setPreferredSize(new Dimension(900,100));

Upvotes: 1

Views: 15207

Answers (1)

Jabrown207
Jabrown207

Reputation: 225

I believe setting GridLayout(2,2) will override size changes made to the panels. To be more precise, use GridBagConStraints;

private JTextField field1 = new JTextField();
private JButton addBtn = new JButton("Save: ");

 public void addComponents(Container pane) {
        pane.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
// Components
    c.gridwidth = 1;
    c.weightx = .01;
    c.weighty = .2;
    c.gridx = 0;
    c.gridy = 1;
    pane.add(field1, c);

        c.gridwidth = 1;
    c.weightx = .01;
    c.weighty = .2;
    c.gridx = 0;
    c.gridy = 1;
    pane.add(addBtn, c);
}
public MainView()  {
        //Create and set up the window.
        JFrame frame = new JFrame("NAME");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Set up the content pane.
        addComponents(frame.getContentPane());

        //Display the window.
        frame.pack();
        frame.setVisible(true);
        frame.setResizable(false);
        frame.setSize(400, 125);
        frame.setLocation(400, 300);
    }

Upvotes: 2

Related Questions