Garrett
Garrett

Reputation: 17

Making a window resizable in Java using KeyEvent

It has been a while since I last programmed in Java and I have unfortunately almost forgotten everything I knew...Just so you know, I did a Google search and couldn't find anything I needed for this particular problem. I want to make my window toggle between full screen and a window. Here is my code...

public class Window extends JFrame implements KeyListener{

   ImageIcon i= new ImageIcon("icon.png");
   Image ico=i.getImage();

   public void create(){
    this.setSize(800,600);
    this.setVisible(true);
    this.setFocusable(true);
    this.setIconImage(ico);
    this.setLocationRelativeTo(null);
    this.setResizable(false);
    this.setTitle("MYTITLE");
   }

   public void keyPressed(KeyEvent e) {
   }

   public void keyReleased(KeyEvent e) {
   }

   public void keyTyped(KeyEvent e){
    if (e.getKeyChar()==KeyEvent.VK_F1){
        this.setSize(1280,1024);
        this.setUndecorated(true);
    }else{
        this.setSize(800,600);
    }
   }
}

It makes the window, but I cannot get it to resize the window and I have imported the event library for those of you wondering. Help is much appreciated.

Upvotes: 0

Views: 68

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347332

First, take a look at the key bindings API, this will give you greater control over the focus level required to generate key events.

Second, take a look at JFrame#setExtendedState, which will allow you to control in a platform independent manner, the size state of the window

Upvotes: 2

usama8800
usama8800

Reputation: 875

You can't use e.getKeyChar in keyTyped. It returns nothing. Either shift the process to keyPressed method or do something like this

ArrayList<Integer> keysDown = new ArrayList<>();
    public void keyPressed(KeyEvent e) {
        keysDown.add(e.getKeyCode());
    }

    public void keyReleased(KeyEvent e) {
        keysDown.remove(keysDown.indexOf(e.getKeyCode()));
    }

    public void keyTyped(KeyEvent e) {
        if(keysDown.contains(KeyEvent.VK_F1)) {
            //Do Something
        }
    }

Upvotes: -1

Related Questions