Meli497
Meli497

Reputation: 53

Panel doesn't have border

I'm working on a project and I just started on the GUI. Since this isn't my most favorite topic, I stumbled real quick on something not working quite right. Everything (PacmanGrid,PacmanScore) is shown correctly but the borders I wrote for the PacmanScore Panel! Anyway here is the code, hope someone can help.

public class PacmanFrame extends JFrame{



public PacmanFrame() {
    this.setLayout(new BorderLayout());
    this.setTitle("Pacman");
    PacmanGrid p1=new PacmanGrid();
    PacmanScore p2 = new PacmanScore();


    this.add(p1,BorderLayout.CENTER);
    this.add(p2,BorderLayout.EAST);
    super.setDefaultCloseOperation(EXIT_ON_CLOSE);
    super.repaint();
    pack();
    super.setVisible(true);


}


public static void main(String[] args) {
    PacmanFrame p1 = new PacmanFrame();
}

 }

PacmanScore

public class PacmanScore extends JPanel{
private TitledBorder t3 = BorderFactory.createTitledBorder("Menu");
private Border etched = BorderFactory.createEtchedBorder(Color.WHITE, Color.white);


public PacmanScore() {
    setLayout(new FlowLayout());
    setPreferredSize(new Dimension(100,800));
    setBackground(Color.DARK_GRAY);
    t3.setBorder(etched);
    setBorder(t3);

    setVisible(true);
    setOpaque(true);


}

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D)g;
    super.paintComponent(g2);
    g2.setColor(Color.white);
    g2.drawString("Score: ", 20, 400);

}

}

PacmanGrid is also extended by a Panel and draws the classical PacmanGrid using predefined patterns. But I don't think it is relevant since the problem is clearly on the PacmanScore Panel. I will post the code if anyone needs tho. Thanks in Advance!

Upvotes: 0

Views: 84

Answers (1)

camickr
camickr

Reputation: 324118

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D)g;
    super.paintComponent(g2);
    g2.setColor(Color.white);
    g2.drawString("Score: ", 20, 400);

}

You didn't override paint() properly because you didn't invoke super.paint() and therefore the border is not painted.

Don't override paint(). Custom painting is done by overriding paintComponent().

Read the section from the Swing tutorial on A Closer Look at the Paint Mechanism for more information.

Why are you even doing custom painting? Just add a JLabel to the panel.

Also, Swing components (except for top level windows) are visible by default so there is no need to make the panel visible.

Upvotes: 1

Related Questions