[英]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.