gpt4 book ai didi

java - 在 JPanel 上绘制图像并将其添加到 JFrame

转载 作者:搜寻专家 更新时间:2023-11-01 02:29:26 28 4
gpt4 key购买 nike

我是一名初学 Java 的高中生,我必须制作一个简单的盒子和 mustache 。我无法让我在 JPanel 上绘制的内容显示在 JFrame 上。就是画不出来。谁能帮帮我?

public class BoxPlot extends JFrame {

public final int MIN;
public final double Q1;
public final double MEDIAN;
public final double Q3;
public final int MAX;

public BoxPlot(int[] data){
this.setLayout(new GridBagLayout());

this.MIN = Statistics.min(data);
this.Q1 = Statistics.lowerQuartile(data);
this.MEDIAN = Statistics.median(data);
this.Q3 = Statistics.upperQuartile(data);
this.MAX = Statistics.max(data);

this.addBox(data);
this.addSummary();

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800, 600);
this.setResizable(true);
this.setVisible(true);
}

// Adds a panel with the boxplot
private void addBox(int[] data) {
Box box = new Box(data);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.weighty = 1;
this.add(box, c);
}

// Adds a panel with the five number summaries as JLabels
// to the bottom of the JFrame
private void addSummary() {
JPanel summary = new JPanel();
summary.setLayout(new GridLayout());
JLabel l = new JLabel("Minimum: "+this.MIN, JLabel.CENTER);
summary.add(l);
l = new JLabel("First Quartile: "+this.Q1, JLabel.CENTER);
summary.add(l);
l = new JLabel("Median: "+this.MEDIAN, JLabel.CENTER);
summary.add(l);
l = new JLabel("Third Quartile: "+this.Q3, JLabel.CENTER);
summary.add(l);
l = new JLabel("Maximum: "+this.MAX, JLabel.CENTER);
summary.add(l);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
c.weightx = 1;
c.ipady = 10;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_END;
this.add(summary, c);
}

``

public class Box extends JPanel{

private int min;
private double q1;
private double median;
private double q3;
private int max;

public Box(int[] data) {
this.min = Statistics.min(data);
this.q1 = Statistics.lowerQuartile(data);
this.median = Statistics.median(data);
this.q3 = Statistics.upperQuartile(data);
this.max = Statistics.max(data);
}

// paints the box onto the JPanel
public void paintComponent(Graphics g){
int d1 =10 * (int) (this.q1-this.min);
int d2 =10 * (int) (this.median-this.q1);
int d3 =10 * (int) (this.q3-this.median);
int d4 =10 * (int) (this.max-this.q3);
g.drawLine(100, 150, 100+d1, 150);
g.drawLine(100+d1+d2+d3, 150, 100+d1+d2+d3+d4, 150);
g.setColor(Color.RED);
g.fillRect(100+d1, 100, d2, 100);
g.setColor(Color.BLUE);
g.fillRect(100+d1+d2, 100, d3, 100);
}

最佳答案

您没有为您的 Box 组件设置 GridBagConstraints 填充值,因此该组件实际上没有大小。

你可以使用:

c.fill = GridBagConstraints.BOTH;

关于java - 在 JPanel 上绘制图像并将其添加到 JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13095483/

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