GUI组件在不同类中难以访问,郁闷了半天
来源:百度知道 编辑:UC知道 时间:2024/06/03 13:46:55
JButton;
JButton.addActionListener(ActionListener1);
}
class ActionListener1{
public void actionPerformed(ActionEvent e){
Object obj=e.getSource();
if(obj==new Frame().JButton) ///这两句是关键
{
--------------------
}
}
代码只是把重点写出来了
如果将两个类的内容写在同一个类中,访问起来很方便
但是现在我想把功能清晰的分出来,写在两个类中
在ActionListener1访问的JButton,感觉和Frame中的JButton不是同一个,就是
在界面中点了也没反应,其中的代码没有问题,问题应该出在实例化对象中,但具体哪一点错
了,我不知道,如果把JButton定义为静态的也能解决问题,就没有其它别的办法了吗
访问个组件应该不是件难事吧
/*
*ActionListen1 需要继承 ActionListener 接口
*如果要区分 JButton 可以用 setActionCommand() 和 getActionCommand() 方法
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class test extends JFrame
{
private JButton dbutton;
private JButton hbutton;
private JLabel label1;
public test()
{
JPanel contentPane = (JPanel)getContentPane();
contentPane.setLayout(null);
label1 = new JLabel("Hello World!");
label1.setBounds(90,40,80,30);
contentPane.add(label1);
dbutton = new JButton("显示");
dbutton.setBounds(90,90,80,20);
dbutton.setActionCommand("dbutton");
dbutton.addActionListener(new ActionListen1(label1));
contentPane.add(dbutton);
hbutton = new JButton("隐藏");
hbutton.setBounds(180,90,80,20);
hbutton.setActionCommand("hbutton");
hbutton.addAc