I have a main class that creates the instance of the JFrame
and JPanel
and I set the JPanel
as public so I can access it from another class to add more things into it (I don't know if this is how it works, that's just my logic).
public class Main {
private JFrame obj;
public Gameplay gamePlay;
public Main() {
obj = new JFrame();
gamePlay = new Gameplay();
}
public void execute() {
//properties of the jframe
obj.setBounds(10, 10, 700, 600);
obj.setTitle("Brick breaker");
obj.setResizable(false);
obj.setVisible(true);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//add the jpanel inside the jframe
obj.add(gamePlay);
}
public static void main(String[] args) {
Main main = new Main();
main.execute();
}
}
Then, I have another class named Gameplay
which extends JPanel
. One of the methods inside has to draw things inside the JPanel and add a label when a condition is true.
Note that the commented region at the end where "GAME OVER" is drawn by with graphics g
it does work correctly, but I want to put a label instead because I want to use custom font. The label never shows up. All the other things that the method pait()
has to paint also work fine.
public void paint(Graphics g) {
//background
g.setColor(Color.black);
g.fillRect(1, 1, 692, 592);
//more code of drawing things
//...
if(ballposY > 570) {
play = false;
ballXdir = 0;
ballYdir = 0;
lblGameOver = new JLabel("GAME OVER");
lblGameOver.setForeground(Color.green);
lblGameOver.setFont(pixels);//custom font
Main main = new Main();
main.gamePlay.add(lblGameOver);
//g.setColor(Color.green);
//g.setFont(new Font("serif", Font.BOLD, 30));
//g.drawString("GAME OVER", 250, 300);
}
g.dispose();
}