我想顯示使用鍵盤輸入的字符。下面是我的程序:擺動:字符不顯示在屏幕上
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
public class CenterJPanel extends JPanel implements MouseMotionListener, KeyListener
{
protected static int circleSize 20;
private int lastX = 0, lastY = 0;
protected static int recordX;
protected static int recordY;
public CenterJPanel()
{
setBackground(Color.gray);
JLabel jl = new JLabel("CENTER");
this.add(jl);
this.addMouseMotionListener(this);
this.addKeyListener(this);
}
@Override
public void mouseDragged(MouseEvent e)
{
int x = e.getX();
int y = e.getY();
drawLine(x, y);
}
private void drawLine(int x, int y)
{
Graphics g = getGraphics();
Graphics2D g2D = (Graphics2D)g;
g2D.setColor(Color.Black);
g2D.setStroke(new BasicStroke(circleSize));
g2D.drawLine(lastX, lastY, x, y);
record(x, y);
}
protected void record(int x, int y)
{
lastX = x;
lastY = y;
}
@Override
public void mouseMoved(MouseEvent e) {
}
@Override
public void keyTyped(KeyEvent e)
{
String s = String.valueOf(e.getKeyChar());
Graphics g = getGraphics();
g.setColor(Color.RED);
g.setFont(new Font("Times New Roman", Font.BOLD, 2));
g.drawString(s, lastX + 10, lastY + 10);
System.out.println(lastX + " " + lastY + " String: " + s);
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
}
正如你看到的,我可以很重寫keyTyped
功能,但它似乎並沒有做任何事情。請有人幫忙!
'getGraphics()'不是應該如何完成繪畫,除了它可以返回null的事實之外,繪製到它上面的任何東西都會在下一個繪製週期中被清除乾淨。首先查看[在AWT和Swing中繪畫](http://www.oracle.com/technetwork/java/painting-140037.html)和[執行自定義繪畫](https://docs.oracle.com/javase/tutorial/uiswing/painting /)以便更好地理解繪畫是如何工作的以及它應該如何完成 – MadProgrammer
爲了更快地獲得更好的幫助,請發佈[MCVE]或[Short,Self Contained,Correct Example](http:// www.sscce.org/)。 –