java 向JFrame动态添加组件

5vf7fwbs  于 2023-03-28  发布在  Java
关注(0)|答案(1)|浏览(215)

我正在寻找一种方法,在JFrame设置为可见后,动态地将Component添加到JFrame中。具体来说,我向数据库发出请求,并根据结果的长度,在屏幕上显示JRadioButton。我使用以下代码:

try {
        Class.forName(Mavenproject1.SQL_DRIVER);
        Connection c = (Connection) DriverManager.getConnection(Mavenproject1.DB, Mavenproject1.ROOT, Mavenproject1.PASSWORD);
        PreparedStatement ps = c.prepareStatement("Select * from calendriers where user = ?");
        ps.setString(1, Login.USER);
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            int cal_id = rs.getInt(1);
            ps = c.prepareStatement("Select * from creneaux where calendrier = ?");
            ps.setInt(1, cal_id);
            rs = ps.executeQuery();
            while (rs.next()) {
                JRadioButton radio = new JRadioButton("Hello world");
                radio.setVisible(true);
                Date debut = Date.getDateFromString(rs.getString(2), true);
                Date fin = Date.getDateFromString(rs.getString(3), true);
                Creneau cr = new Creneau(debut, fin);
                creneaux.add(cr);
                System.out.println(cr.toString());
                getContentPane().add(radio);
                getContentPane().revalidate();
                getContentPane().repaint();
            }
            Component[] components = getContentPane().getComponents();
            for (Component component : components) {
                System.out.println(component.getClass().getName());
            }
        }
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "Error", "error", 1);
    }

作为输出,我有相应的JRadioButton是内容窗格的组件,但我无法在屏幕上看到它,我使用getLocation()检查了位置,它说0,0,我将其更改为100,100,但仍然没有。

j2datikz

j2datikz1#

您必须在事件调度线程上进行UI更改。假设数据库访问是在专用线程上完成的,请将UI更改 Package 在SwingUtilities.invokeLater()中,例如:

SwingUtilities.invokeLater(() -> {
    JRadioButton radio = new JRadioButton("Hello world");
    radio.setVisible(true);
    getContentPane().add(radio);
    getContentPane().revalidate();
    getContentPane().repaint();
});

使用SwingWorker可能也是一个好主意。

相关问题