简体   繁体   English

Java Applet设置颜色动作列表

[英]Java Applet set color action listiner

I have my 3 buttons, added them and have action listeners on each one. 我有3个按钮,添加了它们,每个按钮上都有动作监听器。 In the action performed section, they are suppose to change the g.setcolor to a certain color and repaint my oval. 在执行的动作部分中,他们假设将g.setcolor更改为某种颜色并重新绘制我的椭圆形。 what am i doing wrong ? 我究竟做错了什么 ?

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class  zzz extends Applet implements ActionListener {

  Button a, b, c;

  public void init()
  {
  setLayout(new FlowLayout());

  a = new Button("Red");
  b = new Button("Blue");
  c = new Button("Green");
  add(a);
  add(b);
  add(c);
  a.addActionListener(this);
  b.addActionListener(this);
  c.addActionListener(this);

  }

  public void paint(Graphics g){

  g.drawOval(250,100,100,100);
  g.drawString("Circle",275,100);
  g.setColor(Color.white);
  g.fillOval(250,100,100,100);


  }

  public void actionPerformed (ActionEvent evt)
  {
  if (evt.getSource() == a){
  g.setColor(Color.red);
  repaint(); 
  }
  else if (evt.getSource() == b){
  g.setColor(Color.blue);
  repaint(); 
  }
  else if (evt.getSource() == c){
  g.setColor(Color.green);
  repaint(); 
  }
  }
} 
  1. This is not how painting is done. 这不是绘画的方式。
  2. You should avoid painting directly to a top level container 您应该避免直接在顶层容器上绘画

Instead of trying to change g , which is undefined from the context of your actionPerformed method, you should set a variable to indicate the current color, something more like... 而不是尝试更改从actionPerformed方法的上下文中未定义的g ,应设置一个变量来指示当前颜色,更像是...

public void actionPerformed (ActionEvent evt)
{
    if (evt.getSource() == a){
        drawColor = Color.red;
    }
    else if (evt.getSource() == b){
        drawColor = Color.blue;
    }
    else if (evt.getSource() == c){
        drawColor = Color.green;
    }
    repaint();
}

Then you would need to update you paint method to look more like.... 然后,您需要更新绘画方法,使其看起来更像...。

public void paint(Graphics g){
    super.paint(g);
    g.setColor(drawColor);
    g.drawOval(250,100,100,100);
    g.drawString("Circle",275,100);
    g.setColor(Color.white);
    g.fillOval(250,100,100,100);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM