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); } @Override public 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 对象 } }
原文地址:http://blog.csdn.net/xionghui2013/article/details/45629047