首页 > 解决方案 > 有没有办法改变 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;
 }
}

标签: javaswinguser-interfacecanvasdraw

解决方案


推荐阅读