0
我需要製作一段文字,沿着頁面滾動,將每個字母從一個標籤移動到另一個標籤。這是我的代碼到目前爲止。它需要一個延遲,因爲它太快了,但當字符串結束時它似乎會崩潰。任何幫助,將不勝感激?。JLabel滾動文本
package Lab4;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class Scroll extends JFrame implements ActionListener {
final int scrollNumber = 10;
JTextField inputTextField = new JTextField(10);
JLabel[] output = new JLabel[scrollNumber];
JLabel text = new JLabel("Enter text and press Return",
SwingConstants.CENTER);
public Scroll() {
setLayout(new GridLayout(2, 1));
JPanel row1 = new JPanel(new GridLayout(1, 10));
output[0] = new JLabel();
output[1] = new JLabel();
output[2] = new JLabel();
output[3] = new JLabel();
output[4] = new JLabel();
output[5] = new JLabel();
output[6] = new JLabel();
output[7] = new JLabel();
output[8] = new JLabel();
output[9] = new JLabel();
row1.add(output[9]);
row1.add(output[8]);
row1.add(output[7]);
row1.add(output[6]);
row1.add(output[5]);
row1.add(output[4]);
row1.add(output[3]);
row1.add(output[2]);
row1.add(output[1]);
row1.add(output[0]);
add(row1);
JPanel row2 = new JPanel(new GridLayout(1, 2));
row2.add(text);
row2.add(inputTextField);
add(row2);
inputTextField.addActionListener(this);
}
public void shift() {
output[9].setText(output[8].getText());
output[8].setText(output[7].getText());
output[7].setText(output[6].getText());
output[6].setText(output[5].getText());
output[5].setText(output[4].getText());
output[4].setText(output[3].getText());
output[3].setText(output[2].getText());
output[2].setText(output[1].getText());
output[1].setText(output[0].getText());
}
public void run(String input) {
int length = input.length();
int i = 0;
while (true) {
if (output[0] != null) {
output[0].setText(input.substring(i, i + 1));
} else {
output[0].setText("");
}
i = i + 1;
System.out.println("0" + output[0].getText());
System.out.println("1" + output[1].getText());
System.out.println("2" + output[2].getText());
System.out.println("3" + output[3].getText());
System.out.println("4" + output[4].getText());
System.out.println("5" + output[5].getText());
System.out.println("6" + output[6].getText());
System.out.println("7" + output[7].getText());
System.out.println("8" + output[8].getText());
System.out.println("9" + output[9].getText());
shift();
}
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == inputTextField) {
String j = inputTextField.getText();
run("abcdef");
System.out.println(j);
}
}
}
感謝您的幫助,但最後一個問題,我如何讓它只運行一次? –
您需要一個條件來處理'while'循環,以便在完成時結束。例如:'int runs = 0; while(runs ++ <((length - 1)+ output.length)){[...]}'。 – ArcticLord