nedd help about JTextarea and action listener

+1 adam kido · October 11, 2014
H'm new in java programming language and i try to write a simple code 


public class TextPanel extends JPanel {
private JTextArea textArea;


public TextPanel() {

   textArea = new JTextArea();

   setLayout(new BorderLayout());
   setVisible(true);

   add(new JScrollPane(textArea), BorderLayout.CENTER);


}


public String getTextAreaText() {
   String text = textArea.getText();

   return text;

}
}

and i added an action listener to star button (startBtn) but when i run the program nothing is shown in console even if i put a System.out.println(textPanel.getTextAreaText()) in actionPerformed() method (code below).


public class Toolbar extends JPanel {
private JButton startBtn;
private JButton stopBtn;
private TextPanel textPanel;

public Toolbar() {

   startBtn = new JButton("Start");
   stopBtn = new JButton("Stop");
   textPanel = new TextPanel();

   setLayout(new FlowLayout(FlowLayout.LEFT));
   add(startBtn);
   add(stopBtn);

   startBtn.addActionListener(new ActionListener() {

       @Override
       public void actionPerformed(ActionEvent arg0) {

           System.out.println(textPanel.getTextAreaText());

       }
   });

}
}

I need help to fix this.

Post a Reply

Replies

Oldest  Newest  Rating
0 Alex Sweps · October 12, 2014
Try and change ActionEvent arg0 to ActionEvent event. 
I havent done much GUI work but when I add an action handler to a component this is how I implement it:


startBtn.addActionListener(new startButton()); //Call your inner class containing the action event handler

//This is an inner class inside your current class your working in
class startButton implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println(textPanel.getTextAreaText());
}
}


I find its much easier to organise the events and it looks neater too. 
  • 1

Java / Android Development

106,913 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator