Dynamically changing the size of a JPanel

Hi All,
I am loading multiple images in a JPanel. I want the size of the JPanel to increase dynamically as and when the images are loaded. I have also added a JScrollPane and added the JPanel to this JScrollPane.
However, the images are cut as soon as it crosses 800 pixels (which is the preferred size of the JScrollPane and it starts to give me NullPointerExceptions where I try to access the image height and width. Here is the code that gives me the problem. The files are opened using the filechooser and put into a Vector, which is then retrieved in the paint() method and rendered to the panel.
CurrentScreenSize is a Dimension that stores the value of the current screent size that the image pane should have.
imagePane is the JPanel that contains all the images.
//File | Open action performed
void jMenuFileOpen_actionPerformed(ActionEvent e) {
//Handle open action.
if (e.getSource() == jMenuFileOpen) {
fc = new JFileChooser();
//Filter out only image files (uses Utils.java and ImageFilter.java)
fc.addChoosableFileFilter(new ImageFilter());
fc.setAcceptAllFileFilterUsed(false);
fc.setMultiSelectionEnabled(true);
int returnVal = fc.showOpenDialog(MainFrame.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File[] files = fc.getSelectedFiles();
//This is where a real application would open the file.
int x=10, y=50;
for(int i=0;i<files.length;i++)
try {
Image tempImage = ImageIO.read(files);
image.add(tempImage);
if(tempImage.getHeight(this) > currentScreenSize.getHeight())
currentScreenSize.setSize(currentScreenSize.getWidth()
+ tempImage.getWidth(this),
tempImage.getHeight(this));
else
currentScreenSize.setSize(currentScreenSize.getWidth()
+ tempImage.getWidth(this),
currentScreenSize.getHeight());
if (imagePane.getSize().getWidth() <
currentScreenSize.getSize().getWidth() ||
imagePane.getSize().getHeight() <
currentScreenSize.getSize().getHeight())
imagePane.setSize(currentScreenSize);
this.pack();
//repaint();
catch (IOException ex) {
ex.printStackTrace();
//When all images are loaded then paint it / display it
repaint();
public void paint(Graphics g){
int x=10, y=50;
super.paint(g);
g = imagePane.getGraphics();
for (int j=0; j<image.size() ; j++)
Image img = (Image)image.elementAt(j);
int imageWidth = img.getWidth(this);
int imageHeight = img.getHeight(this);
g.drawImage(img, x, y, imageWidth, imageHeight, this);
x = x+imageWidth;

got the Solution, using validate() method does the work under the hood.

Similar Messages

  • Dynamically change the size of a text field.

    Is it possible to change the size of a text field depending on the amount of text in the field?
    Thanks,
    Chad

    You can find the answer from this post.
    jimmypham, ""Shrink to Fit" - Text Field capability?" #1, 18 Jul 2005 10:36 pm

  • Dynamically changing the size of KM document IView.

    Hi All,
    At present the framework page has 3 KM document Iview. All iviews are calling HTML files. Now if the content in HTML file increases, I get an scroll bar for that Iview. Also based on the resolution of the screen I get the scrollbar. e.g I have fixed the height of the iview to say X for a resolution 1024 * 768 where in no scroll bar appears, now if I choose 1280 * 1024 resolution, iview appears with both horizontal and vertical scroll bar.
    I tried to change the height type as automatic and the minimum height in pixels as 0 and maximum as 1000, then the iview it self disappears i.e it is taking the minimum height.
    Now in my scenario based on the requirement the HTML content will change but instead of automatically adjusting display height of the Iview, it is taking hte minimum height mentioned. 
    How can I display the IView without scroll bar appearing if the content of the HTML is changing or the screen resolution is changing.
    Thanks
    Namit

    Hi Namit,
    The KM doc iview is just like a container for storing and The horizantal scroll bar apperas as and when the content gets bigger than the container.
    One option would be to write a small iview with an imbedded iframe pointing to the KM doc, where the width, height comes from profile attributes. This would remove the option of horizontal bar. Coming to height , Set the height type of the iView to Automatic OR if that doesn't work because of domain issues then set it to fixed and in addition set the iview height to the height of the image + 10~20 px more..
    Hope this helps you.
    GoodLuck!
    Regards,
    Shaila

  • Dynamically change in size of the custom container using ALV GRID (OOPS)

    Hi Gurus!!!!
    I have an issue with the output of the report which is developed using ALV GRID (OOPS). I have used the custom container occupying full screen (Screen painter). When I execute the report using my PC the output displays report as expected in full screen. The problem is when we execute this report in 19 INCH monitor then there is always gap below the report.
    As per my understanding we should have a code to change the size of custom container dynamically.
    Please suggest some help on this.
    Thanks,
    Hemal Shah

    Hi,
    If you set the attributes, Resizing - Vertical and Horizontal for the customer container, than system will resize the size of the custome continer as per the resolution.
    Hope it helps,
    Sumana

  • Changing the size of Jpanel

    Hi,
    I am making a paint application. I want to have a zoom functionality in it. i hava a button which when pressed will zoom the drawing area (JPanel). The Name of the Panel is Pane1.The Code for it is (scaleFactor is a variable in Pane1 Class)
    public void zoom_btn_actionPerformed(ActionEvent e) {
    Dimension d = new Dimension();
    double new_height;
    double new_width;
    // For increasing size of Pane1
    d = Pane1.getPreferredSize();
    new_width = (double)d.width + (double)(Pane1.scaleFactor-1.0) * (double)d.width;
    new_height = (double)d.height + (double)(Pane1.scaleFactor-1.0) * (double)d.height;
    Pane1.scaleFactor = Pane1.scaleFactor + 0.1;
    System.out.print(Pane1.nu_width + " " + Pane1.nu_height);
    //not working
    // Pane1.setPreferredSize(new Dimension(40,40));
    Pane1.update(Pane1.getGraphics());
    public void update(Graphics g)
    Graphics2D g2;
    g2 = (Graphics2D)g;
    g2.scale(scaleFactor,scaleFactor);
    g2.translate(translate_x,transalte_y);
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    setPreferredSize(new Dimension(nu_width,nu_height) );
    try {
    g2.drawImage(buff, 0, 0, this);
    } catch (Exception e) {}
    Pane1 is inside a JscrollPane which works fine.
    The above code works fine and the image drawn is zoomed. However the size of panel remains the same. So if i zoom more it will go out of screen instead of making it scroll. It is as if the setPreferredSize function doesnt work.
    Can anyone pls tell me how to increase the size of a Jpanel at runtime ?

    there is a bit of correction in what i posted above the lines
    //not working
    // Pane1.setPreferredSize(new Dimension(40,40));
    should be
    //not working
    Pane1.setPreferredSize(new Dimension((int)new_width),(int)new_height));

  • Changing the size of a JComboBox

    Greetings,
    I am trying to build a mechanism to perform zooming on a JPanel with an arbitrary collection of components (including nested JPanels). I've tried a number of things with little success. The following is my most promising contraption. It can zoom labels, textfields, checkboxes, and buttons. However, for some reason, the combo box refuses to accept a changes to its size. I'm not sure why this is the case. Its font changes size appropriately.
    Anyway, I'm running in JDK 1.4, and the following program lays out a palette of components. To change the size of the components, hit F1 to zoom in, and F2 to zoom out.
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.KeyEventPostProcessor;
    import java.awt.KeyboardFocusManager;
    import java.awt.event.KeyEvent;
    import java.awt.geom.AffineTransform;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class Demo extends JPanel
        public class Zoomer
            private double m_zoom = 1;
            private JPanel m_panel;
            public Zoomer(JPanel panel)
                m_panel = panel;
            private AffineTransform getTransform()
                return AffineTransform.getScaleInstance(m_zoom, m_zoom);
            private Font transform(Font font)
                return font.deriveFont(getTransform());
            private Dimension transform(Dimension dimension)
                Dimension retval = new Dimension();
                retval.setSize(dimension.getWidth() * m_zoom, dimension.getHeight() * m_zoom);
                return retval;
            private void performZoom(Container container)
                Component[] components = container.getComponents();
                for(int i = 0; i < components.length; i++)
                    Component component = (Component)components;
    component.setFont(transform(component.getFont()));
    component.setSize(transform(component.getSize()));
    for(int i = 0; i < components.length; i++)
    Component component = components[i];
    if(component instanceof Container)
    performZoom((Container)component);
    public double getZoom()
    return m_zoom;
    public void setZoom(double zoom)
    if(zoom > 8.0 || zoom < 0.125) return;
    m_zoom = zoom;
    performZoom(m_panel);
    public void zoom(double factor)
    setZoom(getZoom() * factor);
    public Demo()
    JPanel panel = new JPanel();
    panel.add(buildPanel());
    panel.add(buildPanel());
    final Zoomer zoomer = new Zoomer(panel);
    add(panel);
    KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventPostProcessor(new KeyEventPostProcessor()
    public boolean postProcessKeyEvent(KeyEvent e)
    if(e.getID() != KeyEvent.KEY_PRESSED) return false;
    if(e.getKeyCode() == KeyEvent.VK_F1)
    zoomer.zoom(1.2);
    if(e.getKeyCode() == KeyEvent.VK_F2)
    zoomer.zoom(1/1.2);
    return false;
    private JPanel buildPanel()
    JPanel panel = new JPanel();
    panel.add(new JLabel("label: "));
    panel.add(new JTextField("Hello World"));
    panel.add(new JCheckBox("checkbox"));
    panel.add(new JComboBox(new String[] { "Bread", "Milk", "Butter" }));
    panel.add(new JButton("Hit Me!"));
    return panel;
    * Create the GUI and show it. For thread safety, this method should be
    * invoked from the event-dispatching thread.
    private static void createAndShowGUI()
    // Create and set up the window.
    JFrame frame = new JFrame("Demo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Create and set up the content pane.
    Demo newContentPane = new Demo();
    newContentPane.setOpaque(true); // content panes must be opaque
    frame.setContentPane(newContentPane);
    // Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args)
    // Schedule a job for the event-dispatching thread:
    // creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable()
    public void run()
    createAndShowGUI();

    component.setSize(transform(component.getSize()));First of all the above line is not needed. The LayoutManager will determine the bounds (size and location) of each component in the container based on the rules of the LayoutManager. The Flow Layout is the default layout manager for a panel and it simply uses the preferred size of the component as the size of the component.
    So what happens is that when you change the font of the component you are changing the preferred size of the component.
    So why doesn't the combo box work? Well I took a look at the preferred size calculation of the combo box (from the BasicComboBoxUI) and it actually caches the preferred size. The combo box uses a renderer, so the value is cached for performance one would assume. The method does recalculate the size when certain properties change. Note the isDisplaySizeDirty flag used in the code below:
             else if (propertyName.equals("prototypeDisplayValue")) {
                    isMinimumSizeDirty = true;
                    isDisplaySizeDirty = true;
                    comboBox.revalidate();
             else if (propertyName.equals("renderer")) {
                    isMinimumSizeDirty = true;
                    isDisplaySizeDirty = true;
                    comboBox.revalidate();
                }It also handles a Font property change as well:
                else if ( propertyName.equals( "font" ) ) {
                    listBox.setFont( comboBox.getFont() );
                    if ( editor != null ) {
                        editor.setFont( comboBox.getFont() );
                    isMinimumSizeDirty = true;
                    comboBox.validate();
                }but notice that the isDisplaySizeDirty flag is missing. This would seem to be a bug (but I don't know why two flags are required).
    Anyway, the following change to your code seems to work:
    // component.setSize(transform(component.getSize()));
    if (component instanceof JComponent)
         ((JComponent)component).updateUI();
    }

  • How to change the size of cursor

    How to change the size of cursor  in flash,when we use dynamic text box or input text box the cursor is covering the whole height of the text box.is there any way to reduce the size of cursor

    In input text box while entering some value, the blinking of cursor is covering the whole text box,
    When i use the code
    Selection.setFocus(instance name of text)
    The cursor blinking is covering the whole text box height

  • Dynamically changing the color of nodes in a JTree

    I have created a JTree and want to dynamically change the color of some of the TreeNodes as my program runs. The JTree is displayed in a JPanel. There is an algorithm built into which identifies the nodes whose color I need to change. No user actions is performed (everythign is internal to the program).
    It seems that in the TreeCellRender only kicks in when the tree is first displayed. How do I get it to re-render the tree when the TreeModel changes? It seems that the Listeners are only looking for external user interactions.
    Any help would be greatly appreciated.
    Thanks!

    I think I was a bit too vague in my question. Let me try again...
    I have changed an attribute in a node in a JTree. This attribute is changed after the tree was initially rendered, but while the program is still running. I want to tell the TreeCellRenderer to look again at this node since that attribute that was changed will effect how the node should be renderered. I tried using the nodeChanged() method, but it did not work (the colot of the node did not change). Any advise how I can do this?
    Thanks!

  • Dynamically changing the layout of thre report-urgent please

    Can we change the layout of the report dynamically during runtime for example:the user should have flexibility to change the width, size , position of columns before the report is displayed & also he choose some fields not to display as per his discretion.
    Mahesh

    There are several ways of doing this, it really depends on your requirements as to which is suitable. (There are probably other ways of doing this as well).
    - Try Reports XML Customizations
    This is available in 6i and allows you to create a report dynamically on the fly. The template used will also allow you to change the paper size as well. The main limitation is that you are relying only on Reports defaulting to create the layout for you. The advantage is that you can store all your information to create the report in meta-data which can be driven by another tool.
    - Use lexical parameters for queries and format triggers
    Here, you have a fixed layout but dynamically change the query columns to the correct order. You would normally standardise on a "character" column type in order to do this. Even though the layout is fixed, you can use variable sized fields to push objects around. This can be difficult to setup.
    - Use several layouts
    You're reducing the options for the user, but you can have several layouts in the same report and turn them on/off. Effectively creating differing views of the same data.

  • Dynamically change stage size on runtime

    Hi everyone,
    I need to change the stage size dynamically.
    When i try to do this............
    size_mc.onRelease = function(){
        trace(Stage.height);
        Stage.height += 100;
        trace(Stage.height);
    it comes always the current stage size.
    Thanks in advance

    You cannot change the width and height properties of the Stage using code--it must be done in the editor.  The width and height values can represent different things depending on the value you set for the scale mode, but you cannot reassign them to different values dynamically.
    The solution just offered to you is under the same rules, the stageWidth and stageHeight values cannot be assigned using code, but that code is AS3 code so it will not fit in your AS2 design in any case.
    The same goes for the followup offered in AS2.  You will notice the stage size is not being changed... it cannot be.  This is just a full screen design solution, but is not a soltuion to changing the stage size.  The stage size can only be changed manually in the authoring environment.  I don't know that the offering is answering what you are really trying to do, but it is not answering the titled task of dynamically changing the stage size

  • How Can I Change the Size of My Home Page So That It Fills the Screen?

    I have a PowerBook G4. Up until a couple of weeks ago when I opened Safari the home page filled the screen. Something has happened and now it fills only a portion of the screen. I can move the page around, change the size slightly by using the green button next to the minimizing button, but nothing I do will enlarge it to fill the screen. I have gone to View and Preferences, but find nothing to resolve this. Please help!

    You're welcome Maureen. Glad I could help.
    Thanks for the and Aloha from Big Island.

  • How do I change the size of a windows partition on my MacBook?

    How do I change the size of a windows partition on my MacBook?

    CampTune $19 from Paragon-Software is your best bet.
    http://www.paragon-software.com/mac/

  • What is happening when I change the size of the image in the program sequence window?

    I noticed that I can change the image size of my exported file. I imported a 720 x 480 DV file into CS5.5. I went to my program sequence window and changed the settings to show the smallest image in that window. I then clicked on the image and used the handles that appear to make that small image large enough to nearly fill the screen. When I exported my final file and played the resulting WMV, the image on my screen was nearly twice as large as it would have been if I had not previously altered the image size in the program sequence window. I had to do this alteration for each clip in my timeline, or the unaltered ones would stay at the smaller size. The quality did not seem to be significantly impaired. I learned about this on a youtube video. The person who did the video claimed that this was a simple and quick way to upgrade standard video to HD. Of course this is not true. He was only changing the size of the resulting video. Does anyone know what is really happing when you do this procedure and why it changes the size of the exported  video?

    The size (resolution) of the exported video is not affected by anything you do while editing.  It is dependant solely on the resolution set in the export settings.
    Ideally you want to edit in an sequence that matches your media\, which will be the same size or larger than the required export.  In other words, the same or smaller is OK.  Making things bigger in post is not the best option.  If you need things bigger, shoot them bigger.

  • Troubles by changing the size of a bookmark header text Repot generation Toolkit

    Hello everyone
    I'm having  troubles getting the size of  a header text formatted into a different font size, I attach the code I'm using to get the work done.
    At the end I get all I want from the report generation toolkit but the text size in the header and footer . Does Anyone have a clue?
    Well the image is too small I'm getting an error when I try to post a bigger one. The thing is that the VI's used here to change the size are append report text.vi and format text.vi. The first one is used to insert text through bookmarks in the header and footer  (it works just gereat) and the second one is intended to change the size of the inserted text (it doesn't work at all) I've already used shift registers in the for loop but I get the same results. The last VI is dispose report.vi
    thanks in advance
    Attachments:
    Maquina Etdos Verifica Reporte.vi ‏94 KB

    Hello Julio9,
     sorry for the waiting I had to clean the block diagram up and take into account some data security issues before I could post the information you asked me to. I have to tell you that I already came out with a patch for the issue nonetheless it is not the correct way to solve it and I would appretiate if you or anyone else could help me to do it right.
    Here is what I changed:
    In my code at the Initialize state (within the state machine) there is the New Report.vi I opened it to get also the new report SubVI.vi opened, afterwards I selected the NI_Word.lvclass: new report subvi.vi and opened it in its code yoou can easly see the double numeric constant value for the size of the text inserted as default. I just changed it from 12 to 8 to correct the formatting. As the outcome all the text inserted through the bookmarks have the default size (8 pts). 
    I attached the new version of my code with all the documents you will need. Please follow these steps:
    1.-Open the project named Verifica Temperaturas 2010.lvproj
    2.-Run the main vi named Maquina Etdos verifica reporte 2.vi
    3.-Check the option Laboratorio de Refrigeradores:
    4.-Click OK
    5.-Complete the information as shown:
    (For Selecciona Machote pick the word document named Document.doc attached in the .zip file. For the Selecciona Archivo de temperaturas pick the Estacion1_21-02-2012.txt file also attached in the .zip file)
    6.-Press Siguiente
    After completing the steps you'll see how the document in created. As expected the size of the text in the header is 8 pts.
    Attachments:
    Verificacion_Camaras.zip ‏359 KB

  • Changing the size of a drop down list

    Hi Everyone,
    Is there anyway to change the size of a drop down list?  For example, our customer would like to make the drop down list for the Ship-To field on the logistics tab of the sales orders longer.  Currently, they cannot see the full name when they scroll through it.  Is this possible?  Depending on what Customer Code they enter, the field size appears to change.
    Thank you in advance for your help.
    Amanda

    I am using Tahoma size 10 as well. 
    Is the drop down size somehow related to the size of the first few records?  So, if those are shorter than those at the end, perhaps it doesn't adjust for the size of the bottom records.  For example, in our customer's database here's a sampling of what they have entered and the order:
    Wal-Mart 6124
    Wal-Mart 6125
    Wal-Mart 6126
    Wal-Mart 7001
    Wal-Mart Supercenter 1111
    Wal-Mart Supercenter 2094
    Wal-Mart Supercenter 3475
    The drop down box is large enough to see the Wal-Mart 6124, etc. but not large enough to see the Wal-Mart Supercenter ones at the bottom of the list (keep in mind there are over 100 ship-to's for this Business Parnter).  Does it maybe only look at the first fifty records or something like that?
    Thanks again,
    Amanda

Maybe you are looking for

  • Debugging No longer works after installing 8.01

    Debugging was working great until I installed 8.01, now all i get is Unable to connect to RDS server. I made sure line debugging was started and port information was the same.

  • Error Update was terminated at time of VFO1

    Dear All, I have created sales order with ref to contract no through standard  BAPI ,now i am going to create bill with ref to sales order (which i have created through BAPI),while saving the bill it will give me error Update was terminated and in SB

  • Missing Reader Plugin for Chrome

    I downloaded Acrobat Reader XI for use on a MacbookPro running OSX 10.8.4, with the intention of using it as my default pdf viewer for Chrome, my web browser of choice. However, after installation there is no Reader plugin in Chrome. I assume it woul

  • Look for USER EXIT/Program similar with BADI:  BADI_SCD_ACCTG for SAP 4.5B

    Hello SAP Guru,           We are having the challenging in performing posting to multiple G/L accounts per shipment. This is required, for example, if customer, interplant, and/or inbound orders are combined onto one shipment.          We found this

  • WRT54G wireless router drops internet?

    I'm using my WRT54G with Starband satellite internet.  It seems that every once in awhile or...sometimes way too often, the internet decides to stop working all together!  I've checked this with two other computers on the wireless network.  They all