本人新手,做了一个小球撞击边框的动画面板,又下面加了个面板显示两个按钮.但只显示小球运动的面板,不能显示背景颜色,按钮什么的.代码语法无错误,问了懂的人也不能解释为何,还请高手解释 
代码如下: 
import java.awt.*; 
import javax.swing.*; 
import javax.swing.border.*; 
public class runball extends JFrame 

//定义小球运动所需变量 
int x=0,y=0,with=50,high=50; 
int xh=10,yh=10; 
int xs=1,ys=1; 
//p1为显示按钮面板 
JPanel p1=new JPanel(); 
//p2为显示小球运动面板 
JPanel p2=new JPanel(); public runball() 

super("小球滚动效果"); 
this.setSize(800,600); 
this.setVisible(true); 
this.setBackground(Color.CYAN); 
this.setDefaultCloseOperation(EXIT_ON_CLOSE); 
this.add(p1,java.awt.BorderLayout.SOUTH); 
this.add(p2,java.awt.BorderLayout.CENTER); p1.setBackground(Color.BLUE); 
FlowLayout g1=new FlowLayout(); 
p1.setLayout(g1); 
JButton b1=new JButton("开始滚动");  
JButton b2=new JButton("停止滚动");  
p1.add(b1); 
p1.add(b2); p2.setBorder(new TitledBorder(BorderFactory.createEtchedBorder(),"窗口")); 
p2.setBackground(Color.LIGHT_GRAY); 

public static void main(String args[]) 

runball ff=new runball(); 

//小球运动方法 
public void paint(Graphics g) 

Graphics gh=p2.getGraphics(); 
gh.setColor(Color.red); 
gh.fillOval(x, y, with, high); 
//小球运动 
x=x+2*xh*xs; 
y=y+yh*ys; 
//碰撞后改变方向 
if(((x+with)>p2.getWidth())||(x <0)) xs=-1*xs; 
if(((y+high)>p2.getHeight())||(y <0)) ys=-1*ys; try 

Thread.sleep(41); 

catch(InterruptedException e){} //重绘 
gh.setColor(Color.white); 
gh.fillRect(0, 0, p2.getWidth(), p2.getHeight()); 
repaint(); 
} } 

解决方案 »

  1.   

    通过paint方法貌似是不可行的 即使是通过获得目标组件的Graphics Context
    要用JPanel的paintComponent方法 构造一个自定义的JPanel 将画图操作置于重写的paintComponent方法中
      

  2.   

    我补充一下,代码复制到论坛上后
    if(((x+with)>p2.getWidth()) ¦ ¦(x  <0)) xs=-1*xs;  
    if(((y+high)>p2.getHeight()) ¦ ¦(y  <0)) ys=-1*ys;
    这两句中的“逻辑或”改为 Unicode码了,保存到记事本时要重输入才行
      

  3.   

    这里有你的问题的详细解答
    http://topic.csdn.net/u/20111028/13/ed32a977-284b-402b-8a89-59a227abf64f.html