通过使用JFrame实现了按钮功能,但自定义类线程,希望通过点击相应的按钮后实现相关线程的功能
回答:都没有说明是啥线程,那就简单创建一个线程,随便打印点内容好了
package test;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* @author bbyh
* @date 2022/12/25 0025 12:25
* @description
*/
public class Test extends JFrame {
public Test() {
JButton button = new JButton("测试");
button.addActionListener(new MyActionListener());
setLayout(new BorderLayout());
add(button, BorderLayout.CENTER);
}
private static class MyActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
new Thread(() -> {
for (int i = 0; i < 100; i++) {
System.out.println(i);
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
}
}).start();
}
}
public static void main(String[] args) {
JFrame frame = new Test();
frame.setTitle("Test");
frame.setSize(500, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
一般可以采用线程池进行线程的创建