我正在爲我的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
謝謝。我聽說過關鍵綁定,但沒有看到它們被使用。通常我們只應該使用我們在課堂上看到的技巧。我會進一步看看鍵綁定雖然.. –