java - 有没有办法改变 Java Canvas GUI 的油漆颜色?
问题描述
我有一个程序允许您在 GUI 中的画布上绘图,并且我已将颜色设置为黑色。有没有办法可以做到这一点,例如,如果我按下 2 并且颜色变为蓝色,或者 3 变为绿色?这是我的代码:
import java.awt.*;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
public class Draw extends Canvas {
int x, y;
Color color;
public static void main( String[] args ) {
JFrame draw = new JFrame("Use the arrow keys to draw!");
draw.setSize(1020, 764);
draw.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
draw.add( new Draw() );
draw.setVisible(true);
}
public Draw() {
enableEvents(java.awt.AWTEvent.KEY_EVENT_MASK);
requestFocus();
x = 500;
y = 500;
color = Color.black;
}
public void paint( Graphics g ) {
g.setColor(color);
g.fillOval(x, y, 15, 15);
}
public void update( Graphics g ) {
paint(g);
}
public void processKeyEvent(KeyEvent e) {
// this method automatically gets called when you press a key
if ( e.getID() == KeyEvent.KEY_PRESSED ) {
if ( e.getKeyCode() == KeyEvent.VK_UP )
y -= 10;
if ( e.getKeyCode() == KeyEvent.VK_DOWN )
y += 10;
if ( e.getKeyCode() == KeyEvent.VK_LEFT )
x -= 10;
if ( e.getKeyCode() == KeyEvent.VK_RIGHT )
x += 10;
repaint();
}
}
public boolean isFocusable()
{
return true;
}
}
解决方案
推荐阅读
- python - 使用 os.path.join 打开非扩展文件
- next.js - 如何在 Next.js 中创建可重用组件
- arrays - 为什么在 Perl 中使用正则表达式拆分字符串后数组中还有一个额外的空元素?
- python - Python 基础为什么 set() 有效但 {} 失败?
- python - 为什么绿色运行按钮是灰色/禁用的?皮查姆
- node.js - 如何修复从后端服务器获取的文本数据格式?
- javascript - 脚本试图从错误的文件中定义一个函数
- drupal - Drupal 8 jsonapi:如何更改返回的json关系包含数组的结构?
- python - Odoo 12 如何在一个字段中显示模型记录,具体取决于在其他字段中选择的模型
- python - 切片字符串以满足 if 条件