Java에서 창을 중앙에 배치하는 방법은 무엇입니까?
java.awt.Window
a JFrame
또는 a 와 같이 a 를 가운데에 맞추는 가장 쉬운 방법은 무엇입니까 JDialog
?
에서 이 링크
Java 1.4 이상을 사용하는 경우 대화 상자, 프레임 또는 창에서 간단한 메소드 setLocationRelativeTo (null)를 사용하여 중앙에 배치 할 수 있습니다.
이것은 모든 버전의 Java에서 작동합니다.
public static void centreWindow(Window frame) {
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
frame.setLocation(x, y);
}
setLocationRelativeTo (null) 및 Tookit.getDefaultToolkit (). getScreenSize () 기술은 기본 모니터에서만 작동합니다. 다중 모니터 환경에있는 경우 이러한 종류의 계산을 수행하기 전에 창이있는 특정 모니터에 대한 정보를 얻어야 할 수 있습니다.
때로는 중요하지만 때로는 그렇지 않습니다 ...
이를 얻는 방법에 대한 자세한 정보는 GraphicsEnvironment javadocs 를 참조하십시오 .
setLocationRelativeTo (null)는 setSize (x, y)를 사용하거나 pack ()을 사용한 후에 호출해야합니다.
Linux에서 코드
setLocationRelativeTo(null)
다중 디스플레이 환경에서 창을 시작할 때마다 임의의 위치에 창을 놓습니다. 그리고 코드
setLocation((Toolkit.getDefaultToolkit().getScreenSize().width - getSize().width) / 2, (Toolkit.getDefaultToolkit().getScreenSize().height - getSize().height) / 2);
내 두 디스플레이 사이의 정확한 중앙에 배치하여 창을 반으로 "절단"합니다. 다음 방법을 사용하여 중앙에 배치했습니다.
private void setWindowPosition(JFrame window, int screen)
{
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] allDevices = env.getScreenDevices();
int topLeftX, topLeftY, screenX, screenY, windowPosX, windowPosY;
if (screen < allDevices.length && screen > -1)
{
topLeftX = allDevices[screen].getDefaultConfiguration().getBounds().x;
topLeftY = allDevices[screen].getDefaultConfiguration().getBounds().y;
screenX = allDevices[screen].getDefaultConfiguration().getBounds().width;
screenY = allDevices[screen].getDefaultConfiguration().getBounds().height;
}
else
{
topLeftX = allDevices[0].getDefaultConfiguration().getBounds().x;
topLeftY = allDevices[0].getDefaultConfiguration().getBounds().y;
screenX = allDevices[0].getDefaultConfiguration().getBounds().width;
screenY = allDevices[0].getDefaultConfiguration().getBounds().height;
}
windowPosX = ((screenX - window.getWidth()) / 2) + topLeftX;
windowPosY = ((screenY - window.getHeight()) / 2) + topLeftY;
window.setLocation(windowPosX, windowPosY);
}
창을 첫 번째 디스플레이의 중앙에 표시합니다. 이것은 아마도 가장 쉬운 해결책이 아닐 것입니다.
Linux, Windows 및 Mac에서 제대로 작동합니다.
마침내 메인 jFrame을 중앙에 배치하기 위해 Swing GUI Forms를 사용하여 NetBeans에서 작동하는이 코드 묶음을 얻었습니다.
package my.SampleUIdemo;
import java.awt.*;
public class classSampleUIdemo extends javax.swing.JFrame {
///
public classSampleUIdemo() {
initComponents();
CenteredFrame(this); // <--- Here ya go.
}
// ...
// void main() and other public method declarations here...
/// modular approach
public void CenteredFrame(javax.swing.JFrame objFrame){
Dimension objDimension = Toolkit.getDefaultToolkit().getScreenSize();
int iCoordX = (objDimension.width - objFrame.getWidth()) / 2;
int iCoordY = (objDimension.height - objFrame.getHeight()) / 2;
objFrame.setLocation(iCoordX, iCoordY);
}
}
또는
package my.SampleUIdemo;
import java.awt.*;
public class classSampleUIdemo extends javax.swing.JFrame {
///
public classSampleUIdemo() {
initComponents();
//------>> Insert your code here to center main jFrame.
Dimension objDimension = Toolkit.getDefaultToolkit().getScreenSize();
int iCoordX = (objDimension.width - this.getWidth()) / 2;
int iCoordY = (objDimension.height - this.getHeight()) / 2;
this.setLocation(iCoordX, iCoordY);
//------>>
}
// ...
// void main() and other public method declarations here...
}
또는
package my.SampleUIdemo;
import java.awt.*;
public class classSampleUIdemo extends javax.swing.JFrame {
///
public classSampleUIdemo() {
initComponents();
this.setLocationRelativeTo(null); // <<--- plain and simple
}
// ...
// void main() and other public method declarations here...
}
다음은 JDK 1.7.0.07에서 작동하지 않습니다.
frame.setLocationRelativeTo(null);
왼쪽 상단 모서리를 중앙에 배치합니다. 창을 중앙에 배치하는 것과 다릅니다. 다른 하나는 frame.getSize () 및 dimension.getSize ()와 관련하여 작동하지 않습니다.
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
frame.setLocation(x, y);
getSize () 메서드는 Component 클래스에서 상속되므로 frame.getSize는 창 크기도 반환합니다. 따라서 수직 및 수평 치수에서 수직 및 수평 치수의 절반을 빼서 왼쪽 상단 모서리를 배치 할 위치의 x, y 좌표를 찾으면 중앙 지점의 위치를 알 수 있으며 창 중앙에 위치하게됩니다. 그러나 위 코드의 첫 번째 줄인 "Dimension ..."은 유용합니다. 중앙에 배치하려면 다음을 수행하십시오.
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension( (int)dimension.getWidth() / 2, (int)dimension.getHeight()/2 ));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
frame.setLocation((int)dimension.getWidth()/4, (int)dimension.getHeight()/4);
JLabel은 화면 크기를 설정합니다. Oracle / Sun 사이트의 Java 자습서에서 사용할 수있는 FrameDemo.java에 있습니다. 화면 크기의 높이 / 너비의 절반으로 설정했습니다. 그런 다음 왼쪽 상단을 왼쪽에서 화면 크기 치수의 1/4, 상단에서 화면 크기 치수의 1/4에 배치하여 중앙에 배치했습니다. 비슷한 개념을 사용할 수 있습니다.
아래는 기존 창의 상단 중앙에 프레임을 표시하는 코드입니다.
public class SwingContainerDemo {
private JFrame mainFrame;
private JPanel controlPanel;
private JLabel msglabel;
Frame.setLayout(new FlowLayout());
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
//headerLabel = new JLabel("", JLabel.CENTER);
/* statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
*/ msglabel = new JLabel("Welcome to TutorialsPoint SWING Tutorial.", JLabel.CENTER);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
//mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
// mainFrame.add(statusLabel);
mainFrame.setUndecorated(true);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
mainFrame.setVisible(true);
centreWindow(mainFrame);
}
public static void centreWindow(Window frame) {
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
frame.setLocation(x, 0);
}
public void showJFrameDemo(){
/* headerLabel.setText("Container in action: JFrame"); */
final JFrame frame = new JFrame();
frame.setSize(300, 300);
frame.setLayout(new FlowLayout());
frame.add(msglabel);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
frame.dispose();
}
});
JButton okButton = new JButton("Capture");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// statusLabel.setText("A Frame shown to the user.");
// frame.setVisible(true);
mainFrame.setState(Frame.ICONIFIED);
Robot robot = null;
try {
robot = new Robot();
} catch (AWTException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
final Dimension screenSize = Toolkit.getDefaultToolkit().
getScreenSize();
final BufferedImage screen = robot.createScreenCapture(
new Rectangle(screenSize));
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ScreenCaptureRectangle(screen);
}
});
mainFrame.setState(Frame.NORMAL);
}
});
controlPanel.add(okButton);
mainFrame.setVisible(true);
} public static void main (String [] args) throws Exception {
new SwingContainerDemo().showJFrameDemo();
}
frame.setLocationRelativeTo (null);
전체 예 :
public class BorderLayoutPanel {
private JFrame mainFrame;
private JButton btnLeft, btnRight, btnTop, btnBottom, btnCenter;
public BorderLayoutPanel() {
mainFrame = new JFrame("Border Layout Example");
btnLeft = new JButton("LEFT");
btnRight = new JButton("RIGHT");
btnTop = new JButton("TOP");
btnBottom = new JButton("BOTTOM");
btnCenter = new JButton("CENTER");
}
public void SetLayout() {
mainFrame.add(btnTop, BorderLayout.NORTH);
mainFrame.add(btnBottom, BorderLayout.SOUTH);
mainFrame.add(btnLeft, BorderLayout.EAST);
mainFrame.add(btnRight, BorderLayout.WEST);
mainFrame.add(btnCenter, BorderLayout.CENTER);
// mainFrame.setSize(200, 200);
// or
mainFrame.pack();
mainFrame.setVisible(true);
//take up the default look and feel specified by windows themes
mainFrame.setDefaultLookAndFeelDecorated(true);
//make the window startup position be centered
mainFrame.setLocationRelativeTo(null);
mainFrame.setDefaultCloseOperation(mainFrame.EXIT_ON_CLOSE);
}
}
setLocationRelativeTo(null)
또는 중 하나를 사용하여 창을 중앙에 배치하려고 시도한 후 간과 할 수있는 정말 간단한 것이 있으며 결국 setLocation(x,y)
약간 벗어나게됩니다.
창 자체의 크기를 사용하여 화면에 배치 할 위치를 계산하게되므로 호출 후 이러한 메서드 중 하나를 사용해야합니다 pack()
. pack()
를 호출 할 때까지 치수는 생각할 수있는 것이 아니므로 창을 중앙에 맞추기 위해 계산이 필요하지 않습니다. 도움이 되었기를 바랍니다.
Example: Inside myWindow() on line 3 is the code you need to set the window in the center of the screen.
JFrame window;
public myWindow() {
window = new JFrame();
window.setSize(1200,800);
window.setLocationRelativeTo(null); // this line set the window in the center of thr screen
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().setBackground(Color.BLACK);
window.setLayout(null); // disable the default layout to use custom one.
window.setVisible(true); // to show the window on the screen.
}
Actually frame.getHeight()
and getwidth()
doesnt return values , check it by System.out.println(frame.getHeight());
directly put the values for width and height ,then it will work fine in center. eg: as below
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x=(int)((dimension.getWidth() - 450)/2);
int y=(int)((dimension.getHeight() - 450)/2);
jf.setLocation(x, y);
both 450 is my frame width n height
public class SwingExample implements Runnable {
@Override
public void run() {
// Create the window
final JFrame f = new JFrame("Hello, World!");
SwingExample.centerWindow(f);
f.setPreferredSize(new Dimension(500, 250));
f.setMaximumSize(new Dimension(10000, 200));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void centerWindow(JFrame frame) {
Insets insets = frame.getInsets();
frame.setSize(new Dimension(insets.left + insets.right + 500, insets.top + insets.bottom + 250));
frame.setVisible(true);
frame.setResizable(false);
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
frame.setLocation(x, y);
}
}
The following code center the Window
in the center of the current monitor (ie where the mouse pointer is located).
public static final void centerWindow(final Window window) {
GraphicsDevice screen = MouseInfo.getPointerInfo().getDevice();
Rectangle r = screen.getDefaultConfiguration().getBounds();
int x = (r.width - window.getWidth()) / 2 + r.x;
int y = (r.height - window.getHeight()) / 2 + r.y;
window.setLocation(x, y);
}
You could try this also.
Frame frame = new Frame("Centered Frame");
Dimension dimemsion = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dimemsion.width/2-frame.getSize().width/2, dimemsion.height/2-frame.getSize().height/2);
참고URL : https://stackoverflow.com/questions/144892/how-to-center-a-window-in-java
'Programing' 카테고리의 다른 글
구조체 생성자 : "컨트롤이 호출자에게 반환되기 전에 필드가 완전히 할당되어야합니다." (0) | 2020.08.12 |
---|---|
sed / grep을 사용하여 두 단어 사이의 텍스트를 추출하는 방법은 무엇입니까? (0) | 2020.08.12 |
신속하게 배경에 흐림 효과 추가 (0) | 2020.08.12 |
Java 프로세스 목록 (0) | 2020.08.12 |
자바에서 문자열을 16 진수로 변환 (0) | 2020.08.12 |