gpt4 book ai didi

java - JComponent 不会显示图像

转载 作者:行者123 更新时间:2023-12-02 07:58:41 24 4
gpt4 key购买 nike

我是一名初学者程序员,我正在尝试让这个程序运行。尽管 JComponent 的新 Java 屏幕上没有出现任何图像,但一切都可以正确编译。该程序要做的几乎就是获取一个输入值并将其分配给条形图的大小值。在程序中,我必须使用外部油漆组件类来运行原始类以及驱动程序,这可能是让我失望的原因。提前致谢!

public class BarChartTester
{
public static void main(String[] args)
{

BarChartPaintComponent component = new BarChartPaintComponent();
Scanner in = new Scanner(System.in);
System.out.println("Enter the Values you wish to use (>0). Press -1 on an empty line to stop");
Boolean flag = false;
while(!flag)
{
double numbers = in.nextDouble();
if(numbers == -1)
flag = true;
else if(numbers<-1)
System.out.println("You have typed in invalid number");
else
component.add(numbers);
}
JFrame frame = new JFrame();
frame.setSize(300, 300);
frame.setTitle("A Bar Graph");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(component);
frame.setVisible(true);
}

}

public class BarChart extends JComponent
{
private ArrayList<Double> list;
private double value;
private int i;

public BarChart()
{

list = new ArrayList<Double>();
}


public void add(double value)
{
list.add(i, value);
i++;
}

public void draw(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;

Double greatest = list.get(0);
Double least;
for(int j =1;j<=list.size();j++)
{
if(list.get(j)> greatest)
greatest = list.get(j);
else
least = list.get(j);


}

for(int i = 0;i<=list.size();i++)
{
int x = 20;
int width = 20;
double barNumber = list.get(i);
double size = barNumber;
if(list.get(i) == greatest){
g2.setPaint(Color.BLUE);
g2.fill(new Rectangle2D.Double(x,300,width,300));
}
else
{
g2.setPaint(Color.BLUE);
g2.fill(new Rectangle2D.Double(x,300,width, barNumber));
}

x +=20;

}



}










}


public class BarChartPaintComponent extends BarChart
{
public void paintComponent(Graphics g, double array){
Graphics2D g2 = (Graphics2D) g;
BarChart component= new BarChart();
component.add(array);
component.draw(g2);

}
}

最佳答案

您的主要问题是,打算绘制的代码永远不会被调用,因为您没有实现paintComponent(Graphics g)方法。因此,替换你的paintComponent:

public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
this.draw(g2);
}

然后进行史蒂文斯建议的更正。

此外,在第二个 for 中,您正在初始化变量 x (int x = 20)。这样,每次循环迭代时 x 都将为 20。在 for 循环之前执行此操作。

关于java - JComponent 不会显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9237200/

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