gpt4 book ai didi

Java : JDBC Connection Issue When Click On Button

转载 作者:行者123 更新时间:2023-11-28 23:50:27 26 4
gpt4 key购买 nike

我在这个程序中遇到了一个问题,有两个 GUI。当用户单击按钮时,它检查数据库连接,当连接成功时,第二个 GUI 出现其中有 JComboBox。但是问题是在JComboBox中没有显示mysql的目录。
主要方法:

public class Main {

public static void main(String[] args) {


Gui obj = new 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);

}

}

连接类

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;

}

}

组合框界面

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);

}

}

最佳答案

  1. 连接器

return 类型更改为 Connectionreturn conn

public Connection getConnect() {

....
return conn
}
  1. Gui类,改变条件

     public void actionPerformed(ActionEvent arg0) { 
    Connection conn= c.getConnect();
    if (conn!=null) {
    new Gui2(conn);//pass connection object here
    dispose();
    }

    }
  2. Gui2类,构造函数应该是

    public Gui2(Connection conn)
    {
    connection=conn;
    box = new JComboBox();
    .................
    }
  3. Gui2 类,

     box.setEnabled(true);//should be enabled,

关于Java : JDBC Connection Issue When Click On Button,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32721704/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com