在按钮上添加新标签和文本字段单击 Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30688184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 10:00:10  来源:igfitidea点击:

Add new label and textfield on button click Java

javaswingjbuttonactionlistenerjlabel

提问by Tyrion

I have this code with three buttons. I want to add a label and a textfield after a buttonclick. So for the 'button' I want to add the 'label' and 'textfield.

我有这个带有三个按钮的代码。我想在单击按钮后添加标签和文本字段。所以对于“按钮”,我想添加“标签”和“文本字段”。

For 'button2' I want to add 'label2' and 'textfield2'. And so on.

对于“button2”,我想添加“label2”和“textfield2”。等等。

I already have this code, but it isn't working. I also don't understand how I can create three different ActionListeners.

我已经有了这个代码,但它不起作用。我也不明白如何创建三个不同的 ActionListeners。

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

public class Interface implements ActionListener{

    private JLabel label;
    private JLabel label2;
    private JLabel label3;
    private JTextField textfield;
    private JTextField textfield2;
    private JTextField textfield3;
    private JButton button;
    private JButton button2;
    private JButton button3;
    private JPanel panel;

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

    public Interface()
    {
        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600,600);
        frame.setLayout(null);

        JPanel panel = new JPanel();
        panel.setBounds(10,10,600,600);
        panel.setLayout(null);

        label = new JLabel("Button 1");
        label.setBounds(5,5,600,20);

        label2 = new JLabel("Button 2");
        label2.setBounds(5,5,600,20);

        label3 = new JLabel("Button 3");
        label3.setBounds(5,5,600,20);

        textfield = new JTextField();
        textfield.setBounds(5,30,100,20);

        JButton button = new JButton("cirkel");
        button.setBounds(130,30,100,20);
        button.addActionListener(this);

        JButton button2 = new JButton("driehoek");
        button2.setBounds(250,30,100,20);
        button2.addActionListener(this);

        JButton button3 = new JButton("vierhoek");
        button3.setBounds(370,30,100,20);
        button3.addActionListener(this);

        panel.add(button);
        panel.add(button2);
        panel.add(button3);

        frame.add(panel);
        frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent arg0)
    {
            panel.add(label);
            panel.add(textfield);
            panel.validate();
            panel.repaint();
            String text = textfield.getText();

            // Van de String 'text' een double maken
            double diameter = Double.parseDouble(text);

            cirkel C1 = new cirkel();
            C1.setDiam(diameter);
            label.setText("De diameter = " + C1.getDiam() + " cm \n\n");
            label.setText("De straal = " + C1.getRadius() + " cm");
            label.setText("De oppervlakte van de cirkel = " + C1.berekenOpp() + " cm2");

    }
}

采纳答案by MadProgrammer

You have a few choices:

你有几个选择:

You could...

你可以...

Create a ActionListenerfor each button, this can be done using a outer, inner or anonymous class, this means that you provide a self contained unit of work for each button which is related to only that button.

ActionListener为每个按钮创建一个,这可以使用外部、内部或匿名类来完成,这意味着您为每个只与该按钮相关的按钮提供一个独立的工作单元。

You could also take advantage of the ActionAPI for the same reasons. See How to Use Actionsfor more details

Action出于同样的原因,您也可以利用API。有关更多详细信息,请参阅如何使用操作

You could...

你可以...

Check the ActionEvent#getSourceproperty and compare it to an instance of the button, but your buttons are defined locally

检查ActionEvent#getSource属性并将其与按钮的实例进行比较,但您的按钮是在本地定义的

You could...

你可以...

Use the actionCommandproperty of the buttons, setting each button a unique "command" which you can use the ActionEvent#getActionCommandto compare with when the ActionListeneris triggered

使用actionCommand按钮的属性,为每个按钮设置一个唯一的“命令”,您可以使用它ActionEvent#getActionCommand来比较ActionListener触发时间

Regardless of which choice you use, have a closer look at How to Write an Action Listenersand How to Use Buttons, Check Boxes, and Radio Buttonsfor more details

无论您使用哪种选择,请仔细查看 如何编写动作侦听器如何使用按钮、复选框和单选按钮以获取更多详细信息

Example

例子

Now, having had a chance to run your code, you have a NullPointerExceptionbecause panelis nullin the context of the ActionListener. This is cased by the fact that you are shadowing the variable (declaring it twice)

现在,已经有机会来运行你的代码,你有一个NullPointerException,因为panelnull在的情况下ActionListener。这是因为您正在隐藏变量(声明两次)

// Declared here
private JPanel panel;

public Interface() {
    JFrame frame = new JFrame("Test");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(600, 600);
    frame.setLayout(null);

    // And here...
    JPanel panel = new JPanel();

So, instead, you could use a anonymous class for each button...

因此,您可以为每个按钮使用一个匿名类......

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Interface {

    private JLabel label;
    private JLabel label2;
    private JLabel label3;
    private JTextField textfield;
    private JTextField textfield2;
    private JTextField textfield3;
    private JButton button;
    private JButton button2;
    private JButton button3;
    private JPanel panel;

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

    public Interface() {
        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 600);

        JPanel buttonPane = new JPanel();
        label = new JLabel("Button 1");
        label2 = new JLabel("Button 2");
        label3 = new JLabel("Button 3");

        textfield = new JTextField(5);

        JButton button = new JButton("cirkel");
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                panel.removeAll();
                panel.add(label);
                panel.add(textfield);
                panel.revalidate();
                panel.repaint();
                String text = textfield.getText();

                // Van de String 'text' een double maken
                double diameter = Double.parseDouble(text);

//      cirkel C1 = new cirkel();
//      C1.setDiam(diameter);
                label.setText("De diameter = " + 1 + " cm \n\n");
                label.setText("De straal = " + 2 + " cm");
                label.setText("De oppervlakte van de cirkel = " + 3 + " cm2");
            }
        });

        JButton button2 = new JButton("driehoek");
        button2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                panel.removeAll();
                panel.add(label);
                panel.add(textfield);
                panel.revalidate();
                panel.repaint();
                // driehoek
            }
        });

        JButton button3 = new JButton("vierhoek");
        button3.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                panel.removeAll();
                panel.add(label);
                panel.add(textfield);
                panel.revalidate();
                panel.repaint();
                // vierhoek
            }
        });

        buttonPane.add(button);
        buttonPane.add(button2);
        buttonPane.add(button3);

        panel = new JPanel();

        frame.add(buttonPane, BorderLayout.NORTH);
        frame.add(panel);
        frame.setVisible(true);
    }
}

The next problem you'll have is a NumberFormatException, because you you're trying to convert a blank Stringto a double, because there is nothing in the text field yet...

您将遇到的下一个问题是 a NumberFormatException,因为您正在尝试将空白转换String为 a double,因为文本字段中还没有任何内容......

回答by Kasper Due

If you want to create three different ActionListeners, you can create three inner classes, and implement an ActionListener to each class. and put the instance of the class inside the addActionListener().

如果要创建三个不同的ActionListener,可以创建三个内部类,并为每个类实现一个ActionListener。并将类的实例放在addActionListener().

public class Example {

    ActionListen listen = new ActionListen();

    button.addActionListener(listen);

    private class ActionListen implements ActionListener {

        public void actionPerformed(ActionEvent e) {
            //code here to change...
        }
    }
}