Java:单击按钮时出现JDBC连接问题
我在这个程序中遇到了一个问题,有两个Java:单击按钮时出现JDBC连接问题,java,mysql,swing,jdbc,Java,Mysql,Swing,Jdbc,我在这个程序中遇到了一个问题,有两个GUI。当用户点击按钮时,它会在连接成功时检查数据库连接,然后出现第二个GUI,其中有JComboBox。但问题是它没有在JComboBox中显示mysql的目录 主要方法: public class Main { public static void main(String[] args) { Gui obj = new Gui(); } } 第一个图形用户界面 public class Gui extends
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);
}
}
连接器
类返回
类型更改为连接
和返回
连接
public Connection getConnect() {
....
return conn
}
Gui
class,更改条件
public void actionPerformed(ActionEvent arg0) {
Connection conn= c.getConnect();
if (conn!=null) {
new Gui2(conn);//pass connection object here
dispose();
}
}
Gui2
类,构造函数应该是
public Gui2(Connection conn)
{
connection=conn;
box = new JComboBox();
.................
}
Gui2
class
box.setEnabled(true);//should be enabled,
您在
Gui2
中从何处获得连接。由于您总是调用box.setEnabled(false)
,您如何知道JComboBox包含哪些内容?@Satya我从连接器类获得连接我在Gui2
类中询问。@VGR我想说连接没有连接到jcomboxconnection=c.getConnect();由于getConnect()方法返回布尔值,因此给出错误。因此,请将返回
类型更改为连接
和返回连接
。删除该条件c.getConnect()
,但框架将打开。我希望当按钮cick连接变为真时,它将自动打开。感谢您的帮助,我理解