美好的一天! 我开发程序客户端-服务器遇到一个问题,我真的不知道如何解决。
所以,我的按钮很少。单击按钮时,信息会发送到服务器,服务器会做一些工作并发送结果。按钮的监听器接收到它,然后调用必须在屏幕上绘制结果的其他类的方法。
所以,问题来了。服务器发送给我的结果很少,程序必须立即绘制它。但它不会那样做!它等到所有消息都来了,然后才得出结果。
所以我想知道如何在屏幕上即时绘制结果!
代码: 按钮的监听器:
public class ShowFrame extends JFrame
{
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
try
{
messageToServer.println("Start");
while( true )
{
fserver = answerOfServer.readLine(); //Get result from server
if ( fserver.equals("Finish") )
{
break;
}
if( fserver.equals("Busy 1") )
{
ShowFrame.this.stuff.setBusy( 1 );
}
if( fserver.equals("Busy 2") )
{
ShowFrame.this.stuff.setBusy( 2 );
}
//...Same code
}
} catch (IOException ex) {
Logger.getLogger(ShowFrame.class.getName()).log(Level.SEVERE, null, ex);
}
DrawStuff stuff = new DrawStuff();
//...
}
在屏幕上绘制结果的类:
public class DrawStuff extends JComponent
{
public DrawStuff()
{
s1 = false;
s2 = false;
s3 = false;
s4_1 = false;
s4_2 = false;
s4_3 = false;
}
@Override
public void paintComponent( Graphics g )
{
Graphics2D g2 = (Graphics2D) g;
//...
if ( s1 )
{
g2.draw(line1_of_P1);
g2.draw(line2_of_P1);
}
//...
}
public void setBusy( int i ) //If such id found then figure will be drawn by prog.
{
if ( i == 1 )
{
s1 = true;
}
else if ( i == 2 )
{
s2 = true;
}
else if ( i == 3 )
{
s3 = true;
}
else if ( i == 4 )
{
s4_1 = true;
}
else if ( i == 5 )
{
s4_2 = true;
}
else if ( i == 6 )
{
s4_3 = true;
}
this.repaint(); //DOESN'T WORK AS IT MUST!
}
//...
}
最佳答案
你在事件派发线程中执行读取,这并不好。您应该在单独的线程中执行此操作(因为它是长时间运行的任务)。参见 http://download.oracle.com/javase/tutorial/uiswing/concurrency/index.html
关于java - 无法立即用Java绘制图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6076953/