You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java Frame中按下按钮时获取用户输入?

在Java AWT Frame中点击按钮获取用户输入的实现方案

我来帮你搞定这个需求!在AWT Frame里实现点击按钮获取用户输入,核心就是先把输入组件(比如TextField)加到界面上,然后在按钮的事件处理方法里读取这些组件的内容。咱们结合你给出的代码,一步步调整完善:

关键步骤说明

  • 添加输入界面元素:你已经声明了TextField和Label变量,但还没初始化和添加到窗口里,得先把这些输入框和对应的提示标签加到界面,让用户有地方输入信息。
  • 修正SQL语法错误:原代码里创建学生表的SQL有语法问题(比如字段定义错误、重复字段名),得先改对才能正常创建表。
  • 实现按钮的输入获取逻辑:在actionPerformed方法里,针对不同按钮的点击事件,调用TextField.getText()来获取用户输入的内容,之后就能用这些内容执行JDBC的增改查操作了。
  • 完善窗口关闭功能:原代码里引用了mywindow类但没实现,得补上这个监听器让窗口能正常关闭退出程序。

修改后的完整代码

package jdbcapp5;

import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

class myframe extends Frame implements ActionListener {
    TextField tx1, tx2, tx3;
    Label l1, lRollno, lName, lCourse;
    Button b1, b2, b3;
    Connection con;

    myframe() {
        try {
            // 窗口基础设置
            this.setVisible(true);
            this.setSize(400, 400);
            this.setTitle("JDBC Small Project");
            this.setLayout(new FlowLayout());
            this.setBackground(Color.green);

            // 初始化JDBC连接和创建表(修正SQL语句)
            Class.forName("oracle.jdbc.driver.OracleDriver");
            con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "system");
            Statement st = con.createStatement();
            // 修正表字段的语法错误,定义正确的字段类型
            String q1 = "create table student(rollno number, name varchar2(30), course varchar2(20))";
            int x = st.executeUpdate(q1);
            System.out.println("Table created successfully, affected rows: " + x);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 初始化界面组件
        l1 = new Label("Admission Management System");
        lRollno = new Label("Roll No:");
        lName = new Label("Name:");
        lCourse = new Label("Course:");
        
        tx1 = new TextField(15); // 学号输入框
        tx2 = new TextField(15); // 姓名输入框
        tx3 = new TextField(15); // 课程输入框
        
        b1 = new Button("Add");
        b2 = new Button("Update");
        b3 = new Button("Search");

        // 绑定按钮事件监听器
        b1.addActionListener(this);
        b2.addActionListener(this);
        b3.addActionListener(this);

        // 将组件添加到窗口
        this.add(l1);
        this.add(lRollno);
        this.add(tx1);
        this.add(lName);
        this.add(tx2);
        this.add(lCourse);
        this.add(tx3);
        this.add(b1);
        this.add(b2);
        this.add(b3);

        // 添加窗口关闭监听器
        this.addWindowListener(new mywindow());
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String label = e.getActionCommand();
        try {
            // 获取用户输入的内容,trim()去除前后无效空格
            String rollno = tx1.getText().trim();
            String name = tx2.getText().trim();
            String course = tx3.getText().trim();

            if (label.equals("Add")) {
                // 执行添加操作,用输入内容构造INSERT语句
                System.out.println("Adding student - Roll No: " + rollno + ", Name: " + name + ", Course: " + course);
                Statement st = con.createStatement();
                String insertSql = "insert into student values(" + rollno + ", '" + name + "', '" + course + "')";
                int rows = st.executeUpdate(insertSql);
                System.out.println(rows + " record added");
            }
            if (label.equals("Update")) {
                // 执行更新操作,示例:根据学号更新课程
                System.out.println("Updating student - Roll No: " + rollno + ", New Course: " + course);
                Statement st = con.createStatement();
                String updateSql = "update student set course = '" + course + "' where rollno = " + rollno;
                int rows = st.executeUpdate(updateSql);
                System.out.println(rows + " record updated");
            }
            if (label.equals("Search")) {
                // 执行查询操作,示例:根据学号查询
                System.out.println("Searching student with Roll No: " + rollno);
                Statement st = con.createStatement();
                String searchSql = "select * from student where rollno = " + rollno;
                ResultSet rs = st.executeQuery(searchSql);
                while (rs.next()) {
                    System.out.println("Roll No: " + rs.getInt("rollno") + ", Name: " + rs.getString("name") + ", Course: " + rs.getString("course"));
                }
            }
        } catch (Exception ee) {
            ee.printStackTrace();
        }
    }
}

// 实现窗口关闭监听器,让窗口能正常关闭
class mywindow implements WindowListener {
    @Override
    public void windowOpened(WindowEvent e) {}

    @Override
    public void windowClosing(WindowEvent e) {
        // 关闭窗口时退出程序
        System.exit(0);
    }

    @Override
    public void windowClosed(WindowEvent e) {}

    @Override
    public void windowIconified(WindowEvent e) {}

    @Override
    public void windowDeiconified(WindowEvent e) {}

    @Override
    public void windowActivated(WindowEvent e) {}

    @Override
    public void windowDeactivated(WindowEvent e) {}
}

// 主类,启动程序
public class Main {
    public static void main(String[] args) {
        new myframe();
    }
}

核心代码解释

  1. 获取输入:在actionPerformed方法里,通过tx1.getText()获取输入框的内容,用trim()去除前后空格避免无效输入。
  2. 按钮事件处理:根据按钮的actionCommand(也就是按钮上的文字)判断用户点击的是哪个按钮,然后执行对应的JDBC操作,比如添加时构造INSERT语句,查询时执行SELECT语句。
  3. 窗口关闭:实现WindowListener接口的windowClosing方法,调用System.exit(0)让程序正常退出。

内容的提问来源于stack exchange,提问作者Sitanshu Tripathi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:26:54