如何在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));
答案 0 :(得分:2)
我相信设置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);
}