gpt4 book ai didi

java - 如何通过执行另一个类中的操作来更改一个类中图形的颜色?

转载 作者:太空宇宙 更新时间:2023-11-04 11:31:46 25 4
gpt4 key购买 nike

我是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

最佳答案

为什么不直接声明 Color 变量并为该变量编写一个 setter 。然后不要直接在

中写入颜色
brush.setColor(Color.RED);

使用

 brush.setColor(myColor);

声明变量

Color myColor;

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

在actionPerfomed中只需调用这个方法

关于java - 如何通过执行另一个类中的操作来更改一个类中图形的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43703897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com