我想在按下按钮时在文本框中显示一个数字

时间:2014-03-18 22:46:34

标签: java swing netbeans

我想在按钮属性字段中使用text属性。这是我尝试的代码,但它不起作用。

private void btnOneActionPerformed(java.awt.event.ActionEvent evt) { 
      String btnOneText = btnOne.getText( );
      txtDisplay.setText(btnOneText);
} 

1 个答案:

答案 0 :(得分:1)

我建议你阅读有很好例子的oracle官方教程。 How to use Buttons

我为你做了一个你必须做的事情的例子。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class TextFieldTest {

    private JPanel panel;

    public TextFieldTest(){
        panel = new JPanel();
        final JTextField textfield = new JTextField(10);
        final JButton button = new JButton("Press me");
        //here i add the action listener, that will listen the input event
        button.addActionListener(new ActionListener(){
            //this is anonymous class
            @Override
            public void actionPerformed(ActionEvent evt){
                String text = button.getText();
                textfield.setText(text);
            }
        });

        panel.add(textfield);
        panel.add(button);

    }

     /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("Textfield example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        frame.setLocationByPlatform(Boolean.TRUE);
        frame.add(new TextFieldTest().panel);

        //Display the window.
        frame.pack();
        frame.setVisible(Boolean.TRUE);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }


}

看到它比使用gui-editor更简单,那么你就能理解你的所作所为。最好先做这个,然后当你理解你在做什么时使用netbeans gui-editor。