【问题标题】:Java read input from JButtonJava 从 JButton 读取输入
【发布时间】:2021-08-23 04:26:33
【问题描述】:

我必须实现一种基于用户键盘输入更新 jbutton 文本的方法, 假设我有这个 gui

当用户单击其中一个按钮时,他必须能够通过在键盘上键入来更改其上的数字,交互必须是直接的,因此无需文本字段或在控制台中键入。

我想使用 Reader 类,但实际上我不明白该怎么做...... 在线搜索我发现只有通过控制台/JTextField 来做这件事的方法不是我需要的。我认为这将是一个伪实现:


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

public class Gui extends JFrame implements ActionListener {

    JButton btn;
    
    public static void main( String[] args ) {
        new Gui();
    }
    
    public Gui() {
        this.getContentPane().setLayout(new FlowLayout());;
        this.setTitle("Title");
        
        JButton btn = new JButton("3");
        this.getContentPane().add(btn);
        btn.addActionListener(this);
        btn.setActionCommand("listenForInput");
        btn.setSize(30, 30);s
        
        this.pack();
        this.setSize(100, 100);
        this.setVisible(true);
    }


    @Override
    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();
        if( cmd.equals("listenForInput")) {
            /* ClassThatExtendsReader reader = new ClassThatExtendsReader();
            String oldText = btn.getText();
            boolean notPressedEnter = ture;
            String newNum = "";
            while( notPressedEnter ) {
                String char = reader.nextLine();
                if( char == Enter )  notPressedEnter = false;
                newNum = newNum + char;
                btn.setText(newNum);
            }
            if( newNum is not integer ) {
                showMessage("wrong input");
                btn.setText(oldText);
            } 
            */
        } 
    }

}


所以:

  1. 用里面的按钮初始化 JFrame
  2. 为按钮添加监听器以检测何时被点击
  3. 点击时读取按下的字符
  4. 每次输入字符时都会更新按钮文本
  5. 当按下 ENTER 时停止循环
    • 我认为侦听器内部的循环应该在Runnable 类中,以便将其放入Thread

【问题讨论】:

  • 这能回答你的问题吗? How to detect a key press in Java
  • 不需要任何类型的循环或线程。您可以通过两次按下按钮来更改程序的状态。第一次按下激活 KeyListener 并确保被监听的组件具有焦点,第二次按下de-activates KeyListener。或者通过专门侦听 enter 键来停用 KeyListener(如果在 JTextField 中侦听,则使用 ActionListener)。

标签: java swing jbutton


【解决方案1】:

C,我找不到任何使用 Reader 的方法,但我扩展了普通的 JButtons 以添加该功能

这里是代码


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

public class ChangeButtonText {
    static class SuperButton extends JButton {
        public SuperButton(String text) {
            super(text);
            // make this button focusable so that it can register keys
            setFocusable(true);
            // add a key listener(actually KeyAdapter, as we don't need all the methods)
            addKeyListener(new KeyAdapter() {
                @Override
                public void keyPressed(KeyEvent e) {
                    // get the key code from the key event
                    int keyCode = e.getKeyCode();
                    // now run a check to see if it is a number, if it is not, then there is no use
                    // in an ideal world we would use unary operators here
                    // but let's just use comparators for now
                    // 47 : key code for 0
                    // 57 : key code for 9
                    if (!(keyCode >= KeyEvent.VK_0 && keyCode <= KeyEvent.VK_9)) return;
                    // well, now we know that the keyCode is a number
                    // and so now we will set it as the text
                    char number = (char) keyCode;
                    setText(Character.toString(number));
                }
            });
        }
    }

    public static void main(String[] args) {
        // test
        JFrame frame = new JFrame("Change Button Text");
        frame.setSize(720, 480);
        frame.setVisible(true);
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(1, 0));
        // let's create a few Super Buttons!
        SuperButton jack = new SuperButton("0");
        SuperButton superPotatoMan = new SuperButton("1");
        SuperButton sushiEater1001 = new SuperButton("7");
        // set some interesting colors
        jack.setBackground(Color.RED);
        jack.setOpaque(true);
        superPotatoMan.setBackground(Color.GREEN);
        superPotatoMan.setOpaque(true);
        sushiEater1001.setBackground(Color.WHITE);
        sushiEater1001.setOpaque(true);
        // add them to the JPanel we created
        panel.add(jack);
        panel.add(superPotatoMan);
        panel.add(sushiEater1001);
        frame.add(panel, BorderLayout.CENTER);
    }

}

我在video 中展示了这个程序的输出 请观看此视频

希望这对您有所帮助:)

【讨论】:

  • 好方法,只是尽量不要使用setLayout(null) 并手动设置 JPanel 的边界。 Swing 设计用于布局,从不手动添加尺寸。您可以使用 JFrame 内容窗格的默认 BorderLayout 并将 JButton 的 Panel 添加到它的中心。
  • 谢谢@hexstorm,我编辑了我的代码以匹配你所说的
  • (1+) 编辑键入的值的好主意。默认情况下,接受用户输入的 Swing 组件是可聚焦的。无需扩展 JButton,您只需为 KeyListner 创建一个类并为所有按钮共享相同的 KeyListener。
【解决方案2】:

您应该添加KeyListener,而不是向 JButton 添加 ActionListener

组件的 KeyListener 仅在该组件具有焦点时(在 JButton 中,当它被按下时)检测到某个键已被按下。


两个 JButton 的简单示例如下:

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

public class Gui extends JFrame implements KeyListener {

    private JButton firstBtn, secondBtn;

    public static void main(String[] args) {
        //All the interaction with Swing should be performed on the EDT
        SwingUtilities.invokeLater(() -> new Gui());
    }

    public Gui() {
        setLayout(new FlowLayout());;
        setTitle("Gui");

        firstBtn = new JButton("1");
        firstBtn.addKeyListener(this);

        secondBtn = new JButton("2");
        secondBtn.addKeyListener(this);

        add(firstBtn);
        add(secondBtn);

        setLocationRelativeTo(null); //Center the JFrame on the Screen
        setSize(400, 100);
        setVisible(true); //Make the JFrame Visible
    }


    @Override
    public void keyPressed(KeyEvent e) {
        if(e.getSource() instanceof JButton){
            JButton buttonFocused = ((JButton)e.getSource());
            buttonFocused.setText(buttonFocused.getText() + e.getKeyChar());
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {}

    @Override
    public void keyReleased(KeyEvent e) {}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-29
    • 1970-01-01
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多