创建一个自定义面板,然后把面板添加到窗口中,面板代码:
class JPanelColor extends JPanel
{
int x,y;
Color c;
public JPanelColor()
{
x =50;
y = 50;
c = this.getBackground();
}
protected void paintComponent(Graphics g)
{
// TODO Auto-generated method stub
super.paintComponent(g);
g.setColor(c);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
g.setColor(this.getForeground());
g.drawString("welcom to java", x, y);
}
public void changeColor(Color c)
{
this.c = c;
repaint();
}
public void moveLeft(int dx)
{
x-=dx;
repaint();
}
public void moveRight(int dx)
{
x+=dx;
repaint();
}
public Dimension getPreferedSize()
{
return new Dimension(300,150);