有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JFrames中的java多线程

我想在我的JFrame上显示一个图像和一些文本,使它们能够一部分一部分地同时显示。我已经实现了它,但无法以正确的方式执行它。有没有人能帮我解决这个问题,在图像的某个部分之后,一些文本应该显示出来,然后是图像,然后是文本,直到我的要求,但是在一个单独的框架中。 Thnx

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Show1 extends JFrame implements Runnable
{
ImageIcon i1;
JLabel j1;
Thread t;
JTextField jt;
boolean value=true;
 Show1()
 {

  setSize(1100,800);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().setBackground(Color.black);
setLayout(null);
i1=new ImageIcon("Sunset.jpg");
j1=new JLabel("",i1,JLabel.CENTER);

jt=new JTextField(50);
jt.setBounds(250,750,100,50);
t=new Thread(this,"Main");
/*   try
     {
       SwingUtilities.invokeLater(
        new Runnable()
         {
           public void run()
            {
              makeGUI();
    makeGSI();
             }
         });
     }
    catch(Exception exc)
     {
       System.out.println("can't create because of"+exc);
      }
   }

private void makeGUI()
{*/


while(!value)
{
new Thread(this,"Image").start;

public void run()
{
int i,j;
try
{
for(i=-50;i<=500;i+=50)
{
j1.setBounds(200,100,700,i);
add(j1);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}




public void makeGSI()
{
t1=new Thread(this,"Message");
t1.setPriority(4);
t1.start();
}
public void run()
{
try
{
String msg[]={"Customer"," Care"," Services"};
int x=msg.length;
for(int i=0;i<=x-1;i++)
{
jt.setText(msg[i]);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}
class Show
{
public static void main(String args[])
{
Show1 sh=new Show1();

}}

共 (2) 个答案

  1. # 1 楼答案

    您可能需要使用SwingWorker

    • 在一个线程中加载图像,然后
    • 将框架设置为在AWT线程上可见

    描述SwingWorker

  2. # 2 楼答案

    不管你想在那里做什么(我仍然不太明白它到底是什么),Swing不允许从多个线程更新UI。您必须确保只有AWT事件调度器线程会更新到UI

    SwingUtilities中有invokeAndWait(Runnable)invokeLater(Runnable)等助手方法可以帮助实现这一点