How to make JButton event modify JFrame (this)
I'm trying to make a JButton click event modify the JFrame the button is on. The problem is the class itself is the JFrame (extending from it), so I can't invoke 'this' from the inner class that handles the event. I found a solution which works but I think it could lead to other problems, so I'm trying to find another way. The code is as follows:
public class ClassX extends JFrame {
...
this.setTitle("Title1"); //works fine
jButton1 = new JButton();
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
//this.setTitl开发者_运维知识库e("Title1"); //calling 'this' won't work inside an inner class
//Ugly Solution
JButton btn = (JButton) e.getSource();
JFrame frme = (JFrame) btn.getParent().getParent().getParent().getParent();
frme.setTitle("Title2");
}
});
...
}
I'm trying to avoid the multiple getParent calls, but can't find another solution. Any ideas? Is there perhaps a way to pass 'this' or any other parameter to the action listener method?
Thanks.
Of course you can :
ClassX.this.setTitle("Title1");
Will do the job (and Jon Skeet agrees with me).
ClassX.this.setTitle("Title2");
Instead of having an inner ActionListener class why not implement the ActionListener interface ?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ClassX extends JFrame implements ActionListener
{
JButton jButton1;
public ClassX()
{
jButton1 = new JButton();
jButton.addActionListener(this);
this.add(jButton);
}
public void actionPerformed(ActionEvent e)
{
this.setTitle("Button Clicked!")
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ClassX frame1 = new ClassX();
frame1.setVisible(true);
}
} );
}
}
精彩评论