将JFrame容器对象居中

时间:2012-06-23 13:39:24

标签: java swing jframe containers centering

每次制作新的JFrame对象时,框架都会显示在0,0位置。我已经尝试使用setLocationRelativeTo()查找如何使窗口居中,但我尝试在容器上调用的所有内容都显示为不可编译的代码。这是我正在使用的课程之一:

package Ginfo;

import java.awt.*;
import java.awt.event.*;
import java.io.*;

import javax.swing.*;

public class EditUsers extends JFrame implements ActionListener
{
    Container EU;

    JPanel modUsers, button, output;
    JLabel user, password;
    JTextField tuser, tpassword;
    JTextArea toutput;
    JButton addAdmin, addStand, editPass, removeUser, exit;

    ObjectOutputStream oout;
    ObjectInputStream oin;

    Message m;
    ConnectInfo c;

public EditUsers (ObjectOutputStream oout2, ObjectInputStream oin2, Message m2, ConnectInfo a)
{
    super("User Modifications");
    EU = getContentPane();
    oout = oout2;
    try 
    {
        oout.reset();
    } 
    catch (IOException e)
    {
        e.printStackTrace();
    }
    oin = oin2;
    m = m2;
    c = a;

    buildUserInfoPanel();
    buildOutputPanel();
    buildButtonPanel();
    EU.add(modUsers, BorderLayout.NORTH);
    EU.add(output, BorderLayout.CENTER);
    EU.add(button, BorderLayout.SOUTH);
    pack();
    setVisible(true);

}

private void buildUserInfoPanel()
{
    modUsers = new JPanel();
    modUsers.setLayout(new GridLayout (2,2));
    user = new JLabel ("Enter the username you wish to edit: ");
    tuser = new JTextField (15);
    password = new JLabel("Enter their new password: ");
    tpassword = new JTextField(15);

    modUsers.add(user);
    modUsers.add(tuser);
    modUsers.add(password);
    modUsers.add(tpassword);
}

private void buildOutputPanel()
{
    output = new JPanel();
    toutput = new JTextArea();
    toutput.setPreferredSize(new Dimension (400,100));

    output.add(toutput);
}

private void buildButtonPanel()
{
    button = new JPanel();
    addAdmin = new JButton ("Add user as administrator");
    addStand = new JButton ("Add user as standard");
    editPass = new JButton ("Change password");
    removeUser = new JButton ("Remove user");
    exit = new JButton ("Back");

    button.add(addAdmin);
    button.add(addStand);
    button.add(editPass);
    button.add(removeUser);
    button.add(exit);

    addAdmin.addActionListener(this);
    addStand.addActionListener(this);
    editPass.addActionListener(this);
    removeUser.addActionListener(this);
    exit.addActionListener(this);
}

public void actionPerformed(ActionEvent e) 
{
    if (e.getSource() == addAdmin)
    {
        m.type = Message.ADDADMIN;
        m.main = tuser.getText();
        m.setPassword = tpassword.getText();
        m.setPermission = 1;
    }
    else if (e.getSource() == addStand)
    {
        m.type = Message.ADDSTANDARD;
        m.main = tuser.getText();
        m.setPassword = tpassword.getText();
        m.setPermission = 2;
    }
    else if (e.getSource() == editPass)
    {
        m.type = Message.CHANGEPASSWORD;
        m.main = tuser.getText();
        m.setPassword = tpassword.getText();
    }
    else if (e.getSource() == removeUser)
    {
        m.type = Message.REMOVEUSER;
        m.main = tuser.getText();
    }
    else if (e.getSource() == exit)
    {
        new WhatToDo (oout, oin, m, c);
        dispose();
        return;
    }
    try 
    {
        oout.writeObject(m);
        m = (Message)oin.readObject();
        toutput.setText(m.response);
    } 
    catch (IOException e1) 
    {
        e1.printStackTrace();
    } 
    catch (ClassNotFoundException e1) 
    {
        e1.printStackTrace();
    }
}
}

