当前位置: 代码迷 >> J2SE >> 为什么小弟我JPanel设置不了背景颜色
  详细解决方案

为什么小弟我JPanel设置不了背景颜色

热度:51   发布时间:2016-04-24 00:24:01.0
为什么我JPanel设置不了背景颜色
package   com.chcbz;

import   javax.swing.JFrame;
import   javax.swing.JPanel;
import   java.awt.BasicStroke;
import   java.awt.Color;
import   java.awt.Container;
import   java.awt.Graphics2D;
import   java.awt.Graphics;


public   class   Chart   {
public   static   void   main(String[]   args){
JFrame   jf   =   new   JFrame( "Test ");
Wall   w   =   new   Wall();
Container   contentPane   =   jf.getContentPane();
contentPane.add( "Center ",w);
jf.setSize(100,100);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
}
}

class   Wall   extends   JPanel{
public   void   paint(Graphics   g){
Graphics2D   g2d   =   (Graphics2D)g;
setBackground(Color.blue);
g2d.setColor(Color.red);
g2d.setStroke(new   BasicStroke(4f,0,0));
g2d.drawRect(10,   10,   50,   50);
g2d.drawLine(10,   40,   60,   40);
g2d.drawLine(35,   10,   35,   40);
}
}
我是想将JPanel背景颜色改成黑色,而不是在JFrame设,为什么显示不了背景颜色啊?请各位高手赐教.

------解决方案--------------------
改下你那个Wall类

class Wall extends JPanel{
public void paintBorder(Graphics g){
Graphics2D g2d = (Graphics2D)g;
setBackground(Color.blue);
g2d.setColor(Color.red);
g2d.setStroke(new BasicStroke(4f,0,0));
g2d.drawRect(10, 10, 50, 50);
g2d.drawLine(10, 40, 60, 40);
g2d.drawLine(35, 10, 35, 40);
}
}
------解决方案--------------------
good
------解决方案--------------------
还有个办法,就是在你现有的代码里,加一句话: super.paint(g);

class Wall extends JPanel{
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
setBackground(Color.blue);
g2d.setColor(Color.red);
g2d.setStroke(new BasicStroke(4f,0,0));
g2d.drawRect(10, 10, 50, 50);
g2d.drawLine(10, 40, 60, 40);
g2d.drawLine(35, 10, 35, 40);
}
}



------解决方案--------------------
JPanel绘图时,不要用paint这个方法了,推荐用paintComponent(Graphics g)这个方法,使用如下:

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//绘制代码
....
// 如果设置背景不成功的话,可以试一下,先把整个panel用背景色自己绘制一下
}

下面的代码能很好的工作:

import java.awt.*;
import javax.swing.*;

public class Test extends JPanel {

public Test() {
this.setBackground(Color.BLACK);
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

// draw code
Graphics2D g2d = (Graphics2D) g;
setBackground(Color.blue);
g2d.setColor(Color.red);
g2d.setStroke(new BasicStroke(4f, 0, 0));
g2d.drawRect(10, 10, 50, 50);
g2d.drawLine(10, 40, 60, 40);
g2d.drawLine(35, 10, 35, 40);
}

private static void createUIAndShow() {
JFrame frame = new JFrame();

Test test = new Test();
frame.getContentPane().add(test);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);