我有这段代码,它制作了一个JPanel并将其添加到JScrollPanel中。它工作正常,但是当我尝试添加第二个JPanel时,它将删除第一个JPanel并添加第二个。我希望能够将JPanels放在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);
    }
}

最佳答案

您可能希望考虑将面板放入使用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);

09-13 06:51