当我运行此代码时,窗口从(0,0)位置开始。我想做的是,将窗口大小调整为运行计算机分辨率大小的1/4,并重置窗口的位置,使窗口的中心位于屏幕的中心。如果分辨率为1000x1000,窗口应为250x250,位于(500 - 250/2)X,(500 - 250/2)Y(左上角)乘(500 + 250/2)X,(500 + 250/2 )Y(右下角)

(请注意,我正在为每个窗口使用不同的类,我正在打开并在进程完成时关闭它,所以没有其他类,这将无法完全编译。我传递的是ObjectOutputStream,ObjectInputStream,我称之为Message的对象,另一个我称之为ConnectInfo的对象。输出和输入流是为了使连接保持活动状态,Message是来回发送的序列化信息,ConnectionInfo基本上保存cookie信息(用户连接,会话信息,权限级别等。)

好的,我现在

package Ginfo;

import java.awt.*;
import java.awt.event.*;
import java.io.*;

import javax.swing.*;

public class EditUsers implements ActionListener
{

Container EU;

JFrame myJFrame;

JPanel modUsers, button, output;
JLabel user, password;
JTextField tuser, tpassword;
JTextArea toutput;
JButton addAdmin, addStand, editPass, removeUser, exit;

ObjectOutputStream oout;
ObjectInputStream oin;

Message m;
ConnectInfo c;

public EditUsers (ObjectOutputStream oout2, ObjectInputStream oin2, Message m2, ConnectInfo a)
{
    myJFrame = new JFrame("User Modifications");
    EU = myJFrame.getContentPane();
    oout = oout2;
    try 
    {
        oout.reset();
    } 
    catch (IOException e)
    {
        e.printStackTrace();
    }
    oin = oin2;
    m = m2;
    c = a;

    buildUserInfoPanel();
    buildOutputPanel();
    buildButtonPanel();
    EU.add(modUsers, BorderLayout.NORTH);
    EU.add(output, BorderLayout.CENTER);
    EU.add(button, BorderLayout.SOUTH);
    myJFrame.add(EU);
    myJFrame.pack();
    myJFrame.setVisible(true);

}

private void buildUserInfoPanel()
{
    modUsers = new JPanel();
    modUsers.setLayout(new GridLayout (2,2));
    user = new JLabel ("Enter the username you wish to edit: ");
    tuser = new JTextField (15);
    password = new JLabel("Enter their new password: ");
    tpassword = new JTextField(15);

    modUsers.add(user);
    modUsers.add(tuser);
    modUsers.add(password);
    modUsers.add(tpassword);
}

private void buildOutputPanel()
{
    output = new JPanel();
    toutput = new JTextArea();
    toutput.setPreferredSize(new Dimension (200,100));

    output.add(toutput);
}

private void buildButtonPanel()
{
    button = new JPanel();
    addAdmin = new JButton ("Add user as administrator");
    addStand = new JButton ("Add user as standard");
    editPass = new JButton ("Change password");
    removeUser = new JButton ("Remove user");
    exit = new JButton ("Back");

    button.add(addAdmin);
    button.add(addStand);
    button.add(editPass);
    button.add(removeUser);
    button.add(exit);

    addAdmin.addActionListener(this);
    addStand.addActionListener(this);
    editPass.addActionListener(this);
    removeUser.addActionListener(this);
    exit.addActionListener(this);
}

public void actionPerformed(ActionEvent e) 
{
    if (e.getSource() == addAdmin)
    {
        m.type = Message.ADDADMIN;
        m.main = tuser.getText();
        m.setPassword = tpassword.getText();
        m.setPermission = 1;
    }
    else if (e.getSource() == addStand)
    {
        m.type = Message.ADDSTANDARD;
        m.main = tuser.getText();
        m.setPassword = tpassword.getText();
        m.setPermission = 2;
    }
    else if (e.getSource() == editPass)
    {
        m.type = Message.CHANGEPASSWORD;
        m.main = tuser.getText();
        m.setPassword = tpassword.getText();
    }
    else if (e.getSource() == removeUser)
    {
        m.type = Message.REMOVEUSER;
        m.main = tuser.getText();
    }
    else if (e.getSource() == exit)
    {
        new WhatToDo (oout, oin, m, c);
        myJFrame.dispose();
        return;
    }
    try 
    {
        oout.writeObject(m);
        m = (Message)oin.readObject();
        toutput.setText(m.response);
    } 
    catch (IOException e1) 
    {
        e1.printStackTrace();
    } 
    catch (ClassNotFoundException e1) 
    {
        e1.printStackTrace();
    }
}
}

现在问题在于myJFrame.add(EU)它说“java.lang.IllegalArgumentException:将容器的父级添加到自身”。感谢您提前提供任何帮助。

3 个答案:

答案 0 :(得分:7)

尝试myJFrameObject.setLocationRelativeTo(null);

来自JavaDoc

  • 如果组件为null,或者与此组件关联的GraphicsConfiguration为null,则窗口将放置在屏幕的中心。可以使用GraphicsEnvironment.getCenterPoint方法获取中心点。
  • 如果组件不为null,但当前未显示,则窗口将放置在与此组件关联的GraphicsConfiguration定义的目标屏幕的中心。
  • 如果组件不为空并显示在屏幕上,则窗口的位置使得窗口的中心与组件的中心重合。

修改

我刚刚在这个(不太高级的)构造函数上测试了你的代码,它看起来像你想要的那样(至少那是我希望的)。我在setLocationRelativeTo(null)之前放置setVisible(true)以确保Frame包含其所有元素并知道在居中时使用的大小。

public EditUsers() {
    super("User Modifications");
    //I removed some not GUI operations

    EU = getContentPane();

    buildUserInfoPanel();
    buildOutputPanel();
    buildButtonPanel();
    EU.add(modUsers, BorderLayout.NORTH);
    EU.add(output, BorderLayout.CENTER);
    EU.add(button, BorderLayout.SOUTH);
    pack();
    //put setLocationRelativeTo before setVisible() 
    setLocationRelativeTo(null);
    setVisible(true);
}

答案 1 :(得分:5)

你必须在GUI构造函数中调用最后的代码行

JFrame#pack();
JFrame#setLocationRelativeTo(null); // Windows OS
//or JFrame#setLocationByPlatform(true); //depends of Native OS
JFrame#setVisible(true);

另一个建议

修改

将代码行EditUsers eu = new EditUsers();放在主类中,返回带有JFrame的新GUI实例,包装代码创建GUI到InitialThread,希望别的: - )

   public static void main(String[] a_args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                EditUsers eu = new EditUsers();
            }
        });
    }

