如何为按钮添加动作? [英] How to add action to a button?

查看:123
本文介绍了如何为按钮添加动作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试为 JButon 输入事件,我创建:

  JButton botton1 = new JButton(欢迎来到我的表演数据库!让我们开始吧); 
botton1.setFont(新字体( 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){

现在我要输入我创建的另一个 JFrame ,并使第一个消失。怎么样?

解决方案

对于您的原始问题:


如何向按钮添加操作?


您可能要检查

 导入java.awt。*; 
import java.awt.event。*;
import javax.swing。*;

类CardLayoutDemo {
JButton button1,button2;

CardLayoutDemo(){
JFrame gui = new JFrame( CardLayoutDemo);
button1 = new JButton(转到窗格2);
button2 = new JButton(转到窗格1);
JPanel窗格1 =新的JPanel();
pane1.setLayout(new BoxLayout(pane1,BoxLayout.PAGE_AXIS));
JPanel窗格2 =新的JPanel();
pane2.setLayout(new BoxLayout(pane2,BoxLayout.PAGE_AXIS));
final CardLayout cl = new CardLayout();
张最终的JPanel卡=新的JPanel(cl);

pane1.add(new JLabel(这是我的窗格1));
pane1.add(button1);

pane2.add(new JLabel(这是我的窗格2));
pane2.add(button2);

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

ActionListener al = new ActionListener(){
public void actionPerformed(ActionEvent ae){
if(ae.getSource()== button1){
cl。显示(卡片, frame2);
}否则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();
}
}

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



一个这里的提示是:如果您要打开第二个 JFrame 以防止用户在第一天做某事,则应考虑使用

  import java.awt。*; 
import javax.swing。*;
import java.awt.event。*;
公共类TwoJFrames {
JFrame框架;
JButton按钮;

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标签;
AnotherFrame(){
frame2 = new JFrame( Second Frame);
label = new JLabel(这是我的第二帧);

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

在这种情况下,您可能想要考虑 setVisible() 相反,如果您想返回上一个状态或在关闭第二个 JFrame 时重新打开该状态,






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



您应该考虑阅读我提供的所有链接(包括这些链接)以及您的f提出问题以做出像我在上文中所做的那样,那样您就可以避免混淆,并且可以得到更多,更快和更好的答复。


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

    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?

解决方案

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?

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.

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!

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.

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).


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:

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


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.

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.

这篇关于如何为按钮添加动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