Reputation: 81
I have an application creating a JPanel within a JFrame as follows:
public class Frame1{
public Frame1(){
Frame2 f2 = new Frame2();
f2.pack();
f2.setVisible(true);
}
class Frame2 extends JFrame{
public Frame2(){
JPanel p1 = new JPanel();
JTextField txt1 = new JTextField("Test",12);
p1.add(txt1);
JButton btn1 = new JButton("Click Me!");
p1.add(btn1);
add(p1);
btn1.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
JOptionPane.showDialog(null,text of the textbox);
}
}
}
Is there a way to reference the text field even though it is not a field variable and it is just declared inside the constructor (this.getRootPane().getParent()
will give me the frame I believe, but where do I go from there)?
Upvotes: 1
Views: 1643
Reputation: 117589
If you want to get a reference to a JTextField that you declared it only inside the constructor, then your only option is to get it using the main JFrame, something like this:
JTextField textField = (JTextField) ((JPanel) getContentPane().getComponents()[0]).getComponents()[0];
JOptionPane.showMessageDialog(null, textField.getText());
Or for a general solution:
private JTextField textField;
getJTextField(this); // Call this from inside the constructor
// ...
private boolean getJTextField(Container c)
{
Component[] cmps = c.getComponents();
for (Component cmp : cmps)
{
if (cmp instanceof JTextField)
{
textField = (JTextField) cmp;
return true;
}
if (cmp instanceof Container)
{
if(getJTextField((Container) cmp)) return true;
}
}
return false;
}
However, declaring the JTextField as a class filed makes you life easier.
Upvotes: 2
Reputation: 285403
Again to reiterate, why not just make your JTextField a private non-static field of the class:
import java.awt.event.*;
import javax.swing.*;
public class Frame1 {
public Frame1() {
Frame2 f2 = new Frame2();
f2.pack();
f2.setVisible(true);
}
class Frame2 extends JFrame implements ActionListener {
private JTextField txt1;
public Frame2() {
JPanel p1 = new JPanel();
// JTextField txt1 = new JTextField("Test", 12);
txt1 = new JTextField("Test", 12);
p1.add(txt1);
JButton btn1 = new JButton("Click Me!");
p1.add(btn1);
add(p1);
btn1.addActionListener(this);
}
// if outside classes need to see the text
public String getTxt1Text() {
return txt1.getText();
}
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(this, txt1.getText());
}
}
}
Upvotes: 3