如何为按钮添加动作?

时间:2022-08-23 23:37:13

I am trying to enter an event for JButon I create:

我正在尝试为我创建的JButon创建一个事件:

    JButton botton1=new JButton("welcom to my show db! lets start");
    botton1.setFont(new Font ("Eras Medium ITC",Font.BOLD,20));
    this.add(botton1);

    JPanel Basic_panel=new JPanel();
    Basic_panel.setName("SHOW DB ");
    Basic_panel.setBounds(x,y,width,hight);

    botton1.addActionListener(this) ;
}
          public void actionPerformed(ActionEvent e) {
                if (e.getSource()==botton1){

Now I want to enter another JFrame I made, and make the first disappear. How?

现在我想进入另一个我制作的JFrame,让第一个消失。怎么样?

1 个解决方案

#1


3  

For your original question:

对于您的原始问题:

How to add action to a button?

如何为按钮添加动作?

you might want to check How to write an Action Listener.

您可能想要检查如何编写动作侦听器。

For your second question:

对于你的第二个问题:

Now I want to enter another JFrame I made, and make the first disappear. How?

现在我想进入另一个我制作的JFrame,让第一个消失。怎么样?

please check both approaches :)

请检查两种方法:)

Option 1 (Recommended)

If you want to do it the right way, you should use a CardLayout as recommended by @AndrewThompson in his comment above.

如果你想以正确的方式做到这一点,你应该使用@AndrewThompson在上面的评论中推荐的CardLayout。

I also saw you were using a Null Layout (because of setBounds() method), you might also want to get rid of it, see Why is it frowned upon to use a null layout in Swing? and Null Layout is Evil to know why, insted you should be using a Layout Manager or combinations of them as shown in the following code based on @AndrewThompson's answer (The same that was linked in his comment above) but a bit modified to work with a JFrame instead of a JOptionPane, so give him credit by upvoting his Original Answer too!

我也看到你使用Null Layout(因为setBounds()方法),你可能也想摆脱它,看看为什么在Swing中使用null布局不赞成?和Null Layout是邪恶的,知道为什么,你应该使用布局管理器或它们的组合,如下面的代码所示,基于@ AndrewThompson的答案(在上面的评论中链接的相同)但有点修改后可以使用一个JFrame而不是一个JOptionPane,所以通过提升他的原始答案给予他信任!

This produces the following outputs:

这会产生以下输出:

如何为按钮添加动作? 如何为按钮添加动作?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class CardLayoutDemo {
    JButton button1, button2;

    CardLayoutDemo() {
        JFrame gui = new JFrame("CardLayoutDemo");
        button1 = new JButton("Go to pane 2");
        button2 = new JButton("Go to pane 1");
        JPanel pane1 = new JPanel();
        pane1.setLayout(new BoxLayout(pane1, BoxLayout.PAGE_AXIS));
        JPanel pane2 = new JPanel();
        pane2.setLayout(new BoxLayout(pane2, BoxLayout.PAGE_AXIS));
        final CardLayout cl = new CardLayout();
        final JPanel cards = new JPanel(cl);

        pane1.add(new JLabel("This is my pane 1"));
        pane1.add(button1);

        pane2.add(new JLabel("This is my pane 2"));
        pane2.add(button2);

        gui.add(cards);
        cards.add(pane1, "frame1");
        cards.add(pane2, "frame2");

        ActionListener al = new ActionListener(){
            public void actionPerformed(ActionEvent ae) {
                if (ae.getSource() == button1) {
                    cl.show(cards, "frame2");
                } else if (ae.getSource() == button2) {
                    cl.show(cards, "frame1");
                }
            }
        };

        button1.addActionListener(al);
        button2.addActionListener(al);

        gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gui.pack();
        gui.setVisible(true);
    }
    public static void main(String[] args) {
        new CardLayoutDemo();
    }
}

With this option you only have 1 JFrame but you can change through different views, and you don't annoy user with multiple windows on the task bar.

使用此选项,您只有1个JFrame,但您可以通过不同的视图进行更改,并且您不会在任务栏上烦扰具有多个窗口的用户。

One more tip here is: If you're going to open this second JFrame to prevent user from doing something on the 1st one, you should consider using a JOptionPane or this second JFrame will contain just a bit information which you don't want to have there for the whole time (Something like a pop up).

