gpt4 book ai didi

java - ActionListener 上未找到符号错误

转载 作者:行者123 更新时间:2023-12-01 10:44:10 25 4
gpt4 key购买 nike

import javax.swing .*;    
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.JOptionPane;
import java.io.FileWriter;
class Myclass extends JFrame
{
Myclass()
{
setLayout(null);
setLayout(new FlowLayout());
//setBounds(50,50,700,700);
JLabel lfname=new JLabel("Name ");
JLabel llname=new JLabel("Lastname ");
JLabel lmidname=new JLabel("Middlename ");
JTextField tname=new JTextField(15);
JTextField tmidname=new JTextField(15);
JTextField tlastname=new JTextField(15);
add(lfname);add(tname);
add(lmidname);add(tmidname);
add(llname);add(tlastname);
JButton addrec=new JButton("Add Record");
JButton delrec=new JButton("Delete Record");
GridBagConstraints g=new GridBagConstraints();

JPanel p=new JPanel(new GridLayout(1,2,20,20));

add(p);

p.add(addrec);
p.add(delrec);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/*tname.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent oe)
{
System.out.println("Text="+tname.getText());
}


});*/
//tname.addActionListener(obj);
JButton save=new JButton("Save");
MyListener obj=new MyListener();
add(save);
save.addActionListener(obj);

setVisible(true);



}


public static void main(String args[])
{
new Myclass();


}

class MyListener implements ActionListener
{

public void actionPerformed(ActionEvent oe)
{

//if(ae.getSource().equals(calRect))
if(oe.getSource().equals(save))
{
FileWriter fw=null;
try{
fw=new FileWriter("c:\\users\\dell\\desktop\\File.txt");
}catch(Exception e){}

}
}

}

我正在尝试通过在 Mylistener 类上实现 ActionListener 来添加名为 Mylistener 的自定义监听器
我不知道这段代码有什么问题,但在 actionPerformed() 中,if 条件开始的地方是错误的位置。谁能更正我的代码吗?

Error is Layout.java:69: error: cannot find symbol
if(oe.getSource().equals(save))

^
symbol: variable save
location: class MyListener
1 error

最佳答案

您的保存按钮未在监听器类中定义。您必须将其作为参数添加到构造函数中:

class MyListener implements ActionListener {

private JButton save;
public MyListener(JButton save){
this.save = save;
}
public void actionPerformed(ActionEvent oe) {

// if(ae.getSource().equals(calRect))
if (oe.getSource().equals(save)) {
FileWriter fw = null;
try {
fw = new FileWriter("c:\\users\\dell\\desktop\\File.txt");
} catch (Exception e) {}

}
}


//tname.addActionListener(obj);
JButton save=new JButton("Save");
MyListener obj=new MyListener();
add(save);
save.addActionListener(obj);

关于java - ActionListener 上未找到符号错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34284463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com