簡體   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