[英]How to get JPanel equal width and height
我在http://www.java-forums.org/new-java/7995-how-plot-graph-java-given-samples.html中找到了以下代碼。
我不明白為什么w = getWidth()和h = getHeight()不相等。 以及如何使它們彼此相等?
謝謝
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);
}
}
您似乎假設框架的大小是可查看內容區域的大小。
框架由內容和框架裝飾組成。 所以在我的系統上,一個400x400的幀,導致內容可視區域為384x362
你應該做的第一件事是擺脫f.setSize()
,它是不可靠的,因為它創建的可視內容區域對於你的程序運行的每個系統都是不同的。 相反,您應該使用f.pack()
,它使用幀內容來確定窗口的大小(以便可視內容區域優先)。
接下來,在GraphingData
類中,您需要覆蓋getPreferredSize
並返回您想要使用的面板的首選大小。
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
這將允許(某些)布局管理員更好地決定如何最好地展示您的組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.