有多少技巧可以多次调用JFrame.setGlassPane(Component)
吗?在下面的代码中,我首先调用它在玻璃窗格中创建一个红色框。这很好。然后,在鼠标单击处理程序中,我再次调用它以在新的玻璃窗格中创建一个蓝色框。这不起作用。原始的红色玻璃窗格消失,但不显示蓝色玻璃窗格。我在这里做错了什么?
public class GlassPaneProblem extends Component {
private BufferedImage img;
private JFrame f;
public void paint(Graphics g) {
g.drawImage(img, 0, 0, null);
}
public GlassPaneProblem() {
try {
img = ImageIO.read(new File("images/AppleCorps.JPG"));
} catch (IOException e) {
}
this.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
BlueGlassPane blueGlassPane = new BlueGlassPane();
setTheGlassPane(blueGlassPane);
}
});
}
public Dimension getPreferredSize() {
if (img == null) {
return new Dimension(100, 100);
} else {
return new Dimension(img.getWidth(null), img.getHeight(null));
}
}
public void run() {
f = new JFrame("Glass Pane Problem");
f.add(this);
f.pack();
RedGlassPane redGlassPane = new RedGlassPane();
setTheGlassPane(redGlassPane);
f.setVisible(true);
}
void setTheGlassPane(JComponent glassPane) {
f.setGlassPane(glassPane);
f.getGlassPane().setVisible(true);
}
public static void main(String[] args) {
GlassPaneProblem glassPaneProblem = new GlassPaneProblem();
glassPaneProblem.run();
}
}
class RedGlassPane extends JComponent {
protected void paintComponent(Graphics g) {
Rectangle clip = g.getClipBounds();
g.setColor(Color.RED);
g.fillRect(clip.x + clip.width / 3, clip.y + clip.height / 3,
clip.width / 3, clip.height / 3);
}
}
class BlueGlassPane extends JComponent {
protected void paintComponent(Graphics g) {
Rectangle clip = g.getClipBounds();
g.setColor(Color.BLUE);
g.fillRect(clip.x + clip.width / 3, clip.y + clip.height / 3,
clip.width / 3, clip.height / 3);
}
}
像这样调用repaint()
并不能解决问题:
void setTheGlassPane(JComponent glassPane) {
f.setGlassPane(glassPane);
f.getGlassPane().setVisible(true);
f.repaint();
}
答案 0 :(得分:1)
在setTheGlassPane()
中,将其添加为第一行:
f.getGlassPane().setVisible(false);