我有一个 JScrollPane 的以下代码,上面有一个 JTextArea。 这样做的目的是创建一个查询并通过 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);
监听器“SaveQueryListener”的代码如下
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);
}
JDBC 工作正常,因为我硬编码的其他查询工作正常(基本上每个查询有 1 个按钮)。但我无法从此 TextArea 获取文本。 当我运行程序时,控制台打印:
The query is:
Conecction Successfull
org.postgresql.util.PSQLException: No result from query. //Translated
关于为什么 getText() 不返回我在 TextArea 中输入的内容有什么想法吗?
最佳答案
第二次查看代码后,这显然行不通:
this.getBtnFinishButton().addActionListener(new SaveQueryListener(display.getText(), this));
您将文本设置为首次创建文本区域时文本区域具有的任何值。显然这是一个空字符串。
可能需要这样的东西:
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);
}
以及启动 GUI 的位置:
this.getBtnFinishButton().addActionListener(new SaveQueryListener(display, this));
关于java - JTextArea.getText() 没有返回它应该返回的内容(SWING),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46530888/