这里还有一个提示:如果你打算打开第二个JFrame来防止用户在第一个上做某事,你应该考虑使用JOptionPane,或者第二个JFrame只包含一些你不想要的信息。一直都在那里(像弹出一样)。


Option 2 (Not recommended)

But if you really really really want to use multiple JFrames (which is not recommended) you can dispose() it. At the time you're calling your new JFrame to be created. For example, the following code produces this output:

但如果你真的真的想要使用多个JFrame(不推荐使用),你可以处理()它。当您正在调用要创建的新JFrame时。例如,以下代码生成此输出:

如何为按钮添加动作? 如何为按钮添加动作?

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TwoJFrames {
    JFrame frame;
    JButton button;

    TwoJFrames() {
        frame = new JFrame("1st frame");
        button = new JButton("Click me!");

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new AnotherFrame();
                frame.dispose();
            }
        });

        frame.add(button);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String args[]) {
        new TwoJFrames();
    }

    class AnotherFrame {
        JFrame frame2;
        JLabel label;
        AnotherFrame() {
            frame2 = new JFrame("Second Frame");
            label = new JLabel("This is my second frame");

            frame2.add(label);
            frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame2.pack();
            frame2.setVisible(true);
        }
    }
}

In this case you might want to consider setVisible() instead if you want to go back to previous state or reopen this one when closing the second JFrame

在这种情况下,你可能想要考虑setVisible(),如果你想回到以前的状态或在关闭第二个JFrame时重新打开这个状态


Both of my above codes are called a Minimal, Complete, and Verifiable example (MCVE) or Runnable Example or Short, Self Contained, Correct Example (SSCCE) which are code you can copy-paste and see the same output as me, when you have an error in your code, these examples are very handy because we can see where your errors are or be able to find them easier and/or faster.

我上面的两个代码都被称为最小,完整和可验证的示例(MCVE)或可运行的示例或简短的,自包含的,正确的示例(SSCCE),这些代码可以复制粘贴并看到与我相同的输出,当您在您的代码中出现错误,这些示例非常方便,因为我们可以查看您的错误位置,或者能够更轻松和/或更快地找到它们。

You should consider reading all the links I provided (included these ones) and for your future questions to make something like I've done above, that way you'll prevent confusion and you'll get more, faster and better responses.

您应该考虑阅读我提供的所有链接(包括这些链接)以及您将来的问题以制作类似我上面所做的事情,这样您就可以避免混淆,并且您将获得更多,更快和更好的响应。

#1


3  

For your original question:

对于您的原始问题:

How to add action to a button?

如何为按钮添加动作?

you might want to check How to write an Action Listener.

您可能想要检查如何编写动作侦听器。

For your second question:

对于你的第二个问题:

Now I want to enter another JFrame I made, and make the first disappear. How?

现在我想进入另一个我制作的JFrame,让第一个消失。怎么样?

please check both approaches :)

请检查两种方法:)

Option 1 (Recommended)

If you want to do it the right way, you should use a CardLayout as recommended by @AndrewThompson in his comment above.

如果你想以正确的方式做到这一点,你应该使用@AndrewThompson在上面的评论中推荐的CardLayout。

I also saw you were using a Null Layout (because of setBounds() method), you might also want to get rid of it, see Why is it frowned upon to use a null layout in Swing? and Null Layout is Evil to know why, insted you should be using a Layout Manager or combinations of them as shown in the following code based on @AndrewThompson's answer (The same that was linked in his comment above) but a bit modified to work with a JFrame instead of a JOptionPane, so give him credit by upvoting his Original Answer too!

我也看到你使用Null Layout(因为setBounds()方法),你可能也想摆脱它,看看为什么在Swing中使用null布局不赞成?和Null Layout是邪恶的,知道为什么,你应该使用布局管理器或它们的组合,如下面的代码所示,基于@ AndrewThompson的答案(在上面的评论中链接的相同)但有点修改后可以使用一个JFrame而不是一个JOptionPane,所以通过提升他的原始答案给予他信任!

This produces the following outputs:

这会产生以下输出:

