[英]How to change position of a JLabel?
我正在嘗試使用計時器將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值的位置,則可以更改標簽的位置。
如果您要尋找一些動畫,請嘗試使用Swing Timer 。
請看看如何使用Swing計時器
這是示例代碼:
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//...Perform a task...
}
};
new Timer(delay, taskPerformer).start();
示例代碼:( 以200 ms的間隔左右水平移動Hello World消息10px )
private int x = 10;
...
final JPanel panel = new JPanel() {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("Hello World", x, 10);
}
};
int delay = 200; // milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
x += 10;
if (x > 100) {
x = 10;
}
panel.repaint();
}
};
new Timer(delay, taskPerformer).start();
我做了一個類似的例子,只是您可以得到它的基本玩笑,請嘗試將其復制粘貼到一個名為“ 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(毫秒數)。
為什么不在位置a創建一個JLabel,將其設置為可見,而在位置b創建另一個JLabel,將其設置為不可見? 計時器啟動后,隱藏第一個並顯示第二個。
您是否打算為某些類型的游戲創建一些運動的imageIcon? 還是有些標簽隨處可見? 我會使用絕對布局並每次手動設置位置。
myPanel.setLayout(null);
// an initial point
int x = 100;
int y =100;
while (
//some moving pattern
x++; // 1 pixel per loop
y+=2; // 2 pixels per loop
myLabel.setLocation(x,y);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.