1

I have a JFrame containing three JPanel. The first JPanel contains a JTextField and a JButton. Once the JButton pressed, a JLabel at the second JPanel can show the text input from the JTextField. And then, the third JPanel will change its background according to the JLabel at the second JPanel.

My question is: How to access the content of JTextField at the first JPanel and then transfer it to the other two JPanel?

jalopaba
  • 8,039
  • 2
  • 44
  • 57
sluk
  • 13
  • 2

4 Answers4

3

you can create

please carrefully read all comments by @Hovercraft Full Of Eels to both options

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
1

So you have three panels:

JPanel panel1;
JTextField textFieldOnFirstPanel;
JButton buttonOnFirstPanel;
JLabel labelOnSecondPanel;
JPanel panel2;
JPanel panel3;

Keep a reference to all these three panels and all the components in you main object, this could be your JFrame Object itself. Based on the events, update these components accordingly.

NiranjanBhat
  • 1,812
  • 13
  • 17
0

You will first store the data from the first text field in a variable. You could do this in the actionPerformed method when the button is pressed.

Following this you use the setText function to change your JLabel's text.

And last you change the JPanel color by calling its setBackground method.

String text = textField.getText();
label.setText(text);
myJPanel.setBackground(Color.white);
Dennis
  • 3,962
  • 7
  • 26
  • 44
0

I think that the most clean way to achieev your goal is to access the getter of the field text after receiving notifications from changes as enabled by the classical Observer/Observable pattern. You may have here for details about this pattern . http://en.wikipedia.org/wiki/Observer_pattern My 2 pieces Jerome

romje
  • 650
  • 3
  • 4