我做了大约30次不同的谷歌搜索,但没有得到答案,所以我来到这里。所以我试图在屏幕上左右移动播放器的矩形(黑色方块)。当我使用常规图形时,它工作正常,但现在我使用Graphics2D,repaint()似乎什么都不做(即当你按下左右箭头键时,矩形不会移动)。 / p>
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
此外,&#34; boxobj&#34; class现在只是一个空类。我计划将随机矩形的初始化放在哪里。我只是把它放在这里以便于复制粘贴。
public class boxobj {
}
答案 0 :(得分:0)
问题是您正在更新x
变量,但是绘制player
对象。
当您构造player
(通过Rectangle player = new Rectangle(x, y, 50, 50);
)时,它会在执行该行时获取x
的值的副本。由于您同时声明和初始化,我们知道x
为零,因此player
将(0, 650, 50, 50)
实例化。
稍后,用户点击右箭头键并触发事件监听器。这会将x
增加到50并调用repaint
,但重要的是,根本不会更新player
对象。当绘画系统paintComponent
调用player
方法时,(0, 650, 50, 50)
仍为x
。
基本上y
和player
会记录玩家的位置,但您正在使用x
对象来绘制玩家,并且这些变量不会同时更新。
纠正此问题的最佳方法是将玩家的位置存放在一个地方。您可以保留y
和paintComponent
并修改player
方法以使用这些方法,也可以丢弃这两个变量并修改player.setLocation
对象(使用{{ 1}})。无论哪种方式都可行。