【问题标题】:Java Swing - How i give value of Button(0-9) on Textfied(there are 3 textfield in a FrameJava Swing - 我如何在文本字段上给出按钮(0-9)的值(框架中有 3 个文本字段
【发布时间】:2015-04-13 19:06:09
【问题描述】:

在一个框架中,我有两个文本字段和 10 个按钮(0-9)。我想用鼠标选择的按钮值填充文本字段。 我该怎么做????

【问题讨论】:

  • 您尝试了什么,您当前使用什么代码来检测点击等...!?

标签: java swing jframe textfield


【解决方案1】:

您需要为按钮添加一个 ActionListener 以在单击按钮时更新文本字段。阅读 How to Use Buttons 上的 Swing 教程部分了解基础知识。

这是一个简单的实现,展示了如何为每个按钮重用 ActionListener:

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

public class CalculatorPanel extends JPanel
{
    private JTextField display;

    public CalculatorPanel()
    {
        Action numberAction = new AbstractAction()
        {
            @Override
            public void actionPerformed(ActionEvent e)
            {
//              display.setCaretPosition( display.getDocument().getLength() );
                display.replaceSelection(e.getActionCommand());
            }
        };

        setLayout( new BorderLayout() );

        display = new JTextField();
        display.setEditable( false );
        display.setHorizontalAlignment(JTextField.RIGHT);
        add(display, BorderLayout.NORTH);

        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout( new GridLayout(0, 5) );
        add(buttonPanel, BorderLayout.CENTER);

        for (int i = 0; i < 10; i++)
        {
            String text = String.valueOf(i);
            JButton button = new JButton( text );
            button.addActionListener( numberAction );
            button.setBorder( new LineBorder(Color.BLACK) );
            button.setPreferredSize( new Dimension(50, 50) );
            buttonPanel.add( button );

            InputMap inputMap = button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
            inputMap.put(KeyStroke.getKeyStroke(text), text);
            inputMap.put(KeyStroke.getKeyStroke("NUMPAD" + text), text);
            button.getActionMap().put(text, numberAction);
        }
    }

    private static void createAndShowUI()
    {
//      UIManager.put("Button.margin", new Insets(10, 10, 10, 10) );

        JFrame frame = new JFrame("Calculator Panel");
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.add( new CalculatorPanel() );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

上面的代码还在按钮上添加了一个Key Binding,这样用户输入的数字也将调用添加到按钮的动作。 GUI 应设计为与鼠标或键盘配合使用。

【讨论】:

    猜你喜欢
    • 2018-05-22
    • 2011-08-21
    • 2016-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多