在下面的代码中,箭头键用于在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