java 用swing、ActionListener类画的圆到边框可以弹回、可以控制开始/停止的小程序
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class SimpleCarton2{
JFrame frame;
MyPanel figurePanel; //the container displays the move of figure
JPanel controlPanel; //the container which contains the control buttons
JButton startOrStopButton;
int x = 50; //the start x coordinate
int y = 50; //the start y coordinate
boolean startOrStop = false; // if ture,figure moves;if false,figure stops
boolean xMinus = false; //if true,minus
boolean xAdd = true;//if true,add;initialize with true,the oval can move
boolean yMinus = false; //if true,minus
boolean yAdd = true;//if true,add;initialize with true,the oval can move
int w = 50;//the width of oval
int h = 50;//the height of oval
public static void main(String[] args){
SimpleCarton2 sc = new SimpleCarton2();
sc.setGUI();
sc.go();
}
public void setGUI(){ //initialize the GUI
frame = new JFrame("Simple Carton2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
figurePanel = new MyPanel();
frame.getContentPane().add(BorderLayout.CENTER, figurePanel);
controlPanel = new JPanel();
controlPanel.setBackground(Color.darkGray);
startOrStopButton = new JButton("start");
startOrStopButton.addActionListener(new StartOrStopListener());
controlPanel.add(startOrStopButton);
frame.getContentPane().add(BorderLayout.EAST, controlPanel);
frame.setSize(700, 700);
frame.setVisible(true);
}
public void go(){ //change the coordinate and repaint the figure
while(true){
figurePanel.repaint(); // paint the start figure and medial figure
while(startOrStop){ //if true,continue to paint;if false,stop
changeCoordinate();
figurePanel.repaint();
try{
Thread.sleep(50); //program delay 50 milliseconds every time
}catch(Exception ex){ }
}
}
}
public void changeCoordinate(){
if(x >= (figurePanel.getWidth()-w)){ //oval moves to the right border
xMinus = true;
xAdd = false;
}
if(x <= 0){ //oval moves to the left border
xAdd = true;
xMinus = false;
}
if(xMinus == true){
x--;
}
if(xAdd == true){
x++;
}
if(y >= (figurePanel.getHeight()-h)){ //oval moves to the bottom
yMinus = true;
yAdd = false;
}
if(y <= 0){ //oval moves to the top
yAdd = true;
yMinus = false;
}
if(yMinus == true){
y--;
}
if(yAdd == true){
y++ ;
}
}
public class StartOrStopListener implements ActionListener{
public void actionPerformed(ActionEvent a){
if(startOrStopButton.getText().equals("start")){ //click start
startOrStop = true;
startOrStopButton.setText("stop");
}else if(startOrStopButton.getText().equals("stop")){ //click stop
startOrStop = false;
startOrStopButton.setText("start");
}
}
}
class MyPanel extends JPanel{
public void paintComponent(Graphics g){
//before each repaint,set background to be white so as to erase the last time imprint
g.setColor(Color.white);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
//use the new coordinate to repaint new figure
g.setColor(Color.red);
g.fillOval(x, y, w, h);
}
}
}
因为图像是移动的,不方便截图展示,大家可以自己运行一下看看