嘿大家我一直用它作为我的指南,也是我一直在努力的代码基础:
我想要做的是在所有窗格中添加一个共享按钮。我不想为每个按钮声明一个唯一的按钮,但是要共享一个按钮。我的第一个想法是将框架更改为boxlayout,然后在将窗格添加到框架后只需按一下按钮:
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BoxLayout(frame, BoxLayout.PAGE_AXIS));
//Add content to the window.
//frame.add(new GUI(), BorderLayout.CENTER);
frame.add(new GUI());
//setup Find button
//findButton.setSize(110,55);
findButton.setText("Find");
findButton.setVisible(true);
//add button to frame
frame.add(findButton);
但是,我收到运行时错误:无法共享BoxLayout。所以现在我结束了。当我调查为什么我收到此错误时,如果这是正确的方法,有人可以告诉我吗?
答案 0 :(得分:2)
建议:
setAction(...)
方法将它传递给每个JButton。frame.getContentPane()
传递给BoxLayout的第一个构造函数参数:frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.PAGE_AXIS));
这是我不喜欢直接在顶级窗口添加组件或设置布局的一个原因,因为它只不过是误导性的语法糖。
我更喜欢:
JPanel contentPane = (JPanel) frame.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS));