我有一个框架,其中有一个显示不同形状的组合框和一个按钮,为此按钮添加了一个动作侦听器,该侦听器将从组合框中获取选定的项并将其存储为字符串,我将其声明为公共类变量,我的主要方法是想访问此字符串以使雀科机器人绘制该形状,但是无论尝试如何,我似乎都无法访问它
public class DrawShape
{
private JFrame frame;
private String[] choices = {"circle", "square", "triangle", "rectangle", "quit"};
public String choice = "";
//class constructor
public DrawShape()
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
JPanel p = new JPanel();
final JComboBox cb = new JComboBox(choices);
JButton button = new JButton("Done");
p.add(cb);
p.add(button);
frame.add(p);
//create an action listener that, when button is clicked, gets the selected choice and stores it to
//the string variable 'choice'
button.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
choice = (String)cb.getSelectedItem();
}
}) ;
frame.pack();
}
public static void main(String[] args)
{
new DrawShape();
System.out.println(choice);
}
}
解决方案如下:
我不建议使用非私有变量。但是,您需要保留对您创建的对象的引用,然后通过该引用访问字段,就像您在调用对象上的方法一样。
DrawShape draw = new DrawShape();
System.out.println(draw.choice);
但是,您应该看到
null
,因为在构造对象之后而不是从侦听器会立即调用它。
您可能希望从侦听器执行代码。因此,要么将打印代码放入侦听器中,要么让侦听器使用该方法调用另一个方法。
GUI编程往往是事件驱动的。不要期望能够对用户交互进行排序-用户驱动。