简体   繁体   中英

JLabels don't show when button clicked

I want to see labels when my show Button clicked, But don't work!

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

You have not implemented the ActionListener interface

EDIT: your updated code shows that you have. Now as Hovercraft Full Of Eels suggests, the next step is to isolate the problem with debugging techniques.

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

You're calling myPanel() twice , and by doing this, you're adding JLabels to a JPanel that is never added to the GUI.

Solution: don't do this. Your myPanel() is kind of screwy to begin with since it returns a JPanel and also sets the class field panel at the same time. So set the panel variable once, and then use the variable.

And yes, revalidate() and repaint() the container after adding components to it as per Azad's recommendations (1+ to him).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM