无法在Java中为JPanel设置颜色

问题描述 投票:1回答:3

我刚开始使用java中的Graphics,我已经卡住了。我试图将JPanel的颜色设置为红色,但似乎没有任何效果!任何帮助都非常感谢。

JFrame类:

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类:

   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);

     }
  }

正如您所看到的,我已经尝试在JFrame类和JPanel类中声明颜色,但它们似乎都不起作用。谢谢!

java swing jpanel
3个回答
0
投票

这里的每个人似乎都错过了在绘图之前应该设置颜色的事实。

为了演示目的,我将主背景设置为BLUE。

public static void main(String[] args) {
    //...
    JPanel p = new redBoxPanel();
    // BLUE bg. This covers the whole panel.
    p.setBackground(Color.BLUE);
    //...
}

而现在红色的盒子!

public static class redBoxPanel extends JPanel {
    @Override public void paintComponent(Graphics g) {
        // You need to call the superclass' paintComponent() so that the 
        // setBackground() you called in main() is painted.
        super.paintComponent(g);

        // You need to set the colour BEFORE drawing your rect
        g.setColor(Color.RED);

        // Now that we have a colour, perform the drawing
        g.fillRect(0, 0, 100, 100);

        // More, for fun
        g.setColor(Color.GREEN);
        g.drawLine(0, 0, 100, 100);
    }
}

0
投票

我认为你在paintComponent方法中缺少qazxsw poi。


0
投票

我相信解决方案正在运行,但就像您在问题中所说的那样,在JFrame类和JPanel类中设置背景。如果从JFrame类中删除setBackground,则应该只看到要绘制的矩形。请尝试以下解决方案,并告知我们是否有效。

JFrame类:

super.paintComponent(g);

JPanel类:

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();
        f.add(p);
        f.setVisible(true);
  }

} 
© www.soinside.com 2019 - 2024. All rights reserved.