我目前正在制作一个News Ticker类型的程序,用于滚动用户在JLabel上输入的文本。目前我可以让它在字符串变量中显示文本。但是,当我尝试将文本输入传递到字段时,会导致错误。到目前为止,我的工作如下:
public class Scroll2 extends JPanel implements Runnable, ActionListener{
JLabel label;
JLabel prompt;
JPanel LabelPan;
JPanel panelForText;
String str= "Hello";
String text;
JFrame mainFrame;
JTextField t;
public Scroll2(){
super();
mainFrame = new JFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(new Dimension(840, 280));
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
mainFrame.setLayout(new GridLayout(0,1));
LabelPan = new JPanel();
LabelPan.isMaximumSizeSet();
LabelPan.setSize(620, 180);
label = new JLabel(str);
label.setFont(new Font("Serif", Font.PLAIN, 70));
LabelPan.add(label);
panelForText = new JPanel();
panelForText.setLayout(new GridLayout(0, 2));
prompt = new JLabel("Enter Text Here;");
panelForText.add(prompt);
t = new JTextField();
t.setSize(80, 53);
t.addActionListener(this);
panelForText.add(t);
mainFrame.add(LabelPan, BorderLayout.NORTH);
mainFrame.add(panelForText, BorderLayout.SOUTH);
Thread t = new Thread(this);
t.start();
}
public void run(){
while(true){
char c = str.charAt(0);
String rest = str.substring(1);
str = rest + c;
label.setText(str);
try{
Thread.sleep(200);
}catch(InterruptedException e){}
}
}
public void actionPerformed(ActionEvent evt) {
JTextField t = (JTextField) evt.getSource();
}
public static void main(String[] args) {
Scroll2 TextScroll = new Scroll2();
}
}
任何帮助将不胜感激,谢谢。
答案 0 :(得分:3)
您永远不会在str
方法中更新actionPerformed()
:
public void actionPerformed( ActionEvent evt )
{
// JTextField t = (JTextField) evt.getSource();
str = t.getText();
}
说真的,如果你花了一分钟来查看代码,你就可以找到它。也许适当的缩进可以帮助您更好地阅读代码。
(我将忽略代码中的多线程错误。阅读Swing并发:https://docs.oracle.com/javase/tutorial/uiswing/concurrency/)