2个回答
展开全部
//重写JPanel
import java.awt.Graphics;
import javax.swing.JPanel;
public class MyPanel extends JPanel {
public static int x = 10;
public static int y = 10;
@Override
public void paint(Graphics g) {
g.drawRect(x, y, 30, 30);
}
}
//程序入口
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
public class MyFrame extends JFrame{
private MyPanel mp;
public MyFrame() {
mp = new MyPanel();
this.add(mp);
this.setVisible(true);
this.setBounds(400, 200, 500, 500);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
if(e.getKeyCode()==38){
MyPanel.y -= 10;
mp.repaint();
}else if(e.getKeyCode()==40){
MyPanel.y += 10;
mp.repaint();
}else if(e.getKeyCode()==37){
MyPanel.x -= 10;
mp.repaint();
}else if(e.getKeyCode()==39){
MyPanel.x += 10;
mp.repaint();
}
}
});
}
public static void main(String[] args) {
new MyFrame();
}
}
import java.awt.Graphics;
import javax.swing.JPanel;
public class MyPanel extends JPanel {
public static int x = 10;
public static int y = 10;
@Override
public void paint(Graphics g) {
g.drawRect(x, y, 30, 30);
}
}
//程序入口
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
public class MyFrame extends JFrame{
private MyPanel mp;
public MyFrame() {
mp = new MyPanel();
this.add(mp);
this.setVisible(true);
this.setBounds(400, 200, 500, 500);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
if(e.getKeyCode()==38){
MyPanel.y -= 10;
mp.repaint();
}else if(e.getKeyCode()==40){
MyPanel.y += 10;
mp.repaint();
}else if(e.getKeyCode()==37){
MyPanel.x -= 10;
mp.repaint();
}else if(e.getKeyCode()==39){
MyPanel.x += 10;
mp.repaint();
}
}
});
}
public static void main(String[] args) {
new MyFrame();
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询