我正在用java swing制作一个应用程序。在应用程序的一个按钮中,我需要每x分钟制作一次。我认为我必须使用新线程来做到这一点,但我有两个问题。首先是我必须向这些线程传递一个参数。我用一个扩展 Thread 和构造函数的类解决了它。我认为这些方式是正确的不是吗?我无法解决的第二件事是,我需要在线程运行时更新 jtextpane,但是如果我尝试更新 JTextPane propierties Eclipse 说我无法解决。我认为问题是这些线程不是主线程。但。。。有办法解决吗?非常感谢,对不起我的英语!
代码为:
btnIniciar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//String file = "D:\prueba.torrent";
// while (true) {
Hilo ejecutar = new Hilo(listaBuscar);
ejecutar.run();
public class Hilo extends Thread {
public Hilo(List<String> aBuscar){
}
public void run(){
System.out.println("Trabajo por hacer dentro de MiHilo");
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
lblNewLabel.setText("hola");
}
});
}
}
它说我 lblNewLabel 无法解决。
有什么帮助吗?谢谢
我现在正在尝试使用这些代码,但不起作用:
public class Hilo implements Runnable {
private JLabel etiqueta;
public Hilo (List <String> aBuscar, JLabel label){
System.out.println("Hemos entrado en el puto hilo");
etiqueta = label;
}
@Override
public void run() {
etiqueta.setText("hola");
System.out.println("vamos a coneseguirlo");
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
public void run() {
etiqueta.setText("hola");
System.out.println("vamos a coneseguirlo");
}
});
}
}
使用摆动计时器。它非常像在给定间隔内定期按下的隐形按钮。它将在 Swing 线程中调用您的actionPerformed
,您可以从中操作组件(与 JButton
ActionListener
相同)。因此,您很可能不需要为此任务运行自己的线程。
- 您在问题标题中提到了
JTextPane
,但仅提及JLabel
?
虽然你看到的主要问题是你没有在你的线程范围内声明JLabel
,你可以传递你的JLabel
实例,该实例有一个方法,可以通过构造函数获取对线程JLabel
的引用,因此它有一个对JLabel
的引用, 现在没有。
- 另外,我建议使用
SwingUtilities
而不是EventQueue
- 并且不要扩展类
Thread
(除非添加自定义功能),而是implement
Runnable
像这样:
图形.java:
public class GUI {
private JFrame frame;
private JLabel label;
private JButton btnIniciar;
public void getJLabel() {
return label;
}
public void initComponents() {
//create UI and components here
btnIniciar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//String file = "D:\prueba.torrent";
Hilo ejecutar = new Hilo(listaBuscar,Gui.this);//pass reference of to our class
}
}
}
希洛.java:
public class Hilo implements Runnable {
private Thread t;
private final GUI gui;
public Hilo(List<String> aBuscar, GUI ui){
this.gui=ui;
t=new Thread(this);
startThread();
}
@Override
public void run(){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
gui.getJLabel().setText("hola");
}
});
}
//so we can start thread from other class
public void startThread() {
if(!t.isAlive()) //if the thread is not started alreade
t.start();
}
}
虽然根据你正在做什么,摆动计时器可能是你需要的,但它将允许你以间隔/延迟运行代码,所有这些都已经在EDT上完成。