Pages

Saturday, December 11, 2010

Java Tips

How to Center the JFrame/JDialog in the screen

In the JFrame/JDialog initialize method add the following code lines along with the correct dimensions of your container instead of values 300, 200.

private void initialize() {
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (dim.width - 300)/2;
        int y = (dim.height - 200)/2;
        this.setLocation(x, y);
        this.setSize(300, 200);
        ……
}

In the first line it gets the Screen Size to a variable named dim. Please note that the example container’s width is 300px and height is 200px. Using these values we can calculate the x, y positions for the container to appear in the center of the screen. Then the calculated x, y values are fed to the component using setLocation method while dimensions of the container is fed using setSize method inside initialize method of the container.

 

How to get the working directory in java

It is a quite simple, yet very useful feature provided by Java.

System.getProperty("user.dir");

This will return the current working directory as a string and comes very handy to define relative paths inside Java programs.

 

How to add an image to a Java container

This can be achieved by adding a new label with the required image’s size, to the container and setting the label’s icon to point the image that is required to be added to the container.

private JPanel getJContentPane() {
        if (jContentPane == null) {
            lbl_Img = new JLabel();
            lbl_Img.setBounds(new Rectangle(101, 9, 164, 16));
            lbl_Img.setIcon(new ImageIcon(System.getProperty("user.dir")+"/icons/edit.png"));
            ……
        }
        ……
}

This code will display  the ‘edit.png’ image in the icons folder of the working directory of the program. Please note that if the image is lager than the label bounds, this will display only the upper left corner of the image to the extent of the defined label bounds. Please refer the “Resize a given image in Java” blog entry to learn how to resize an image in java.

No comments:

Post a Comment