請 - 我需要我正在處理的這段代碼的幫助 - 我知道它很小,但我找不到它有什麼問題。我想要移動紅色的矩形左右,爲此我創建了一個單獨的方法,然後在keyPressed
方法中調用它,但它不起作用。Java圖形按鍵移動
import java.awt.Color;
import java.awt.Dialog;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
import javax.swing.Timer;
public class PanelGraph extends JPanel implements KeyListener,ActionListener {
int BARX=100,BARY=230,Width=60,Hight=10;
int BARVELX=0,BARVELY=0;
int BX=100,BY=100,BWidth=20,BHight=20;
int VELX=2,VELY=2;
public Timer t= new Timer(20,this);
//@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(BARX, BARY, Width, Hight);
g.setColor(Color.black);
g.fillOval(BX, BY, BWidth, BHight);
t.start();
}
public void balMovement() {
BX+=VELX;
BY+=VELY;
//Checking for X border collution
if(BX<0||BX>260){
VELX=-VELX;
}
//Checking for Y border collution
if(BY<0||BY>240){
VELY=-VELY;
}
repaint();
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_RIGHT){
rightKey();
}
if(e.getKeyCode()==KeyEvent.VK_DOWN){
downKey();
}
repaint();
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent e) {
balMovement();
}
//Moving right methods
public void rightKey(){
BARX+=BARVELX;
BARY=0;
}
//Moving left method
public void downKey(){
BARX-=BARVELX;
BARY=0;
}
}
主要
import javax.swing.JFrame;
public class MiniTeniis {
public JFrame frame;
public MiniTeniis(){
PanelGraph panelG= new PanelGraph();
frame= new JFrame("Mini Tennis");
frame.setSize(300,300);
frame.setVisible(true);
frame.add(panelG);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
MiniTeniis M= new MiniTeniis();
PanelGraph P = new PanelGraph();
P.setFocusable(true);
P.setFocusTraversalKeysEnabled(false);
}
}
見[運動使用鍵盤(https://tips4java.wordpress.com/2013/06/09/motion-using-the-keyboard/),用於與鑰匙的示例綁定。另外,變量名不應以大寫字母開頭,單個字母變量名稱可怕。變量名應該是描述性的!最後你的代碼創建兩個PanelGraph對象。第二個是從來沒有用過,所以擺脫它。 – camickr 2015-04-03 22:43:33
你是指主要方法中的一個? – user3500147 2015-04-03 22:57:06