package chapt7;
import java.awt.*;
import javax.swing.*;
public class NotHelloWorld {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
EventQueue.invokeLater(new Runnable()
{
public void run()
{
NotHelloWorldFrame frame=new NotHelloWorldFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
);
}
}
class NotHelloWorldPanel extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2=(Graphics2D)g;
g2.drawString("not hello world", MESSAGE_X, MESSAGE_Y);
Font sansbold14=new Font("SansSerif",Font.BOLD,14);
g2.setFont(sansbold14);
String message="hello world";
g2.drawString(message, 175, 100);
}
public static final int MESSAGE_X=75;
public static final int MESSAGE_Y=100;
}
class NotHelloWorldFrame extends JFrame
{
public NotHelloWorldFrame()
{
setTitle("NotHelloWorld");
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
NotHelloWorldPanel panel=new NotHelloWorldPanel();
[color=red]panel.setBackground(Color.red);[/color]
add(panel);
}
public static final int DEFAULT_WIDTH=300;
public static final int DEFAULT_HEIGHT=300;
}
红色字体是要添加背景色的语句,为什么添加不上呢?NotHelloWorldPanel类是容器吗?我对容器还不了解
将你的NotHelloWorldPanel的实现改成:
class NotHelloWorldPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.drawString("not hello world", MESSAGE_X, MESSAGE_Y);
Font sansbold14 = new Font("SansSerif", Font.BOLD, 14);
g2.setFont(sansbold14);
String message = "hello world";
g2.drawString(message, 175, 100);
}
public static final int MESSAGE_X = 75;
public static final int MESSAGE_Y = 100;
}
并且注意调用了父类的super.paintComponent(g);方法, 如果人直接继承JComponent, 就要自己处理opaque属性了,具体的人可以看paintComponent(g)方法的Java Doc