[英]Java : JDBC Connection Issue When Click On Button
I'm facing a problem in this program there are two GUI's
.When user click on button it checks for a database connection when connection become successful then second GUI
appear which has JComboBox
. 我在这个程序中遇到一个问题,有两个GUI's
。当用户单击按钮时,它会在连接成功时检查数据库连接,然后出现第二个具有JComboBox
GUI
。 But the problem is it doesn't show the catalogs of mysql
in JComboBox
. 但是问题是它没有在JComboBox
显示mysql
的目录。
Main Method: 主要方法:
public class Main {
public static void main(String[] args) {
Gui obj = new Gui();
}
}
First Gui 第一桂
public class Gui extends JFrame {
Connector c = new Connector();
private JButton b1;
public Gui() {
b1 = new JButton("Click To Connect");
b1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (c.getConnect() == true) {
dispose();
new Gui2();
}
}
});
add(b1);
setLayout(new FlowLayout());
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
}
Connection Class 连接等级
public class Connector {
private Connection conn;
public boolean getConnect() {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/", "john", "root");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
if (conn == null) {
System.out.println("Connection Failed");
return false;
}
System.out.println("Connection Success");
return true;
}
}
ComboBox GUI ComboBox GUI
public class Gui2 extends JFrame {
private JComboBox box;
Connection connection;
public Gui2() {
box = new JComboBox();
opencatalog();
add(box);
setLayout(new FlowLayout());
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
private void opencatalog() {
try {
DatabaseMetaData meta = connection.getMetaData();
ResultSet rs = meta.getCatalogs();
List ct = new ArrayList();
while (rs.next()) {
ct.add(rs.getString(1));
}
rs.close();
box.setModel(new DefaultComboBoxModel(ct.toArray()));
box.setSelectedItem(connection.getCatalog());
box.setEnabled(ct.size() > 0);
}
catch (Exception e) {
System.out.println(e.toString());
}
box.setEnabled(false);
}
}
Connector
class Connector
类别 change the return
type to Connection
and return
conn
. 将return
类型更改为Connection
并return
conn
。
public Connection getConnect() {
....
return conn
}
Gui
class, change the condition Gui
课,改变条件
public void actionPerformed(ActionEvent arg0) { Connection conn= c.getConnect(); if (conn!=null) { new Gui2(conn);//pass connection object here dispose(); } }
Gui2
class, constructor should be Gui2
类,构造函数应为
public Gui2(Connection conn) { connection=conn; box = new JComboBox(); ................. }
Gui2
class, Gui2
班,
box.setEnabled(true);//should be enabled,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.