paintComponent画的图怎么使用KeyListener使它动起来?
1个回答
展开全部
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
/**
* 简单例子,按下哪个键,就会显示什么内容,不可显字符就算了,不多解释了
*/
public class Sanke extends JFrame implements KeyListener {
public MyComponent my = new MyComponent();
public Sanke() {
this.setSize(100, 100);
this.add(my);
this.addKeyListener(this);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
char c = e.getKeyChar();
my.update(c);
}
@Override
public void keyReleased(KeyEvent e) {
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Sanke();
}
});
}
}
class MyComponent extends JComponent {
char c = 'a';
Font font = new Font("宋体", Font.BOLD, 30);
public void update(char c) {
this.c = c;
this.repaint();
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.setFont(this.font);
g.drawString(String.valueOf(c), 20, 50);
}
}
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
/**
* 简单例子,按下哪个键,就会显示什么内容,不可显字符就算了,不多解释了
*/
public class Sanke extends JFrame implements KeyListener {
public MyComponent my = new MyComponent();
public Sanke() {
this.setSize(100, 100);
this.add(my);
this.addKeyListener(this);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
char c = e.getKeyChar();
my.update(c);
}
@Override
public void keyReleased(KeyEvent e) {
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Sanke();
}
});
}
}
class MyComponent extends JComponent {
char c = 'a';
Font font = new Font("宋体", Font.BOLD, 30);
public void update(char c) {
this.c = c;
this.repaint();
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.setFont(this.font);
g.drawString(String.valueOf(c), 20, 50);
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询