gpt4 book ai didi

java - BoxLayout 无法使用 "createComponents"方法共享

转载 作者:行者123 更新时间:2023-11-30 07:47:13 26 4
gpt4 key购买 nike

我在运行代码来创建简单的调查时遇到问题。我刚刚开始使用 UI,BoxLayout 给了我一个错误:线程“AWT-EventQueue-0”中的异常 java.awt.AWTError:BoxLayout 无法共享。帮忙?

import java.awt.Container;
import java.awt.Dimension;
import javax.swing.*;

public class UserInterface implements Runnable {

private JFrame frame;

@Override
public void run() {
frame = new JFrame("Survey");

frame.setPreferredSize(new Dimension(200, 300));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

createComponents(frame);
frame.pack();
frame.setVisible(true);
}

private void createComponents(Container container) {
BoxLayout bl = new BoxLayout(container, BoxLayout.Y_AXIS);
container.setLayout(bl);

container.add(new JLabel("Are you?"));
container.add(new JCheckBox("Yes!"));
container.add(new JCheckBox("No!"));
container.add(new JLabel("Why?"));

JRadioButton one = new JRadioButton("No reason.");
JRadioButton two = new JRadioButton("Because it is fun!");

ButtonGroup bg = new ButtonGroup();
bg.add(one);
bg.add(two);

container.add(one);
container.add(two);

container.add(new JButton("Done!"));
}

public JFrame getFrame() {
return frame;
}
}

最佳答案

However, is there a way to keep these two methods separate?

简单:只需将 contentPane 传递到方法中即可。

createComponents(frame.getContentPane());

关于java - BoxLayout 无法使用 "createComponents"方法共享,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33747584/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com