JButton上没有名字的Java Actionlistener?

JButton上没有名字的Java Actionlistener?,java,swing,jbutton,actionlistener,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);

我有以下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();
    }
所以我有一个框架,它有一个按钮,目前什么都不做。我一直在互联网上寻找解决方案,但我不知道如何将actionlistener添加到按钮,因为它没有名称?比如,我如何判断actionlistener按下了什么按钮?除此之外,我认为我必须实现它,因此我认为在主要方法中这样做可能是个坏主意?我只是想在将它移动到另一个类或方法之前尝试一下


好的,我希望你能给我一些建议或建议,提前谢谢

让我们看看这一行:

panel.add(new Button("Press here :)"));
创建一个新按钮并将其传递到
面板的
添加方法。如果要对按钮执行任何操作,例如向其添加
ActionListener
,则首先创建按钮并将其分配给变量,然后再将其传递给
面板。添加

// 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教程,例如关于的教程。

让我们看一下这一行:

panel.add(new Button("Press here :)"));
创建一个新按钮并将其传递到
面板的
添加方法。如果要对按钮执行任何操作,例如向其添加
ActionListener
,则首先创建按钮并将其分配给变量,然后再将其传递给
面板。添加

// 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教程,例如关于。答案代码中的
按钮
更改为
JButton
@彼得:请注意这一点,因为这很重要。您不希望在没有充分理由和远见的情况下混合使用Swing和AWT组件。
按钮
在应答代码中更改为
JButton
@彼得:请注意这一点,因为这很重要。如果没有充分的理由和远见,您不会希望混合Swing和AWT组件。