问题
I got a class that's supposed to launch a game (with main()
), and the game's opening screen. The class with main()
(named Starter
), that extends JFrame
, creates a new OpeningScreen
class (extending JPanel), and adds it to the JFrame.
For some reason, the OpeningScreen
won't be added to the JFrame. Code:
Starter
class:
import javax.swing.*;
import java.awt.*;
public class Starter extends JFrame {
public Starter(){
setSize(500,500);
setResizable(false);
setTitle("Ping-Pong Battle");
setDefaultCloseOperation(EXIT_ON_CLOSE);
OpeningScreen openingS = new OpeningScreen();
add(openingS);
setVisible(true);
}
public static void main(String[]args){
Starter starter = new Starter();
}
}
OpeningScreen
class:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class OpeningScreen extends JPanel {
public OpeningScreen(){
setBackground(Color.BLACK);
setFocusable(true);
setVisible(true);
}
public void paint(Graphics g){
// Soon code here to be drawn.
}
public void startGame(){
Board board = new Board();
}
}
What's the problem? Thanks
EDIT: The constructor of OpeningScreen does run, but doesn't paint the background black. Also, trying to draw things in paint() doesn't work.
回答1:
Your problem arises from overriding paint
in your OpeningScreen
class. The background is not drawn because you never draw it! Call super.paint(g)
to fix this.
However, it is generally recommended to use paintComponent() instead of paint(). Just move your code to paintComponent
.
This method correctly draws a black background a red square:
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.fillRect(100, 100, 100, 100);
}
回答2:
I think because you override paint() the background doesn't get painted, so it appears like the Panel isn't added. Commenting out the paint method results in the Window being black for me.
Also, drawing in the paint method works for me, maybe your color is set to black so it doesn't show on the black background ? Try g.setColor(Color.white) before drawing.
来源:https://stackoverflow.com/questions/20830382/jpanel-wont-display