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