日期:2014-05-20  浏览次数:20769 次

swing:为什么一个类里调用另一个类的panel不显示
//这是index类,要在这个类里调用另外一个类的panel
public class IndexFrame extends JFrame {

private static final long serialVersionUID = 1L;

protected ImagePanel backgroundPanel;
protected NavigationPanel navigationPanel;

public IndexFrame() {
init();
}

private void init() {
JFrame frame = new JFrame();
backgroundPanel = new ImagePanel(new ImageIcon(
"images/backgroundImg.png").getImage());
backgroundPanel.setOpaque(false);
navigationPanel = new NavigationPanel();
backgroundPanel.add(navigationPanel);
frame.getContentPane().add(backgroundPanel);
frame.pack();
frame.setVisible(true);
frame.setLocation(200, 80);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new IndexFrame();
}

}



//这是被调用的类,此类里构造一个panel
public class NavigationPanel extends JPanel {
protected static ImagePanel navigationPanel;
protected JPanel navButtonPanel;

public NavigationPanel() {
init();
}

private void init() {
navigationPanel = new ImagePanel(new ImageIcon(
"images/navigationBgr2.png").getImage());
navigationPanel.setOpaque(false);
navigationPanel.setOpaque(false);
navigationPanel.setVisible(true);
System.out.println("navigationPanel 初始化完毕");
}
public static void main(String[] args) {
new NavigationPanel();
JFrame frame = new JFrame();
frame.add(navigationPanel);
frame.setSize(600, 200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

这样调用,为什么不显示?
单独运行navigationPanel就能显示
请大家帮解决,谢谢!

------解决方案--------------------
ImagePanel代码没有贴出来,楼主将这个类代码贴出来看看
------解决方案--------------------
你的 NavigationPanel 类能自己执行正常显示是因为
你在这个类的mian方法中,把
protected static ImagePanel navigationPanel;
这个静态变量直接塞到了JFrame中

而你在 IndexFrame 这个类中,只是把一个 NavigationPanel 类的对象塞了进去
而不是把 NavigationPanel 类的 protected static ImagePanel navigationPanel; 这个静态成员变量塞了进去
当然显示不正常

NavigationPanel 类只是一个普普通通的 JPanel 上面什么都没有
你在 NavigationPanel 实现过程中也没有把 
protected static ImagePanel navigationPanel;
这个成员变量 add 到 NavigationPanel 上去,

总之,你这个结构写的很混乱把你的两个类小改了下,你试试吧

Java code
public class NavigationPanel extends ImagePanel {

    protected JPanel navButtonPanel;

    public NavigationPanel() {
        super(new ImageIcon(
                "images/navigationBgr2.png").getImage());
        init();
    }

    private void init() {
        setOpaque(false);
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.add(new NavigationPanel());
        frame.setSize(600, 200);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}