0

我想在我的显示按钮单击时看到标签,但不工作!

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();
}
}
4

3 回答 3

5

你还没有实现 ActionListener 接口

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

于 2013-07-09T19:45:27.707 回答
5

尝试调用revalidate()repaint()将标签添加到面板后,您还需要调用pack()框架以调整框架大小以适应新组件。

于 2013-07-09T20:01:54.767 回答
4

您调用myPanel() 了两次,通过这样做,您将 JLabels 添加到从未添加到 GUI 中的 JPanel。

解决方案:不要这样做。你myPanel()的开始有点古怪,因为它返回一个 JPanel 并同时设置类字段面板。所以设置面板变量一次,然后使用该变量。

是的,revalidate()根据repaint()Azad 的建议(给他 1+)添加组件后的容器。

于 2013-07-09T20:02:40.763 回答