Java JFrame size and centre
I'm working on a uni project which is to create a dice face using 2d graphics shapes. I have got that all done but I have a problem: I want my shape to change size when I adjust the window size, instead of just staying still also so that it stays in the middl开发者_Go百科e.
I thought I could set the position so that is was center tried this but didn't work. I'm not sure but would I have to write co-ordinates so that its changes size with the window? Any help with both problems would be great.
GUI setup 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();
}
}
Painting 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);
}
}
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 changes size when the frame changes size. Then based on this current size you can draw your components. This means that you can't hardcode the values in your drawing methods.
If you want to shift all the drawing coordinates with one command then you can use:
g.translate(5, 5);
at the top of the method. Then all hardcoded (x, y) values will be adjusted by 5 pixels each. This will allow you to change the centering of the drawing.
精彩评论