效果图如下:
CMain函数:
package com.shubing.main; public class CMain
{
public static void main(String[] args)
{
MainFrame mainFrame = new MainFrame();
mainFrame.setVisible(true);
}
}
MainFrame函数:
package com.shubing.main; import java.awt.*;
import java.awt.event.*;
import javax.swing.*; public class MainFrame extends JFrame implements ActionListener
{
public static boolean flag = false;
public JButton enter = new JButton("确定");
public JButton exit = new JButton("退出");
public JLabel text = new JLabel("点名");
public JLabel name = new JLabel("姓名");
public String[] nameList = {"王一","刘二","赵三","周四","马五","龙六","张七","贾八","钟九"};
public JLabel message = new JLabel("学生总数:"+nameList.length);
public EnterThread mainThread = null;
public MainFrame()
{
this.setTitle("点名系统");
this.setSize(,);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setLayout(null); //布局为空;
this.setFocusable(false); text.setBounds(, , , );
name.setBounds(, , , );
enter.setBounds(, , , );
exit.setBounds(, , , );
message.setBounds(, , , ); this.add(text);
this.add(name);
this.add(enter);
this.add(exit);
this.add(message); enter.setEnabled(true);
exit.setEnabled(false); Font font = new Font("华文行楷",Font.BOLD,);
this.text.setFont(font);
this.name.setFont(font); enter.addActionListener(this);
exit.addActionListener(this);
} @Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == enter)
{
mainThread = new EnterThread(this);
mainThread.start();
enter.setEnabled(false);
exit.setEnabled(true);
}
if(e.getSource() == exit)
{
new ExitThread(this).start();
exit.setEnabled(false);
} } }
EnterThread函数:
package com.shubing.main; public class EnterThread extends Thread
{
private MainFrame mainFrame = null;
private boolean isStop = true;
public int time = ; public EnterThread(MainFrame mainFrame)
{
this.mainFrame = mainFrame;
}
public void stopThread()
{
this.isStop = false;
}
public void run()
{
try
{
int index = ;
while(isStop)
{
if(index == this.mainFrame.nameList.length)
{
index = ;
}
this.mainFrame.name.setText(mainFrame.nameList[index]);
index ++; Thread.sleep(time);
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
this.mainFrame.enter.setEnabled(true);
}
}
ExitThread函数:
package com.shubing.main; public class ExitThread extends Thread
{
private MainFrame mainFrame = null; public ExitThread(MainFrame mainFrame)
{
this.mainFrame = mainFrame;
} public void run()
{
try
{
for(int i=;i<=;i+=)
{
this.mainFrame.mainThread.time += i;
sleep();
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
mainFrame.mainThread.stopThread();
}
}