[英]Error on basic Java program - cannot find symbol ActionListener()
[英]Symbol not Found error on ActionListener
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条件开始的地方是错误的位置。 谁能纠正mycode?
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.