【发布时间】:2014-03-14 13:30:02
【问题描述】:
我有三个 Java 类:
- First 有一个 setter 和一个 getter
- 第二个有一个 JComboBox
- 第三个有一个 MySQL 查询和生成列表。
我使用 setter 来设置值,并从组合框类中设置值。
现在,我想在另一个类中获取这个值。
这是我的代码:
public class Settings {
private static String RootName;
public static void setRootName(String rootName){
RootName = rootName;
}
public static String getRootName(){
return RootName;
}
}
combobox.java
public class ComboBoxDemo extends JPanel
implements ActionListener {
String connectionURL = "jdbc:mysql://localhost:3306/Trainpis";
JLabel picture;
public static String i="hello";
public String rootname;
public ComboBoxDemo() {
JComboBox combo=new JComboBox();
combo.addActionListener(this);
JFrame f=new JFrame();
JPanel p=new JPanel();
try{
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection conn = DriverManager.getConnection(connectionURL, "root", "");
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("Select route from route");
while(rs.next()){
combo.addItem(rs.getString("route"));
//System.out.println(rs.getString("route"));
}
}
catch(Exception e){}
p.add(combo);
f.add(p);
f.setExtendedState(JFrame.MAXIMIZED_BOTH);
f.setUndecorated(true);
f.setVisible(true);
}
/** Listens to the combo box. */
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
String selectedRoute = (String)cb.getSelectedItem();
// System.out.println(rootname);
String root1="Huda City Center - Noida City Center";
if(selectedRoute.equalsIgnoreCase(root1))
{
System.out.println("hello");
//new Test();
//Settings mysettings = new Settings();
Settings.setRootName(selectedRoute);
RootSelection1 r1 = new RootSelection1();
r1.print();
}
else{
System.out.println("bye");
}
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ComboBoxDemo();
}
});
}
}
现在我想使用组合框的选定值:
String rootSelection = Settings.getRootName();
String selectStoredProc = "SELECT sino,stationname,distance from station where route ='"+rootSelection+"'";
String [] root;
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(connectionURL, "root", "");
PreparedStatement ps = conn.prepareStatement(selectStoredProc);
ResultSet rs=ps.executeQuery();
while(rs.next()){
String s1=rs.getString("stationname");
nameList.add(s1);
root = nameList.toArray(new String[nameList.size()]);
}
}
catch(Exception e){}
我想对组合框的选定项执行所有这些操作。
我怎样才能做到这一点?
【问题讨论】:
-
请问应该做什么,目标是什么
-
它应该将值组合框选定项传递给第三类
-
只是一个提示,我会小心
"SELECT sino,stationname,distance from station where route ='"+rootSelection+"'";这可能对安全性(注入)很危险。 -
你能提供你创建组合框和东西的来源吗?因为(除了在好的代码方面它非常可怕之外)你在那里做的那些静态的东西剪断了这个值将在第三个剪断时可用......例如您已经按照 String rootSelection = Settings.getRootName(); 的要求完成了您的要求这让我猜你只是没有从你的查询中得到任何东西? ;)