在玻璃板上绘制图形

Drawing a graphic on Glass Pane

我目前正在制作棋盘游戏 Khet 的一个版本,并计划使用玻璃板显示回合之间发射的激光,但对于我来说,我根本无法显示图纸.为了节省发布游戏的所有代码,我只发布了与玻璃板相关的代码,因为它在下面有自己的单独应用程序。谁能告诉我为什么图形不显示?

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

}

我这样做了,结果显示了一行:

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

您的 line 组件大小为零。那是因为 JFrame.getGlassPane() returns 没有默认布局管理器的 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 一样大