oww*_*ess 0 java swing jbutton actionlistener
我有这个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();
}
Run Code Online (Sandbox Code Playgroud)
所以我有这个框架有一个按钮,目前什么都不做.我一直在互联网上寻找解决方案,但我无法弄清楚如何将actionlistener添加到按钮,因为它没有名称?就像我怎么告诉使用actionlistener按下了什么按钮?除此之外,我相信我必须实现它,因此我认为在main方法中执行此操作可能是个坏主意?我只想在将它移动到另一个类或方法之前尝试一下.
好的,我希望你能提前给我一些建议或意见,谢谢!
我们来看看这一行:
panel.add(new Button("Press here :)"));
Run Code Online (Sandbox Code Playgroud)
您创建一个新按钮并将其传递给add方法panel.如果你想对按钮做任何事情,比如添加一个按钮,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);
Run Code Online (Sandbox Code Playgroud)
这是Java编程的基本知识.有关如何使用对象和变量的更多信息,请参阅Oracle的教程,例如关于变量的教程.
| 归档时间: |
|
| 查看次数: |
293 次 |
| 最近记录: |