我正在尝试使用计时器将JLabel的位置从JPanel上的一个位置更改为另一个位置。我不确定是否可以使用.getLocation(),然后仅更改水平x值,最后使用.setLocation()有效地修改JLabel。我还使用了.getBounds.setBounds,但是仍然不确定如何获取旧的水平x值以进行更改并重新应用到新的x值。

我尝试的代码看起来像这样,但是这都不是更改JLabel位置的有效方法。

// mPos is an arraylist of JLabels to be moved.

for(int m = 0; m < mPos.size(); m++){
        mPos.get(m).setLocation(getLocation()-100);
    }


要么

    for(int m = 0; m < mPos.size(); m++){
        mPos.get(m).setBounds(mPos.get(m).getBounds()-100);
    }


如果我可以获取水平x值的位置,则可以更改标签的位置。

最佳答案

我做了一个类似的示例,只是您可以得到它的基本笑话,请尝试将其复制粘贴到一个名为“ LabelPlay”的新类中,它应该可以正常工作。

import java.awt.EventQueue;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;


public class LabelPlay {

private JFrame frame;
private JLabel label;
private Random rand;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                LabelPlay window = new LabelPlay();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public LabelPlay() {
    initialize();
}

private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 659, 518);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    label = new JLabel("YEEEHAH!");
    label.setBounds(101, 62, 54, 21);
    frame.getContentPane().add(label);

    JButton btnAction = new JButton("Action!");
    rand = new Random();
    btnAction.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            int a = rand.nextInt(90)+10;
            int b = rand.nextInt(90)+10;
            int c = rand.nextInt(640)+10;
            int d = rand.nextInt(500)+10;
            label.setBounds(a, b, c, d);
        }
    });
    btnAction.setBounds(524, 427, 89, 23);
    frame.getContentPane().add(btnAction);

}


}

如果希望在特定时间在循环中发生这种情况,可以将其放入循环中,然后在运行代码之前在循环中使用Thread.sleep(毫秒数)。

07-28 01:56
查看更多