简体   繁体   English

在JDialog中更改JPanel内容

[英]Change JPanel contents in JDialog

I'm trying to add components to a JDialog after it has been created and displayed. 我正在尝试在创建和显示JDialog之后将其添加到JDialog中。 Nothing I try makes the changes actually update to the screen, and I've read and applied every question I could find related to this. 我没有尝试使更改实际更新到屏幕,我已阅读并应用我能找到的与此相关的每个问题。

This example code creates a modal JDialog showing the word "test". 此示例代码创建一个显示单词“test”的模态JDialog。 I cannot get it to display "test2". 我不能让它显示“test2”。 Almost exactly the same code but with a JFrame instead of a JDialog behaves as I expect, so I don't understand. 几乎完全相同的代码,但使用JFrame而不是JDialog的行为与我期望的一样,所以我不明白。 I'm new to Java and especially to swing. 我是Java的新手,特别是摇摆。

import javax.swing.*;
public class DialogTester {
    public static void main(String[] args) {
        new DialogTester();
    }

    public DialogTester() {
        JFrame jframe = new JFrame();
        jframe.setVisible(true);
        JDialog jdialog = new JDialog(jframe,true);
        JPanel jpanel = new JPanel();
        jpanel.add(new JLabel("test"));
        jdialog.add(jpanel);
        jdialog.setVisible(true);
        jpanel.add(new JLabel("test2"));
        jpanel.revalidate();
        jdialog.getContentPane().validate();
        jdialog.pack();

    }
}

I also tried calling 我也试着打电话

jdialog.repaint();

which did nothing. 什么也没做。

You created a modal dialog. 您创建了一个模态对话框。 So, as soon as you call setVisible(true) , the following instructions wait for the dialog to be closed to be executed. 因此,只要调用setVisible(true) ,以下指令就会等待关闭对话框以执行。

Put the code adding a label before the dialog is made visible, or put it in an event handler called after the dialog is shown, for example, when you click on a button in this dialog. 在对话框可见之前添加标签的代码,或者在显示对话框后将其放入调用的事件处理程序中,例如,当您单击此对话框中的按钮时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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