问题
I'm working on a small game project and am having an issue with java graphics not being displayed. I've searched similar questions here on Stackoverflow and used overriding the paintComponent() method of the JPanel which many ppl advised but am still having this issue. I hope to get my background image and menubar, and music at the same time. Music works fine but background image and menubar doesn't show up at all.
here's my code :
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class DynamicBeat extends JFrame {
private Image screenImage;
private Graphics screenGraphic;
private Image introBackground = new ImageIcon(Main.class.getResource("../images/introBackground(Title).jpg")).getImage();
private JLabel menuBar = new JLabel(new ImageIcon(Main.class.getResource("../images/menuBar.png")));
public DynamicBeat() {
menuBar.setBounds(0, 0, 1280, 30);
add(menuBar);
Music introMusic = new Music("introMusic.mp3", true);
introMusic.start();
setUndecorated(true);
setTitle("Dynamic Beat Game");
setSize(Main.SCREEN_WIDTH, Main.SCREEN_HEIGHT);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setBackground(new Color(0, 0, 0, 0));
setLayout(null);
add(new DynamicBeatPane());
pack();
}
public void paint(Graphics g) {
screenImage = createImage(Main.SCREEN_WIDTH, Main.SCREEN_HEIGHT);
screenGraphic = screenImage.getGraphics();
screenDraw(screenGraphic);
g.drawImage(screenImage, 0, 0, null);
}
public void screenDraw(Graphics g) {
g.drawImage(introBackground, 0, 0, null);
this.repaint();
}
public static class DynamicBeatPane extends JPanel {
@Override
protected void paintComponent(Graphics g) {
// Call the superclass paint method.
super.paintComponent(g);
}
}
}
来源:https://stackoverflow.com/questions/62673819/java-graphics-not-showing-on-mac-even-with-overriding-the-paintcomponent-metho