我遇到的问题是每隔几秒就将RandomText(随机大小,字体,x,y)添加到JFrame这是我的代码
第一个是JComponent,它希望Randomly Made String出现
public class RandomTextGenerator extends JComponent{
private String str;
private Random r;
private Color c;
private Font f;
private int x;
private int y;
Graphics g;
public RandomTextGenerator(String s)
{
r = new Random();
c = new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255));
f = new Font("random",Font.BOLD,r.nextInt(100));
x = r.nextInt(100);
y = r.nextInt(100)+100;
//setPreferredSize(new Dimension(500,500));
str = s;
}
public void paintComponent(Graphics g)
{
g.setColor(c);
g.setFont(f);
System.out.println(str);
g.drawString(str, x, y);
}
}
另一个是JFrame
public class TextFrame extends JFrame{
public TextFrame() {
this.setSize(500, 500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Random Text Generator");
this.getContentPane().setBackground(Color.BLACK);
this.setLayout(new GridLayout(1,1));
this.add(new RandomTextGenerator("AAAAAAAA"));
this.add(new RandomTextGenerator("BBBBBBBBBB"));
this.setVisible(true);
}
public void addRandomText(RandomTextGenerator r)
{
this.add(r);
this.add(new RandomTextGenerator("CCC"));
System.out.println("Method called");
this.repaint();
}
}
以上代码,
this.add(new RandomTextGenerator("AAAAAAAA"));
this.add(new RandomTextGenerator("BBBBBBBBBB"));
那些工作得很好并在屏幕上显示,但问题是方法addRandomText
this.add(r);
this.add(new RandomTextGenerator("CCC"));
那些根本不起作用。
我的主要方法是
public class tfmain {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter Your Message");
String str = s.nextLine();
TextFrame tf = new TextFrame();
Timer t = new Timer(1000,new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
tf.addRandomText(new RandomTextGenerator(str));
}
});
t.start();
}
}
使用此代码显示方法Called,这意味着Timer实际上有效。
但是为什么添加Jcomponent并不工作?在AddRandomtext中添加Jcomponent永远不会起作用(paintComponent也不会被调用)
请给我一些建议。抱歉我的英文不好