简体   繁体   中英

JTextArea string won't print to my console?

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();
}

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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM