Size and Center Java JFrame

I am working on a uni project that is designed to create a face in a bone using 2 graphic shapes. I have everything, but I have a problem: I want my shape to resize when I resize the window, and not just stay still so that it stays in the middle.

I thought that I could set the position so that it was in the center, but did not work. I'm not sure, but should I write the coordinates so that the changes change using the window? Any help on both issues would be great.

GUI customization code

import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import javax.swing.JComponent; import javax.swing.JFrame; public class DiceSimulator { public static void main(String[] args) { JFrame frame = new JFrame("DiceSimulator"); frame.setVisible(true); frame.setSize(400, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); draw object = new draw(); frame.add(object); frame.setLocationRelativeTo(null); object.drawing(); } } 

Color code

 import javax.swing.*; import java.awt.*; //import java.util.Random; public class draw extends JComponent { public void drawing() { repaint(); } public void paintComponent(Graphics g) { super.paintComponent(g); //Random1 random = new Random1(); Graphics2D g2 = (Graphics2D) g; g.setColor(Color.BLACK); Rectangle box = new Rectangle(115, 60, 150, 150); g2.fill(box); g.setColor(Color.WHITE); g.fillOval(145, 75, 30, 30); g.setColor(Color.WHITE); g.fillOval(205, 75, 30, 30); g.setColor(Color.WHITE); g.fillOval(145, 115, 30, 30); g.setColor(Color.WHITE); g.fillOval(205, 115, 30, 30); g.setColor(Color.WHITE); g.fillOval(145, 155, 30, 30); g.setColor(Color.WHITE); g.fillOval(205, 155, 30, 30); } } 
+4
source share
1 answer

In the paintComponent () method you need to use

 int width = getSize().width; int height = getSize().height; 

to get the current size of the component as it resizes when the frame size changes. Then, based on this current size, you can draw your components. This means that you cannot hardcode values ​​in your drawing methods.

If you want to move all the coordinates of a drawing with a single command, you can use:

 g.translate(5, 5); 

at the top of the method. Then, all hard-coded (x, y) values ​​will be adjusted to 5 pixels each. This will allow you to change the centering of the drawing.

+4
source

All Articles