Swing/Java: How to use the getText and setText string properly

吃可爱长大的小学妹 提交于 2020-01-21 07:01:30

问题


I'm trying to make input nameField appear in a Label called label1 after a Button called button1 is clicked. Right now it says: 'txt' and I understand why. But I don't know how I can use the string! Can anyone explain me what I'm doing wrong and how to use this string properly?

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

public class thisismytest2 {
    public static void main(String[] args) {

        final JFrame frame = new JFrame();  
        JPanel panel = new JPanel();    
        JTextField nameField = new JTextField("...", 2);    
        JButton button1 = new JButton();
        final JLabel label1 = new JLabel();
        label1.setText("txt");
        label1.setVisible(false);
        String txt = nameField.getText();

        frame.add(panel);
        panel.add(button1);
        panel.add(label1);
        frame.setSize(200,200);
        frame.setVisible(true);
        panel.add(nameField);
        frame.setSize(600,400); 
        nameField.setBounds(400, 40, 400, 30);

        button1.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {

                label1.setVisible(true);
            }
        });
        }
        }

回答1:


You are setting the label text before the button is clicked to "txt". Instead when the button is clicked call setText() on the label and pass it the text from the text field.

Example:

label1.setText(nameField.getText()); 



回答2:


in your action performed method, call:

label1.setText(nameField.getText());

This way, when the button is clicked, label will be updated to the nameField text.




回答3:


the getText method returns a String, while the setText receives a String, so you can write it like label1.setText(nameField.getText()); in your listener.




回答4:


Setup a DocumentListener on nameField. When nameField is updated, update your label.

http://download.oracle.com/javase/1.5.0/docs/api/javax/swing/JTextField.html



来源:https://stackoverflow.com/questions/5477241/swing-java-how-to-use-the-gettext-and-settext-string-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!