Java 显示窗口以获取用户输入

Java 显示窗口以获取用户输入,java,swing,frame,Java,Swing,Frame,我不熟悉用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.setDefaultCloseOp

我不熟悉用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!");
        }
    }

}
import java.util.*;
公开课考试{
公共静态void main(字符串[]args){
智力年龄;
扫描仪键盘=新扫描仪(System.in);
System.out.println(“你多大了?”);
年龄=键盘.nextInt();

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

这是一个工作示例,我已经在这里和那里进行了评论。 这不是near java的最佳实践,它错过了很多验证(只需看看在textfield中输入几个字母或什么都不输入时会发生什么)

另外,请忽略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!");
        }
    }
}
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入javax.swing.*;
//您需要实现ActionListener来监听按钮链接
公共类年龄实现ActionListener{
//声明类变量,以便在不同的函数中使用它们
JLabel标签;
JTextField-textfield;
//不要在静态主函数中执行所有代码,而是创建一个实例
公共静态void main(字符串[]args){
新时代();
}
//当您创建新的Age()时,将调用此构造函数,如上面的主函数中所示。
公众年龄()
{
JFrame=新JFrame(“测试”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
框架。设置尺寸(300300);
frame.setLayout(空);
JPanel面板=新的JPanel();
面板立根(0,0300);
panel.setLayout(空);
标签=新的JLabel(“你好”);
标签.立根(5,5100,20);
//JTextfield允许用户编辑字段中的文本。
textfield=新的JTextField();
textfield.setBounds(5,30100,20);
JButton button=新JButton(“你好”);
按钮.立根(130,30100,20);
//将此实例添加为actionlistener,当单击该按钮时,将调用actionPerformed函数。
addActionListener(这个);
面板。添加(标签);
panel.add(textfield);
面板。添加(按钮);
框架。添加(面板);
frame.setVisible(true);
}
//ActionListener的必需函数actionPerformed。单击按钮时,调用此函数。
@凌驾
已执行的公共无效操作(操作事件e)
{
//从输入中获取文本。
String text=textfield.getText();
//分析字符串中的整数值(!需要验证错误的输入!)
int age=Integer.parseInt(文本);
如果(年龄)
这样用户就会看到一个窗口,上面写着“你多大了”,他们可以输入自己的年龄

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


不要忘记查看与Swing相关的其他主题的目录,了解Swing的基本信息。

您需要一个输入字段来获取文本,然后向按钮添加一个
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!");
                }
            }
        });
    }
}
import javax.swing.*;
导入java.awt.event.*;
公开课辅导{
公共静态void main(字符串[]args){
JFrame=新JFrame(“测试”);
frame.setVisible(true);
框架。设置尺寸(300300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel标签=新的JLabel(“你好”);
JPanel面板=新的JPanel();
框架。添加(面板);
面板。添加(标签);
final JTextField input=new JTextField(5);//宽度为5列的输入字段
面板。添加(输入);
JButton button=新JButton(“你好”);
面板。添加(按钮);
final JLabel output=new JLabel();//输出的标签
面板。添加(输出);
addActionListener(new ActionListener(){//当按下按钮时会注意到的操作侦听器
已执行的公共无效操作(操作事件e){
字符串inputText=input.getText();
int age=Integer.parseInt(inputText);
if(年龄<18岁){
output.setText(“Hi youngster!”);
}否则{
setText(“你好,成熟!”);
}
}
});
}
}

在该示例中,我们不验证输入。因此,如果输入不是整数
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;
        }
    }
}
package-example.tutorial;
导入java.awt.BorderLayout;
导入java.awt.FlowLayout;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入javax.swing.JButton;
导入javax.swing.JFrame;
导入javax.swing.JLabel;
导入javax.swing.JPanel;
导入javax.swing.JTextField;
公共类教程扩展了JPanel{
私有静态最终字符串YOUNG_RESPONSE=“Hi youngster!”;
private static final String成人_RESPONSE=“你好,成熟!”;
私有静态最终字符串无效\u AGE=“无效年龄!”;
私有静态最终整数最小值=0;
私人静态最终整数最大年龄=100;
私有静态JTextField-ageField;
私有静态JLabel res;
私人辅导