准确而简洁: 是否可以使用一组组件(如复选框,单选按钮等)来布局框架容器,而不是逐个将它们添加到框架中?因此,将它们放在框架中会更容易。
private void initializaUI(){
setSize(700, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Panel container to wrap checkboxes and radio buttons
JPanel panel = new JPanel(null);
JPanel checkBoxPanel = new JPanel(new BoxLayout(panel, defaultCloseOperation, null));
JPanel radioPanel_1 = new JPanel(new GridLayout());
JPanel radioPanel_2 = new JPanel(new GridLayout());
//Text field to display order
JTextField orderField = new JTextField(20);
orderField.setBounds(100, 100, 100, 20);
//Button to process place the order
JButton button = new JButton("Process Selection");
button.setBounds(300, 100, 100, 40);
//toppings check boxes
checkBoxPanel.setVisible(true);
checkBoxPanel.setBounds(100, 200, 100, 50);
String Topping[] = {"Tomato", "Green Pepper", "Black Olives", "Mushrooms", "Extra Cheese", "Pepperoni", "Sausage"};
checkBoxPanel.add(new JCheckBox("Tomato"));
checkBoxPanel.add(new JCheckBox(Topping[1]));
checkBoxPanel.add(new JCheckBox(Topping[2]));
checkBoxPanel.add(new JCheckBox(Topping[3]));
checkBoxPanel.add(new JCheckBox(Topping[4]));
checkBoxPanel.add(new JCheckBox(Topping[5]));
checkBoxPanel.add(new JCheckBox(Topping[6]));
//sizes radio buttons
String size[] = {"Small:$6.50", "Medium:$8.50", "Large:$10.00"};
JRadioButton radio = new JRadioButton(size[0]);
radio.setBounds(100, 50, 100, 20);
//
panel.add(checkBoxPanel);
//
setContentPane(panel);
这是应该根据用户输入执行某些操作的代码。请帮我把它说清楚和可读。 这是错误:“字段Component.x不可见”
答案 0 :(得分:3)
是的,这就是JPanel
的用途。它是一个空容器,具有内部布局管理器,可以放在JFrame
内(或另一个JPanel
内)的任何位置。所以,只是给你一个例子,你可以:
JPanel checkBoxPanel = new JPanel(new GridLayout(..));
JPanel fieldsPanel = new JPanel(new BoxLayout(..));
checkBoxPanel.add(new JCheckBox(..));
fieldsPanel.add(new JTextField(..));
frame.setLayout(new BorderLayout());
frame.add(checkBoxPanel, BorderLayout.NORTH);
frame.add(..)