[英]Java - How to assign a variable from an inner class to a variable in the outer class/ or any other class?
我有一个包含文本字段的类,并且在该类中包含一个执行动作的方法的内部类。 输入文本并按Enter键后,我希望将文本分配给实现Action Listener的内部类之外的字符串“ s”。 我想在另一个类中使用该字符串。
public class Peaches extends JFrame {
private JTextField item1;
public Peaches() {
super("the title");
setLayout(new FlowLayout());
item1 = new JTextField(10);
add(item1);
thehandler handler = new thehandler(); //object of thehandler inner class
item1.addActionListener(handler);
// I want to use the textfield content here, or in other classes, updated
// with the new text everytime i hit enter after entering new text in the textfield
//String s = the content of the textfield
}
private class thehandler implements ActionListener { // inner class
@Override
public void actionPerformed(ActionEvent event) {
String string = "";
string = String.format(event.getActionCommand());
JOptionPane.showMessageDialog(null, string);
}
}
有什么办法吗? 必须在程序的其他部分中使用文本字段的输入。 我希望我能说清楚,谢谢大家。
编辑感谢您的答复,因此使变量字符串成为类变量而不是在构造函数中声明它可以使整个类都可以访问它,这很简单,但是我只是不了解。 谢谢马尔科
我建议你这样做:
public class Peaches extends JFrame {
private JTextField item1;
private String string;
public Peaches() {
super("the title");
setLayout(new FlowLayout());
item1 = new JTextField(10);
add(item1);
item1.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent event) {
string = String.format(event.getActionCommand() );
JOptionPane.showMessageDialog(null, string);
}});
}
}
这使用一个匿名类,比周围有许多内部类要简单。 加上这些,您可以进行闭包(使用在匿名类外部声明的局部变量)。 而且您的字符串在外面,因此您可以访问它。
我想在这里或其他班级中使用文本字段内容,每次在文本字段中输入新文本后按回车键时都使用新文本更新
简短的答案是,如果您希望每次更改文本字段中的值时都执行代码,则必须将侦听器附加到文本字段并通过侦听器触发该代码。 那就是侦听器的目的……唯一知道文本已更改的是文本字段,他将告知其侦听器已进行更改的事实( 观察者模式 )。
如果您想在几节课中获悉这一变化,可以选择
是否使用内部类,匿名类,成熟类作为侦听器并不重要。
如果将s用作类变量而不是方法变量(当前在构造函数中已注释掉),则它将起作用。
您可以在内部类的构造函数中将外部类作为参数传递。
您根本不需要内部类。 只需在Peaches
实现一个ActionListener,并使其监听ActionEvent
:
public class Peaches extends JFrame implements ActionListener
{
private JTextField item1;
public Peaches()
{
super("the title");
setLayout(new FlowLayout());
item1 = new JTextField(10);
add(item1);
item1.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == item1){
String string = "";
string = String.format(event.getActionCommand() );
JOptionPane.showMessageDialog(null, string);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.