我想做一个东西,显示网络接收到的数据,每次发送的数据都是4个int类型的数,然后有四个progressBar显示。收到一个Socket连接后我想通过Swing的界面显示出来,而连接的Socket的东西我单独做到一个类里面,而且做了线程。因为前面相当一个服务器,对处理Socket连接做了一个线程,而这个线程里面的run方法中只要一调用Swing中的组件(比如JProgressBar)就抛出线程异常。曾经看到有帖子说用户线程访问Swing线程中的东西就会抛异常……那如何才能做到用户线程访问Swing主线程中的组件呢?
谁有类似的可运行代码?:) 保证一个星期内揭帖,大家多多帮忙.
------解决方案--------------------
JProgressBar并不是同步的~抛的社么异常~LZ贴出来~
随便贴个例子,LZ看看有没有用~~不太明白LZ想要社么效果
/**
@version 1.03 2004-08-22
@author Cay Horstmann
*/
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.Timer;
/**
This program demonstrates the use of a progress bar
to monitor the progress of a thread.
*/
public class ProgressBarTest
{
public static void main(String[] args)
{
JFrame frame = new ProgressBarFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
/**
A frame that contains a button to launch a simulated activity,
a progress bar, and a text area for the activity output.
*/
class ProgressBarFrame extends JFrame
{
public ProgressBarFrame()
{
setTitle( "ProgressBarTest ");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// this text area holds the activity output
textArea = new JTextArea();
// set up panel with button and progress bar
JPanel panel = new JPanel();
startButton = new JButton( "Start ");
progressBar = new JProgressBar();
progressBar.setStringPainted(true);
panel.add(startButton);
panel.add(progressBar);
checkBox = new JCheckBox( "indeterminate ");
checkBox.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
progressBar.setIndeterminate(checkBox.isSelected());
}
});
panel.add(checkBox);
add(new JScrollPane(textArea), BorderLayout.CENTER);
add(panel, BorderLayout.SOUTH);
// set up the button action
startButton.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
progressBar.setMaximum(1000);
activity = new SimulatedActivity(1000);
new Thread(activity).start();
activityMonitor.start();
startButton.setEnabled(false);
}
});
// set up the timer action
activityMonitor = new Timer(500, new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
int current = activity.getCurrent();
// show progress
textArea.append(current + "\n ");
progressBar.setStringPainted(!progressBar.isIndeterminate());
progressBar.setValue(current);
// check if task is completed
if (current == activity.getTarget())
{
activityMonitor.stop();
startButton.setEnabled(true);
}
}
});
}
private Timer activityMonitor;
private JButton startButton;