CSDN上的高手哪去了?怎么提问过没人解答啊?

generalxu 2008-04-19 10:02:40
本人新手,做了一个小球撞击边框的动画面板,又下面加了个面板显示两个按钮.但只显示小球运动的面板,不能显示背景颜色,按钮什么的.代码语法无错误,问了懂的人也不能解释为何,还请高手解释
代码如下:
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();
}

}
...全文
97 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
数据流 2011-10-28
  • 打赏
  • 举报
回复
这里有你的问题的详细解答
http://topic.csdn.net/u/20111028/13/ed32a977-284b-402b-8a89-59a227abf64f.html
generalxu 2008-04-19
  • 打赏
  • 举报
回复
我补充一下,代码复制到论坛上后
if(((x+with)>p2.getWidth()) ¦ ¦(x <0)) xs=-1*xs;
if(((y+high)>p2.getHeight()) ¦ ¦(y <0)) ys=-1*ys;
这两句中的“逻辑或”改为 Unicode码了,保存到记事本时要重输入才行
dracularking 2008-04-19
  • 打赏
  • 举报
回复
通过paint方法貌似是不可行的 即使是通过获得目标组件的Graphics Context
要用JPanel的paintComponent方法 构造一个自定义的JPanel 将画图操作置于重写的paintComponent方法中

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