繁体   English   中英

java jlabel在游戏循环中消失

[英]java jlabel disappears in game loop

这里的目标是将 jlabels 与包含 BufferedImage 的图像图标一起使用。 这些 jlabels 然后可以很容易地用鼠标移动,而不必在屏幕上搜索大量不同的 BufferedImages 来找出哪个被点击了。

这在标准的 JFrame 中很容易做到。 我已经在这里搜索了一个小时,试图弄清楚如何在覆盖paintComponent 的游戏循环中实现这一点。

import javax.swing.*;
import java.awt.*;

public class Main {

    public Main() {
    }

    public static void main(String[] args) {
        JFrame window = new JFrame();

        GamePanel gamePanel = new GamePanel();

        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setResizable(true);
        window.setLayout(new FlowLayout());
        window.setTitle("FX Test");
        window.add(gamePanel);
        window.pack();
        window.setLocationRelativeTo(null);
        window.setVisible(true);
        gamePanel.startGameThread();

    }
}

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

public class GamePanel extends JPanel implements ActionListener {
    private Timer gameLoopTimer;
    public int screenWidthPixels = 640;
    public int screenHeightPixels = 480;
    private int counter;

    private int x = 1;
    private float alpha = 1;
    private final int DELAY = 15;
    private final int INITIAL_DELAY = 200;
    public GamePanel() {
        this.setPreferredSize(new Dimension(screenWidthPixels, screenHeightPixels));
        this.setBackground(Color.black);
        this.setDoubleBuffered(true);
        this.setFocusable(true);
        this.requestFocus();
        counter = 0;
        JButton testButton = new JButton("Button Test");
        this.add(testButton);
        JLabel label = new JLabel(new String("Label test"));
        label.setVisible(true); // Doesn't seem to be needed.
        this.add(label);
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        Graphics2D g2 = (Graphics2D) g;
        g2.setColor(Color.WHITE);
        g2.drawString("Game Panel Testing: " + counter,128,129);

        g2.dispose();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        repaint();
        update();
    }

    void startGameThread() {
        gameLoopTimer = new Timer(DELAY,this);
        gameLoopTimer.setInitialDelay(INITIAL_DELAY);
        gameLoopTimer.start();

    }
}

该代码绘制“游戏面板测试:”和递增计数器,但没有按钮和标签。

如果我注释掉我要覆盖的整个paintComponent,按钮和标签会按预期显示。

我无法理解的是,一旦paintComponent 被覆盖,如何让标签和按钮再次出现。 我认为super.paintComponent(g)会自动处理这个问题,但显然我在这里遗漏了一些东西。 我到底怎样才能在这个游戏循环中添加一堆 JLabel 而不必在鼠标拖动时手动处理 g2 绘制的 BufferedImages 的移动?

由于您覆盖了paintComponent 方法,因此未绘制jlabels。 对 super 的调用在 super 类上,因此您误解了该调用的工作原理。 如果你把你的类放在一个继承自你的类的类中,它会工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM