2017-02-28 56 views
0

我想顯示使用鍵盤輸入的字符。下面是我的程序:擺動:字符不顯示在屏幕上

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功能,但它似乎並沒有做任何事情。請有人幫忙!

+0

'getGraphics()'不是應該如何完成繪畫,除了它可以返回null的事實之外,繪製到它上面的任何東西都會在下一個繪製週期中被清除乾淨。首先查看[在AWT和Swing中繪畫](http://www.oracle.com/technetwork/java/painting-140037.html)和[執行自定義繪畫](https://docs.oracle.com/javase/tutorial/uiswing/painting /)以便更好地理解繪畫是如何工作的以及它應該如何完成 – MadProgrammer

+0

爲了更快地獲得更好的幫助,請發佈[MCVE]或[Short,Self Contained,Correct Example](http:// www.sscce.org/)。 –

回答

2

將KeyEvent分派給焦點組件。默認情況下,JPanel不可聚焦,因此它不會收到KeyEvent。

嘗試添加以下到您的類的構造函數:

setFocusable(true); 

如果這是你的幀面板上僅有那麼它應該獲得焦點。

+0

我已經嘗試過,但它沒有奏效。我總共有4個面板連接到Jframe。 –

+1

@ therimovie2ATmail.com,因此您需要將KeyListener添加到具有焦點的組件。 – camickr

+1

@ therimovie2ATmail.com一次只能聚焦一個組件,你可以通過調用requestFocusInWindow來強制聚焦,但我傾向於在鼠標事件上做到這一點,以確保 – MadProgrammer