在Glass Pane上绘制图形

时间:2016-01-07 13:33:08

标签: java swing glasspane

我目前正在制作棋盘游戏Khet的一个版本,并计划使用Glass Pane显示在转弯之间发射的激光,但是对于我的生活,我根本无法让图纸显示出来。为了节省发布游戏的所有代码,我发布了仅与玻璃窗格相关的代码,因为它是下面的独立应用程序。谁能告诉我为什么图形没有出现?

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

}

2 个答案:

答案 0 :(得分:4)

您的line组件大小为零。那是因为JFrame.getGlassPane()返回没有默认layoutManager的java.awt.Component。因此,为glassPane设置layoutManager可以解决您的问题。

glass = (JPanel) f.getGlassPane();
glass.setLayout(new BorderLayout());
glass.add(new line(), BorderLayout.CENTER);
glass.setVisible(false);

现在你的line Compnent应该和glassPane一样大

答案 1 :(得分:3)

我做了这个并且线出现了:

    glass = (JPanel) f.getGlassPane();
    glass.setLayout(new BorderLayout());
    glass.add(new line());