ウインドウが書き換えられるのは隠れていたウインドウが見えるようになったときだけではありません。ウィンドウの大きさをマウスのドラッグなどで変更した時にもpaintComponent()が呼び出されます。
ウインドウの大きさを調べてそれを元に書き換えるようにプログラムをすればウインドウが大きくなると図も大きくなるようにできます。
import java.awt.*; import javax.swing.*; public class DrawRectG3 extends JFrame{ public DrawRectG3() { setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(400,300); setTitle("グラフ"); MyPanel mypnl = new MyPanel(); mypnl.setSize(400,300); mypnl.setBackground(Color.white); setLayout(new BorderLayout()); add(mypnl, BorderLayout.CENTER); setVisible(true); } public static void main(String[] args){ DrawRectG2 myframe = new DrawRectG2(); } public class MyPanel extends JPanel{ double[] data={100, 40.5, 520, 360.4, 480.8, 250, 40, 82}; double max = 600; Color c = new Color(0,0,0); Color cf = new Color(128,128,128); public void paintComponent(Graphics myg){ super.paintComponent(myg); int pw = getWidth(); //パネルの幅 int ph = getHeight(); //パネルの高さ int top = 20; //topマージン int bottom= ph-50; //これだけマージンでなく位置 int left = 50; int right = 20; int dx = (pw-left-right)/data.length; //1項目の幅 double rate = (bottom-top)/max; //値*rate→パネル上の値 myg.setColor(c); myg.drawLine(left,bottom,left+dx*data.length,bottom); //x軸 myg.drawLine(left,bottom,left,top); //y軸 myg.setColor(cf); for(int i=0; data.length>i ; i++){ int w = (int)(dx*0.8); int h = (int)(data[i]*rate); int x = (int)(left+dx*i); int y = bottom-h; myg.fillRect(x,y,w,h); } } } }
これだけでOKです。class MyPanelのなかで、getWidth()をすればMyPanelから作られたインスタンス(ここではmypnl)の幅を得ることができます。
詳しくいうとマウスで変更すると幅が変わるのはJFrameを拡張したDrawRectG3のインスタンスであるmyframeなのです。 ですが、レイアウトマネージャーであるBorderLayoutにより、mypanelはmyframeいっぱいまで引き伸ばされます。この引き伸ばされたmypanelの幅を得ていることになります。
小さくすることも可能です。leftとbottomを固定している事が分かるでしょう。
スケール(目盛り)も入れてみましょう
myg.drawString(Integer.toString(整数),x,y);