線程基礎,滾動字,“尼瑪炸了!!!”有BUG請大嬸指出,尼瑪bug
import java.awt.FlowLayout;import java.awt.GridLayout;import java.awt.Panel;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JTextField;import sun.org.mozilla.javascript.internal.regexp.SubString;public class WelcomeJFrame extends JFrame {private class RollbyJPanel extends JPanel implements ActionListener,Runnable {JTextField tw, tSleep, ts;int sleeptime; // 睡眠時間JButton btnS, btnI; // 啟動按鈕和中止按鈕Thread t; // 線程RollbyJPanel(String str) {this.setLayout(new GridLayout(2, 1));char[] space = new char[60];tw = new JTextField(str + new String(space)); // 若是“Welcome”,則這個結果為“welcome// ”;this.add(tw);JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));this.add(p);p.add(new JLabel("sleep"));this.sleeptime = (int) (Math.random() * 100); // 用隨機數初始化睡眠時間tSleep = new JTextField("" + sleeptime, 5);p.add(tSleep);tSleep.addActionListener(this); // 監聽t = new Thread(this);btnS = new JButton("開始");btnI = new JButton("中止");btnS.addActionListener(this);btnI.addActionListener(this);p.add(btnS);p.add(btnI);}@Overridepublic void actionPerformed(ActionEvent e) { // 相應事件if (e.getSource() == tSleep) {setSleeptime(); // 設定睡眠時間}if (e.getSource() == btnS) { // 啟動線程t = new Thread(this);setSleeptime();t.start();btnS.setEnabled(false); // 摁下後使開始按鈕變成不可操作btnI.setEnabled(true); // 摁下後使中止按鈕變成可操作}if (e.getSource() == btnI) {t.interrupt(); // 中止線程btnS.setEnabled(true); // 摁下後使開始按鈕變成可操作btnI.setEnabled(false); // 摁下後使中止按鈕變成不可操作}}private void setSleeptime() {try { // 一定要捕獲異常sleeptime = Integer.parseInt(tSleep.getText()); // 從tSleep中獲得睡眠時間} catch (NumberFormatException e1) {JOptionPane.showMessageDialog(this, "你媽炸了!!!"); // 彈出對話方塊}}public void run() { //實現滾動字while (true) {String str = tw.getText();str = str.substring(1) + str.substring(0, 1); tw.setText(str);try {Thread.sleep(sleeptime);} catch (InterruptedException e) {break;}}}}public WelcomeJFrame(String[] str) {super("滾動字");this.setBounds(500, 100, 400, 400);this.setDefaultCloseOperation(EXIT_ON_CLOSE);if (str == null || str.length == 0) { // 防止輸入為空白this.getContentPane().add(new RollbyJPanel("Welcome")); // 為空白,則初始顯示“Welcome”} else {for (int i = 0; i < str.length; i++) {this.getContentPane().setLayout(new GridLayout(str.length, 2));this.getContentPane().add(new RollbyJPanel(str[i]));}}this.setVisible(true);}public static void main(String[] args) {String[] str = { "你媽炸了!!!", "你媽炸了??", "你媽真炸了", "你媽炸了哦" }; // 需要滾動的字new WelcomeJFrame(str); // new 對象}}