当我使用组合框时,我在将另一个JPanel添加到我的框架时遇到问题。 我想根据组合框中的选择更改中心面板。 我为所有选项制作了不同的面板,但它没有添加到我的主面板。 我添加了代码。
谢谢:)
import AllClasses.FlightCompany;
{
public class WorkerDialog extends JFrame {
private JPanel Worker;
private String[] LabelNames = { "Worker Type:", " Worker Name:" };
String [] str = { "Office", "Host",
"Pilot" };
JComboBox<String> ChooseBox = new JComboBox<>(str);
public JPanel MainPanel;
private JPanel [] p= new JPanel[3];
public WorkerDialog(FlightCompany f) {
super("Worker Dialog");
p[0] = new Office_Gui();
p[1] = new Host_Gui();
p[2] = new Pilot_Gui();
Worker = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
JLabel LabelName = new JLabel(LabelNames[0]);
JLabel LabelName2 = new JLabel(LabelNames[1]);
JTextField fieldBox = new JTextField();
LabelName.setSize(40, 25);
ChooseBox.setPreferredSize(new Dimension(180, 22));
Worker.add(LabelName);
Worker.add(ChooseBox);
Worker.add(LabelName2);
fieldBox.setPreferredSize(new Dimension(180, 22));
Worker.add(fieldBox);
JPanel AddPanel = new JPanel(new GridLayout(2, 1, 1, 1));
AddPanel.add(new JButton("Add"));
AddPanel.add(new JButton("TakeOff"));
MainPanel = new JPanel(new BorderLayout(3, 3));
AddPanel.setPreferredSize(new Dimension(0, 110));
ChooseBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
//String str = e.getActionCommand();
String jb = (String) ChooseBox.getSelectedItem();
if (jb.equals("Office")){
MainPanel.add(p[0],BorderLayout.CENTER);
System.out.println("Office");}
}
});
MainPanel.add(Worker, BorderLayout.NORTH);
MainPanel.add(AddPanel, BorderLayout.SOUTH);
add(MainPanel);
//pack();
setSize(560, 300);
setAlwaysOnTop(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
答案 0 :(得分:1)
您要做的是为CardLayout
使用mainPanel
,这样您就可以在面板之间轻松切换。然后将所有面板添加到mainPanel
,指定面板的名称。该名称将放在组合框中。如果您想要显示某个面板,请拨打cardLayout.show(mainPanel, "nameOfPanel")
要详细了解Cardlayout
,请参阅How to Use CardLayout。您还可以看到一个简单示例here
抛开:使用Java命名约定。变量以小写字母开头,使用骆驼外壳。即:
ChooseBox
→chooseBox
MainPanel
→mainPanel