每次通过Swing计时器更改GUI坐标时,如何重新绘制?
这是我的代码片段:
t = new Timer(500,new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
for(int i=0;i<=100;i++) {
panel.setBounds(i,100,550,336);
panel.repaint();
}
t.stop();
}
});
t.start();
我的面板只在循环完成后重新绘制,因此不会显示我想要看到的过渡效果。
答案 0 :(得分:1)
我的面板只在循环完成后重新绘制,因此不会显示我想要看到的过渡效果。
以下是仅使用Swing Timer
成功移动组件的示例。我的结论是问题出现在上面没有显示的代码中。
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.*;
public class BouncingLabel {
private JComponent ui = null;
int xD = 1;
int yD = 1;
int l = 101;
int r = 100;
int t = 50;
int b = 50;
BouncingLabel() {
initUI();
}
public void initUI() {
if (ui != null) {
return;
}
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new CompoundBorder(
new EmptyBorder(4, 4, 4, 4),
new LineBorder(Color.BLACK)));
final JLabel label = new JLabel(new ImageIcon(
new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB)));
ui.add(label);
EmptyBorder emptyBorder = new EmptyBorder(t, l, b, r);
label.setBorder(emptyBorder);
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Border border = label.getBorder();
Insets insets = border.getBorderInsets(label);
if (l == 0 | r == 0) {
xD = -xD;
}
if (t == 0 || b == 0) {
yD = -yD;
}
l = l + xD;
r = r - xD;
t = t + yD;
b = b - yD;
label.setBorder(new EmptyBorder(t, l, b, r));
}
};
Timer timer = new Timer(15, listener);
timer.start();
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
BouncingLabel o = new BouncingLabel();
JFrame f = new JFrame("Bouncing Square");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}