如何为按钮添加动作? 如何为按钮添加动作?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class CardLayoutDemo {
    JButton button1, button2;

    CardLayoutDemo() {
        JFrame gui = new JFrame("CardLayoutDemo");
        button1 = new JButton("Go to pane 2");
        button2 = new JButton("Go to pane 1");
        JPanel pane1 = new JPanel();
        pane1.setLayout(new BoxLayout(pane1, BoxLayout.PAGE_AXIS));
        JPanel pane2 = new JPanel();
        pane2.setLayout(new BoxLayout(pane2, BoxLayout.PAGE_AXIS));
        final CardLayout cl = new CardLayout();
        final JPanel cards = new JPanel(cl);

        pane1.add(new JLabel("This is my pane 1"));
        pane1.add(button1);

        pane2.add(new JLabel("This is my pane 2"));
        pane2.add(button2);

        gui.add(cards);
        cards.add(pane1, "frame1");
        cards.add(pane2, "frame2");

        ActionListener al = new ActionListener(){
            public void actionPerformed(ActionEvent ae) {
                if (ae.getSource() == button1) {
                    cl.show(cards, "frame2");
                } else if (ae.getSource() == button2) {
                    cl.show(cards, "frame1");
                }
            }
        };

        button1.addActionListener(al);
        button2.addActionListener(al);

        gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gui.pack();
        gui.setVisible(true);
    }
    public static void main(String[] args) {
        new CardLayoutDemo();
    }
}

With this option you only have 1 JFrame but you can change through different views, and you don't annoy user with multiple windows on the task bar.

使用此选项,您只有1个JFrame,但您可以通过不同的视图进行更改,并且您不会在任务栏上烦扰具有多个窗口的用户。

One more tip here is: If you're going to open this second JFrame to prevent user from doing something on the 1st one, you should consider using a JOptionPane or this second JFrame will contain just a bit information which you don't want to have there for the whole time (Something like a pop up).

这里还有一个提示:如果你打算打开第二个JFrame来防止用户在第一个上做某事,你应该考虑使用JOptionPane,或者第二个JFrame只包含一些你不想要的信息。一直都在那里(像弹出一样)。


Option 2 (Not recommended)

But if you really really really want to use multiple JFrames (which is not recommended) you can dispose() it. At the time you're calling your new JFrame to be created. For example, the following code produces this output:

但如果你真的真的想要使用多个JFrame(不推荐使用),你可以处理()它。当您正在调用要创建的新JFrame时。例如,以下代码生成此输出:

如何为按钮添加动作? 如何为按钮添加动作?

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TwoJFrames {
    JFrame frame;
    JButton button;

    TwoJFrames() {
        frame = new JFrame("1st frame");
        button = new JButton("Click me!");

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new AnotherFrame();
                frame.dispose();
            }
        });

        frame.add(button);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String args[]) {
        new TwoJFrames();
    }

    class AnotherFrame {
        JFrame frame2;
        JLabel label;
        AnotherFrame() {
            frame2 = new JFrame("Second Frame");
            label = new JLabel("This is my second frame");

            frame2.add(label);
            frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame2.pack();
            frame2.setVisible(true);
        }
    }
}

In this case you might want to consider setVisible() instead if you want to go back to previous state or reopen this one when closing the second JFrame

在这种情况下,你可能想要考虑setVisible(),如果你想回到以前的状态或在关闭第二个JFrame时重新打开这个状态


Both of my above codes are called a Minimal, Complete, and Verifiable example (MCVE) or Runnable Example or Short, Self Contained, Correct Example (SSCCE) which are code you can copy-paste and see the same output as me, when you have an error in your code, these examples are very handy because we can see where your errors are or be able to find them easier and/or faster.

我上面的两个代码都被称为最小,完整和可验证的示例(MCVE)或可运行的示例或简短的,自包含的,正确的示例(SSCCE),这些代码可以复制粘贴并看到与我相同的输出,当您在您的代码中出现错误,这些示例非常方便,因为我们可以查看您的错误位置,或者能够更轻松和/或更快地找到它们。

You should consider reading all the links I provided (included these ones) and for your future questions to make something like I've done above, that way you'll prevent confusion and you'll get more, faster and better responses.

您应该考虑阅读我提供的所有链接(包括这些链接)以及您将来的问题以制作类似我上面所做的事情,这样您就可以避免混淆,并且您将获得更多,更快和更好的响应。