Reputation: 55
so i have a program where i display an image using paintComponent (arcs and ovals, to be precise) beside a set of JButtons and a JTextArea, and i want the arcs/ovals to change size when/if the user changes the size of the frame. i have implemented the getWidth, getHeight stuff, but i cant seem to get it to work.
this is my code. if i dont setPreferredSize, then it doesnt work; the arcs/ovals get squished between the edge of the frame and the buttons. if i try to use getWidth() and getHeight() instead of 200 for size, it doesnt work either; the arcs/ovals dont show up at all. not sure what to do.
also, any tips on making my code less convoluted (eg. if only need one class) would be appreciated.
public class GUIDesign
{
public static void main(String[] args)
{
GUIFrame frame = new GUIFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class GUIFrame extends JFrame
{
PaintPanel2 canvas = new PaintPanel2();
public GUIFrame()
{
...
add(mainHolder, BorderLayout.CENTER); //has the JButtons, JTextArea.
add(canvas, BorderLayout.WEST);
this.setTitle("this");
this.pack();
this.setLocationRelativeTo(null);
}
}
class PaintPanel2 extends JPanel
{
private static int SIZE = 200;
public PaintPanel2()
{
setPreferredSize(new Dimension(SIZE, SIZE));
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
int xCenter = getWidth()/2;
int yCenter = getHeight()/2;
int startOvalX = (int) (xCenter/5);
int startOvalY = (int) (yCenter/5);
int endOvalX = (int) (xCenter * 1.5);
int endOvalY = (int) (yCenter * 1.5);
g.setColor(Color.green);
g.fillArc(startOvalX, startOvalY, endOvalX, endOvalY, 0, 180);
g.setColor(Color.black);
g.drawArc(startOvalX, startOvalY, endOvalX, endOvalY, 0, 180);
g.setColor(Color.black);
g.fillOval((int)(startOvalX/1.5) - 1, (int) (startOvalY * 2.5),(int) (endOvalX * 1.1) + 2,(int)(endOvalY/1.5));
g.setColor(Color.green);
g.fillOval((int)(startOvalX/1.5), (int) (startOvalY * 2.5) -1,(int) (endOvalX * 1.1),(int)(endOvalY/1.5));
}
}
Upvotes: 3
Views: 718
Reputation: 32391
When you are using a BorderLayout
as the layout manager, the component that is added in the CENTER
will be the one to resize when the main container resizes. So, if you change the code to have the canvas in the center, you will get the expected results:
add(mainHolder, BorderLayout.WEST); //has the JButtons, JTextArea.
add(canvas, BorderLayout.CENTER);
Upvotes: 2