I am currently making a version of the board-game Khet and was planning on displaying the laser fired between turns using a Glass Pane, but for the life of me I can't get the drawings to show up at all. To save posting all of the code for the game I've posted the code only related to the glass pane as it's own separate application below. Can anyone tell me why the graphics aren't showing up?
package glasspane;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.Line2D;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GlassPane {
JPanel panel, glass;
GlassPane() {
JFrame f = new JFrame("GlassPane");
panel = new JPanel();
JButton show = new JButton("Show glass");
JButton hide = new JButton("Hide glass");
show.addActionListener(e -> changeVisibility());
hide.addActionListener(e -> changeVisibility());
panel.add(show);
panel.add(hide);
glass = (JPanel) f.getGlassPane();
glass.add(new line());
glass.setVisible(false);
f.add(panel);
f.setSize(300, 300);
f.setVisible(true);
}
private void changeVisibility() {
glass.setVisible(!glass.isVisible());
panel.repaint();
}
@SuppressWarnings("serial")
private class line extends JComponent {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
Shape s = new Line2D.Float(0, 0, 300, 300);
g2.setColor(Color.GREEN);
g2.setStroke(new BasicStroke(20));
g2.draw(s);
System.out.println("doing something...");
}
}
public static void main(String[] args) {
new GlassPane();
}
}
Your line
Component has zero size. Thats because JFrame.getGlassPane()
returns a java.awt.Component
that has no default layoutManager. So set a layoutManager for your glassPane should solve your problem.
glass = (JPanel) f.getGlassPane();
glass.setLayout(new BorderLayout());
glass.add(new line(), BorderLayout.CENTER);
glass.setVisible(false);
Now your line
Compnent should be as big as glassPane