首页 > 解决方案 > Can't set color to JPanel in Java

问题描述

I have just started with Graphics in java, and I'm already stuck. I have tried to set the color of the JPanel to red but nothing seems to work! Any help is highly appreciated.

JFrame class:

import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.Color;


public class redBoxFrame{

    public static void main(String[]args){
        JFrame f = new JFrame();
        f.setSize(400, 200);
        f.setTitle("A red box");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel p = new redBoxPanel();
        p.setBackground(Color.RED);
        f.add(p);
        f.setVisible(true);
  }

} 

JPanel class:

   import java.awt.Graphics;
   import javax.swing.JPanel;
   import java.awt.Color;

  public class redBoxPanel extends JPanel {

     public void paintComponent(Graphics g){
     g.fillRect(0, 0, 100, 100);
     g.setColor(Color.RED);

     }
  }

As you can see I have both tried to declare the color in the JFrame class and in the JPanel class but none of them seem to work. Thank you!

标签: javaswingjpanel

解决方案


I think you you are missing super.paintComponent(g); in your painComponent method.


推荐阅读