Чтобы расположить JFrame в центре экрана в Java, можно использовать несколько методов. Вот некоторые из часто используемых методов:
Метод 1: использование класса Toolkit
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Set frame size
frame.setSize(400, 300);
// Get the screen dimensions
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int screenWidth = screenSize.width;
int screenHeight = screenSize.height;
// Calculate the position of the frame
int xPos = (screenWidth - frame.getWidth()) / 2;
int yPos = (screenHeight - frame.getHeight()) / 2;
// Set the frame position
frame.setLocation(xPos, yPos);
// Make the frame visible
frame.setVisible(true);
}
}
Метод 2: использование класса GraphicsEnvironment
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Set frame size
frame.setSize(400, 300);
// Get the graphics environment
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
Dimension screenSize = ge.getMaximumWindowBounds().getSize();
// Calculate the position of the frame
int xPos = (screenSize.width - frame.getWidth()) / 2;
int yPos = (screenSize.height - frame.getHeight()) / 2;
// Set the frame position
frame.setLocation(xPos, yPos);
// Make the frame visible
frame.setVisible(true);
}
}
Метод 3: использование класса SwingUtilities
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("Title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Set frame size
frame.setSize(400, 300);
// Set the frame position to the center of the screen
frame.setLocationRelativeTo(null);
// Make the frame visible
frame.setVisible(true);
}
});
}
}