将多个JPanel放在一起

时间:2012-11-29 21:42:36

标签: java swing jpanel layout-manager

我有这个代码,它生成一个JPanel并将其添加到JScrollPanel。它工作正常,但是当我尝试添加第二个JPanel时,它会删除第一个JPanel并添加第二个JPanel。我希望能够将JPanel放在JPanels之上,我该怎么做?

// Location of an image:
String file = wfc.getSelectedFile().getPath();

// Creates images from different types:
ImageHandler image = new ImageHandler();
BufferedImage imageData = image.imageData(file);

// Extends JPanel, Layer is a JPanel
Layer layer = new Layer(image.width(), image.height());
layer.setImage(imageData);
layer.setSizeFromLoaded();
// A list of all the JPanels added
Layers.set(Layers.layers.size(), layer);

// Adds a JPanel to the JScrollPanel
imagePane.getViewport().add(layer, BorderLayout.CENTER);

这是完整的方法,它打开一个文件浏览器,然后当选择图像时它会运行上面的代码

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
    WebFileChooser wfc = null;
    if(wfc == null){
        wfc = new WebFileChooser(this, "Open an Image");
        wfc.setSelectionMode(SelectionMode.SINGLE_SELECTION);
        wfc.setAvailableFilter(GlobalConstants.IMAGES_AND_FOLDERS_FILTER);
        wfc.setChooseFilter(GlobalConstants.IMAGES_FILTER);
        wfc.setCurrentDirectory("/Users");
    }
    wfc.setVisible(true);

    if(wfc.getResult() == StyleConstants.OK_OPTION){
        String file = wfc.getSelectedFile().getPath();

        ImageHandler image = new ImageHandler();
        BufferedImage imageData = image.imageData(file);

        Layer layer = new Layer(image.width(), image.height());
        layer.setImage(imageData);
        layer.setSizeFromLoaded();
        Layers.set(Layers.layers.size(), layer);

        imagePane.getViewport().add(layer, BorderLayout.CENTER);
    }
}

3 个答案:

答案 0 :(得分:6)

您可以考虑将面板放入使用CardLayout的单个主面板。

这样您就可以轻松地在面板之间切换,从而产生分层面板的错觉,而无需手动操作。

像...一样的东西。

JPanel master = new JPanel(new CardLayout());
master.add(new ChildPane()); // Or what ever child you want to add
master.add(new ChildPane()); // Or what ever child you want to add
//...
JScrollPane scrollPane = new JScrollPane(master); 

答案 1 :(得分:3)

我使用了Zove Games建议并将其放置在JLayerdPanel中,它完美无缺!

答案 2 :(得分:1)

您可以将两个面板放在一个JPanel中,然后将其放在JScrollPane中。