JAVA

Tired of running a java application and it pops up at the top left corner of the screen? Here is the way out.


    public class TestingCenter extends javax.swing.JFrame {
        java.awt.Toolkit toolkit = Toolkit.getDefaultToolkit();
        java.awt.Dimension dim = toolkit.getScreenSize();
        
        public TestingCenter() {
            super("Testing Center");
            show()    //your IDE should strikethrough this.Can be replaced with setVisible(true)
            setSize(300, 400);
            setLocation(myWidth(this), myHeight(this));
            setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
        }
        
        public int myWidth(javax.swing.JFrame frame) {
            int centerWidth, frameWidth, systemWidth;
            frameWidth = frame.getWidth() / 2;
            systemwidth = dim.width / 2;
            centerWidth = systemWidth - frameWidth;
            return centerWidth;
        }

        public int myHeight(javax.swing.JFrame frame) {
            int centerHeight, frameHeight, systemHeight;
            frameHeight = frame.getHeight() / 2;
            systemHeight = dim.height / 2;
            centerHeight = systemHeight - frameHeight;
            return centerHeight;
        }
    }

And there you have it. When you run your application, it should not pop up at the top left corner of the screen (because you didn't specify the location in the first place) but should now pop up at the center of your screen and you can be guaranteed that the same will occur on any other system.

No comments:

Post a Comment

Your suggestion counts...