繁体   English   中英

如何通过从另一个类中执行操作来更改一个类中的Graphics的颜色?

[英]How can I change the color of my Graphics in one class by preforming an action from another class?

我是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取消一个Color变量并为该变量写一个setter。 然后而不是写直接颜色

brush.setColor(Color.RED);

采用

 brush.setColor(myColor);

揭开你的变量

Color myColor;

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

在actionPerfomed中只需调用此方法即可

暂无
暂无

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

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