Matt Westlake
Matt Westlake

Reputation: 3651

center a JFrame container object

Every time i make a new JFrame object, the frame appears in the 0,0 location. I have tried looking up how to center the window using setLocationRelativeTo(), but everything I've tried invoking on my container shows as non-compilable code. here is one of my classes that I am using:

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();
    }
}
}

When I run this code, the window starts in the (0,0) location. what i wish to do, is re size the window to 1/4 the size of the resolution of the computer it's running on, and to reset the location of the window so the center of the window is in the center of the screen. If resolution 1000x1000, window should be 250x250 and be located at (500 - 250/2)X,(500 - 250/2)Y (top left corner) by (500 + 250/2)X, (500 + 250/2)Y (bottom right corner)

(please note, i'm using a different class for each window I'm opening and closing it when the process is done, so without the other classes this will not be fully compilable. I am passing my ObjectOutputStream, ObjectInputStream, an object I call Message, and another object I call ConnectInfo. The output & input streams are to keep the connection alive to the server, Message is the serialized information being sent back and forth, and ConnectionInfo holds essencially cookie information (user connected, session info, permission level, etc).

Ok now i have

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();
    }
}
}

now the problem is with myJFrame.add(EU) it says "java.lang.IllegalArgumentException: adding container's parent to itself". Thanks for any help in advance.

Upvotes: 2

Views: 4827

Answers (3)

mKorbel
mKorbel

Reputation: 109813

you have to call as last code lines in the GUI constructor

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

another suggestions

EDIT

put code line EditUsers eu = new EditUsers(); in the main class, returns new GUI instance with JFrame, wrap code creates GUI to the InitialThread, hope nothing else :-)

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

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

EDIT2

modified code returns

enter image description here

from code

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;
    }*/

EDIT 3

JTextArea should be in JScrollPane,

Upvotes: 5

Pshemo
Pshemo

Reputation: 124225

Try myJFrameObject.setLocationRelativeTo(null);

from JavaDoc

  • If the component is null, or the GraphicsConfiguration associated with this component is null, the window is placed in the center of the screen. The center point can be obtained with the GraphicsEnvironment.getCenterPoint method.
  • If the component is not null, but it is not currently showing, the window is placed in the center of the target screen defined by the GraphicsConfiguration associated with this component.
  • If the component is not null and is shown on the screen, then the window is located in such a way that the center of the window coincides with the center of the component.

Edit

I just tested your code on this (less advanced) constructor and it seems to works like you wanted (at least thats what I hope). I placed setLocationRelativeTo(null) just before setVisible(true) to make sure Frame will contains all its elements and know what size to use when centering.

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);
}

Upvotes: 7

semTex
semTex

Reputation: 343

the setLocationRelativeTo should be called after you window is more or less initialized in its dimensions.

regarding to you sample directly after the pack command. the pack() command possibly rearranges your frame.

Upvotes: 2

Related Questions