Kei*_*lan 4 java swing jlabel jbutton actionlistener
我试图在单击JButton时显示JLabel.我添加了一个动作侦听器并将该组件添加到布局中.在actionPerformed中单击JButton时,我正在使用label1.setVisible(true).我仍然无法使它工作.有人可以看看我的代码吗?
public class LearnAppMain extends JFrame implements ActionListener {
// Define variables
public JButton button1;
public JLabel label1;
public JTextField field1;
private Image image1;
private String apple = "apple.jpg";
public LearnAppMain() {
ImageIcon image1 = new ImageIcon(this.getClass().getResource(apple));
JLabel label1 = new JLabel(image1);
button1 = new JButton("A");
button1.addActionListener(this);
field1 = new JTextField(10);
// Create layout
setLayout(new FlowLayout());
// create Container
final Container cn = getContentPane();
cn.add(button1);
cn.add(field1);
cn.add(label1);
// setLayout(new FlowLayout());
setSize(250, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (e.getSource() == button1) {
label1.setVisible(true);
field1.setText("Apple");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我在另一个类文件中有我的main方法.我得到的错误引导我到label1.setVisible(true);
我看到他们说过的每一个问题都是这样做的,但我想知道是否还有其他东西需要补充.
这里有几个问题:
label1被隐藏了JLabel label.你基本上声明了另一个label1在你的构造函数中调用的变量,它隐藏了类本身的变量.label.setVisible(false)测试,但您可能不需要我也把创作Image放在一边,因为我没有图像,所以取消注释并适当改变.
这是一个完整的工作版本:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class LearnAppMain extends JFrame implements ActionListener {
// Define variables
public JButton button1;
public JLabel label1;
public JTextField field1;
private Image image1;
private String apple = "apple.jpg";
public LearnAppMain() {
//ImageIcon image1 = new ImageIcon(this.getClass().getResource(apple));
//JLabel label1 = new JLabel(image1);
label1 = new JLabel("hello");
label1.setVisible(false);
button1 = new JButton("A");
button1.addActionListener(this);
field1 = new JTextField(10);
// Create layout
setLayout(new FlowLayout());
// create Container
final Container cn = getContentPane();
cn.add(button1);
cn.add(field1);
cn.add(label1);
// setLayout(new FlowLayout());
setSize(250, 250);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (e.getSource() == button1) {
label1.setVisible(true);
field1.setText("Apple");
}
}
public static void main(String[] args) {
new LearnAppMain();
}
}
Run Code Online (Sandbox Code Playgroud)
我建议使用单独的(通常是内部类)ActionListener实例而不是覆盖actionPerformed.如果您感兴趣,请参阅以下类似示例:
此外,如果您在更大的应用程序中使用它(即不仅仅是试验或原型),请确保所有Swing代码都在EDT上运行.
您通常使用SwingUtilities.invokeLater来实现此目的.
希望这可以帮助.