EDIT2

修改后的代码返回

enter image description here

来自代码

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;

public class EditUsers implements ActionListener {

    private JFrame myJFrame;
    private JPanel modUsers, button, output;
    private JLabel user, password;
    private JTextField tuser, tpassword;
    private JTextArea toutput;
    private JButton addAdmin, addStand, editPass, removeUser, exit;
    private ObjectOutputStream oout;
    private ObjectInputStream oin;
    //private Message m;
    //private ConnectInfo c;

    public static void main(String[] a_args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                EditUsers eu = new EditUsers();
            }
        });
    }

    public EditUsers() {
        //editUsers(oout2, oin2, m2, a);
        buildUserInfoPanel();
        buildOutputPanel();
        buildButtonPanel();
        myJFrame = new JFrame("User Modifications");
        myJrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myJFrame.add(modUsers, BorderLayout.NORTH);
        myJFrame.add(output, BorderLayout.CENTER);
        myJFrame.add(button, BorderLayout.SOUTH);
        myJFrame.pack();
        myJFrame.setLocationRelativeTo(null);
        myJFrame.setVisible(true);
    }

    /*private void editUsers(ObjectOutputStream oout2, 
          ObjectInputStream oin2, Message m2, ConnectInfo a) {
        oout = oout2;
        try {
            oout.reset();
        } catch (IOException e) {
            e.printStackTrace();
        }
        oin = oin2;
        m = m2;
        c = a;
    }*/

编辑3

JTextArea应该在JScrollPane

答案 2 :(得分:2)

在窗口或多或少初始化后,应调用setLocationRelativeTo

关于您在pack命令后直接采样。 pack()命令可能会重新排列您的框架。