这里有几个问题:
>通过在构造函数中执行JLabel标签来隐藏label1.您基本上在构造函数中声明了另一个名为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();
}
}
我建议使用单独的(通常是内部类)ActionListener实例,而不是重写actionPerformed.参见例如如果您有兴趣,这可以用于类似的示例:
此外,如果您在更大的应用程序中使用它(即不仅仅是试验或原型),请确保所有Swing代码都在EDT上运行.
希望这可以帮助.