您好,我有3个单独的类,一个用于框架,一个用于面板,一个用于keyListener
每当我按左键箭头时,我都希望它在框架上打印一些东西。我已经使用过getGraphics(),但是我已经读过它是不好的作法,而且我不确定如何正确地做到这一点。 我阅读了有关以下内容的教程:https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html
“ paintComponent方法是所有自定义绘画所用的地方 地点。该方法由javax.swing.JComponent定义,然后 由您的子类重写以提供其自定义行为。”
因此,我尝试在KeyboardListener中扩展DrawingBoard类 但是在keyPressed方法中,我不知道如何调用paintCompoment(Graphics g)作为参数放置什么,这是正确的方法吗?
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(new UserInterface());
}
}
public class UserInterface implements Runnable {
private JFrame frame;
private DrawingBoard drawingBoard;
@Override
public void run() {
// TODO Auto-generated method stub
frame = new JFrame("");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
createComponents(frame.getContentPane());
addListener();
frame.pack();
frame.setVisible(true);
}
public void createComponents(Container container) {
drawingBoard = new DrawingBoard();
container.add(drawingBoard);
}
public void addListener() {
frame.addKeyListener(new KeyboardListener(drawingBoard));
}
}
public class DrawingBoard extends JPanel {
public Dimension getPreferredSize() {
return new Dimension(250, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
}
}
public class KeyboardListener extends DrawingBoard implements KeyListener {
private DrawingBoard drawingBoard;
public KeyboardListener(DrawingBoard drawingBoard) {
this.drawingBoard = drawingBoard;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("Hello", 50, 50);
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
// How do I call paintComponent
// What do I put as a parameter ?
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}