Timer类通过JFrame移动JLabel!为什么JLabel文本不能变量?

时间:2012-09-25 09:13:53

标签: java swing timer jframe jlabel

如果我说

,请在最后一行和第三行
label.setText("x = ");

标签移动完美但我将其更改为

label.setText("x = "+ x);

它不动。具体来说,我希望看到JLabel在变量 x 移动时的宽度位置! 除此之外,我说label.setBounds(x,(getHeight()/2),300,300);将标签的Y边界设置为帧大小的一半,但它不在帧的中间?有什么想法吗?

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.Timer;

import javax.swing.JFrame;

public class myTiemr {

    public static void main(String args[])
    {
        TimeFrame frame = new TimeFrame();
    }
}

class TimeFrame extends JFrame
{
    private static final long serialVersionUID = 1L;
    private int x = 0;
    JLabel label = new JLabel("Here is my label");
    public TimeFrame()
    {
        int d = 10;
        setTitle("My Frame");
        setSize(500,500);
        this.setLocationRelativeTo(null);
        add(label);
        Timer time = new Timer(d,new TimerListener());
        time.start();       
        setVisible(true);
    }
    class TimerListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            if(x>getWidth()){
                x=-100;
            }
            x+=1;
            label.setText("x = "+ x);
            //label.setText("x = ");
            label.setBounds(x,(getHeight()/2),300,300);
        }
    }

}

2 个答案:

答案 0 :(得分:3)

TimeFrame构造函数中,添加:

this.setLayout(null);

this.setLocationRelativeTo(null);之后。

答案 1 :(得分:3)

label.setText("x = "+ x)导致文字保持不动但行label.setText("x = ")导致标签在框架中移动的原因是revalidate()上调用了JLabel 。这将导致应用当前布局管理器规则的正确行为(在这种情况下为BorderLayout)。

如果文字没有改变,则永远不会调用revalidate()

由于@SébastienLeCallonnec建议在框架上设置任何布局都不会导致

label.setText("x = "+ x)

按要求移动。