HTML中按钮在java中action,java – 在actionPerformed中单击JButton时设置JL...

这里有几个问题:

>通过在构造函数中执行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上运行.

希望这可以帮助.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值