Swing / Java: how to use getText and setText string correctly

I am trying to make the nameField input displayed in a Label called label1 after clicking Button called button1 . Now he says: "txt", and I understand why. But I do not know how I can use the string! Can someone explain to me what I'm doing wrong and how to use this line correctly?

 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); } }); } } 
+4
source share
4 answers

You set the text of the labels before pressing the button on "txt". Instead, when the button is clicked, type setText() on the shortcut and pass the text from the text box to it.

Example:

 label1.setText(nameField.getText()); 
+5
source

in the action you performed, call:

 label1.setText(nameField.getText()); 

Thus, when the button is pressed, the label will be updated to the text nameField.

+2
source

the getText method returns a string, and setText receives a string, so you can write it as label1.setText(nameField.getText()); in his listener.

+1
source

Set DocumentListener to nameField. When the field name is updated, update your label.

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

0
source

Source: https://habr.com/ru/post/1345766/


All Articles