Javaでウィンドウを中央に配置する方法は?
-
02-07-2019 - |
質問
JFrame
や JDialog
など、 java.awt.Window
を中央に配置する最も簡単な方法は何ですか?
解決
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 を参照してください。これを取得する方法についての情報。
setSize(x、y)を使用するか、pack()を使用した後、setLocationRelativeTo(null)を呼び出す必要があります。
Linuxではコード
setLocationRelativeTo(null)
マルチディスプレイ環境で、起動するたびにウィンドウをランダムな場所に配置します。 そしてコード
setLocation((Toolkit.getDefaultToolkit().getScreenSize().width - getSize().width) / 2, (Toolkit.getDefaultToolkit().getScreenSize().height - getSize().height) / 2);
" cut" 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フォームを使用して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);
ウィンドウの中央揃えとは異なり、左上隅を中央に配置します。もう1つは、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()
が呼び出されるまで、寸法はあなたが思っているものではないため、ウィンドウを中央に配置するために計算が行われます。これがお役に立てば幸いです。
例:3行目のmyWindow()内には、画面の中央にウィンドウを設定するために必要なコードがあります。
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.
}
実際にはframe .getHeight()
および getwidth()
は値を返さないため、 System.out.println(frame.getHeight());で確認してください。
は、幅と高さの値を直接入力し、中央で正常に機能します。例:以下のとおり
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x=(int)((dimension.getWidth() - 450)/2);
int y=(int)((dimension.getHeight() - 450)/2);
jf.setLocation(x, y);
450は両方とも私のフレームの幅と高さです
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);
}
}
次のコードは、現在のモニターの中央(マウスポインターがある場所)の Window
を中央に配置します。
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);
}
これも試すことができます。
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);