其实不是推箱子,就是一个相应键盘的可视化小程序。
java可视化的重绘机制很牛逼,键盘监听事件,也可以调用重绘,机制以后再研究一下。
新建一个frame的时候核心技术,提供了一种方法,用这个
EventQueue.invokeLater(new Runable()
public void run(){
SimpleFrame frame = new SimpleFrame();
frame.setDefaultCloseOperation(JFrame.Exit_ON_CLOSE);
frame.setVisible(true);
}
);
好像没啥用,不加也没事,在java的主线程(Main Thread)中是使用事务的方式来处理事件的,主线程中有一个事件队列,
当你所要做的动作将被放到主线程中处理而又不需要马上处理(或不想中断目前正在执行的事务),
则可以使用InvokeLater方法将该事务放到事件队列的最后。
让主线程自行执行。
使用InvokeLater不知道在什么时候会执行该事务,但好处是不会和其它事务起冲突。
//====================================================================================================================
SimpleFrame是一个自定义的类,
class SimpleFrame extends JFrame {
setSize(300, 300);
this.setVisible(true);
myDraw = new DrawComponent(this.getGraphics());//getGraphics()一定要在 this.setVisible(true); 之后执行,只有setVisible(true)之后才有这个上下文,不然getGraphics()会返回空指针。
add(myDraw);
this.addKeyListener(new myAdapter(this.getGraphics()));//加上键盘的监听响应
}
//===============================================================================================================
//继承自JComponent的类可以覆盖paintComponent(Graphics g)这个方法会在重绘的时候调用。
//想要在重绘的时候写点别的,可以覆盖paint(Graphics g),下面要加上 super.paint(g);
//
class DrawComponent extends JComponent {
public DrawComponent(Graphics g) {
}
@Override
public void paint(Graphics g){
super.paint(g);
paintComponent(g);
super.repaint();
}
@Override
public void paintComponent(Graphics g) {
}}
//============================================================================================
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(Color.blue); //这样设置画笔的颜色
for(int i=0;i<4;i++)
rects[i]= new Rectangle2D.Double(pos[i][0]*50,pos[i][1]*50,49,49);
for(int i=0;i<4;i++)
g2.fill(rects[i]); //fill是实心的,draw是空心的。
}
哈工大 java实验2 推箱子
最新推荐文章于 2022-11-28 08:54:02 发布