【发布时间】:2014-01-18 06:54:57
【问题描述】:
GridBagLayout 和 CardLayout 怎么搭配使用?
我正在尝试将这些按钮添加到面板中,但它破坏了 GridBagLayout,这是文档中的内容;
button = new JButton("Button 1");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
pane.add(button, c);
button = new JButton("Button 2");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 1;
c.gridy = 0;
pane.add(button, c);
我正在努力:
JPanel m = new JPanel();
button = new JButton("Button 1");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
m.add(button, c);
button = new JButton("Button 2");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 1;
c.gridy = 0;
m.add(button, c);
windows = new JPanel(new CardLayout());
windows.add(m, "test");
pane.add(windows, c);
但是它会像使用 flowlayout 一样恢复。
我错过了什么?非常感谢任何帮助。
完整
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public final class GUI extends JPanel implements ActionListener {
// buttons
private JButton newButton, findButton;
JPanel panels;
public void addComponentToPane (Container pane) {
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
JPanel mainMenu = new JPanel();
// add
mainMenu.add(newButton = new JButton("Add"), c);
newButton.setActionCommand("new");
newButton.addActionListener(this);
// find
mainMenu.add(findButton = new JButton("Find"), c);
findButton.setActionCommand("find");
findButton.addActionListener(this);
panels = new JPanel(new CardLayout());
panels.add(mainMenu, "mainWindow");
pane.add(panels, c);
}
public void actionPerformed(ActionEvent e) {
CardLayout allpanels = (CardLayout)(panels.getLayout());
switch (e.getActionCommand()) {
case "new":
allpanels.show(panels, "add");
break;
case "find":
System.out.println("find");
break;
}
}
private static void createGUI () {
JFrame frame = new JFrame("Check");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI contentPane = new GUI();
contentPane.addComponentToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
createGUI();
}
}
【问题讨论】:
-
如需尽快获得更好的帮助,请发帖MCVE。
-
您将网格包约束添加到您的 mainMenu 但您尚未为此 mainMenu JPanel 定义 GridBagLayout。
标签: java swing layout-manager gridbaglayout cardlayout