M Argus Chopin Gyver M Argus Chopin Gyver - 1 year ago 66
Java Question

Changing Height of Jframe using button

I want to change the height of my jFrame using a click of a button.

But I don't know where to start. I only have a button and don't know the code.

The code that I know can change the size of JFrame and move it's position to the top right corner is this

Dimension screenSize = new Dimension(Toolkit.getDefaultToolkit().getScreenSize());
setPreferredSize(new Dimension(311, 430));
Dimension windowSize = new Dimension(getPreferredSize());
int wdwLeft = 530 + screenSize.width / 2 - windowSize.width / 2;
int wdwTop = 0;
setLocation(wdwLeft, wdwTop);

But I don't know specific code that can change the size of JFrame

*EDIT2 : Here's my
public static void main(String args[])

public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
final VoucherChecker frame = new VoucherChecker();

I don't know how to call
to use at

Answer Source

To run code when a button is pressed, add an ActionListener to the button with the .addActionListener() method. Have a look at this code here, and see if that works for you: (Read the comments to see what's going on)

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Main {

    private JFrame frame;

    public static void main(String[] args){

        SwingUtilities.invokeLater(new Runnable(){

            public void run() {
                new Main();                                 //Create a Main object, wrapped by SwingUtilities.invokeLater to make it thread safe


    public Main() {                                         //Main's constructor

        frame = new JFrame();                               //Create JFrame
        frame.setTitle("Test Frame");

        init((JPanel)frame.getContentPane());               //'init' frame's JPanel
        setFrameSizeAndPos(frame);                          //Set the frame's size


    private void setFrameSizeAndPos(JFrame frame) {

        //Set JFrame size here! Eg:
        frame.pack();                                       //Set the frame size, you could change this to set it in a different way.
        frame.setLocationRelativeTo(null);                  //Place frame in the center of the screen

    private void init(JPanel panel) {
        //Setup your GUI here...
        JButton button1 = new JButton("Click me!");         //Create button
        button1.addActionListener(new ActionListener(){     //add an ActionListener to the button, passing in an Anonymous Class

            public void actionPerformed(ActionEvent e) {
                setFrameSizeAndPos(frame);                  //This will be called then the button is pressed


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download