tags:

views:

297

answers:

1

Is there any trick to calling JFrame.setGlassPane(Component) more than once? In the code below, I first call it to create a red box in the glass pane. That works fine. Then, in a mouse click handler, I call it again to create a blue box in a new glass pane. This doesn't work. The original red glass pane disappears, but the blue glass pane does not appear. What am I doing wrong here?

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);
    }
}

Calling repaint() like this does not fix the problem:

void setTheGlassPane(JComponent glassPane) {
 f.setGlassPane(glassPane);
 f.getGlassPane().setVisible(true);
 f.repaint();
}
A: 

In setTheGlassPane(), add this as the first line:

f.getGlassPane().setVisible(false);
Devon_C_Miller