我已经在谷歌上搜索了大约30次,但都没有找到答案,所以我来到了这里。所以我试着在屏幕上左右移动玩家的矩形(黑色方块)。当我使用常规图形时,它工作得很好,但是现在我使用的是Graphics2D,repaint()似乎什么也不做(例如,当你按左右箭头键时,矩形不会移动)。
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class boxface extends JComponent implements KeyListener {
private boxobj obj;
private int x=0, y=650;
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()== KeyEvent.VK_RIGHT)
moveRight();
else if(e.getKeyCode()== KeyEvent.VK_LEFT)
moveLeft(); }
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
Rectangle player = new Rectangle(x, y, 50, 50);
Rectangle floor = new Rectangle(0, 700, 750, 700);
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g.setColor(Color.GREEN);
g2.fill(floor);
g.setColor(Color.BLACK);
g2.fill(player); }
public void moveLeft() {
if(x > 0) {
x -= 50;
repaint(); }}
public void moveRight() {
if(x < 700) {
x += 50;
repaint(); }}
public boxface(){
this.obj=new boxobj();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false); }
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setBounds(400, 200, 756, 779);
f.setMinimumSize(new Dimension(756, 0));
f.setResizable(false);
f.getContentPane().add(new boxface());
f.setVisible(true);
}
});
final java.util.Timer tmr = new java.util.Timer();
tmr.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
System.out.println("A second has passed.");
/* the idea is that I could make a square with random
* dimensions (within a certain limit), so that every
* time the timer loops, a new, random square is made.
* I just can't seem to move the rectangles using
* repaint(); because they're Graphics2D rectangles,
* and I can't find a way around this.
*
* An example of this can be shown if you run this
* code; the "player" rectangle cannot be moved, even
* though keylistener is picking up inputs and the
* rectangle's co-ordinates are being changed. In
* other words, repaint(); isn't doing anything. */
}
},0,1000);
}//end main
}//end class另外,"boxobj“类现在只是一个空类。我打算把随机矩形的初始化放在这里。我只是把它放在这里,方便复制粘贴。
public class boxobj {
}发布于 2018-01-23 12:49:00
问题是您正在更新x变量,但是绘制了player对象。
当您构造player (通过Rectangle player = new Rectangle(x, y, 50, 50);)时,它会获取执行该行时x的值的一个副本。由于您同时声明和初始化,因此我们知道x为零,因此将使用(0, 650, 50, 50)实例化player。
稍后,用户点击向右箭头键,您的事件侦听器就会触发。这会将x增加到50并调用repaint,但重要的是,根本不会更新player对象。当绘制系统调用paintComponent方法时,player仍然是(0, 650, 50, 50)。
本质上,x和y记录玩家的位置,但是您使用player对象来绘制玩家,并且这些变量没有同步更新。
纠正这个问题的最好方法是将玩家的位置存储在一个位置。您可以保留x和y并修改您的paintComponent方法以使用它们,也可以丢弃这两个变量而改为修改player对象(使用player.setLocation)。无论哪种方式都行得通。
https://stackoverflow.com/questions/48394013
复制相似问题