我正在为我的java课程进行keylistener练习,但过去一周一直在卡住。我很欣赏任何有用的建议。这次演习是:使用Java中的keylistener在GUI中使用箭头键绘制线条
“写绘制使用箭头键线段程序的 线从帧的中心开始,向华东,华北, 西,或南画时,右箭头键,上箭头键,左箭头键, 或单击向下箭头键。“
经过调试我想通了KeyListener的工作,以获得对drawComponent(图形克)点 ,但是当我按下 向下或向右只汲取,只有工作的第一对夫妇倍。这里是我的代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class EventProgrammingExercise8 extends JFrame {
JPanel contentPane;
LinePanel lines;
public static final int SIZE_OF_FRAME = 500;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
EventProgrammingExercise8 frame = new EventProgrammingExercise8();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public EventProgrammingExercise8() {
setTitle("EventExercise8");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(SIZE_OF_FRAME, SIZE_OF_FRAME);
contentPane = new JPanel();
lines = new LinePanel();
contentPane.add(lines);
setContentPane(contentPane);
contentPane.setOpaque(true);
lines.setOpaque(true);
lines.setFocusable(true);
lines.addKeyListener(new ArrowListener());
}
private class LinePanel extends JPanel {
private int x;
private int y;
private int x2;
private int y2;
public LinePanel() {
x = getWidth()/2;
y = getHeight()/2;
x2 = x;
y2 = y;
}
protected void paintComponent(Graphics g) {
g.drawLine(x, y, x2, y2);
x = x2;
y = y2;
}
public void drawEast() {
x2 += 5;
repaint();
}
public void drawWest() {
x2 -= 5;
repaint();
}
public void drawNorth() {
y2 -= 5;
repaint();
}
public void drawSouth() {
y2 += 5;
repaint();
}
}
private class ArrowListener extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_RIGHT) {
lines.drawEast();
} else if (key == KeyEvent.VK_LEFT) {
lines.drawWest();
} else if (key == KeyEvent.VK_UP) {
lines.drawNorth();
} else {
lines.drawSouth();
}
}
}
}
谢谢。
就个人而言,我会使用[键绑定API](http://docs.oracle.com/javase/tutorial/uiswing/ misc/keybinding.html),从长远来看这是一个更安全的赌注,但你可能有理由不这样做... – MadProgrammer
谢谢。我听说过关键绑定,但没有看到它们被使用。通常我们只应该使用我们在课堂上看到的技巧。我会进一步看看键绑定虽然.. –