我有這段代碼,它創建一個JPanel並將它添加到一個JScrollPanel。它工作正常,但是當我嘗試添加第二個JPanel時,它會刪除第一個並添加第二個JPanel。我希望能夠將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);
}
}
試試JLayeredPane。但要小心,你可能必須'setOpaque(false)' – DankMemes
完美!當我添加時,我可以將它放在舊窗格的頂部,而不是放在它的後面? –
是的,只需使用JLayeredPane.add(Component,int),其中int是圖層編號。 – DankMemes