如何通过从另一堂课的动作中进行动作来更改一个类中的图形颜色



我是Java的新手,绝望了,所以我们走了!!!当我单击菜单中的某个选项时,我正在尝试更改GUI内容的颜色,但是我不确定如何。这是带有ActionPreform方法的菜单

    public JMenuBar makeMenuBar(DrawHere drawHTree) {
    JMenuBar menuBar = new JMenuBar();
    JMenu menSize = new JMenu("Color");
    menuBar.add(menSize);
    JMenuItem mitSmall = new JMenuItem("Black");
    mitSmall.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            //Do stuff here...
        }
    });
    menSize.add(mitSmall);
    JMenuItem mitMedium = new JMenuItem("Red");
    mitMedium.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            // Do stuff here...
        }
    });
    menSize.add(mitMedium);
    JMenuItem mitLarge = new JMenuItem("Cyan");
    mitLarge.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            // Do stuff here...
        }
    });
    menSize.add(mitLarge);
    return menuBar;
}

这是我希望更改的图形颜色的类的片段

    private void drawHTree(Point location) {
    int x = (int)location.getX();
    int y = (int)location.getY();
    int boxSize = (int)(this.getHeight()*HTREE_SIZE);
    // Rough draft test: 13:50.55 for n = 13
    // Optimized test: 11:42.42 for n = 13
    int n = 5;
    _drawHTree(n,x,y,boxSize);
}
private void _drawHTree(int n, int x, int y, int boxSize) {
    if (n == 0) {
        return;
    }
    Graphics brush = this.getGraphics();
    //brush.setColor(Color.getHSBColor(1,1,1));
    brush.setColor(Color.RED);// <------- NEED HELP HERE! I WANT TO  
                                      // BE ABLE OT CHANGE THIS COLOR 
    ((Graphics2D) brush).draw(new Line2D.Double
            (x, y, x + boxSize, y));
    ((Graphics2D) brush).draw(new Line2D.Double
            (x + boxSize, y - boxSize/2, x + boxSize, y + boxSize/2));
    ((Graphics2D) brush).draw(new Line2D.Double
            (x , y - boxSize/2, x, y + boxSize/2));
    // compute x- and y-coordinates of the 4 half-size H-trees
    int x1 = x - boxSize/2;
    int x2 = x + boxSize/2;
    int y1 = y - boxSize/2;
    int y2 = y + boxSize/2;
    // recursively draw 4 half-size H-trees of order n-1
    _drawHTree(n-1, x1, y1, boxSize/2);
    _drawHTree(n-1, x1, y2, boxSize/2);   
    _drawHTree(n-1, x2 + boxSize/2, y1, boxSize/2);    
    _drawHTree(n-1, x2 + boxSize/2, y2, boxSize/2);    
}

那么,有人有任何想法吗?谢谢; D

为什么不jus声明一个颜色变量并为该变量编写一个设置器。然后,而不是在

中编写直接颜色
brush.setColor(Color.RED);

使用

 brush.setColor(myColor);

声明您的变量

Color myColor;
public void setMyColor(Color myColor){
     this.mayCOlor = myColor;

在ActionPerfem中只需称呼此方法

最新更新