java - 我已经重写了paintComponent(),那么为什么我的形状没有出现呢?

标签 java swing awt event-dispatch-thread jcomponent

我正在摆弄 awt 图形,一开始我设法得到了我想要的一切,但是在清理我的代码之后,突然除了一个空框架之外什么都没有出现,其中包含 JPanel。

这可能是非常明显的,但我找不到为什么我的形状不再出现。我做错了什么?

public class Main {
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Game().setVisible(true);
            }
        });
    }
}
public class Game extends JFrame {
    static int width = 500;
    static int height = 500;

    public Game() {
        this.setPreferredSize(new Dimension(width, height));
        JPanel menuPanel = new JPanel(); // Menypanel
        JPanel filmPanel = new JPanel(); // Filmpanel
        JPanel gamePanel = new JPanel(); // Spelpanel
        gamePanel.setBackground(Color.WHITE);

        // Intro texts
        Queue<String> intro = new ArrayDeque<>();
        intro.add("Welcome to the jungle!");
        intro.add("We've got fun and games.");
        FadingTextBox introBox = new FadingTextBox(intro);
        gamePanel.add(introBox);

        getContentPane().add(gamePanel);
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        pack();
    }
}

这个根本没有出现:

class FadingTextBox extends JComponent implements ActionListener {
    private RoundRectangle2D rr;
    private String text = "";
    private float alpha;
    private float alphaDelta = 0.05f; // Alpha fade speed
    private final int fps = 60;  // FPS
    private javax.swing.Timer timer = new Timer(1000 / fps, this);
    private java.util.Queue<String> textQueue; // Contains lines of texts

    public FadingTextBox(java.util.Queue<String> textQueue) {
        this.textQueue = textQueue;
        this.setFont(new Font("OCR A EXTENDED", Font.BOLD, 24));

        int arc = 10;
        int height = (int) (Game.height * 0.2);
        int width = (int) (Game.width - Game.width * 0.1);
        int x = Game.width / 2 - width / 2;
        int y = (int) (Game.height - height * 1.5);

        rr = new RoundRectangle2D.Double(x, y, width, height, arc, arc);

        setText(textQueue.remove());
        timer.start();
    }

    private void setText(String text) {
        this.text = text;
    }

    boolean isRunning() {
        return timer.isRunning();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;

        // Set component alpha
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));

        // Draw RoundRectangle
        g2.setBackground(Color.DARK_GRAY);
        g2.fill(rr);

        // Draw text
//        g2.setColor(Color.BLUE);
        final FontMetrics fm = g.getFontMetrics();
        Rectangle2D textBounds = fm.getStringBounds(text, g2);
        g2.drawString(text, (float) (rr.getCenterX() - (textBounds.getWidth() / 2)), (float) (rr.getCenterY() + textBounds.getHeight() / 2));
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (alpha >= 0) {
            alpha += alphaDelta;
        }
        if (alpha < 0) {
            alpha = 0;
            try {
                setText(textQueue.remove());
            } catch (NoSuchElementException ex) {
                timer.stop();
            }
            alphaDelta *= -1;
        } else if (alpha >= 1) {
            alpha = 1;
            alphaDelta *= -1;

            // Sleep 1 sec on full alpha
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
        repaint();
    }
}

新观点:

public class Game extends JFrame {
    ...
    GameCanvas gameCanvas;

    public Game() {
        ...
        gameCanvas = new GameCanvas(); // Spelpanel
        getContentPane().add(gameCanvas);
        ...
        pack();
    }
}
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import java.util.ArrayDeque;
import java.util.NoSuchElementException;

public class GameCanvas extends Canvas implements Runnable {
    private final int fps = 24;  // FPS
    private RoundRectangle2D rr;
    private String text;
    private float alpha;
    private float alphaDelta = 0.05f; // Alpha fade speed
    private javax.swing.Timer timer = new Timer(1000 / fps, a -> repaint());
    private java.util.Queue<String> textQueue; // Contains lines of texts

    public GameCanvas() {
        this.setFont(new Font("OCR A EXTENDED", Font.BOLD, 20));
        // Intro texts
        textQueue = new ArrayDeque<>();
        textQueue.add("Welcome to the jungle!");
        textQueue.add("We've got fun and games.");

        // RoundRectangle
        int arc = 10;
        int height = (int) (Game.height * 0.2);
        int width = (int) (Game.width - Game.width * 0.1);// (int) (Game.width - Game.width * 0.5);
        int x = Game.width / 2 - width / 2 - 10;
        int y = (int) (Game.height - height * 1.5);
        rr = new RoundRectangle2D.Double(x, y, width, height, arc, arc);

        this.text = textQueue.remove();
        Thread thread = new Thread(this);  // Fade thread
        thread.start();
        timer.start();

    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2 = (Graphics2D) g;

        // Set component alpha

//        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));

        // Draw RoundRectangle
        g2.setBackground(Color.DARK_GRAY);
        g2.fill(rr);

        // Draw text
        final FontMetrics fm = g2.getFontMetrics();
        Rectangle2D textBounds = fm.getStringBounds(text, g2);
        g2.setColor(Color.WHITE);
        g2.drawString(text, (float) (rr.getCenterX() - (textBounds.getWidth() / 2)), (float) (rr.getCenterY() + textBounds.getHeight() / 2));
        g2.setColor(Color.DARK_GRAY);
    }

    @Override
    public void run() {
        while (true) {
            if (alpha >= 0) {
                alpha += alphaDelta;
            }
            if (alpha < 0) {
                alpha = 0;
                try {
                    this.text = textQueue.remove();
                } catch (NoSuchElementException ex) {
                    timer.stop();
                }
                alphaDelta *= -1;
            } else if (alpha >= 1) {
                alpha = 1;
                alphaDelta *= -1;

                // Sleep 1 sec on full alpha
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

最佳答案

因为你gamePanel没有 LayoutManager (默认情况下它使用 FlowLayout)用组件填充面板。为了查看某些内容,请将其更改为 JPanel gamePanel = new JPanel(new BorderLayout());

但是,在 Timer你的行动Thread.sleep() 。这将卡住整个 GUI,因为 Timer的 Action 监听器在事件调度线程中运行,这是一个 Thread那不应该sleep 。相反,您可以使用第二个 Timer或某种标志变量,或者可能是 SwingWorker .

关于java - 我已经重写了paintComponent(),那么为什么我的形状没有出现呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58039397/

相关文章:

java - 如何强制使用 GridBagLayout 的 JPanel 通过 JFrame 调整大小

c# - Java 和 C# 中的原始类型是否不同?

java - 哪个引用终结器(FinalReference)或弱/幻影/软引用对于GC具有更高的优先级

java - 在 MouseEvent 上绘制可见的 JComponents

java - JFrame 有时根本不出现?

java - KeyListener 不产生任何响应

java - JTextArea 和显示格式问题

java - 在 Java 中为图像添加边框

java - 如何使用java中的下一个按钮从文本字段中的数据库移动数据

java - 如何在android中的后台服务中获取当前位置