JButton在运行时添加了但不可见

时间:2013-03-10 11:43:36

标签: java swing jbutton

public class Pencere{
    JFrame pencere = new JFrame();
    JButton buton1, buton2;

    public Pencere() {
        pencere.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pencere.setTitle("Ana Pencere");
        pencere.setBackground(Color.getHSBColor(15f, 120f, 220f));
        pencere.setLocation(new Point(500, 300));
        pencere.setSize(613, 253);
        pencere.addMouseListener(new Dinle());
        pencere.setLayout(new FlowLayout());
        pencereDegis();
    }
    public void goster(){
        pencere.setVisible(true);
    }

    public void pencereDegis(){
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch (ClassNotFoundException | InstantiationException
                | IllegalAccessException | UnsupportedLookAndFeelException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        buton2 = new JButton("Butonnn"); //This button not visible
        pencere.add(buton2);
        pencere.pack();
    }
}

当我运行我的应用程序(我显示JFrame窗口)时,所有代码都正常工作但在我看不到“Butonnn”按钮后调用pencereDegis()方法。

Sory因为我的英语不好谢谢你们..

2 个答案:

答案 0 :(得分:1)

此代码适用于我goster()方法main调用。 按钮buton2可见(我刚刚取消注释了您的addMouseListener(),因为我没有Dinle课程)。 我不确定,但这可能是因为你的LookAndFeel陈述。我有OSX,我无法在第一时间显示您的框架(因为您使用的是WindowsLookAndFeel),但是通过此修正可以很好地进行。

public class Pencere{
    JFrame pencere = new JFrame();
    JButton buton1, buton2;

    public Pencere() {
        pencere.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pencere.setTitle("Ana Pencere");
        pencere.setBackground(Color.getHSBColor(15f, 120f, 220f));
        pencere.setLocation(new Point(500, 300));
        pencere.setSize(613, 253);
        //pencere.addMouseListener(new Dinle());
        pencere.setLayout(new FlowLayout());
        pencereDegis();
    }
    public void goster(){
        pencere.setVisible(true);
    }

    public void pencereDegis(){
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException
                | IllegalAccessException | UnsupportedLookAndFeelException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        buton2 = new JButton("Butonnn"); //This button not visible
        pencere.add(buton2);
        pencere.pack();
    }

    public static void main(String[] args)
    {
        Pencere p = new Pencere();
        p.goster();
    }
}

答案 1 :(得分:0)

public static void main(String[] arg)
{
    pencereDegis();
    goster();
}

将此信息包含在您的代码中,它可以正常工作。