Implementing JFrame Resizing Rules?

Recently I've needed to enforce rules on a JFrame's dimensions (for example: preserving an aspect ratio).
The obvious solution is to call setSize() from ComponentListener's componentResize() method. This is functional, but looking at the Java source, it's pretty inelegant. It actually starts a setSize() -> componentResized() -> setSize() loop that only terminates when setSize() is called with dimensions matching the current dimensions (see Component.reshape()). Also, its visually ugly because when maximized you can see the window snap back to the "fixed" size.
It would seem that a more elegant way to add this functionality would be to have a method like "public Dimension checkDimensions(Dimension)" available for overriding.
Does something like this already exist that I've missed?
I've tried following the source, but I can't find the place where JFrame resizing is handled.

The optimal solution would be to use a Look&Feel which doesn't have to use the OS window decorations, so the resize events are only generated in Java (not optimal in the fact that you don't get to have the OS frame decorations of course). Then you should be able to add your own RootPaneUI which simple doesn't allow resizing beyond a maximum size or auto resizing respecting an aspect ratio.
See JFrame#isDefaultLookAndFeelDecorated and (for example) MetalRootPaneUI#MouseInputHandler. Perhaps there are thrid party look and feel where you can more easily replace a similar handler.

Similar Messages

  • JFrame resizing setUndecorated(true)

    I have a JFrame that it's title bar has several Images.
    In Order to set these images I used setUndecorated(true)
    and added the images with panels to the north area of the panel.
    After this change my Frame has a fixed size.
    I implementes MouseListener and MouseMotionListener handler to deal with drugging of the JFrame -how can I implement the resize of the frame?
    thanks
    liat

    Thats why a frame has a title bar, so the mouse can click on a component and drag it somewhere. If you remove the title bar then you need to add the dragging logic to some other component. Check out this thread for a simple example:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=406114

  • How to resize the components in a JFrame when the JFrame Resizes?

    Hi all,
    i have some problems with my app. I have set the JFrame resizable and that works fine for the JFrame but not for the components in the JFrame.
    So my question is how can i set the components in a JFrame to resize automatically when the JFrame resizes?
    Here are the important things from my code,...if you need more, just let me know, its my first post in a forum .
    Its a JFrame with a JTabbedPane and on the Tabs are Panels with buttons and Tables.
    Thank you in advance!
    public class MainMonitor extends JFrame {
    public MainMonitor() {
              super();
              initialize();
              setVisible(true);
         private void initialize() {
              this.setSize(1145, 785);
              this.setIconImage(Toolkit.getDefaultToolkit().getImage("Images/c.gif"));
              this.setContentPane(getJContentPane());
              this.setTitle("Company Manager");
              this.setResizable(true);
              this.setLocationRelativeTo(null);
         private JPanel getJContentPane() {
              if (jContentPane == null) {
                   jContentPane = new JPanel();
                   jContentPane.setLayout(null);
                   jContentPane.setOpaque(true);
                   jContentPane.add(getJTabbedPane(), null);
                   jContentPane.add(getJPanel11(), null);
              return jContentPane;
         private JTabbedPane getJTabbedPane() {
              if (jTabbedPane == null) {
                   jTabbedPane = new JTabbedPane();
                   jTabbedPane.setLocation(new Point(6, 69));
                   jTabbedPane.setSize(new Dimension(1120, 684));
                   jTabbedPane.addTab("P", null, getJPanel(), null);
                   jTabbedPane.addTab("K", null, getJPanel1(), null);
                   jTabbedPane.addTab("B", null, getJPanel2(), null);
              return jTabbedPane;
         

    Giasaste wrote:
    Thanks a lot, i didnt knew that the Layout Manager is a must.It's not a must, but it is the way to allow your app to be resized nicely and makes it much easier to maintain and enhance your program. Imagine creating a complex gui then later decide that you want another radiobutton and to remove a jlabel / jtextfield pair. with layout managers a chore becomes easy.

  • JFrame resize dynamically in response to content pane size changes

    Hi -
    I have a JFrame that uses CardLayout. The CardLayout panel content is of varied dimensions. it means the JComponents added to CardPanel will change size dynamically.
    Is it possible to have the JFrame resize dynamically in response to the content of the CardLayout panel changing?

    camickr wrote:
    No, the preferred size of a panel using a CardLayout is the preferred size of the largest component added to it.
    As a user I think it would be terrible to have the frame resize every time a turn a page to go to the next card. I have never seen this any any application.
    If you really need this functionality, then manage the panels yourself. Remove the existing Component before adding the next component and then do a frame.pack().My Application will be a JFrame.
    inside this JFrame i want to have three JPanels. according to some events and logic my GUI should switch to a given JPanel from those three panels. as i said the Jpanels sizes will change size on runtime depending on a automatic swing JPanel generation and i will have to add the new generated JPanel to parent JFrame with its new size
    any Ideas how to achive this ?

  • During the JFrame resize, unable to call mylogic.How to know JFrame rezing?

    {font:Arial}{size:10pt}Hi
    In my project i came across an issue. In that I had a JFrame (with FlowLayout) added with 24 JButtons (Its appearence will be similar as JToolbar). On this JFrame i called pack(). When i try to resize the JFrame, its componentResize() listener will not be called every time, instead it is calling only when its resizing complete.
    I am looking for a solution, that will rearrange JButtons (as specified Column/Row wise) during the JFrame resize. Can any body help me why componentResize() is not calling, during the resize. Tell me all alternate solutions. Pls help me.
    Waiting for your reply
    {size}{font}

    Can any body help me why componentResize() is not calling, during the resizeBecause its not very efficient to layout the frame every time you move the mouse 1 pixel. So by default this behaviour is turned off. I think you can turn in on by adding the following at the start of your program:
    Toolkit.getDefaultToolkit().setDynamicLayout(true);

  • Resizing Image when JFrame resized?

    I have a JFrame with a JPanel added to the contentPane (BorderLayout.CENTER). In the JPanel is a JLabel (BorderLayout.CENTER) with an ImageIcon set to it. The image is a subimage of a larger image whose width is scaled to fit the current JLabel width (which is dictated by the JPanel width and finally dictated by the JFrame width).
    When the user resizes the JFrame, the image of the ImageIcon should be replaced with a new image which has been scaled to fit the new width and that reflects the new portion of the larger source image that is visible.
    The JFrame already has a ComponentListener added for retaining the current JFrame size and screen position, but calling my resizeDisplay() method from componentResized() does not seem to have the updated JLabel size. I have added a ComponentListener to the JLabel and called my resizeDisplay() method from componentResized() but it does not seem to have the updated JLabel size either.
    How can my application properly react to JFrame resizes so that the method is retrieving the new size values?
    Thanks,
    Robert Templeton

    Its always easier to solve a problem when sample code (not a complete program) is posted with the question.
    Maybe I don't understand the question, but when I run the following code the output reflects the size of the label after it has been resized. I'm using JDK1.3 on Window 98.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class TestLabel extends JFrame
         public TestLabel()
              JPanel panel = new JPanel();
              setContentPane( panel );
              panel.setPreferredSize( new Dimension( 200, 200 ) );
              panel.setLayout(new BorderLayout() );
              final JLabel myLabel = new JLabel( new ImageIcon("dukeWaveRed.gif"), JLabel.CENTER );
              panel.add( myLabel );
              myLabel.addComponentListener( new ComponentAdapter()
                   public void componentResized(ComponentEvent e)
                        System.out.println( myLabel.getSize() );
         public static void main(String[] args)
              TestLabel frame = new TestLabel();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }

  • Undecorated jframe resize problem

    i created a custom jframe look by setting a jframe to undecorated and designing my own maximize/minimize/close buttons and other things to improve its appearence
    the problem is that when set to undercorated all the default resizing/move methods are gone
    i tried implementing my own resize methods, they seem to work but it flashes like crazy while resizing
    anyone have any idea how to stop all the flashing or a better way to implement this?
    the following is a small example of the problem i am having, i only implemented the north resize part so the code can be easier to read.
    thnx in advance
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.imageio.*;
    import java.io.*;
    import java.awt.image.BufferedImage;
    public class TestFrame extends JFrame implements MouseMotionListener, MouseListener
         Point sp;
         int     compStartHeight;
         int minHeight = 100;
         JPanel frameContent = new JPanel();
         public TestFrame()
              super("testing frame");
              setSize(600, 600);
              setContentPane(frameContent);
              frameContent.setBackground(Color.black);
              frameContent.setLayout(new BoxLayout(frameContent, BoxLayout.Y_AXIS));     
              setUndecorated(true);
              addMouseMotionListener(this);
              addMouseListener(this);
              JButton testButton = new JButton("TEST");
              JButton testButton2 = new JButton ("TEST2");
              frameContent.add(testButton);
              frameContent.add(Box.createVerticalGlue());
              frameContent.add(testButton2);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setVisible(true);
         public void mouseMoved(MouseEvent e)
              Point p = e.getPoint();
              if (p.y > e.getComponent().getSize().height - 5)
                   setCursor( Cursor.getPredefinedCursor( Cursor.N_RESIZE_CURSOR ));
              else
                   setCursor( Cursor.getPredefinedCursor( Cursor.DEFAULT_CURSOR));
         public void mouseDragged(MouseEvent e)
              Point p = e.getPoint();
              int compWidth = getSize().width;
              if (getCursor().getType() == Cursor.N_RESIZE_CURSOR)
                   int nextHeight = compStartHeight+p.y-sp.y;
                   if (nextHeight > minHeight)
                        setSize(compWidth,nextHeight);
                        validate();
              else
                   int x = getX()+p.x-sp.x;     
                   int y = getY()+p.y-sp.y;     
                   setLocation(x,y);
         public void mousePressed(MouseEvent e)
              sp = e.getPoint();
              compStartHeight = getSize().height;
         public void mouseEntered(MouseEvent e)
        public void mouseExited(MouseEvent e)
              if (sp == null)
                   setCursor( Cursor.getPredefinedCursor( Cursor.DEFAULT_CURSOR));
        public void mouseClicked(MouseEvent e)
        public void mouseReleased(MouseEvent e)
              sp = null;
         public static void main(String[] args)
         new TestFrame();
    }

    I doubt there is a faster / easier way to resize.
    Have you tried adding
    public boolean isDoubleBuffered()
      return true;
    }To over-ride Component.isDoubleBuffered. This should sort out your flickering problem.
    Bamkin

  • JFrame (resize -- disallow certain size)

    Hi,
    I have some code that disallows a JFrame from being resized smaller than a certain width and height. (see code below)
    But my problem is that this code allows the frame to be resized for a split second before it resizes it back to the defined minimum. My question is:
    Is there a way I can get the frame to NOT be resized below a certain width and height? Hence, when the user grabs the corner of the JFrame and tries to make the window smaller than the minimum defined width and height, the frame just stops moving (i.e. it becomes rigid and not elastic).
    The main reason for this question is that everything works great most of the time but since the frame is allowed to resize to a very small size for a split second some of my components get squished. I have set their min, max, and preferred size too, but it still squishes them and they are un-squishable after it happens. This would never occur if there was a way to do what I propose above.
    public final static void lockInMinSize(final JFrame frame, int width, int height){
       final int origX = width;
       final int origY = height;
       frame.addComponentListener(new ComponentAdapter() {
          public void componentResized(ComponentEvent event) {
             frame.setSize((frame.getWidth() < origX) ? origX : frame.getWidth(),
                 (frame.getHeight() < origY) ? origY : frame.getHeight());
    }

    The main reason for this question is that everything works great most
    of the time but since the frame is allowed to resize to a very small size
    for a split second some of my components get squished.As a rule, I place all of my panels into one large "content" JPanel. This content panel is then placed in a JScrollPane. It's the scroll pane that gets added to the JFrame's contentPane. The scroll policy (both horizontal and vertical) on the scrollPane is SCROLL_AS_NEEDED.
    After calling pack() on the frame, the frame comes up perfectly without visible scrollBars, since I've been diligent in giving each individual widget (JTextFields, JLists, etc.) a preferredSize.
    As the frame gets stretched, the fields adapt accordingly and still look fine. As the frame is shrunk, the fields squish only to their original positions. Anything more would cause the scrollBars kick in.
    So, I always size all of the individual fields, but never the panels or frames.
    Keep in mind that different layout managers rely on different sizes for the components. Since I use GridBag for the individual panels, I make sure to give each component a preferredSize
    I guess as an alternate, after construction is complete you could pack the frame, then call getSize to capture its "natural" size. Use this natural size for comparison in your componentResized method.
    Hope this helps. Good luck.

  • Problem with JFrame resizing at runtime

    Hi All,
    I have a problem with resizing the JFrame at runtime. Even if i resize the JPanel. It is not affection on all the components over the frame. How can i solve that I am using AbsoluteLayout(jre1.6) and here i am going to provide you code snippet. My requirement is to resizt the form. If form is small in size then all the component should also be according tothe size of the form.
    public void initComponents(int size) {
    if(size >= 50) {
    x_co_or = 300;
    y_co_or = 300;
    } else if(size < 50) {
    x_co_or = 200;
    y_co_or = 200;
    jPanel1 = new javax.swing.JPanel();
    jButton1 = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
    jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
    jButton1.setText("jButton1");
    jPanel1.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 40, 110, 40));
    getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, x_co_or, y_co_or));
    pack();
    Can anybody suggest any idea/solution.
    Any idea/solution are most welcome.
    Regards,
    Pradeep Dubey

    How can i solve that I am using AbsoluteLayout(jre1.6)
    and here i am going to provide you code snippet.no need for the snippet, you're using absolute positioning, which means you're responsible for location and size on every single change.
    start coding now, take about a week, or you could use a layout manager, take maybe, 5 minutes

  • Ways to implement image resizing using plug-ins?

    Hi Photoshop developers,
    I'm a developer with a few Photoshop filter and selection plug-ins under my belt, and I have a good understanding of the SDK and tools and suites it provides. My next project is an algorithm for enlarging/resampling images to different pixel dimensions. I'm wondering if anyone has any suggestions for or experience with the best combination of plug-in types to implement this.
    Clearly, I can't just write it as a filter plug-in, since there is no way to change the image dimensions from within a filter.
    I'd like the resized image to remain within Photoshop (as a new window or in the original one), so an export plug-in on its own is not sufficient.
    Import plug-ins seem promising, since they allow the creation of a new document of the required size. However, as best I can tell from the Photoshop 6.0 SDK documentation, import plug-ins cannot access the image data from other open documents (or even the clipboard), nor do they provide any support for channel ports and the Channel Port suite.
    My best idea at this stage is to create an export plug-in to provide the user interface and calculate the resized image, and then an import plug-in to import the resized image back into a new window. (I'm supposing a further automation plug-in would then be written to perform this export/import sequence.) The difficulty I see with this approach is how to communicate the resized image data between the two plug-ins. Since the resized image will potentially be very large, the ideal solution would be to store it in channels managed by the Channel Ports suite. However, I cannot see how the channel ports created in the export plug-in could be communicated to and used by an import plug-in. The alternative would be for the export plug-in to save the resized image to a temporary file on disk, however this seems unnecessary.
    So, my questions, specifically, are:
    a) Is it possible to create new channels using the Channel Ports suite (sPSChannelPorts->New()) in one plug-in, and have those channels persist to be used in another plug-in?
    b) If so, how would the channel ports be communicated between the plug-ins?
    c) Alternately, are there any alternative architectures available for implementing an image-resizing algorithm using the plug-in types that are available for Photoshop developers.
    Any responses would be greatly appreciated; I know this is a low-traffic forum...
    Thanks,
    Matthew.

    I would make an automation plug-in and a filter plug-in.<br /><br />1) Run the automation which runs your filter to gather current image <br />information<br />2) Create a temp file of the new document<br />3) Make a new document<br />4) Call the filter again to reload the temp data on disk<br /><br /><[email protected]> wrote in message <br />news:[email protected]...<br />> Hi Photoshop developers,<br />><br />> I'm a developer with a few Photoshop filter and selection plug-ins under <br />> my belt, and I have a good understanding of the SDK and tools and suites <br />> it provides. My next project is an algorithm for enlarging/resampling <br />> images to different pixel dimensions. I'm wondering if anyone has any <br />> suggestions for or experience with the best combination of plug-in types <br />> to implement this.<br />><br />> Clearly, I can't just write it as a filter plug-in, since there is no way <br />> to change the image dimensions from within a filter.<br />><br />> I'd like the resized image to remain within Photoshop (as a new window or <br />> in the original one), so an export plug-in on its own is not sufficient.<br />><br />> Import plug-ins seem promising, since they allow the creation of a new <br />> document of the required size. However, as best I can tell from the <br />> Photoshop 6.0 SDK documentation, import plug-ins cannot access the image <br />> data from other open documents (or even the clipboard), nor do they <br />> provide any support for channel ports and the Channel Port suite.<br />><br />> My best idea at this stage is to create an export plug-in to provide the <br />> user interface and calculate the resized image, and then an import plug-in <br />> to import the resized image back into a new window. (I'm supposing a <br />> further automation plug-in would then be written to perform this <br />> export/import sequence.) The difficulty I see with this approach is how to <br />> communicate the resized image data between the two plug-ins. Since the <br />> resized image will potentially be very large, the ideal solution would be <br />> to store it in channels managed by the Channel Ports suite. However, I <br />> cannot see how the channel ports created in the export plug-in could be <br />> communicated to and used by an import plug-in. The alternative would be <br />> for the export plug-in to save the resized image to a temporary file on <br />> disk, however this seems unnecessary.<br />><br />> So, my questions, specifically, are:<br />><br />> a) Is it possible to create new channels using the Channel Ports suite <br />> (sPSChannelPorts->New()) in one plug-in, and have those channels persist <br />> to be used in another plug-in?<br />><br />> b) If so, how would the channel ports be communicated between the <br />> plug-ins?<br />><br />> c) Alternately, are there any alternative architectures available for <br />> implementing an image-resizing algorithm using the plug-in types that are <br />> available for Photoshop developers.<br />><br />> Any responses would be greatly appreciated; I know this is a low-traffic <br />> forum...<br />><br />> Thanks,<br />> Matthew.

  • JFrame resizing

    Hi,
    I have a JFrame, it displays on the right upper corner the icons minimize, maximize and exit.
    Minimize and Exit icons are working fine.
    I have the problem with the maximize button.
    The application I am writing allows to resize the JFrame. Thats fine!
    If I run the application, it has an initial size w=800, h=600
    If I click the maximize button, the JFrame fits to the window maximal size.
    But if I click the maximize button again, I want to have the initial size. This does not work.
    It keeps the maximal size.
    How can I switch
    - between maximal size and "initial" size
    or
    - between maximal size and last set size (so the size before Jframe was maximized)
    if I click the maximize button.
    Thanks
    A.

    Hi,
    I found the issue and fixed it.
    The issue is the following code.
    If I run the application, I call this function, it works fine.
    What it does is, it just horizontal center the window.
      public static void centerWindow(Window window) {
          Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
          int x = (int)((screen.width - window.getSize().width) / 2);
          int y = 0;
          window.setLocation(x, y);
      }If I run this function later on again after resizing the window, it causes the issue.
    So if I resize the window, I don't call this function anymore.
    Thanks
    A.

  • JFrame resizing question

    When i resize a JFrame the components it hold remain unchanged until I stop resizing the frame. Then the components conform to the frame size. Is there a way to have the components resize dynamically?

    Thank for the answer, that's exactly what I nedded!

  • JFrame resizing problem......

    Hi All,
    can anyone guide me how to stop resizing or dragging the JFrame.
    my frame should not be movable or resizable by the user.
    Urgent!!
    Regards
    sd

    Have you tried frameObj.setResizable(false)?
    Phani

  • How to implement a conversion rule in KC7R (External Data transfer-Tool)

    Hi,
    I am familiar with programming conversion rules in ABAP in the LSMW and IS-U Migration workbench.
    Unfortunately we have to work with EDT (transaction KCLJ).
    I need to implement a simple conversion rule: migration file has the external BP number BPEXT and I must retrieve the internalone (PARTNER) for the migration program.
    So I must implement a short ABAP code (select single * from BUT000 ...).
    Now I see that in KC7R you can use constants and conversion rules. There are also "General Ruels" and "conversion routines".
    Can someone explain how to implement this simple ABAP conversion rule in KC7R giving a short example?
    This would be great.
    EDT is the workst of all SAP Standard Migration Tools I have seen.....
    Kind regards,
    Thomas

    Thomas,
    Coud you please share your findings as I am now in a similar to your original post.
    ie I too would like to know how to code convesions for use within the transfer rules used by KCLJ.
    Kind Regards,
    Hiten Mistry.

  • Implementing roles and rules based authorisation with Azure AD

    Hi all,
    I would greatly appreciate some input on feasibility and patterns I should look at for a complex technical requirement that I am currently tasked with designing.
    We have a system that comprises a web and mobile app. In the past we have implemented session based authentication through ADAM and authorisation through custom business rules contained within the applications. The authentication mechanism is in the process
    of being migrated to Azure AD and authorisation is planned to be moved to Azure AD for our next release.
    Existing authorisation within our web application is already complex. We have users that belong to different groups with a range of permissions such as read, write or admin. Additionally each user is granted access to N customers and also N locations within
    each customer. We have a requirement that any number of combinations of customers and locations be supported. Users also need to have different permissions for each entity, i.e. read access to customer 1 location 2, write access to customer 4 and administer
    customer 7. Currently these privileges are maintained within a relational database and enforced as part of each PageLoad(). Essentially this is a combination of roles and rules based authorisation.
    We are struggling to represent this complex matrix structure within Azure AD and efficiently implement the authorisation decision in Azure AD. The driver for this technical requirement is to provide re-usability of the authorisation component to other (as
    yet unidentified) applications.
    Currently the best option we have come up with is implementing custom attributes for each class of permissions and storing within this 2048 bit field a bitmask that represents whether this permission is granted for a given location (which has a many to one
    relationship with customer).
    Any help or comment would be gratefully received,
    Phil

    Hi
    When "Advance routing" is used for Task assignment; the task service asserts the folllowing fact types : Task, PreviousOutcome and TaskAction to the rules engine. These facts gives all the reqd info about the task (like outcome of the participant, task stage .. etc)
    Now in the defined ruleset; we can have rules as per our requirement that can extract info from the asserted fact types and assign task to the required/next participant.
    Also note that we write the advance rules for exception cases only.
    For example; let's say all participants have 2 possible Outcomes [COMPLETE, RECHECK]. We have defined the ideal task routing flow as :
    Participant A -> Participant B -> Participant C. This is the flow when all participant selects "COMPLETE"
    Now suppose B selects outcome as "RECHECK" then the task shld move back to A. So for this case only we need to write a advance rule.
    Pls refer to the code sample at : http://download.oracle.com/technology/sample_code/hwf/workflow-106-IterativeDesign.zip
    Also dev guide : refer to section 28.3.7.2 http://download.oracle.com/docs/cd/E14571_01/integration.1111/e10224/bp_hwfmodel.htm#BABBFEJJ
    Thanks
    Edited by: Kania on May 19, 2010 2:41 AM

Maybe you are looking for