JAVA是支持多线程的,可SWING大部分是单线程的。游戏是离不开多线程的,可游戏同样也需要可视化界面。当我们做一些小游戏时同时用动线程与SWING了就可能带来一些麻烦,最起码不能在线程中调用Label.setText()之类的语句。我现在用两种方式间接缓解了一部分问题,比如用TIMER。如下面的例子
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class ThreadTest extends JFrame
{
JPanel jpnz=new JPanel(new BorderLayout());
JPanel jpns=new JPanel(new FlowLayout());
JPanel jpnx=new JPanel(new FlowLayout());
JTextField jf=new JTextField(20);
JButton jbtn=new JButton( "start ");
ThreadTest()
{
try
{
jInit();
}
catch(Exception e)
{
e.getStackTrace();
}
}
public void jInit() throws Exception
{
getContentPane().add(jpnz);
jpnz.add(jpns,BorderLayout.NORTH);
jpnz.add(jpnx,BorderLayout.SOUTH);
jpns.add(jf);
jpnx.add(jbtn);
Jtp jtp=new Jtp();
jbtn.addActionListener(jtp);
}
ActionListener al;
public static void main(String[] args)
{
try
{
final ThreadTest tt=new ThreadTest();
tt.setSize(300,200);
tt.setVisible(true);
tt.setLocation(300,200);
tt.jf.setText( "hello ");
tt.al=new ActionListener()
{
Random rdm=new Random();
public void actionPerformed(ActionEvent ae)
{
tt.jf.setText(String.valueOf(rdm.nextInt(10)));
}
};
final javax.swing.Timer t=new javax.swing.Timer(100,tt.al);
t.start();
ActionListener al2=new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if(tt.jbtn.getText().equals( "stop "))
{
t.stop();
}
else
{
t.start();
}
}
};
javax.swing.Timer t2=new javax.swing.Timer(100,al2);
t2.start();
}
catch(Exception e)
{
e.getStackTrace();