gpt4 book ai didi

java - 通过线程访问父类对象

转载 作者:行者123 更新时间:2023-12-02 08:14:05 26 4
gpt4 key购买 nike

我的问题是,在我的代码中,我在主类中创建了一个 JTable。现在我正在创建一个线程来执行一些任务并收集一些数据,我想在线程收集数据后立即将其填充到 JTable 中。该线程应该运行一段时间。那么我可以通过创建的线程访问主类的JTable吗?

编辑:我在这里提供我的代码。

测试.java

package test;


import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;

public class Test implements ActionListener {

Thread t;
JTable table;
JScrollPane scrollPane;
JButton b;
JFrame frame;


public void body() {

frame = new JFrame("TableDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());

table = new JTable(new MyTableModel());
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);

scrollPane = new JScrollPane(table);
frame.add(scrollPane);

b = new JButton("OK");
frame.add(b);

thread a = new thread(new MyTableModel());
t = new Thread(a);

frame.pack();
frame.setVisible(true);

b.addActionListener(this);

}


public static void main(String[] args) {

new Test().body();

}


@Override
public void actionPerformed(ActionEvent e) {

t.start();

}
}


class MyTableModel extends AbstractTableModel {

private String[] columnNames = {
"First Name",
"Last Name",
"Sport"
};

private Object[][] data = {
{
"a",
"a",
"a"
}
};

@Override
public int getColumnCount() {
return columnNames.length;
}

public int getRowCount() {
return data.length;
}

public String getColumnName(int col) {
return columnNames[col];
}

public Object getValueAt(int row, int col) {
return data[row][col];
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public boolean isCellEditable(int row, int col) {
if (col < 3) {
return false;
} else {
return true;
}
}
public void setValueAt(Object value, int row, int col) {
data[row][col] = value;
fireTableCellUpdated(row, col);
}

}

thread.java

package test;

public class thread implements Runnable {

MyTableModel model;

thread(MyTableModel model){
this.model = model;
}

@Override
public void run() {
Object aa = "new value";
this.model.setValueAt(aa, 0, 0);
System.out.println(this.model.getValueAt(0, 0));
}

}

我真正想要的是JTable显示屏上0,0处的值应该从“a”更改为“新值”。

请提供一些帮助。

最佳答案

当你创建一个线程时,你实际上创建了一个 Runnable 类,可以通过扩展 Thread 或实现 Runnable。所以你将拥有自己的类,例如这样

 MyClass implements Runnable {
public void run() { ... your work here ... }
}

只需将您喜欢的任何对象传递给此类的构造函数

 MyClass implements Runnable {


JTable m_jtable;

public MyClass( JTable theTable ) { m_jtable = theTable; }

public void run() { do things with m_jtable }
}

关于java - 通过线程访问父类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6772328/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com