开发者

How to create a JFrame within a JFrame?

How can 开发者_运维技巧we create a main JFrame with background image and a JFrame inside the main JFrame with Java Swing?


I believe you are looking for internal frames.

For the background image bit, sublass JPanel, override its paintComponent() method, and blit your image there. Then set an instance of that panel as your JFrame's content pane.

public class BackgroundPanel extends JPanel {
    private BufferedImage bgImg;

    public BackgroundPanel() {
        try {
            bgImg = ImageIO.read(BackgroundPanel.class.getResourceAsStream(
                    "mybackgroundimage.png"));
        } catch (IOException ex) {
            System.err.println("Could not load background image!");
            ex.printStackTrace();
        }
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (bgImg != null) {
            g.drawImage(bgImg, 0, 0, null);
        }
    }
}

public class MyJFrame extends JFrame {

    public MyJFrame() {
        setContentPane(new BackgroundPanel());
    }

}


It is hard to know what you are meaning with

a JFrame inside the main JFrame

Have a read about what a JFrame really is. Maybe you want a dialog window in your application, or maybe an internal window. Or maybe just another panel.

To get an background image in a JFrame, I recommend that you simply add a JPanel with a backround image to the JFrame:s contentpane.


Based on my understanding, you won't need to nest a JFrame inside another JFrame and I don't think it is good design to do so too. What you can do is nest JPanels instead.

You will mainly need to know about these two classes:

  • JPanel -> http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JPanel.html
  • Graphics -> http://java.sun.com/javase/6/docs/api/java/awt/Graphics.html
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