我正在尝试解决使用箭头键绘制线条的练习。当按下其中一个箭头键时,该线从中心开始向东,西,北或南方延伸。代码只能在东或西方向运行,而不能在北方或南方运行,这是我的问题!如何使用箭头键绘制线条(线段)?
有人能给我一个关于这件事的想法吗?谢谢。
下面的代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DrawingLinesUsingTheArrowKeys extends JFrame {
// Create a panel
private LinesUsingTheArrowKeys LinesUsingTheArrowKeys = new LinesUsingTheArrowKeys();
public DrawingLinesUsingTheArrowKeys() {
add(LinesUsingTheArrowKeys);
/*
* A component (keyboard) must be focused for its can receive the
* KeyEvent To make a component focusable , set its focusable property
* to true
*/
LinesUsingTheArrowKeys.setFocusable(true);
}
public static void main(String[] args) {
JFrame frame = new DrawingLinesUsingTheArrowKeys();
frame.setTitle("Drawing Lines Using The Arrow Keys");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
frame.setVisible(true);
}
// Inner class: LinesUsingTheArrowKeys (keyboardPanel) for receiving key
// input
static class LinesUsingTheArrowKeys extends JPanel {
private int x = 200;
private int y = 100;
private int x1 = x + 10;
private int y1 = y;
// register listener
public LinesUsingTheArrowKeys() {
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
// x1 += y1;
y1 += 10;
repaint();
} else if (e.getKeyCode() == KeyEvent.VK_UP) {
y1 -= 10;
repaint();
} else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
x1 += 10;
repaint();
} else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
x1 -= 10;
repaint();
}
}
});
}
// Draw the line(s)
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(x, y, x1, y1);
}
}
}
我认为在您进一步学习之前,您可能想了解Java和JavaScript之间的区别 – MadProgrammer
好的...我是所以强调了关于java中的pbm + new =发布这个问题时的一些错误......但我会照顾那个.. – Kurt16