在下面的代碼中,箭頭鍵用於在etch-a-sketch中繪製一條線(但您必須先調整窗口大小以在正確的時間觸發面板的焦點請求 - 這是針對不同的問題時間,也許)。圖形命令g.drawLine()發生在keyPressed()函數中,repaint()不是顯式調用的,但圖像會在按下箭頭鍵時自動更新。這是爲什麼?我所看到的所有文檔都只是談論JPanel在調整大小或發現大小時自動重新繪製自己。什麼是導致此代碼重新繪製自己?
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Etch extends JPanel implements KeyListener{
public int xPrev, yPrev, xNew, yNew, inc;
public Etch(int start){
xPrev = start;
yPrev = start;
xNew = start;
yNew = start;
inc = 10;
addKeyListener(this);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
this.requestFocusInWindow();
}
public static void main(String[] args)
{
JFrame w = new JFrame("Keyboard");
w.setBounds(100, 100, 600, 600);
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Etch panel = new Etch(200);
panel.setFocusable(true);
panel.setBackground(Color.RED);
Container c = w.getContentPane();
c.add(panel);
w.setResizable(true);
w.setVisible(true);
}
public void keyPressed(KeyEvent e){
int code = e.getKeyCode();
if (code == KeyEvent.VK_UP){
xPrev = xNew;
yPrev = yNew;
yNew -= inc;
}
if (code == KeyEvent.VK_DOWN){
xPrev = xNew;
yPrev = yNew;
yNew += inc;
}
if (code == KeyEvent.VK_LEFT){
xPrev = xNew;
yPrev = yNew;
xNew -= inc;
}
if (code == KeyEvent.VK_RIGHT){
xPrev = xNew;
yPrev = yNew;
xNew += inc;
}
Graphics g = this.getGraphics();
g.setColor(Color.BLUE);
g.drawLine(xPrev, yPrev, xNew, yNew);
}
// Not used but required by the KeyListener interface
public void keyReleased (KeyEvent e) { }
public void keyTyped (KeyEvent e) { }
}
'this.requestFocusInWindow();'是'paintComponent'方法中的一個壞主意。繪畫應繪製當前狀態並永不改變組件的狀態 – MadProgrammer 2014-11-04 23:11:59