简体   繁体   English

JLabel不显示在JFrame上,而仅显示在JOptionPane上

[英]JLabel not displaying on JFrame but only on JOptionPane

I'm receiving a buffered image as byte[] but when I update the icon of JLabel nothing changes on JFrame even revalidating both JFrame and JLabel. 我正在接收一个作为byte []的缓冲图像,但是当我更新JLabel的图标时,即使重新验证JFrame和JLabel,JFrame上也没有任何改变。 Instead, when I try to show the JLabel in a JOptionPane it works fine. 相反,当我尝试在JOptionPane中显示JLabel时,它可以正常工作。 I don't understand why. 我不明白为什么。 Here is the code : 这是代码:

public class ScreenMonitorServer extends JFrame
{
private String botIPAddress;
private ServerSocket serverSocket;
private Socket botSocket;
private JLabel screen;

public ScreenMonitorServer(String botIPAddress)
{
    super(botIPAddress+" - Screen Monitor");
    this.botIPAddress=botIPAddress; 
    setLayout(new FlowLayout());
    screen=new JLabel();
    add(screen);
    setVisible(true);
    try
    {
        serverSocket=new ServerSocket(54323);
        do
            botSocket=serverSocket.accept();
        while(!botSocket.getInetAddress().getHostAddress().equals(botIPAddress));
        ObjectInputStream ois=new ObjectInputStream(botSocket.getInputStream());
        while(true)
        {
            BufferedImage image;
            InputStream in=new ByteArrayInputStream((byte[])ois.readObject());
            BufferedImage bImageFromConvert=ImageIO.read(in);
            ImageIcon screenImage=new ImageIcon(bImageFromConvert);
            setSize(bImageFromConvert.getWidth(),bImageFromConvert.getHeight());
            screen.setIcon(screenImage); //black screen
            JOptionPane.showMessageDialog(null,screen);  //works fine
        }
    }   
    catch(IOException exc)
    {
        exc.printStackTrace();
    }
    catch(ClassNotFoundException exc)
    {

    }
  }
}

All Swing component can have just one parent component, so when you call JOptionPane.showMessageDialog(null,screen); 所有Swing组件只能有一个父组件,因此,当您调用JOptionPane.showMessageDialog(null,screen); you ovveride previous parent and your JLabel remove from ScreenMonitorServer . 您ovveride的上一个父级,您的JLabelScreenMonitorServer删除。

Read here . 在这里阅读。

You need to use two instance of JLabel in that case. 在这种情况下,您需要使用两个JLabel实例。

I resolved by placing the infinite loop in an other thread. 我通过将无限循环放置在另一个线程中来解决。 Thanks for the help. 谢谢您的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM