📄 ball.java
字号:
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.util.EventListener;
class MyPanel extends JPanel implements ActionListener,KeyListener
{
private int x,y;
private int xsteep=2;
private int ysteep=2;
private int xr=200;
private int yr=400;
private int rsteep=2;
public JButton mb1=new JButton("开始");
public JButton mb2=new JButton("停止");
Timer t=new Timer(2,this);
Timer t1=new Timer(2,this);
MyPanel (){
mb1.addActionListener(this);
mb2.addActionListener(this);
this.addKeyListener(this);
}
public void paintComponent(Graphics g)
{
Graphics2D g2d=(Graphics2D)g;
super.paintComponent(g2d);
this.requestFocus(true);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.red);
g2d.fillOval(x,y,20,20);
g2d.setColor(Color.green);
g2d.fillRect(xr,yr,100,20);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==mb1)
t.start();
else if(e.getSource()==mb2)
t.stop();
else if(e.getSource()==t)
{
x+=xsteep;
y+=ysteep;
//右
if(x+20>=this.getWidth())
xsteep=-xsteep;
//左
if(x<=0)
xsteep=-xsteep;
//与挡板相撞
if((y==yr-20)&&(x>=xr-10)&&(x<=xr+90))
{
ysteep=-ysteep;
// System.out.println ("yr="+yr);
// System.out.println ("xr="+xr);
}
//下
else if(y+20>=this.getHeight())
ysteep=-ysteep;
// else
// {if(y+20>=this.getHeight())
// ysteep=-ysteep;
// }
if(y<=0)
ysteep=-ysteep;
this.repaint();
}
else if(e.getSource()==t1)
{
xr-=rsteep;
System.out.println ("xr="+xr);
if(xr<=0)
rsteep=-rsteep;
if(xr+100>=this.getWidth())
rsteep=-rsteep;
this.repaint();
}
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e)
{
// System.out.println (e.getKeyCode());
t1.start();
}
public void keyReleased(KeyEvent e)
{
t1.stop();
}
}
public class Ball extends JFrame{
JPanel mpl=new JPanel();
MyPanel mp=new MyPanel();
public Ball() {
this.setSize(500,500);
this.setLocation(60,20);
this.setDefaultCloseOperation(3);
mpl.add(mp.mb1);
mpl.add(mp.mb2);
mpl.setBackground(Color.gray);
this.add(mpl,"North");
this.add(mp);
this.setVisible(true);
}
public static void main (String[] args) {
new Ball();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -