gpt4 book ai didi

java - XMotion 处理 JComponent

转载 作者:行者123 更新时间:2023-12-01 10:00:41 25 4
gpt4 key购买 nike

我遇到麻烦了。我想在 JPanel 上绘制一个矩形,并将其添加到我的 JFrame contentPane 中。我希望 x 处于设定位置,但移动 -x 并在 +x 开始的地方重新启动。即,如果我有一个 800 x 400 的 JPanel,我希望 rext 接受这些参数,但沿 x 轴 (x - Velx) 移动,在 800 处重新绘制自身,并继续沿 - x 方向移动。我知道这还不够,我读过的书都没有涉及到我想要做的事情,所以我缺乏正确的术语。

最佳答案

//这是执行此操作的一个很好的示例

公共(public)类动画船{

public static void main(String[] args) {
new AnimatedBoat();
}

public AnimatedBoat() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}

JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new AnimationPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

});
}

public class AnimationPane extends JPanel {

private BufferedImage boat;
private int xPos = 0;
private int direction = 1;

public AnimationPane() {
try {
boat = ImageIO.read(new File("boat.png"));
Timer timer = new Timer(40, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
xPos += direction;
// change directions off window width
if (xPos + boat.getWidth() > getWidth()) {
xPos = getWidth() - boat.getWidth();
direction *= -1;
} else if (xPos < 0) {
xPos = 0;
direction *= -1;
}
repaint();
}

});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
} catch (IOException ex) {
ex.printStackTrace();
}
}

@Override
public Dimension getPreferredSize() {
return boat == null ? super.getPreferredSize() : new Dimension(boat.getWidth() * 4, boat.getHeight());
}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

int y = getHeight() - boat.getHeight();
g.drawImage(boat, xPos, y, this);

}

}

}

关于java - XMotion 处理 JComponent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36830943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com