[英]Java Actionlistener on JButton with no name?
我有这个java代码:
public static void main(String[] args) throws IOException
{
JPanel panel = new JPanel();
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.add(panel, BorderLayout.SOUTH);
panel.add(new Label("south"));
panel.add(new Button("Press here :)"));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(loader);
frame.getContentPane().addMouseListener(loader);
//frame.getContentPane().addMouseMotionListener(loader);
frame.pack();
frame.repaint();
frame.setVisible(true);
//Deleted some unimportant content
panel.setVisible(true);
panel.add("south", panel);
t.start();
}
所以我有这个框架,其中有一个按钮目前不执行任何操作。 我一直在互联网上寻找解决方案很多,但由于它没有名称,我不知道如何在按钮上添加动作监听器? 就像我如何判断动作监听器按下了什么按钮? 除此之外,我认为我必须执行它,因此我认为在主要方法中执行此操作可能不是一个好主意? 我只是想尝试一下,然后再将其移至另一个类或方法。
好吧,希望您能向我提供一些建议或意见,谢谢!
让我们看一下这一行:
panel.add(new Button("Press here :)"));
您创建一个新按钮,并将其传递给panel
的add
方法。 如果要对按钮执行任何操作(例如向其添加ActionListener
,请先创建按钮并将其分配给变量,然后再将其传递给panel.add
:
// Create a Button and assign it to a variable
JButton button = new JButton("Press here :)");
// Add an action listener to the button
button.addActionListener(...);
// Add the button to the panel
panel.add(button);
这是基本的Java编程知识。 有关如何使用对象和变量的更多信息,请参见Oracle教程,例如有关变量的教程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.