要么使JTextField
final
或使其在类中的实例字段。
final JTextField textField = ...
或
public class ... {
private JTextField textField;
public ...() { = new JTextField(...);
您可以为其他变量来做到这一点。通常情况下,除非你有其他理由,否则我会建议使用实例字段。看看Understanding Class Members了解更多详细信息...
您可以考虑像C中的“私有”变量这样的实例字段,那些在C文件本身中声明的实例字段,其中不能在文件的外部引用它们在
更新
首先,GUI的(对不起,很长一段时间,因为我已经做了ç所以可能不完全正确)宣布往往是事件驱动的,也就是说,它们不运行在线性/程序化的方式。你设置了一堆回调,并等待一些东西来触发它们。当触发回调,您采取适当的行动......
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField textField;
private JComboBox comboBox;
private String theValue;
public TestPane() {
textField = new JTextField(10);
comboBox = new JComboBox(new String[]{"Banana", "Apple", "Grapes", "Strawberries"});
comboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
theValue = (String)comboBox.getSelectedItem();
textField.setText(theValue);
}
});
comboBox.setSelectedItem(null);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(textField, gbc);
add(comboBox, gbc);
}
}
}
在这个例子中,分配给JComboBox
的ActionListener
没有立即叫,这意味着分配下的剩余代码会立即运行和前ActionListener
有任何被调用的机会。
认为它像一个函数指针或回调。你可以把它传递给另一个函数,但你不知道什么时候会被称为......
当的JComboBox
变化和触发器和操作事件的状态下,ActionListener
小号actionPeformed
方法被调用,此时您可以获取当前值并将其应用到文本字段并将其分配给您的变量...或者您还需要做什么......
请注意,我附加了ActionListener
和被调用comboBox.setSelectedItem(null)
,这将会实际上会导致ActionListener
被通知...棘手;)
澄清:在actionPerformed()方法内赋值给值不会产生错误。但是当我稍后尝试将该值分配给侦听器之外的另一个变量时,我收到了报告的错误。 – frododot 2014-10-10 04:16:22
谢谢MadProgrammer!问题解决了...! – frododot 2014-10-10 18:26:16