我通过套接字获取图像。现在,我实际上得到了它,但只有我想象的一次。
我已经检查了一些可以添加事件的类,例如 ImageReader ,但它不会与我的 JFrame 通信。当我完成框架时,它似乎根本没有更新。
服务器:
public static void main(String[] args) {
try {
DefaultWindow window = new DefaultWindow();
window.frame.setVisible(true);
ServerSocket ss = new ServerSocket(4305);
Socket cs = ss.accept(); // only 1 client is assumed
// this bit should be in some sort of complete event
BufferedImage bi = ImageIO.read(cs.getInputStream());
window.image.setIcon(new ImageIcon(bi));
window.frame.validate();
window.frame.repaint();
} catch (Exception e) {
e.printStackTrace();
}
}
我该怎么办?什么是最佳做法?
编辑11-11-11 16:19
我遵循了mKorbel的回答,似乎效果更好,但我仍然遇到错误。
我的客户端脚本:
public static void main(String[] args) {
try {
Socket cs = new Socket(InetAddress.getByName("localhost"), 4305);
OutputStream os = cs.getOutputStream();
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
BufferedImage[] screenshots = new BufferedImage[gs.length];
DisplayMode mode;
Rectangle bounds;
while(true) {
try {
for(int i = 0; i < gs.length; i++)
{
mode = gs[i].getDisplayMode();
bounds = new Rectangle(0, 0, mode.getWidth(), mode.getHeight());
screenshots[i] = new Robot(gs[i]).createScreenCapture(bounds);
}
if(screenshots[0] != null) {
ImageIO.write(screenshots[0], "png", os);
}
os.flush();
Thread.sleep(500);
} catch (AWTException e) {
} catch (InterruptedException e) {}
}
} catch(IOException e) {}
}
我在这一行得到一个IndexOutOfBoundsException:ImageIO.write(screenshots[0], "png", os);
我将输出写入输出流。
似乎while循环只运行了3次。为什么只有3次?为什么它会产生IndexOutOfBoundsException?
编辑11-11-11 16:38
似乎我已经对它进行了排序,但是,我的标签不会更新。有什么想法吗?
服务器:
public static void main(String[] args) {
try {
final DefaultWindow window = new DefaultWindow();
window.frame.setVisible(true);
ServerSocket ss = new ServerSocket(4305);
final Socket cs = ss.accept();
SwingWorker<ImageIcon, Void> sw = new SwingWorker<ImageIcon, Void>() {
BufferedImage bi = ImageIO.read(cs.getInputStream());
BufferedImage bis;
Graphics2D graphics2D;
ImageIcon icon = null;
@Override
protected ImageIcon doInBackground() throws Exception {
bis = new BufferedImage(window.image.getWidth(), window.image.getHeight(), BufferedImage.TYPE_INT_ARGB);
graphics2D = bis.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(bi, 0, 0, window.image.getWidth(), window.image.getHeight(), null);
graphics2D.dispose();
if(icon != null) {
icon.getImage().flush();
}
icon = new ImageIcon(bis);
return icon;
}
protected void done() {
window.image.setIcon(icon);
window.frame.validate();
window.frame.repaint();
}
};
sw.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
答案 0 :(得分:2)
因为Concurency in Swing存在一些问题,请将其添加到后台任务
SwingWorker,教程中的similair示例,在这种情况下,GUI仍然可以访问,并且不等待任务结束
Runnable#Thread
,但输出到GUI必须包装到invokeLater()
,在这种情况下,GUI仍然可以访问,并且不等待任务结束
简单包装到invokeLater()
,但在这种情况下,GUI冻结是不可访问的并且等待任务结束,但这种方式是错误的,根本不这样做