JButton没有出现在JDialog上

时间:2014-07-11 06:41:59

标签: java swing jframe jbutton

我在此代码中遇到问题,即我在JButton上添加了JDialog但是当对话框出现时按钮不可见。请帮忙。

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;

public class A implements ActionListener {
    JFrame f = new JFrame();

    public A() {
        JButton b = new JButton("JDialog");
        f.add(b);
        b.addActionListener(this);
        f.setVisible(true);
        f.setSize(500,500);
    }

    public static void main(String arg[]) {
        new A();
    }

    public void actionPerformed(ActionEvent e) {
        JDialog d = new JDialog(f,"Dialog",true);
        d.setSize(100,100);
        d.setVisible(true);
        d.setLayout(new FlowLayout());
        JButton b  = new JButton("OK");
        d.add(b);
    }
}

2 个答案:

答案 0 :(得分:2)

在致电setvisible(true)之前添加按钮。

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;


public class A implements ActionListener {
    JFrame f = new JFrame();
    public A() {


        JButton b = new JButton("JDialog");
        f.add(b);
        b.addActionListener(this);
        f.setVisible(true);
        f.setSize(500,500);
    }

    public static void main(String arg[]) {
        new A();
    }

    public void actionPerformed(ActionEvent e) {
        JDialog d = new JDialog(f,"Dialog",true);
        d.setSize(100,100);

        d.setLayout(new FlowLayout());
        JButton b  = new JButton("OK");
        d.add(b);
        d.setVisible(true);
    }

}

答案 1 :(得分:0)

我相信在您添加按钮之前会呈现您的Component。尝试在呈现Component之前添加按钮。在致电setVisiblerepaint Component

之前,请尝试添加