João Pedro Abubakir João Pedro Abubakir - 1 year ago 168
Java Question

JTextArea.getText() not returning what it should (SWING)

I have the following code for a JScrollPane witha a JTextArea on it.
The purpose of this is to create a query and send it to a database via JDBC

// create the middle panel components
JTextArea display = new JTextArea(16, 58);
display.setLineWrap(true);
display.setEditable(true); // set textArea editable
JScrollPane scroll = new JScrollPane (display);
scroll.setBounds(19, 21, 487, 294);
scroll.setVerticalScrollBarPolicy (ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
middlePanel.add(scroll, BorderLayout.CENTER);

//Add Textarea in to middle panel
middlePanel.add(scroll);

JFrame frame = new JFrame();
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(middlePanel);

this.setBtnFinishButton(new JButton("FINISH"));
this.getBtnFinishButton().addActionListener(new SaveQueryListener(display.getText(), this));
this.getBtnFinishButton().addFocusListener(new CreateQueryWindowFocusListener(this));
middlePanel.add(btnFinishButton, BorderLayout.SOUTH);


And the code for the listener "SaveQueryListener" is as follows

private String query;
private CreateQueryWindow cqw;

public SaveQueryListener(String query, CreateQueryWindow cqw) {
this.setQuery(query);
this.setCqw(cqw);
}

@Override
public void actionPerformed(ActionEvent e) {
System.out.println("The query is: "+query); //Use this to know what it is returning
new PostgreSQLJDBC(this.query);
}


The JDBC is working fine, as the other querys that I hard-coded are working fine (1 button for each query basically). But I can't get the text from this TextArea.
When I run the program, the console prints:

The query is:
Conecction Successfull
org.postgresql.util.PSQLException: No result from query. //Translated


Any ideas as to why the getText() is not returning what I type into the TextArea?

Answer Source

After looking at your code a second time, this obviously can't work:

this.getBtnFinishButton().addActionListener(new SaveQueryListener(display.getText(), this));

You're setting the text to be whatever value the text area has when you first create it. Obviously that's an empty string.

Something like this is probably needed:

private JTextArea view;

public SaveQueryListener(JTextArea view, CreateQueryWindow cqw) {
    this.view = view;
    this.setCqw(cqw);
}

@Override
public void actionPerformed(ActionEvent e) {
    String query = view.getText();
    System.out.println("The query is: "+query); //Use this to know what it is returning
    new PostgreSQLJDBC(this.query);
}

And where you init the GUI:

this.getBtnFinishButton().addActionListener(new SaveQueryListener(display, this));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download