Pages

Get JFrame size

Source code below will create a JFrame with a button in it. You can know current JFrame size by click the button. You also can try resize the JFrame first, and after that click the button.

*****************************************************************************
COMPLETE SOURCE CODE FOR : GetJFrameSize.java
*****************************************************************************


import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import java.awt.FlowLayout;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class GetJFrameSize extends JFrame
{
//Create ActionListener for listen when someone click button
ActionListener al=new ActionListener()
{
//Overwrite abstract method ( actionPerformed ) in ActionListener class
public void actionPerformed(ActionEvent event)
{
//Show message box that contain information about current JFrame width and height in pixels
JOptionPane.showMessageDialog(null,"JFrame size in pixels is : \n"+"WIDTH : "+getSize().width+"\n"+"HEIGHT : "+getSize().height);
}
};

public GetJFrameSize()
{
//Create JFrame title ( Resize me and click button )
super("Resize me and click button");

//Set JFrame layout to FlowLayout
setLayout(new FlowLayout());

//Create a button with text ( Click me to see current JFrame size )
JButton button=new JButton("Click me to see current JFrame size");

//Add ActionListener to the button
button.addActionListener(al);

//Add the button into created JFrame
add(button);

//Set default close operation for JFrame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set initial JFrame size to :
//WIDTH = 500 pixels
//HEIGHT = 500 pixels
setSize(500,500);

//Make JFrame visible
setVisible(true);
}

public static void main(String[]args)
{
GetJFrameSize gjfs=new GetJFrameSize();
}
}


*****************************************************************************
JUST COMPILE AND EXECUTE IT
*****************************************************************************
Related Posts Plugin for WordPress, Blogger...