Reputation: 15
I'm trying to make it so when I press a button what ever is in my JTextArea will be printed out via the System.out.print method, but something is quite not right. Here's my code:
public static void text(){
JButton jb = new JButton("Button");
final String s;
JFrame frame = new JFrame();
t1= new JTextArea(3,10);
s=t1.getText();
ActionListener al = new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
System.out.print(s);
}
};
jb.addActionListener(al);
jp.add(jb);
jp.add(t1);
frame.add(jp);
frame.setTitle("Card");
frame.setSize(700,500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main(String [ ] args){
text();
}
Upvotes: 0
Views: 66
Reputation: 58929
When you write s=t1.getText()
, this does not mean that s
always contains the text in t1
. That means to set s
to whatever text t1
contains right now (i.e. when that line executes, which in your case is when setting up the GUI).
You probably want to get the text when the button is pressed:
@Override
public void actionPerformed(ActionEvent e) {
// System.out.print(s); <- delete this
System.out.print(t1.getText());
}
You can then also remove everything to do with s
, since it's not used.
Upvotes: 3