Oracle“如何制作对话”tutorial对我没有帮助,也没有我见过的任何其他帖子,因为它们没有解决将值 传递给 showMessageDialog ..
我有一个Java Swing应用程序,如下所示:
当用户按下“获取推文”按钮时,用户将信息输入三个字段中的每一个字段,这些字段将合并到MySQL查询中。
按下按钮后,我想将行计数返回给showMessageDialog,为用户提供继续或不继续的选项。
问题:我无法弄清楚如何将ResultSet值传递给showMessageDialog。我是否需要在JOptionPane上设置动作侦听器?如果是这样,你如何管理时机?
我的showMessageDialog如下所示。如您所见,“0”的值不正确。
我的JButton和相关动作监听器的代码片段:
JButton btnFetch = new JButton("Fetch Tweets!");
btnFetch.setBackground(new Color(255, 153, 51));
btnFetch.setForeground(new Color(0, 0, 128));
btnFetch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
app.Query_Variable = queryText.getText();
app.Start_Date = startText.getText();
app.End_Date = endText.getText();
try {
app.getTweetCount();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
response = new ResponseOption(app.Tweet_Count);
/*
try {
app.runApplication();
} catch (InstantiationException | IllegalAccessException
| ClassNotFoundException | ParseException
| SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/
JOptionPane.showMessageDialog(frame, "Find your file at " + app.Printed_Filename);
}
});
我为showMessageDialog创建了一个名为“ResponseOption”的类,认为这是初始化对话框所必需的。但是,对话框显示时不包含ResultSet值...
public class ResponseOption {
int RowCount;
Object[] options = {"Yes, Please.",
"No, Thanks."};
String question = "There are " + RowCount + " Tweets. Do you want to print them?";
int n = JOptionPane.showOptionDialog(frame,
"There are " + X + " Tweets. Do you want to print them?",
"Question",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, // do not use custom icon
options, // titles of buttons
options[0]); // default button title
public ResponseOption(int Rowcount) {
this.RowCount = RowCount;
}
}
getTweetCount()代码: ---本守则没问题。
public int getTweetCount() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
// create a mysql database connection
String myDriver = "com.mysql.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost:3306/?";
Class.forName(myDriver).newInstance();
Connection conn = DriverManager.getConnection(myUrl, User, Password);
PreparedStatement setNames = conn.prepareStatement("SET NAMES 'utf8mb4'");
setNames.execute();
// fetch tweet count
String CountSQL = "SELECT count(*) "
+ "FROM test.tweet "
+ "WHERE text LIKE '%" + Query_Variable + "%' "
+ "AND created_at BETWEEN '" + Start_Date + "' AND '" + End_Date + "';";
PreparedStatement CountPS = conn.prepareStatement(CountSQL);
ResultSet CountRS = CountPS.executeQuery();
if (CountRS.next()) {
Tweet_Count = CountRS.getInt(1);
}
System.out.println("Tweet count = " + Tweet_Count);
return Tweet_Count;
}