如何在包含多个形状的 Java Swing JPanel 中更改特定形状的颜色?

问题描述 投票:0回答:0

我正在尝试为 certine 图(只有一个图)制作一个 gui 可视化工具,我想在上面可视化旅行推销员问题,所以首先我将绘制图形,然后我将使用一些算法解决它,我使用 swing我通过覆盖绘画方法在面板上绘制所有形状(圆圈和线条),我想做的是在我的程序中间更改我想要的任何形状的颜色
我遇到的问题是如何更改我绘制的任何形状的颜色 ,我所有的顶点都有一个形状对象,我将把它添加到我将在其上绘制的面板的 Graphics2D 对象中,但是如何从我在同一面板上绘制的许多形状中仅更改一个形状的颜色 shape 没有 setcolor() 方法,我只能改变 Graphics2D 对象颜色,如果我这样做,整个图形将更改为新颜色

我想在 JPanel 中绘制许多形状,并且我希望能够在我的程序中更改我想要的任何形状的颜色

public class Graphtesting {


public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    JFrame frame=new JFrame();
    frame.setDefaultCloseOperation(3);
    My_Panel panel=new My_Panel();
    frame.add(panel);
    frame.pack();
    frame.setVisible(true);
    int var=sc.nextInt();
    if(var==0)
    {
        // i want to change the color of oval 2 only and not both 
        //panel.oval_1.setcolor()    i want to do something like this but shape dosn't have a function to set color 
        // its like i want a seprate graphics2d object for each one of my shapes because i want to be able to change the color of each one individualy 
    }
    else
    {
        // i want to change the color of oval 1 only and not both 
    }
     
}
}


class My_Panel extends JPanel
{
    Ellipse2D.Double oval_1;
    Ellipse2D.Double oval_2;
    
    My_Panel()
    {
        setPreferredSize(new Dimension(500,500));
    
    }
    @Override
    public void paintComponent(Graphics g){

Graphics2D g2d=(Graphics2D)g;

 oval_1=new Ellipse2D.Double(10,10,50,50);

 oval_2=new Ellipse2D.Double(60,60,50,50);

g2d.setColor(Color.orange);  

g2d.fill(oval_2);    
         
g2d.setColor(Color.red); 

g2d.fill(oval_1);
}
}
java swing
© www.soinside.com 2019 - 2024. All rights reserved.