gpt4 book ai didi

java - 单击按钮时 JLabels 不显示

转载 作者:行者123 更新时间:2023-12-01 06:31:00 26 4
gpt4 key购买 nike

我想在单击我的节目按钮时看到标签,但不起作用!

public class d4 extends JFrame implements ActionListener {

Connection con;
String dbName = "mydb";
String bdUser = "root";
String dbPassword = "2323";
String dbUrl = "jdbc:mysql://localhost/mydb";
JButton showButton;
static JLabel[] lbl;
JPanel panel;

public d4() {

try {
con = DriverManager.getConnection(dbUrl, bdUser, dbPassword);
System.out.println("Connected to database successfully!");

} catch (SQLException ex) {
System.out.println("Could not connect to database");
}

add(mypanel(), BorderLayout.PAGE_START);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 500);
setLocation(300, 30);
setVisible(true);
pack();
}

public JPanel mypanel() {
panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
showButton = new JButton("Show");
showButton.addActionListener(this);
panel.add(showButton);
revalidate();
repaint();

return panel;
}

@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == showButton) {
lbl = recordsLabel();
for(JLabel jlabel : lbl){
panel.add(jlabel);
}
}
public JLabel[] recordsLabel() {
try {
Statement st1 = con.createStatement();
ResultSet result1 = st1.executeQuery("select * from mytable");
ArrayList<String> lableList = new ArrayList<>();
while (result1.next()) {
String resultRow = result1.getString(1) + " " + result1.getString(2);
System.out.println(resultRow);
lableList.add(resultRow);
}
Object[] arrayResultRow = lableList.toArray();

int rows = result1.last() ? result1.getRow() : 0;

lbl = new JLabel[rows];
for (int i = 0; i < rows; i++) {
lbl[i] = new JLabel(arrayResultRow[i].toString());
}

} catch (SQLException sqle) {
System.out.println("Can not excute sql statement");
}
return lbl;
}

public static void main(String[] args) {
new d4();
}
}

最佳答案

您尚未实现 ActionListener 接口(interface)

编辑:您更新的代码表明您已经。现在,正如 Hovercraft Full Of Eels 所建议的那样,下一步是通过调试技术来隔离问题。

关于java - 单击按钮时 JLabels 不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17556804/

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