Window resize event?

后端 未结 5 2039
星月不相逢
星月不相逢 2021-02-02 07:55

I\'m writing a simple painting program using java, and I want some method to be called whenever the JFrame component is resized. But I can\'t find any method like windowRes
5条回答
  •  独厮守ぢ
    2021-02-02 08:03

    To access the Window Re-size method event I used Implement ComponentListener inside a subclass. This is a custom JPanel class you can use to write the window-size to a JLabel inside a GUI. Just implement this class in your main method and add it to your JFrame and you can resize the window and it will dynamically show you the Pixel size of your window. (Note you must add your JFrame object to the Class)

    package EventHandledClasses;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.ComponentListener;
    public class DisplayWindowWidth extends JPanel{
    JLabel display;
    JFrame frame;
    public DisplayWindowWidth(JFrame frame){
            display = new JLabel("---");
            this.frame = frame;
    
            frame.addComponentListener(new FrameListen());
            add(display);
            setBackground(Color.white);
        }
    
        private class FrameListen implements ComponentListener{
            public void componentHidden(ComponentEvent arg0) {
            }
            public void componentMoved(ComponentEvent arg0) {   
            }
            public void componentResized(ComponentEvent arg0) {
                String message = " Width: " +
                Integer.toString(frame.getWidth());
                display.setText(message);
    
            }
            public void componentShown(ComponentEvent arg0) {
    
            }
        }
    }
    

提交回复
热议问题