java在jpanel中显示字符串

在java application中,我想在一个jpanel上显示字符串,但不是程序刚开始就显示,而是运行到一定时候再显示,应该怎么写呢?目前我只知道drawString方法只能在paint方法里用,而paint方法是程序自动调用的,我想在其他方法里用drawString方法,不知道这样有可行性么?

第1个回答  2013-06-10
TestStr.java文件,handleStr方法是进行逆向的功能,其他都是作了一个界面,为了方便测试。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
*
* @author Administrator
*/
public class TestStr extends JFrame implements ActionListener{
JTextField txtInput=new JTextField("请输入字符串");
JTextField txtOutput=new JTextField("转换后的字符串");
JButton ok=new JButton("转换");

/** Creates a new instance of TestStr */
public TestStr() {
setLayout(new BorderLayout());
JPanel p=new JPanel();
txtInput.setSize(70,30);
txtOutput.setSize(70,30);
p.add(txtInput);
p.add(txtOutput);
ok.addActionListener(this);
add(p,BorderLayout.CENTER);
add(ok,BorderLayout.SOUTH);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(200,100);

}

public void actionPerformed(ActionEvent e){
txtOutput.setText(handleStr(txtInput.getText()));

}

public String handleStr(String input){
if(input!=null && !input.trim().equals("")){
int len=input.length();
char[] output=new char[len];
for(int i=0,j=len-1;i<len;i++,j--){
output[i]=input.charAt(j);
}
return new String(output);
}
return "";
}

public static void main(String args[]){
TestStr t=new TestStr();
t.setVisible(true);
}
}
第2个回答  2019-05-17
为什么一定要用JPanel?用JLabel不行么?
JLabel
label
=
new
JLabel();//此时是空的,不显示文字
你可以在事件代码种使用:label.setText("some
message");
来使它改变文字
第3个回答  2013-06-10
在new paint方法所在类的实例时 会自动调用paint方法。按你的要求你在创建此类实例时加上Thread.sleep(3000)看看;不知道lz是不是这个意思!
第4个回答  2013-06-10
必须加一个线程,此线程用于检测时间,一定时间后,就开始drawString
相似回答