如何在JFrame上绘制文本并用Java清除? [英] How to drawing a text on JFrame and clearing in java?
问题描述
我想在键盘上按'h'时使用drawString方法在JFrame上绘制文本,而在键盘上按'c'时清除文本,这是我的代码,可以用于绘制,但是我不知道不知道该如何工作.
I want to draw a text on the JFrame using drawString method when I press 'h' on the keyboard and clear the text when I press 'c' on the keyboard this is my code, it is working for drawing but I don't know how to work for clear.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class test extends JPanel implements KeyListener {
char help,clear;
public test() {
super();
setFocusable(true);
this.addKeyListener(this);
}
//********************************************************************
public void paintComponent(Graphics g) {
repaint();
g.setColor(Color.red);
g.drawString("press 'H' for help ",150,50);
if(help=='h'){
g.drawString("one",150,100);
}//end id help
if(clear=='c'){
g.drawString("",150,100);
}//end id clear
}
//******************keyyyyyyy******************************************
public void keyPressed(KeyEvent e) {
if(e.getKeyChar()=='h'){
help='h';
}
if(e.getKeyChar()=='c'){
clear='c';
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
//********************************************************************
public static void main(String[] args) {
test panel=new test();
JFrame frame = new JFrame("java lover");
frame.add(panel);
frame.setSize(400,400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
感谢您的帮助.
推荐答案
g.drawString("",150,100);
与擦除"先前的图形相反,它什么也没画.
That would draw nothing, as opposed to 'erasing' the previous drawing.
public void paintComponent(Graphics g) {
repaint();
那将导致无限循环.应该是:
That would cause an infinite loop. It should be:
public void paintComponent(Graphics g) {
super.paintComponent(g); // paint the BACKGROUND and borders
这样做,原始字符串将被删除.
Doing it this way, the original string will be erased.
一般提示:对于Swing,通常在基于AWT的较低级别的 KeyListener
上使用键绑定.有关如何使用键绑定的详细信息,请参见如何使用键绑定.
As a general tip: For Swing, typically use key bindings over the AWT based, lower level, KeyListener
. See How to Use Key Bindings for details on how to use them.
这篇关于如何在JFrame上绘制文本并用Java清除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!