gpt4 book ai didi

java - 如何将 JButton 传递给 Action Listener 类

转载 作者:行者123 更新时间:2023-12-01 23:29:39 28 4
gpt4 key购买 nike

我是一名初学者程序员,我正在尝试学习如何将主类中创建的某些对象传递给其他类(在本例中为操作监听器类)。

我的问题是 - 如何将按钮传递给操作监听器类?这是我的代码片段。

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);
}
}

非常感谢您的帮助!

最佳答案

移动

   ActionListener clickListener = new myListener();
button.addActionListener(clickListener); //this is the line

例如,到您的 main 方法

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");

ActionListener clickListener = new myListener();
button.addActionListener(clickListener); //this is the line

panel.add(button);
panel.add(button2);
frame.pack();
frame.setVisible(true);

}

关于java - 如何将 JButton 传递给 Action Listener 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19531334/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com