如何通过代码编辑awt文本字段

时间:2014-11-05 13:51:50

标签: java textbox awt

我无法找到如何更改AWT文本框中的文字。我已经尝试过了:

textBox1.setText("text");
textBox1.validate();

textBox1.setText("text");
textBox1.repaint();

它们都不起作用。这可能是什么问题?

1 个答案:

答案 0 :(得分:1)

查看此示例我如何将文本设置为文本字段

import java.awt.*;
import java.awt.event.*;

public class AwtControlDemo {

    private Frame mainFrame;
    private Label headerLabel;
    private Label statusLabel;
    private Panel controlPanel;

    public AwtControlDemo(){
        prepareGUI();
    }

    public static void main(String[] args){
        AwtControlDemo  awtControlDemo = new AwtControlDemo();
        awtControlDemo.showTextFieldDemo();
    }

    private void prepareGUI(){
        mainFrame = new Frame("Java AWT Examples");
        mainFrame.setSize(400,400);
        mainFrame.setLayout(new GridLayout(3, 1));
        mainFrame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent windowEvent){
                System.exit(0);
            }        
        });    
        headerLabel = new Label();
        headerLabel.setAlignment(Label.CENTER);
        statusLabel = new Label();        
        statusLabel.setAlignment(Label.CENTER);
        statusLabel.setSize(350,100);

        controlPanel = new Panel();
        controlPanel.setLayout(new FlowLayout());

        mainFrame.add(headerLabel);
        mainFrame.add(controlPanel);
        mainFrame.add(statusLabel);
        mainFrame.setVisible(true);  
    }

    private void showTextFieldDemo(){
        headerLabel.setText("Control in action: TextField"); 

        Label  namelabel= new Label("User ID: ", Label.CENTER);
        final TextField userText = new TextField(16);
        userText.setText("name");
        Button displayButton = new Button("Display");
        displayButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {     
                String data = "Username: " + userText.getText();
                statusLabel.setText(data);        
            }
        }); 

        controlPanel.add(namelabel);
        controlPanel.add(userText);
        controlPanel.add(displayButton);
        mainFrame.setVisible(true);  
    }
}