public static final int DEFAULT_WIDTH = 300; public static final int DEFAULT_HEIGHT = 200; }// A panel that display a messageclass NotHelloWorldPanel extends JPanel { public void paintCompotent(Graphics g) { Graphics2D g2 = (Graphics2D)g; super.paintComponents(g);
Rectangle2D rect = new Rectangle2D.Double(10.0, 25.0, 22.5, 20.0); g.drawString("Not a hello world program!", MESSAGE_X, MESSAGE_Y); g2.draw(rect); }
public static final int MESSAGE_X = 2; public static final int MESSAGE_Y = 3; }
如果没有弄错的话,是因为你的窗体的显示部分被 NotHelloWorldPanel panel = new NotHelloWorldPanel(); 的panel遮住了,你设置背景颜色和前景颜色都是对于窗体的而不是panel的,当然显示是灰灰的啦
可是我的panel里应该有显示东西才对啊……我就奇怪为什么文本和那个矩形都不输出?
不好意思,我打错了一个地方…… public void paintCompotent(Graphics g) 应该是 public void paintComponent(Graphics g) 呵呵,真是抱歉~
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;public class NotHelloWorld
{
public static void main(String[] args)
{
NotHelloWorldFrame frame = new NotHelloWorldFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBackground(SystemColor.window);
frame.setForeground(Color.black);
frame.show();
}
}class NotHelloWorldFrame extends JFrame
{
public NotHelloWorldFrame()
{
setTitle("NotHelloWorld");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
//add panel to frame
NotHelloWorldPanel panel = new NotHelloWorldPanel();
Container contentPane = getContentPane();
contentPane.add(panel);
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
}// A panel that display a messageclass NotHelloWorldPanel extends JPanel
{
public void paintCompotent(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
super.paintComponents(g);
Rectangle2D rect = new Rectangle2D.Double(10.0, 25.0, 22.5, 20.0);
g.drawString("Not a hello world program!", MESSAGE_X, MESSAGE_Y);
g2.draw(rect);
}
public static final int MESSAGE_X = 2;
public static final int MESSAGE_Y = 3;
}
NotHelloWorldPanel panel = new NotHelloWorldPanel();
的panel遮住了,你设置背景颜色和前景颜色都是对于窗体的而不是panel的,当然显示是灰灰的啦
public void paintCompotent(Graphics g)
应该是
public void paintComponent(Graphics g)
呵呵,真是抱歉~