How to get JPanel equal width and height

2019-09-05 17:28发布

I found the following code from http://www.java-forums.org/new-java/7995-how-plot-graph-java-given-samples.html.

I don't understand why w = getWidth() and h = getHeight() are not equal. And how to make them equal to each other?

Thanks

import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;

public class GraphingData extends JPanel {
 int[] data = {
     21, 14, 18, 03, 86, 88, 74, 87, 54, 77,
     61, 55, 48, 60, 49, 36, 38, 27, 20, 18
 };
 final int PAD = 20;

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON);
    int w = getWidth();
    int h = getHeight();
    // Draw ordinate.
    g2.draw(new Line2D.Double(PAD, PAD, PAD, h-PAD));
    // Draw abcissa.
    g2.draw(new Line2D.Double(PAD, h-PAD, w-PAD, h-PAD));
    double xInc = (double)(w - 2*PAD)/(data.length-1);
    double scale = (double)(h - 2*PAD)/getMax();
    // Mark data points.
    g2.setPaint(Color.red);
    for(int i = 0; i < data.length; i++) {
        double x = PAD + i*xInc;
        double y = h - PAD - scale*data[i];
        g2.fill(new Ellipse2D.Double(x-2, y-2, 4, 4));
    }
}

private int getMax() {
    int max = -Integer.MAX_VALUE;
    for(int i = 0; i < data.length; i++) {
        if(data[i] > max)
            max = data[i];
    }
    return max;
}

public static void main(String[] args) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(new GraphingData());
    f.setSize(400,400);
    f.setLocation(200,200);
    f.setVisible(true);
}
}

1条回答
2楼-- · 2019-09-05 17:40

You seem to be under the assumption that the size of frame is the size of the viewable content area.

A frame is made up of the content AND frame decorations. So on my system, a frame of 400x400, results in a content viewable area of 384x362

Frame Size

The first thing you should do is get rid of f.setSize(), it is unreliable as the viewable content area it creates will be different for each system your program runs on. Instead, you should be using f.pack(), which uses the frame contents to determine the size of the window (so that the viewable content area is given precedence).

Next, in you GraphingData class, you will need to override getPreferredSize and return the preferred size of the panel you would like to use.

@Override
public Dimension getPreferredSize() {
    return new Dimension(400, 400);
}

This will allow (some) layout managers to make better decisions about how best to present your component.

查看更多
登录 后发表回答