我已经覆盖了paintComponent(),所以为什么我的形状没有出现?

时间:2019-09-21 10:29:25

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

1 个答案:

答案 0 :(得分:0)

这是因为您的gamePanel没有LayoutManager(默认情况下使用FlowLayout)来填充面板中的组件。为了查看内容,将其更改为JPanel gamePanel = new JPanel(new BorderLayout());

但是,在Timer的操作中,您Thread.sleep()。这将冻结整个GUI,因为Timer的动作侦听器在事件调度线程中运行,该线程是Thread,不应sleep。相反,您可以使用第二个Timer或某种o标志变量,也可以使用SwingWorker