【发布时间】:2017-07-18 21:33:07
【问题描述】:
我正在尝试显示使用键盘输入的字符。这是我的程序:
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) {
}
}
如您所见,我可以覆盖keyTypedfunction,但它似乎没有做任何事情。请有人帮忙!
【问题讨论】:
-
getGraphics()不是应该如何绘制的,除了它可以返回null之外,任何绘制到它上面的东西都会在下一个绘制周期中被擦干净。首先查看Painting in AWT and Swing 和Performing Custom Painting,以更好地了解绘画的工作原理以及应该如何完成 -
如需尽快获得更好的帮助,请发帖minimal reproducible example 或Short, Self Contained, Correct Example。
标签: java swing user-interface keylistener