I wanted to make my JFrame and JTextField in the center of my screen, but I feel like I could simplify the code a lot. How would I do it?
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.*;
import java.lang.Math;
public class window {
static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
static double width = screenSize.getWidth();
static double height = screenSize.getHeight();
static int width2 = (int) Math.round(width);
static int height2 = (int) Math.round(height);
static int frame_width = 500;
static int frame_height = 450;
That is the instance fields(is it called instance fields? I don't know, I'm fairly new to java) which contain the width and height of your screen. It rounds the width and height so they can be casted from long to int, because as far as I know, the setLocation() method only accepts int's.
public static void main(String[] args) {
//New Panel object
JPanel panel = new JPanel();
panel.setLayout(null);
//New JFrame object
JFrame miWindow = new JFrame();
miWindow.setSize(frame_width, frame_height);
miWindow.setLocation(width2/2 - frame_width/2 , height2/2 - frame_width/2);
miWindow.setResizable(false);
miWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
miWindow.setTitle("Calculator");
miWindow.add(panel);
//Input 1
JTextField num1 = new JTextField();
int fieldWidth = 120;
num1.setBounds(frame_width/2 - fieldWidth/2, 65, fieldWidth, 25);
panel.add(num1);
miWindow.setVisible(true);
The main method makes a frame, the x of the screen is your screen width divided by 2(so we can get the exact middle), but because 0,0 of the frame is the top left corner, it takes the width of the frame, and divides that by 2, to get the middle of the frame, and subtracts the frame width from the screen width, to position the frame in the exact middle. As you can tell that a LOT of steps, and I was just wondering if their was a much simpler way to clean up the code. I have a feeling I could replace all that with 1 line of code