【发布时间】:2011-11-29 13:52:00
【问题描述】:
我有两个JPanels 在同一个容器中相互叠加。我正在使用container.add(jpanel, 0); 和container.add(otherjpanel, 1)。它工作正常,但是为了让顶层显示我必须用鼠标将鼠标悬停在组件上。
这是一些显示我的问题的可执行代码。
只需将鼠标悬停在屏幕上方即可。
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.event.*;
import javax.swing.*;
import javax.swing.text.*;
import java.io.*;
import java.util.*;
public class test {
public static void main(String args[]) {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {
}
JFrame frame = new GUIframe();
frame.setVisible(true);
frame.setResizable(false);
}
}
class GUIframe extends JFrame{
public GUIframe(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(300,400));
setSize(300, 400);
JLayeredPane content = new JLayeredPane();
content.setPreferredSize(new Dimension(300,400));
content.setSize(300,400);
JPanel board = new JPanel();
for (int i = 0;i<5;i++){
JButton button = new JButton("button");
board.add(button);
}
content.add(new ImagePanel());
this.add(content);
this.add(board);
}
}
class ImagePanel extends JPanel {
private Image img;
String imageLocation = "image location here";
ImagePanel() {
img = new ImageIcon(imageLocation).getImage();
setPreferredSize(new Dimension(300,400));
setSize(300,400);
setLayout(null);
setOpaque(false);
}
public void paint(Graphics g){
super.paint(g);
g.drawImage(img, 0, 0, this);
}
}
【问题讨论】:
-
1) 为了尽快获得更好的帮助,请发布 SSCCE 2) 在 Swing 非 TLC 中,覆盖
paintComponent(Graphics)而不是paint(Graphics)。
标签: java swing panel jlayeredpane jlayer