4

我是一名初学 Java 的高中生,我必须制作一个简单的盒子和胡须。我无法让我在 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);
}
4

1 回答 1

5

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

你可以使用:

c.fill = GridBagConstraints.BOTH;
于 2012-10-26T23:20:41.107 回答