set JButton size in gridLayout

﹥>﹥吖頭↗ 提交于 2019-12-11 09:06:26

问题


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));

回答1:


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);
    }


来源:https://stackoverflow.com/questions/15388870/set-jbutton-size-in-gridlayout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!