Re: Problem with GridLayout
erenay wrote:
Thanks for the answers.
I used frame.pack(); but it didn't help, the same problem goes on.
This is how the frame looks like:
http://img50.imageshack.us/img50/5034/graph1xz.jpg
graphNum was 4 and sliceNum was 6. When I change the size of the frame,
the graph adjusts itself to an appropriate size.
This is how my Graph class is like:
---------------------------------------------------------------------------------
public class Graph extends JComponent{
public SliceVal[] slices;
public Graph(){
slices = new SliceVal[AProject.sliceNum];
}
public SliceVal[] getSliceVal(){
return this.slices;
}
public void setSliceVal(SliceVal[] slices){
this.slices = slices;
}
public void drawGraph(Graphics2D g, Rectangle area, SliceVal[]
slices) {
...
g.setColor(...);
g.fillArc(...);
}
}
public void paint(Graphics g) {
drawGraph((Graphics2D)g, getBounds(), slices);
}
}
------------------------------------------------------------
Maybe the problem is with getBounds(), returning the coordinate of the
rectangle as (0,0)
I don't know. What should I do?
Check this.
- Graph needs to have preferred size.
- Don't override paint, but do paintComponent
(nothing wrong with your example)
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestSlices {
private static Color colors[] = { Color.GREEN, Color.RED, Color.CYAN,
Color.ORANGE, Color.MAGENTA, Color.BLUE };
public static void main(String[] args) {
JPanel pnl = new JPanel(new GridLayout(1, colors.length));
for (int i = 0; i < 7; i++) {
pnl.add(new Graph());
}
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(pnl);
f.pack();
f.setVisible(true);
}
static class Graph extends JComponent {
Graph() {
setPreferredSize(new Dimension(100, 100));
}
protected void paintComponent(Graphics g) {
// public void paint(Graphics g) {
int x = 0;
int y = 0;
int w = getWidth() / 2;
int h = getHeight() / 2;
int shift = 60;
for (int i = 0, angle = 0; i < colors.length; i++, angle += shift) {
g.setColor(colors[i]);
g.fillArc(x, y, w, h, angle, shift);
}
}
}
}