我是一名初学者程序员,我正在尝试学习如何将在主类中创建的某些对象传递给其他类(在本例中为动作侦听器类)。
我的问题是 - 如何将按钮传递给动作侦听器类?这是我的代码片段。
public class MaxMinProgram
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Max Min Program");
GridLayout myLayout = new GridLayout(1,11);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int size = 11;
JTextField[] fields = new JTextField[size];
JPanel panel = new JPanel();
frame.setPreferredSize(new Dimension(500,110));
frame.getContentPane().add(panel);
int k = 0;
for(k=0;k<fields.length;k++)
{
fields[k] = new JTextField("", 3);
panel.add(fields[k]);
}
JButton button = new JButton("Randomize");
JButton button2 = new JButton("Max Min");
panel.add(button);
panel.add(button2);
frame.pack();
frame.setVisible(true);
}
}
public class myListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent evt)
{
ActionListener clickListener = new myListener();
button.addActionListener(clickListener); //this is the line
int [ ] numbers = new int [10];
JTextField [] textFields;
Random randomize = new Random();
int x = randomize.nextInt(100);
}
}
非常感谢您的帮助!