java 在 gridLayout 中设置 JButton 大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15388870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 19:24:47  来源:igfitidea点击:

set JButton size in gridLayout

javaswingawtjbutton

提问by vijay

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.

如何在gridlayout中设置jbutton的大小?否则按钮大小有很多宽度,它不会监听 setSize 或 setBounds 或 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));

回答by Jabrown207

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

我相信设置 GridLayout(2,2) 将覆盖对面板所做的大小更改。更准确地说,使用 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);
    }