显示一个 window 以获取用户输入

Display a window to obtain user input

我是 Java 编程新手。

我有这两个小项目。

import javax.swing.*;

public class tutorial {

    public static void main(String[] args){
        JFrame frame = new JFrame("Test");
        frame.setVisible(true);
        frame.setSize(300,300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel label = new JLabel("hello");
        JPanel panel = new JPanel();
        frame.add(panel);
        panel.add(label);

        JButton button = new JButton("Hello again");
        panel.add(button);
    }
}

还有这个:

import java.util.*;

public class Test {

    public static void main(String[] args){
        int age;
        Scanner keyboard = new Scanner(System.in);
        System.out.println("How old are you?");
        age = keyboard.nextInt();
        if (age<18) 
        {
            System.out.println("Hi youngster!");
        }
        else 
        {
            System.out.println("Hello mature!");
        }
    }

}

如何将第二个代码添加到第一个代码中,以便用户看到 window 上面写着 'How old are you' 并且他们可以输入他们的年龄。

提前致谢!

这不是一个简单的问题,因为您在一个示例中使用命令行,而在另一个示例中使用 Swing GUI。

这是一个工作示例,我在这里和那里发表了评论。 这与 java 最佳实践相去甚远,它错过了很多验证(看看当您在文本字段中输入几个字母或什么都不输入时会发生什么。

另外请忽略 setLayout(null) 和 setBounds() 语句,这只是一个不使用任何布局管理器的简单示例。

希望我的评论能帮助您发现java!

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

//You'll need to implement the ActionListener to listen to buttonclicks
public class Age implements ActionListener{

    //Declare class variables so you can use them in different functions
    JLabel label;
    JTextField textfield;

    //Don't do al your code in the static main function, instead create an instance
    public static void main(String[] args){
        new Age();
    }

    // this constructor is called when you create a new Age(); like in the main function above.
    public Age()
    {
        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300,300);
        frame.setLayout(null);

        JPanel panel = new JPanel();
        panel.setBounds(0,0,300,300);
        panel.setLayout(null);

        label = new JLabel("hello");
        label.setBounds(5,5,100,20);

        // a JTextfield allows the user to edit the text in the field.
        textfield = new JTextField();
        textfield.setBounds(5,30,100,20);

        JButton button = new JButton("Hello again");
        button.setBounds(130,30,100,20);
        // Add this instance as the actionlistener, when the button is clicked, function actionPerformed will be called.
        button.addActionListener(this);

        panel.add(label);
        panel.add(textfield);
        panel.add(button);

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

    //Required function actionPerformed for ActionListener. When the button is clicked, this function is called.
    @Override
    public void actionPerformed(ActionEvent e)
    {
        // get the text from the input.
        String text = textfield.getText();

        // parse the integer value from the string (! needs validation for wrong inputs !)
        int age = Integer.parseInt(text);
        if (age<18) 
        {
            //instead of writing out, update the text of the label.
            label.setText("Hi youngster!");
        }
        else 
        {
            label.setText("Hello mature!");
        }
    }
}

so that the user will see a window that says 'How old are you' and they can type their age.

最简单的开始方法是使用 JOptionPane。查看 Swing 教程中关于 How to Use Dialogs 的部分以获取示例和解释。

关于 Swing 的基本信息,请不要忘记查看其他 Swing 相关主题的 table 内容。

您将需要一个输入字段来获取文本,然后将 ActionListener 添加到包含按下按钮时执行的逻辑的按钮。

我修改了您的代码以实现您所描述的内容:

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

public class tutorial {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Test");
        frame.setVisible(true);
        frame.setSize(300, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel label = new JLabel("hello");
        JPanel panel = new JPanel();
        frame.add(panel);
        panel.add(label);

        final JTextField input = new JTextField(5); // The input field with a width of 5 columns
        panel.add(input);

        JButton button = new JButton("Hello again");
        panel.add(button);

        final JLabel output = new JLabel(); // A label for your output
        panel.add(output);

        button.addActionListener(new ActionListener() { // The action listener which notices when the button is pressed
            public void actionPerformed(ActionEvent e) {
                String inputText = input.getText();
                int age = Integer.parseInt(inputText);
                if (age < 18) {
                    output.setText("Hi youngster!");
                } else {
                    output.setText("Hello mature!");
                }
            }
        });
    }
}

在该示例中,我们不验证输入。所以如果输入不是 Integer Integer.parseInt 将抛出异常。组件也没有很好地排列。但是为了一开始就保持简单,应该这样做。 :)

我不确定你想要的所有东西,因为它是未定义的,但据我所知,你想要一个包含输入字段的 JFrame,你将能够在其中输入值并显示适当的答案。 我还建议您阅读教程,但如果您有任何疑问,请不要犹豫。 我希望它有点接近你想要的。

package example.tutorial;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
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 Tutorial extends JPanel {
    private static final String YOUNG_RESPONSE = "Hi youngster!";
    private static final String ADULT_RESPONSE = "Hello mature!";
    private static final String INVALID_AGE = "Invalid age!";

    private static final int MIN_AGE = 0;
    private static final int MAX_AGE = 100;

    private static JTextField ageField;
    private static JLabel res;

    private Tutorial() {
        setLayout(new BorderLayout());

        JPanel northPanel = new JPanel();
        northPanel.setLayout(new FlowLayout());
        JLabel label = new JLabel("How old are you ? ");
        northPanel.add(label);

        ageField = new JTextField(15);
        northPanel.add(ageField);
        add(northPanel, BorderLayout.NORTH);


        JPanel centerPanel = new JPanel();  
        JButton btn = new JButton("Hello again");
        btn.addActionListener(new BtnListener());
        centerPanel.add(btn);

        res = new JLabel();
        res.setVisible(false);
        centerPanel.add(res);

        add(centerPanel, BorderLayout.CENTER);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Test");
        frame.add(new Tutorial());
        frame.setVisible(true);
        frame.setSize(300, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private static class BtnListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            String content = ageField.getText();
            int age = -1;
            try{
                age = Integer.parseInt(content);
                if(isValid(age)) {
                    res.setText(age < 18 ? YOUNG_RESPONSE : ADULT_RESPONSE);
                } else {
                    res.setText(INVALID_AGE);
                }
                if(!res.isVisible())
                    res.setVisible(true);
            } catch(NumberFormatException ex) {
                res.setText("Wrong input");
            }
        }

        private boolean isValid(int age) {
            return age > MIN_AGE && age < MAX_AGE;
        }
    }
}