【问题标题】:set JButton size in gridLayout在 gridLayout 中设置 JButton 大小
【发布时间】:2013-03-01 14:20:45
【问题描述】:

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

【问题讨论】:

  • 为了尽快获得更好的帮助,请发布SSCCE 和“最小”和“更大”尺寸的 GUI 的 ASCII 艺术。

标签: java swing awt jbutton


【解决方案1】:

我相信设置 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);
    }

【讨论】:

  • 如果我设置了约束,一切都会变成不同的大小,你能否用猜测约束更新你的代码,我在第一行寻找标签和文本文件,在下一行寻找 2 个按钮。谢谢
猜你喜欢
  • 2014-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-12
  • 1970-01-01
  • 2013-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多