【问题标题】:swing - how to switch JPanel using buttonswing - 如何使用按钮切换 JPanel
【发布时间】:2012-11-13 09:13:54
【问题描述】:

大家好,我正计划创建登录面板。在该面板中应该是用户 JLabel、密码 JLabel、用户 JTextField、密码 JTextField 和 JButon。我想使用该按钮切换到新的 JPanel。我读过最好的方法是 CardLayout,我正在尝试修改该代码:

//Where the GUI is assembled:
//Put the JComboBox in a JPanel to get a nicer look.
JPanel comboBoxPane = new JPanel(); //use FlowLayout
String comboBoxItems[] = { BUTTONPANEL, TEXTPANEL };
JComboBox cb = new JComboBox(comboBoxItems);
cb.setEditable(false);
cb.addItemListener(this);
comboBoxPane.add(cb);
...
pane.add(comboBoxPane, BorderLayout.PAGE_START);
pane.add(cards, BorderLayout.CENTER);
...

//Method came from the ItemListener class implementation,
//contains functionality to process the combo box item selecting
public void itemStateChanged(ItemEvent evt) {
    CardLayout cl = (CardLayout)(cards.getLayout());
    cl.show(cards, (String)evt.getItem());
}

我正在尝试修改那部分代码

JComboBox cb = new JComboBox(comboBoxItems);
cb.setEditable(false);
cb.addItemListener(this);
comboBoxPane.add(cb);
pane.add(comboBoxPane, BorderLayout.PAGE_START);
pane.add(cards, BorderLayout.CENTER);

并将其更改为:

JButton loginButton = new JButton();
loginButton.addItemListener(this);
comboBoxPane.add(loginButton);
pane.add(loginButton, BorderLayout.PAGE_START);
pane.add(cards, BorderLayout.CENTER);

我不能使用:

JButton loginButton = new JButton(comboBoxItems);

因为编译器返回错误:构造函数 JButton(String[]) 未定义

有谁能帮我解决我的问题。我是Java编程新手

【问题讨论】:

  • 如果这是一个问题,您最好从一些基本的 Java 教程开始。只是从互联网上复制代码并尝试进行一些修改而不了解它的作用只会将您从一个问题带到另一个问题
  • 是的,我明白你的意思,我正在学习 Java 基础。

标签: java swing button jpanel switch-statement


【解决方案1】:

JButton 没有采用String 数组的构造函数。调用就足够了:

JButton loginButton = new JButton("Login");

见:Creating a GUI With JFC/Swing

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    • 2022-11-18
    • 2014-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多