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

Java Swing编程:如何在自定义窗口添加输入区域替代Eclipse控制台输入

实现窗口输入区域的解决方案

核心修改逻辑

  • 调整JFrame布局为BorderLayout,原有Canvas绘图区域放置在窗口中部
  • 窗口底部新增输入面板,包含提示标签与文本输入框,支持用户直接输入数值
  • 为输入框绑定回车触发事件,自动读取输入内容完成方程运算,错误输入做异常捕获
  • 新增结果存储变量,在渲染周期内将计算结果绘制到界面展示

完整修改后代码

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;

public class Main extends Canvas implements Runnable{
    public static JFrame frame;
    private Thread thread;
    private boolean isRunning = true;
    private final int WIDTH = 160;
    private final int HEIGHT = 120;
    private final int SCALE = 4;
    
    private BufferedImage image;
    // 新增输入框与结果存储变量
    private JTextField inputField;
    private String calculateResult = "请在底部输入高度值,按回车提交计算";
    
    public Main() {
        setPreferredSize(new Dimension(WIDTH*SCALE,HEIGHT*SCALE));
        initFrame();
        image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
    }
    
    public void initFrame() {
        frame = new JFrame("自由落体时间计算(物理)");
        // 设置布局为BorderLayout
        frame.setLayout(new BorderLayout());
        // 原有Canvas放在中部
        frame.add(this, BorderLayout.CENTER);
        
        // 底部输入区域
        JPanel inputPanel = new JPanel(new BorderLayout());
        inputPanel.add(new JLabel("输入高度(单位:米):"), BorderLayout.WEST);
        inputField = new JTextField();
        inputPanel.add(inputField, BorderLayout.CENTER);
        frame.add(inputPanel, BorderLayout.SOUTH);
        
        frame.setResizable(false);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        
        // 绑定输入框回车事件
        inputField.addActionListener(e -> {
            String inputContent = inputField.getText().trim();
            try {
                double height = Double.parseDouble(inputContent);
                double g = 9.8;
                // 自由落体时间计算 t = √(2h/g)
                double time = Math.sqrt(2 * height / g);
                calculateResult = String.format("计算结果:下落时间为 %.2f 秒", time);
            } catch (NumberFormatException ex) {
                calculateResult = "输入错误,请输入合法的数字";
            }
            // 清空输入框
            inputField.setText("");
        });
    }
    
    public synchronized void start() {
        thread = new Thread(this);
        isRunning = true;
        thread.start();
    }
    
    public synchronized void stop() {
        
    }
    
    public static void main(String[] args) {
        // 移除原有Scanner控制台输入逻辑
        Main main = new Main();
        main.start();
    }
    
    public void tick() {
        
    }
    
    public void render() {
        BufferStrategy bs = getBufferStrategy();
        if(bs==null) {
            createBufferStrategy(3);
            return;
        }
        Graphics g = image.getGraphics();
        // 绘制背景
        g.setColor(new Color(19,19,19));
        g.fillRect(0,0,WIDTH,HEIGHT);
        g = bs.getDrawGraphics();
        g.drawImage(image,0,0,WIDTH*SCALE,HEIGHT*SCALE,null);
        // 绘制文本信息
        g.setFont(new Font("Arial",Font.PLAIN,20));
        g.setColor(Color.green);
        g.drawString("计算结果展示区:", 5,20);
        g.drawString(calculateResult, 5, 50);
        bs.show();
    }
    
    public void run() {
        long lastTime  = System.nanoTime();
        double amountOfTicks = 60.0;
        double ns = 1000000000 / amountOfTicks;
        double delta = 0;
        int frames = 0;
        double timer = System.currentTimeMillis();
        while(isRunning) {
            long now = System.nanoTime();
            delta+= (now-lastTime) / ns;
            lastTime = now;
            if(delta >= 1) {
                tick();
                render();
                frames++;
                delta--;
            }
            
            if(System.currentTimeMillis() - timer >= 1000) {
                System.out.println("FPS: "+frames);
                frames = 0;
                timer+=1000;
            }
        }
    }
}

效果说明

运行程序后窗口底部会出现输入框,输入高度数值后按回车即可自动计算自由落体时间,计算结果会展示在画布上方。如果输入非数字内容会提示输入错误,无需再通过控制台输入参数。

内容的提问来源于stack exchange,提问作者Daniel Brossmann Muller

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 22:15:04