에서 thread 종료와 마우스 이벤트 추가(클릭이벤트)를 해 보았습니다.
Begin 버튼을 눌러주면 Thread를 생성하여 칼럼값을 계속 바꿔줍니다.
마우스로 해당 로우를 클릭하고 finish 버튼을 눌러주면 해당 Thread가 죽습니다.
Thread.interrupt()함수를 통해서 Thread를 멈춥니다.
파일명은 final2.java 입니다.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class final2 implements MouseListener{
static int threadNumber = 0;
static JTable table;
static int row = 0;
public void Jtabletest(){
table = new JTable(new DefaultTableModel(new Object[] { "Thread Name", "Progress" , "비고"}, 0));
table.addMouseListener(this);
}
public static void main(String[] args) throws Exception {
final2 f = new final2();
f.Jtabletest();
final Vector<MyThreadClass> v = new Vector<MyThreadClass>();
JButton btnBegin = new JButton("Begin");
btnBegin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
MyThreadClass newThread = new MyThreadClass(model, threadNumber++);
// System.out.println(newThread.getName());
// System.out.println(v.size());
newThread.start();
v.add(newThread);
model.addRow(new Object[] { "Thread " + threadNumber, "!!" });
}
});
JButton btnFinish = new JButton("finish");
btnFinish.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
MyThreadClass t = (MyThreadClass)v.get(row);
//System.out.println(t.cn() + " " + t.getName());
t.interrupt();
System.out.println(row);
}
});
JFrame frame = new JFrame();
frame.add(btnBegin, BorderLayout.NORTH);
frame.add(btnFinish, BorderLayout.SOUTH);
frame.add(table);
frame.setSize(400, 400);
frame.setVisible(true);
}
static class MyThreadClass extends Thread {
private final DefaultTableModel model;
private final int threadNumber;
public MyThreadClass(DefaultTableModel model, int threadNumber) {
super();
this.model = model;
this.threadNumber = threadNumber;
}
int index = 0;
@Override
public void run() {
while(!Thread.currentThread().isInterrupted()){
model.setValueAt(index++, threadNumber, 1);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
//e.printStackTrace();
return;
}
}
}
}
@Override
public void mouseClicked(MouseEvent e) {
row = table.getSelectedRow();
//System.out.println(row);
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}