本程序基于下面教材的例程修改
尉哲明,冀素琴,郭珉. 基于Java的综合课程设计. 北京: 清华大学出版社, 2014(12).
案例:两按钮反向运动——使用Thread子类
案例问题描述
创建一个GUI程序,当单击“开始”按钮,界面中的两个按钮开始朝相反方向运动,单击“停止”按钮,两按钮同时停止运动。要求通过Thread类的子类来实现多线程,再现两按钮反向运动的情景。
案例练习题目
(1)为该应用程序增加一个功能,用户可以控制按钮移动的速度(让用户可以控制按钮两次移动之间的时间间隔)。
(2)读者可以看到,本程序中有一些代码是重复的,请读者重新编写本案例,减少代码的重复率,仍用Thread的子类来实现线程。
//12_1_1
//12_1_2
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class MoveButtonWindow extends JFrame implements ActionListener
{
JButton startButton,stopButton,exitButton;
JButton rightButton,leftButton;
move right,left;
JButton accelerationButton,decelerationButton;
//构造方法,完成窗口的初始化
public MoveButtonWindow()
{
setTitle("测试多线程主窗口");
JPanel centerPanel=new JPanel();
JPanel controlPanel=new JPanel();
add(centerPanel,BorderLayout.CENTER );
add(controlPanel,BorderLayout.SOUTH );
startButton=new JButton("开始/继续");
startButton.addActionListener(this);
stopButton=new JButton("停止");
stopButton.addActionListener(this);
exitButton=new JButton("退出");
exitButton.addActionListener(this);
accelerationButton=new JButton("加速");
accelerationButton.addActionListener(this);
decelerationButton=new JButton("减速");
decelerationButton.addActionListener(this);
controlPanel.add(this.startButton );
controlPanel.add(this.stopButton );
controlPanel.add(this.exitButton );
controlPanel.add(this.accelerationButton);
controlPanel.add(this.decelerationButton);
centerPanel.setLayout(null);
centerPanel.setBackground(Color.white );
rightButton=new JButton("向右移动");
rightButton.setBackground(Color.yellow );
rightButton.setBounds(0, 5, 100, 30);
leftButton=new JButton("向左移动");
leftButton.setBackground(Color.red );
leftButton.setBounds(385,90,100,30);
centerPanel.add(rightButton);
centerPanel.add(leftButton);
right=new move(rightButton,5);
left=new move(leftButton,-5);
setBounds(100,100,500,200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
this.setResizable(false);
setVisible(true);
validate();
}
@Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==this.startButton )
{
if(!right.isAlive())
{
int i=right.getDistance();
right=new move(rightButton,i);
}
if(!left.isAlive())
{
int i=left.getDistance();
left=new move(leftButton,i);
}
right.start();
left.start();
}
else if(e.getSource()==this.stopButton)
{
right.setBoo(false);
left.setBoo(false);
}
else if(e.getSource()==this.exitButton)
{
right.setBoo(false);
left.setBoo(false);
System.exit(0);
}
else if(e.getSource()==this.accelerationButton)
{
int i=right.getTime()-20;
right.setTime(i);
int j=left.getTime()-20;
left.setTime(i);
}
else if(e.getSource()==this.decelerationButton)
{
int i=right.getTime()+20;
right.setTime(i);
int j=left.getTime()+20;
left.setTime(i);
}
}
public static void main(String[] args)
{
new MoveButton