I'm having a hard time calling the variable from first frame
here is how should my program be. In first frame, there is a textfield1 where a user input text and when he press a button, a new frame will be display with a textfield2 that displays the inputted text from the textfield1. please help me with the syntax. i'm still a beginner in java. much thanks guys.
First Frame:
textfield= new JTextField();
textfield.setPreferredSize( new Dimension(200,30) ) ;
textfield.setSize( textfield.getPreferredSize() ) ;
textfield.setLocation(95,198) ;
textfield.setSize(175,28);
cont.add(textfield);
public void actionPerformed(ActionEvent e) {
this.setVisible(false);
new Frame2().setVisible(true); //displays the 2nd frame right?
}
now i don't know what to do on my 2nd frame or where to sta开发者_如何学Gort because i can't get the variable from the first frame
You can pass the desired variables in a constructor of Frame2
:
Frame2 frame2 = new Frame2(textfield.getText());
frame2.setVisible(true);
All you need to do is - Define new constructor for second frame with textfield2:
public Frame2(String toDisplay){
textfield2 = new JTextField(toDisplay);
}
Try this: (just copy into a new file named FrameTest.java in the default package)
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class FrameTest extends JFrame {
public static void main(String[] args) {
JFrame frame = new FrameTest();
frame.pack();
frame.setVisible(true);
}
public FrameTest() {
JPanel panel = new JPanel();
final JTextField textField = new JTextField();
textField.setPreferredSize(new Dimension(100, 20));
panel.add(textField);
JButton button = new JButton("press me");
panel.add(button);
setContentPane(panel);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
FrameTest.this.setVisible(false);
Frame2 secondFrame = new Frame2(textField.getText());
secondFrame.pack();
secondFrame.setVisible(true);
}
});
}
class Frame2 extends JFrame {
public Frame2(String text) {
getContentPane().add(new JTextField(text));
}
}
}
精彩评论