Weird JPanel Resizing Problem

This program works as I want it to with one exception: sometimes when resizing the frame, the contained JPanels do not fully cover the frame's BorderLayout center region. If you run the program you'll discover that a light gray area often appears on the right and bottom edges of the frame when it's resized. Any ideas? Thanks. I'm using version 1.3.1._01 on Windows 98.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Grid extends JPanel implements ComponentListener
private int rows, columns;
private Block[][] block;
public Grid()
rows = 20;
columns = 10;
block = new Block[rows][columns];
setLayout(new GridLayout(rows,columns,0,0));
for (int i = 0; i < rows; i++)
for (int j = 0; j < columns; j++)
block[j] = new Block();
if ((i % 4) >= 1)
block[j].turnOn();
else
block[j].turnOff();
add(block[j]);
}//end inner for loop
}//end outer for loop
setBorder(BorderFactory.createLineBorder(Color.black,4));
addComponentListener(this);
}//end default constructor
public Dimension getPreferredSize()
int horizontalInsets = getInsets().left + getInsets().right;
int verticalInsets = getInsets().top + getInsets().bottom;
return new Dimension((block[0][0].getBlockWidth() * columns) + horizontalInsets,
(block[0][0].getBlockHeight() * rows) + verticalInsets);
}//end getPreferredSize
public void componentHidden(ComponentEvent ce)
//Invoked when the component has been made invisible.
public void componentMoved(ComponentEvent ce)
//Invoked when the component's position changes.
public void componentResized(ComponentEvent ce)
//Invoked when the component's size changes.
int horizontalInsets = getInsets().left + getInsets().right;
int verticalInsets = getInsets().top + getInsets().bottom;
setPreferredSize(new Dimension(getWidth() + horizontalInsets,getHeight() + verticalInsets));
setMinimumSize(new Dimension(getWidth() + horizontalInsets,getHeight() + verticalInsets));
public void componentShown(ComponentEvent ce)
//Invoked when the component has been made visible.
public static void main(String[] args)
JFrame frame = new JFrame();
frame.getContentPane().add(new Grid(),BorderLayout.CENTER);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Block extends JPanel implements ComponentListener
private int blockWidth, blockHeight;
private Color blockBackgroundColor, blockBorderColor, onColor;
private String blockOwner;
private boolean isOn;
public Block()
blockWidth = 20;
blockHeight = 20;
//setSize(20,20);
//setPreferredSize(new Dimension(20,20));
blockBackgroundColor = Color.gray;
blockBorderColor = Color.black;
setLayout(new BorderLayout(0,0));
setBorder(BorderFactory.createLineBorder(blockBorderColor,1));
setBackground(blockBackgroundColor);
isOn = false;
blockOwner = "1";
onColor = Color.orange;
addComponentListener(this);
setVisible(true);
}//end default constructor
public Block(int blockWidth, int blockHeight)
this();
this.blockWidth = blockWidth;
this.blockHeight = blockHeight;
}//end two-arg constructor
public void setBlockWidth(int blockWidth)
this.blockWidth = blockWidth;
public int getBlockWidth()
return blockWidth;
public void setBlockHeight(int blockHeight)
this.blockHeight = blockHeight;
public int getBlockHeight()
return blockHeight;
public void setBlockBorderColor(Color blockBorderColor)
this.blockBorderColor = blockBorderColor;
public Color getBlockBorderColor()
return blockBorderColor;
public void setBlockBackgroundColor(Color blockBackgroundColor)
this.blockBackgroundColor = blockBackgroundColor;
public Color getBlockBackgroundColor()
return blockBackgroundColor;
public void setOnColor(Color onColor)
this.onColor = onColor;
public Color getOnColor()
return onColor;
public void turnOn()
setBackground(onColor);
isOn = true;
public void turnOff()
setBackground(blockBackgroundColor);
isOn = false;
public void setBlockOwner(String blockOwner)
this.blockOwner = blockOwner;
public String getBlockOwner()
return blockOwner;
public Dimension getPreferredSize()
int horizontalInsets = getInsets().left + getInsets().right;
int verticalInsets = getInsets().top + getInsets().bottom;
return new Dimension(blockWidth + horizontalInsets,
blockHeight + verticalInsets);
}//end getPreferredSize
public void paintComponent(Graphics g)
super.paintComponent(g);
if (isOn)
FontMetrics fm = g.getFontMetrics();
int blockOwnerWidth = fm.stringWidth(blockOwner);
int blockOwnerAscent = fm.getAscent();
int x = (blockWidth / 2) - (blockOwnerWidth / 2);
int y = (blockHeight / 2) + (blockOwnerAscent / 2);
g.drawString(blockOwner,x,y);
}//end paintComponent
public void componentHidden(ComponentEvent ce)
//Invoked when the component has been made invisible.
public void componentMoved(ComponentEvent ce)
//Invoked when the component's position changes.
public void componentResized(ComponentEvent ce)
//Invoked when the component's size changes.
int horizontalInsets = getInsets().left + getInsets().right;
int verticalInsets = getInsets().top + getInsets().bottom;
blockWidth = this.getWidth();
blockHeight = this.getHeight();
setPreferredSize(new Dimension(blockWidth + horizontalInsets,blockHeight + verticalInsets));
setMinimumSize(new Dimension(blockWidth + horizontalInsets,blockHeight + verticalInsets));
public void componentShown(ComponentEvent ce)
//Invoked when the component has been made visible.

Your problem is due to the use of a GridLayout.
With a GridLayout, all components must have the same dimension. And the extra space has to be divisible by the number of components to be distributed to each component :
For example : In a component with a GridLayout, you have a line with 10 JPanels. The width of the component is initially 100. In this case, each JPanel will have a width of 10 (10*10=100).
If you resize the main component to a width of 110, each JPanel will have a size of 11 (11*10=110).
But in the case where the width is not divisible by the number of JPanels, there will be an extra-space :
if the width of the component is 109, the width of each JPanel will be 10 and there will be an extra-space of 9 (10*10+9 = 109).
I hope this helps,
Denis

Similar Messages

  • Weird Video Squeezing Problem

    Hello.
    I'm having a weird video problem and I thought I'd see if anyone else has experienced it.
    I'm running the MSI nforce board with an AthlonXP 1700+ with two Micron 256MB PC2100.  Firmware 2.6.  Windows XP Home Edition with SP1.  I have a four-year old ViewSonic GT775 that I've always had good luck with.
    I've been using the latest nForce 2.93 drivers since they came out and am running the 41.03 Detonator drivers.  I've tried downgrading to the 40.72 with no change.
    I run my desktop at 1024x768x32bit and what has started happening the past couple of days is that the image on my desktop will randomly squeeze in about a half-inch on each side.  It will stay like this for a while and then randomly go back.  It wouldn't be a big deal if it just stayed like this, but it randomly clicks back and forth.  Changing the color depth or refresh rate does not affect it.  Even shutting down and then restarting doesn't affect it.  If it was squeezed when I shut down, it'll be squeezed when I restart.
    Very weird.  For now, every time it does it, I just use the monitor controls to resize the display, but it is annoying to have to do it.  It seems like right before its going to switch, I'll see minor tearing.
    Has anyone else experienced this?  Could it be my monitor?  I do have another computer at work and I could bring the monitor home.  My experience in the past with monitors is that when they start to go, the colors change and the brightness dims and then they just stop working.  My monitor today is as crisp and bright as the first day I bought it, so I think it's the onboard video.
    Does anyone have any ideas?
    Thanks!

    Your image resize problem sounds like a refresh rate problem to me. It looks as if your monitor cannot catch the correct refresh or follow the hi speed refresh you ask. It can come from either the board, the monitor or just a bad connection. I would tend to say the monitor, as it is getting a bit old.
    Failures in monitor can come from diffrent parts. If it is the electron canon, you can see a lowering of the luminosity/contrast. Same for the high voltage grid. A problem on your deflection parts could lead to a color shift or distorted image. Here, i'd say it is a problem with your synchronisation signal. Try a degauss also. You may just have a shifty ground.
    Frenchy

  • [SOLVED] GNOME 3.8 annoying window resize problem

    Hello all fellow early-adopters :-)
    A very annoying quirk I've noticed, moving from GNOME 3.6 to 3.8, is that it no longer remembers, nor retains, the size/positions I set for many of my application windows. For example, my mail client (Evolution) is sized to fill most of my screen (centrally), with Empathy and Skype as long narrow windows on both sides - giving me a nice, broad "communications" overview on that particular desktop (with dev tools etc open on others).
    On 3.6, this layout was retained during my session, as well as next time I started these apps up.
    In GNOME 3.8, not only does it insist that these windows are always started as small little bunched-up windows that I need to resize, but every time a window displays a notification/warning (message in internal yellow bar inside the window - such as loss of internet connection, mail retrieval failure etc) it resizes the windows spontaneously to a stupid, small size that overlays the other windows. This is driving me crazy!
    Where can I learn a bit more about how window sizing / positioning works in GNOME 3.8, or is it finally time to switch to awesome wm? I want to love GNOME 3.8, I really do. It's so slick, but so... unpolished.
    I want to dig in an assist with problems like these, but I need some pointers to some background material first to understand the problem. Is it the window manager? Is it the app?
    ** UPDATE: Doing a full system upgrade, as of May 18, 2013, has resolved this annoying problem. My windows now stay where they belong, and start with the same size they were closed with. GNOME is now pleasant to use again :-)
    Last edited by dawid.loubser (2013-05-21 13:37:25)

    dawid.loubser wrote:Thanks for the suggestion drtebi - I'll give it a try.
    I really like GNOME 3.x though (and would like to understand the windowing behaviour), but if the annoying quirks are insurmountable, I will happily switch.
    Man I love GNOME 3.x. I admire the courage they had to change, basically, everything, and I find myself more productive with my GNOME 3 Arch box than with my good ol' Slackware KDE 4 box. I just hate those bugs - for example I filed a task in their bugtracker for this window resize problem I have with gedit. If it's a love/hate relationship, I think it's marriage ^_^
    With the 3.8 upgrade, deadbeef was having a similar problem with window size/position. I just recompiled it against the latest GTK+3 package upgrade (that came after the 'big upgrade' here on Arch) and it was fixed. But not with gedit
    bwat47 wrote:
    Man I really hope this gets fixed soon, because aside from this one incredibly annoying issue I am loving gnome 3.8.
    I get the feeling gnome badly needs more beta testers, sizable regressions like this in "stable" releases happen way too often sad.
    I get the exact same feeling. Well bugs exist everywhere, there's no denying. But I think it would be wiser to 'alternate' the nature of each major stable release - one focusing on new features and one focusing on fixing bugs. For example if the only new features in GNOME 3.10 were the AppsFolder full implementation and the introduction of gnome-calendar, and the rest of the development cicle being devoted to fix bugs, I'd be more than happy.
    Like Fedora and Ubuntu, the fixed 6-month release cycle colaborates with the bugs. They don't do like Debian or Slackware which are released 'when they are ready'.
    EDIT: fout (yet) another bug. At least with facebook chat (haven't tested with other telepathy plugins) the buddy tray icon appear duplicate. Anybody with the same issue?
    Last edited by lmello (2013-05-02 14:06:06)

  • Preview Application Resizing Problem

    Preview Application Resizing Problem
    Microsoft platforms have two significant advantages. The first is the concept of an operating system that can function with hardware that ranges from cellular phones to desktop computers. The second is that Microsoft has excellent software development tools
    for creating and testing computer programs.
    Software compatibility across hardware platforms requires not only meeting CPU and memory requirements. Application programs must be able to automatically adjust Window and control sizes to meet the needs of available window sizes, video display unit sizes
    and screen resolutions, switching between vertical and horizontal viewing, vertical and horizontal scrolling, changes in font sizes , and variations in the available screen space due to usage of vertical and horizontal toolbars.
     Software developers must be careful that resizing doesn’t squeeze controls too close together or make them so small that they cannot be finger or stylus selected when used with touch screens.
    Some of the required automatic resizing options are provided by the Microsoft software compilers and the Windows operating system.  Softgroup Component’s “.NET  Forms Resize” is an example of one of the third party applications that provide advanced
    resizing functionality.
    Many of the resizing functions are programmer options and, if not properly enabled, an application may not have the required resizing functionality. At the current state of the art, application programs are highly variable in their capability to do the “intelligent
    resizing” that is required to handle different display environments.
    A case in point is the Microsoft Preview Application for Windows 10. When entering lengthy comments, the send button becomes positioned off the end of the program window. It is possible to scroll to the button, but the display automatically resets when scroll
    is released. The result is that the text cannot be sent. You can try a "blind" TAB to the SEND button. This appeared to work after several tries, but the comment was apparently not received,
    RERThird

    Hi,
    What do you see when you open the same PDF file in Acrobat Reader? Are the words still squeezed than?
    Dimaxum

  • Illustrator Resizing Problems

    I am having reduction resizing problems in Illustrator CS6.  E.G. Straws & lemon wedge rinds become significantly proportionately wider when reduced.   Also, numerical text does not skew with everything else.  I have a CC membership w/PS & Ai installed.  There are no other Adobe items on my 8 month old imac, Lion 10.7.4 except Flash player & the Adobe Applications Manager.  Additionally, I have no 3rd party plug-ins & deleting the prefs file does not fix the problem.  Any help on this matter would be greatly appreciated. 

    sgem,
    And untick Align to Pixel Grid if ticked (you can do it in the Transform panel, or search for it in the Helpfile).
    Hi Steve. Still summer?

  • JPanel Resizes Self

    This is from fairly large code so I'm trying to pull the important stuff out of two classes:
    MainM.class:
        private void bPlayActionPerformed(java.awt.event.ActionEvent evt) {
            game=new Game(WD+"\\songs\\"+cmbSong.getSelectedItem(),this,settings.FPS,getWidth(),getHeight());
            JPMain.setVisible(false);
            java.awt.GridBagConstraints gc=new java.awt.GridBagConstraints();
            gc.gridx=0;gc.gridy=0;
            getContentPane().add(game,gc);
            game.animator.start();
        }Game.class:
        public Game(String SongFile, MainM JMain, int iFPS, int Width, int Height) {
            addKeyListener(this);
            setVisible(true);
            setMinimumSize(new Dimension(Width,Height));
            setSize(Width,Height);
            animator=new Thread(this);
        public void run() {
            // Remember the starting time
            long tm = System.currentTimeMillis();
            while (Thread.currentThread() == animator) {
                // Display the next frame of animation.
                manpaint();
                // Delay depending on how far we are behind.
                try {
                    tm += 1000/FPS;
                    Thread.sleep(Math.max(0, tm - System.currentTimeMillis()));
                } catch (InterruptedException e) {
                    break;
                // Advance the frame
                CurBeat+=BPF;
        public void manpaint() {
            Graphics g=getGraphics();
            int x,y,xunit,yunit,dx,dy;
            xunit=getWidth()/ScaleX;
            yunit=getHeight()/ScaleY;
            // Now draw the image scaled.
            System.out.println(getWidth());
            g.drawImage(Pics[0],0,0,getWidth(),getHeight(),this);
            g.drawImage(Pics[1],ScaleX*(CurTrack*(ScaleX/10)),yunit*(ScaleY-7),yunit*10,yunit*4,this);
            for(x=0;x<Tracks.length;x++){
                for(y=0;y<Tracks[x].CurBeats.length;y++){
                    if (Tracks[x].CurBeats[y][0]!=-1){
                        dx=xunit*(x*(ScaleX/Tracks.length))+xunit*x+xunit*3*Tracks[x].CurBeats[y][1];
                        dy=yunit*y+yunit*(-2)+(int)(yunit*(CurBeat-(int)CurBeat));
                        g.drawImage(Pics[2],dx,dy,xunit*2,yunit*2,this);
            update(g);
        }And the problem is:
    In this last method there is a line "System.println.(getwidth());" for the first time it prints 400, the correct width, but after the first print it starts printing 10's, so in accordance, on the screen it draws the first frame correctly and then refreshes a tiny fram in the center of the screen 10 pixels wide and tall. There is no code to resize this panel other than when it is initialized, is there any reason it should be resizing itself?

    solved the resizing problem, have to set preferred size instead of just using setsize (for the record)

  • DV resize problem with QuickTime's iPod 320 x 240 export

    Just a heads up for those with new 5th generation iPods who plan on converting their DV movies for display on the iPod. It seems that the iPod 320 x 240 export does not resize DV correctly. Here is a link concerning this problem:
    Waymen, "Possible resize problem with iPod 320 x 240 Export?" #1, 03:02am Oct 13, 2005 CDT

    This article show a workaround to have DV export correctly in QuickTime Pro
    http://docs.info.apple.com/article.html?artnum=302955

  • JViewport Resize problem -- Urgent!

    I am trying to make a program that allows the user to dynamically resize a scrollable JPanel. I have added resize buttons that work well. The JScrollPane works well, but when the JViewport's View is set to the bottom right corner of the JPanel, and the user attempts to resize the JPanel, the JViewport repaints its view to the top left corner, hence undoing any resizing. Resizing should not change the View, even if the component is no longer visible in the view.
    Here is a code example (please pardon the length and lack of comments):
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    public class JViewportBug extends JPanel implements Scrollable, ComponentListener
         public JViewportBug()
              this.setLayout( null );
         public Dimension getPreferredScrollableViewportSize()
              return getPreferredSize();
         public boolean getScrollableTracksViewportHeight()
              return false;
         public boolean getScrollableTracksViewportWidth()
              return false;
         public int getScrollableBlockIncrement( Rectangle visibleRect, int orientation, int direction )
              if( orientation == SwingConstants.VERTICAL )
                   return (int)( visibleRect.getHeight() * 9 / 10 );
              return (int)( visibleRect.getWidth() * 9 / 10 );
         public int getScrollableUnitIncrement( Rectangle visibleRect, int orientation, int direction )
              return 5;
         public void componentHidden(ComponentEvent e)
         public void componentMoved(ComponentEvent e)
         public void componentResized(ComponentEvent e)
              Dimension size = ( (Component)e.getSource() ).getSize();
              this.setBounds( 0, 0, 20 + size.width, 20 + size.height );
              this.setPreferredSize( new Dimension( 20 + size.width, 20 + size.height ) );
         public void componentShown(ComponentEvent e)
         public static void main( String[] args )
              JViewportBug bug = new JViewportBug();
              JFrame frame = new JFrame( "JViewport Bug" );
              frame.setExtendedState( JFrame.MAXIMIZED_BOTH );
              JScrollPane jsp = new JScrollPane( bug );
              JPanel viewable = new JPanel();
              bug.add( viewable );
              viewable.addComponentListener( bug );
              viewable.setBounds( 10, 10, 200, 200 );
              JDesktopPane jdp = new JDesktopPane();
              jdp.setLayout( null );
              for( int i = 0; i < 8; i++ )
                   ResizeButton rb = new ResizeButton( viewable, i, true );
                   bug.add( rb );
                   viewable.addComponentListener( rb );
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              viewable.setBackground( Color.white );
              frame.getContentPane().add( jdp, BorderLayout.CENTER );
              JInternalFrame jif = new JInternalFrame( "", true, true, true, true );
              jif.getContentPane().add( jsp );
              jdp.add( jif );
              jif.setSize( 500, 500 );
              bug.setPreferredSize( new Dimension( viewable.getWidth() + 20, viewable.getHeight() + 20 ) );
              jif.setVisible( true );
              frame.setVisible( true );
    class ResizeButton extends JComponent implements MouseMotionListener, MouseListener, ComponentListener
         public static final int NW_RESIZE_BUTTON = 0;
         public static final int N_RESIZE_BUTTON = 1;
         public static final int NE_RESIZE_BUTTON = 2;
         public static final int E_RESIZE_BUTTON = 3;
         public static final int SE_RESIZE_BUTTON = 4;
         public static final int S_RESIZE_BUTTON = 5;
         public static final int SW_RESIZE_BUTTON = 6;
         public static final int W_RESIZE_BUTTON = 7;
         JComponent resize;
         int buttonType;
         boolean enabled;
         public ResizeButton( JComponent aComponent, int type, boolean isEnabled )
              resize = aComponent;
              buttonType = type;
              setBounds();
              enabled = isEnabled;
              this.addMouseMotionListener( this );
              this.addMouseListener( this );
         public int getType()
              return buttonType;
         public void mouseEntered( MouseEvent e )
              if( enabled )
                   switch( ( (ResizeButton)e.getSource() ).getType() )
                        case 0:
                             getParent().setCursor( new Cursor( Cursor.NW_RESIZE_CURSOR ) );
                             break;
                        case 1:
                             getParent().setCursor( new Cursor( Cursor.N_RESIZE_CURSOR ) );
                             break;
                        case 2:
                             getParent().setCursor( new Cursor( Cursor.NE_RESIZE_CURSOR ) );
                             break;
                        case 3:
                             getParent().setCursor( new Cursor( Cursor.E_RESIZE_CURSOR ) );
                             break;
                        case 4:
                             getParent().setCursor( new Cursor( Cursor.SE_RESIZE_CURSOR ) );
                             break;
                        case 5:
                             getParent().setCursor( new Cursor( Cursor.S_RESIZE_CURSOR ) );
                             break;
                        case 6:
                             getParent().setCursor( new Cursor( Cursor.SW_RESIZE_CURSOR ) );
                             break;
                        case 7:
                             getParent().setCursor( new Cursor( Cursor.W_RESIZE_CURSOR ) );
         public void mouseExited( MouseEvent e )
              if( enabled )
                   getParent().setCursor( new Cursor( Cursor.DEFAULT_CURSOR ) );
         public void mouseClicked( MouseEvent e )
         public void mousePressed( MouseEvent e )
         public void mouseReleased( MouseEvent e )
         public void mouseMoved( MouseEvent e )
         public void mouseDragged( MouseEvent e )
              if( enabled && e.getSource() instanceof ResizeButton )
                   int clickedX = e.getX();
                   int clickedY = e.getY();
                   int width, height;
                   switch( ( (ResizeButton)e.getSource() ).getType() )
                        case NW_RESIZE_BUTTON:
                             width = resize.getX() + resize.getWidth() - this.getX() - clickedX > 1 ? resize.getX() - this.getX() - clickedX + resize.getWidth() : 1;
                             height = ( resize.getY() + resize.getHeight() - this.getY() - clickedY > 1 ? resize.getY() - this.getY() - clickedY + resize.getHeight() : 1 );
                             resize.setBounds( resize.getX() + resize.getWidth() - this.getX() - clickedX > 1 ? this.getX() + clickedX : resize.getX() + resize.getWidth() - 1,
                                                           resize.getY() + resize.getHeight() - this.getY() - clickedY > 1 ? this.getY() + clickedY : resize.getY() + resize.getHeight() - 1,
                                                           width,
                                                           height );
                             break;
                        case N_RESIZE_BUTTON:
                             height = resize.getY() + resize.getHeight() - this.getY() - clickedY > 1 ? resize.getY() - this.getY() - clickedY + resize.getHeight() : 1;
                             resize.setBounds( resize.getX(),
                                                           resize.getY() + resize.getHeight() - this.getY() - clickedY > 1 ? this.getY() + clickedY : resize.getY() + resize.getHeight() - 1,
                                                           resize.getWidth(),
                                                           height );
                             break;
                        case NE_RESIZE_BUTTON:
                             width = this.getX() + clickedX - resize.getX() > 1 ? this.getX() + clickedX - resize.getX() : 1;
                             height = resize.getY() + resize.getHeight() - this.getY() - clickedY > 1 ? resize.getY() - this.getY() - clickedY + resize.getHeight() : 1;
                             resize.setBounds( resize.getX(),
                                                           resize.getY() + resize.getHeight() - this.getY() - clickedY > 1 ? this.getY() + clickedY : resize.getY() + resize.getHeight() - 1,
                                                           width,
                                                           height );
                             break;
                        case E_RESIZE_BUTTON:
                             width = this.getX() + clickedX - resize.getX() > 1 ? this.getX() + clickedX - resize.getX() : 1;
                             resize.setBounds( resize.getX(),
                                                           resize.getY(),
                                                           width,
                                                           resize.getHeight() );
                             break;
                        case SE_RESIZE_BUTTON:
                             width = this.getX() + clickedX - resize.getX() > 1 ? this.getX() + clickedX - resize.getX() : 1;
                             height = this.getY() + clickedY - resize.getY() > 1 ? this.getY() + clickedY - resize.getY() : 1;
                             resize.setBounds( resize.getX(),
                                                           resize.getY(),
                                                           width,
                                                           height );
                             break;
                        case S_RESIZE_BUTTON:
                             height = this.getY() + clickedY - resize.getY() > 1 ? this.getY() + clickedY - resize.getY() : 1;
                             resize.setBounds( resize.getX(),
                                                           resize.getY(),
                                                           resize.getWidth(),
                                                           height );
                             break;
                        case SW_RESIZE_BUTTON:
                             width = resize.getX() + resize.getWidth() - this.getX() - clickedX > 1 ? resize.getX() - this.getX() - clickedX + resize.getWidth() : 1;
                             height = this.getY() + clickedY - resize.getY() > 1 ? this.getY() + clickedY - resize.getY() : 1;
                             resize.setBounds( resize.getX() + resize.getWidth() - this.getX() - clickedX > 1 ? this.getX() + clickedX : resize.getX() + resize.getWidth() - 1,
                                                           resize.getY(),
                                                           width,
                                                           height );
                             break;
                        case W_RESIZE_BUTTON:
                             width = resize.getX() + resize.getWidth() - this.getX() - clickedX > 1 ? resize.getX() - this.getX() - clickedX + resize.getWidth() : 1;
                             resize.setBounds( resize.getX() + resize.getWidth() - this.getX() - clickedX > 1 ? this.getX() + clickedX : resize.getX() + resize.getWidth() - 1,
                                                           resize.getY(),
                                                           width,
                                                           resize.getHeight() );
         public void setBounds()
              switch( buttonType )
                   case NW_RESIZE_BUTTON:
                        this.setBounds( resize.getX() - 5,
                                                 resize.getY() - 5,
                                                 5,
                                                 5 );
                        break;
                   case N_RESIZE_BUTTON:
                        this.setBounds( (int)( ( resize.getWidth() + 2 * resize.getX() ) / 2 ) - 2,
                                                 resize.getY() - 5,
                                                 5,
                                                 5 );
                        break;
                   case NE_RESIZE_BUTTON:
                        this.setBounds( resize.getWidth() + resize.getX(),
                                                 resize.getY() - 5,
                                                 5,
                                                 5 );
                        break;
                   case E_RESIZE_BUTTON:
                        this.setBounds( resize.getWidth() + resize.getX(),
                                                 (int)( ( resize.getHeight() + 2 * resize.getY() ) / 2 ) - 2,
                                                 5,
                                                 5 );
                        break;
                   case SE_RESIZE_BUTTON:
                        this.setBounds( resize.getWidth() + resize.getX(),
                                                 resize.getHeight() + resize.getY(),
                                                 5,
                                                 5 );
                        break;
                   case S_RESIZE_BUTTON:
                        this.setBounds( (int)( ( resize.getWidth() + 2 * resize.getX() ) / 2 ) - 2,
                                                 resize.getHeight() + resize.getY(),
                                                 5,
                                                 5 );
                        break;
                   case SW_RESIZE_BUTTON:
                        this.setBounds( resize.getX() - 5,
                                                 resize.getHeight() + resize.getY(),
                                                 5,
                                                 5 );
                        break;
                   case W_RESIZE_BUTTON:
                        this.setBounds( resize.getX() - 5,
                                                 (int)( ( resize.getHeight() + 2 * resize.getY() ) / 2 ) - 2,
                                                 5,
                                                 5 );
         public void componentHidden(ComponentEvent e)
         public void componentMoved(ComponentEvent e)
         public void componentResized(ComponentEvent e)
              this.setBounds();
         public void componentShown(ComponentEvent e)
         public void setEnabled( boolean enable )
              enabled = enable;
         public boolean isEnabled()
              return enabled;
         public void paint( Graphics g )
              ( (Graphics2D)g ).fillRect( 0, 0, 5, 5 );
    }

    Hi bbritta,
    Thanks for the time. I guess the setLocation MIGHT be off, tho ideally, it should place the tv somewhere near the right bottom corner of the screen.
    The basic requirement I have is in the code written. This is what I want. When I start my application, I want the small tv screen only to appear, with the two colored panels (that shall obviously contain some other code). When my mouse hovers on this small screen, the buttons should appear in a panel just below the small screen. So I have used a JLayered pane that displays two separate gifs, one for the small screen, and one for the buttons panel. On the small screen gif, I have added two panels to layer 1, and on the button panel gif, I have added 3 buttons.
    What is happening is that if I set the frame size to the size of the small screen at startup (before show()), then on mouse hover, the frame size increases, but the layered pane size stays the same, and hence i cannot see the button panel. But if I start out with the button panel showing (frame size initially set to the larger value), then on mouse exit, the button panel disappears, and reappears properly on mouse enter. But I don't want to set the original size to the larger value, since only the small screen must be seen first.
    Did I make my self clear? The whole problem is that on mouse hover, u cannot see the button panel, till u change the setSize() code in initializeFrame() to use c_o_FULL_TV_SIZE instead of c_o_TV_SIZE. That u cannot see the buttons IS my problem!
    Thanks,
    Shefali.

  • JScrollPane resizing problem, I think...

    The Task
    I want to build a dialog that holds different option panels.
    Instead of using a JTabbedPane, I want to use a JTree to select among the different panels.
    I put the tree in a nice scroll pane, place the whole thing in the left side of
    the dialog. I think I have the logic down except for one thing...
    The Problem
    Whenever I click a node when the JTree is expanded, it resizes itself. It does this so that words that go off to the right can be seen.
    I don't want this to happen, but I do have to revalidate the main panel for it to change.
    Apparently, just revalidating the main panel revalidates everything.
    The Question
    Is there a setting in the JTree or the JScrollPane that stops this from happening?
    I have tried to change the LayoutManager, but the same thing happens with GridBagLayout.
    I'll put example code in the following post so you can see my issue. I put the most pertinent code to the front, so that you don't have to read too deeply.
    Can anyone advise me?
    Thanks.

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import java.util.*;
    public class ScrollPaneProblem extends JDialog
       implements TreeSelectionListener
       private JButton jbClose;
       private JTree optionsTree;
       private MainPanel jpMain;
       private ActionListener terminator;
       public ScrollPaneProblem()
          // I would prefer that it stay this size.
          setSize( 535, 375 );
          setResizable( false );
          setTitle( "Preferences" );
          setupGui();
          setDefaultCloseOperation( DO_NOTHING_ON_CLOSE );
       protected void setupGui()
          Container contentPane = getContentPane();
             The left side of dialog will hold the option tree.
          optionsTree = buildTheTree();
          JScrollPane scrollPane = new JScrollPane( optionsTree );
          contentPane.add( scrollPane, BorderLayout.WEST );
             The center panel will hold another panel
             that changes according to what has been selected
             in the JTree.
          JPanel centerPanel = new JPanel( new BorderLayout() );
          Box bxButtons = buildTheButtonBox();
          centerPanel.add( bxButtons, BorderLayout.SOUTH );
          jpMain = new MainPanel();
          centerPanel.add( jpMain, BorderLayout.CENTER );
          contentPane.add( centerPanel, BorderLayout.CENTER );
       } // end setupGui()
          Changes the text on the main panel, according to what
          has been clicked in the JTree.
       public void valueChanged( TreeSelectionEvent evt )
          TreePath path = evt.getPath();
          Object obj = path.getLastPathComponent();
          if ( obj instanceof DefaultMutableTreeNode )
             DefaultMutableTreeNode node =
             (DefaultMutableTreeNode)obj;
             obj = node.getUserObject();
             // The problem happens when I do the following...
             jpMain.setText( obj.toString() );
             jpMain.revalidate();
             jpMain.repaint();
          } // end if ( a DefaultMutableTreeNode )
       } // end valueChanged( TreeSelectionEvent )
       private JTree buildTheTree()
          // First, build the parent nodes
          Object [] smurfNodes =
             "Smurfette", "Vanity", "Papa Smurf",
             "Greedy Smurf", "Lazy Smurf",
             "O.J., the ostracized orange smurf"
          ParentNode theSmurfs = new ParentNode(
                                  "The Smurfs", smurfNodes );
          Object [] dwarfNodes =
             "Doc", "Happy", "Dopey", "Sneezy",
             "Scratchy", "Sniffy", "Stuffy Head",
             "Fever", "So you can rest medicine"
          ParentNode theDwarfs = new ParentNode(
                                  "The Seven Plus Dwarfs", dwarfNodes );
          // These are all the nodes that go on the tree.
          Object [] theNodes =
             "Scooby Doo",
             "Inspector Gadget",
             "Mighty Mouse",
             "Captain Caveman",
             theSmurfs,
             theDwarfs
          JTree theTree = new JTree( theNodes );
          theTree.addTreeSelectionListener( this );
          return theTree;
       } // end buildTheTree()
       public Box buildTheButtonBox()
          Box box = Box.createHorizontalBox();
          box.add( Box.createHorizontalGlue() );
          // Make it so that we can close this JDialog.
          jbClose = new JButton( "Exit" );
          jbClose.addActionListener( terminator );
          box.add( jbClose );
          box.add( Box.createHorizontalGlue() );
          // help button that does absolutely nothing.
          JButton jbHelp = new JButton( "Help" );
          box.add( jbHelp );
          box.add( Box.createHorizontalGlue() );
          return box;
       } // end buildTheButtonBox()
       // Main entry point.
       public static void main( String [] args )
          JDialog dialog = new ScrollPaneProblem();
          dialog.setVisible( true );
       // So we can shut the dialog off
       static
          terminator =
          new ActionListener()
             public void actionPerformed( ActionEvent evt )
                System.exit( 0 );
    } // end ScrollPaneProblem class
       This MainPanel class goes in the middle of the dialog.
       My other program switches panels instead of using
       the same panel, but that's too much code to put here.
    class MainPanel extends JPanel
       String theText = "Tell me what to draw";
       Font theFont = new Font( "Sans Serif", Font.PLAIN, 12 );
       Dimension theSize;
       // Draws the selected text
       public void paintComponent( Graphics g )
          super.paintComponent( g );
          theSize = getSize( theSize );
          Font oldFont = g.getFont();
          g.setFont( theFont );
          g.drawString( theText, theSize.width / 10, theSize.height / 2 );
          g.setFont( oldFont );
       public void setText( String text )
          theText = text;
    } // end class MainPanel
       This helps with the JTree parent nodes.
    class ParentNode extends Vector
       String theName;
       public ParentNode( String name )
          this( name, null );
       public ParentNode( String name, Object [] values )
          theName = name;
          if ( values != null )
             addAll( Arrays.asList(values) );
       public String toString()
          return theName;
    } // end ParentNode class

  • A resize problem I have

    Hi all,
    I have a JTabbedPane with the first tab designed with Intellij's GUI designer. The JTabbedPane, the JPanel that fills the first tab and the JFrame containig the above components are all instantiated from the main class.
    I have a nother panel also designed in the GUI designer that I add as a new tab to my tabbedpane when the program starts runing.
    My problem is:
    The first tab (created and instantiated automaticaly) maintains proportions when the JFrame is resized.
    However, the add tab's content has a fixed size which I can't get to fill the tab.
    I tried the setSize method, I tried using GridBagLayout with GridBagConstraints and nothing, it won't resize.
    Can anyone help please?
    Thanks.

    This is why using a VE before you know how to do it yourself is usually a bad idea. Without code, we can't help you, but what is almost certainly the problem is the LayoutManager for that tab's contents and it's constraints are not setup to fill the available area.
    If you used GridBagLayout you'd have to at the very least set GridBagConstraints fill to BOTH.

  • 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

  • Automatic Resizing Problems

    I am having serious troubles with my components resizing automatically when the window is resized or the contents within the component change. Namely, tree and list components. Every time I add an element to a tree or list component, the container that the tree or list is placed in resizes to match the longest element within the tree or list. I have researched my Pure JFC Swing book from cover to cover trying to find a fix for this, and have had no luck. Can somebody help me remedy this problem?

    Ok, I haven't added anything to exit the system when you close the window. Also, I have chosen not to repeat any code for a JTree at all. It would take too long. This is code for a JList component. Try entering a really long e-mail and also a short one.
    class NameFrame extends JFrame{
         Container contentPane = getContentPane();
         public NameFrame(String title, int w, int h){
              super(title);
              setSize(w,h);
              contentPane.add(new NamePanel());
    class NamePanel extends JPanel implements ActionListener{
         JList list;
         JTextField email;
         JButton addButton;
         Container contentPane = getContentPane();
         Vector listData = new Vector();
         public NamePanel(){
              addButton = new JButton("Add");
              addButton.addActionListener(this);
              addButton.setActionCommand("Add");
              add(addButton);
              email = new JTextField("", 20);
              add(email);
              list = new JList();
              list.setVisibleRowCount(4);
              list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
              list.setSelectionBackground(Color.blue);
              list.setSelectionForeground(Color.white);
              list.addListSelectionListener(this);
              JScrollPane sp = new JScrollPane(list, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              add(sp);
         public void actionPerformed(ActionEvent ae){
              String but = ae.getActionCommand();
              if(but.equals("Add")){
                   listData.addElement(email.getText());
                   list.setListData(listData);
                   email.setText("");
    class A{
         public static void main(String[] args){
              NameFrame nf = new NameFrame();
              nf.show();
    Then, click the window and watch it re-size to match the longest one. I don't like this, I would like to keep it the same size at all times no matter what size e-mail is entered.
    Your dilligence is greatly appreciated....

  • Jpanel, resize, borderlayout, browser, applet

    Sorry i cant find a good topic for my problem. :) I have an applet with a borderlayout, each time the browser is resize, my applet component is resize too , its ok, BUT i need to put a maximum size for my JPanel (in "Center"), is there a way to change the way that the automatic resize works? I explain why, i have a JPanel, the center one, that have a picture draw on it, when the view area of the JPanel is tiner than the size of the image, i put scrollbar, but i dont want to have the view area bigger than the picture..
    so is there a way
    sorry another time, when i have something long to explain in english, it could be not understandable :)
    thx a lot in advance

    try this, maybe works as you want,
    here component is you JPanel;
    Component component = new Component(){
    public Dimensin getMaximumSize()
    return new Dimension( 100, 100 ); // your picture size
    and as this you can overwrite
    getMinimumSize() and getPreferredSize() methods,
    Sorry i cant find a good topic for my problem. :) I
    have an applet with a borderlayout, each time the
    browser is resize, my applet component is resize too ,
    its ok, BUT i need to put a maximum size for my JPanel
    (in "Center"), is there a way to change the way that
    the automatic resize works? I explain why, i have a
    JPanel, the center one, that have a picture draw on
    it, when the view area of the JPanel is tiner than the
    size of the image, i put scrollbar, but i dont want to
    have the view area bigger than the picture..
    so is there a way
    sorry another time, when i have something long to
    explain in english, it could be not understandable :)
    thx a lot in advance

  • Nested JPanel resizing

    In one of my application there is one Jframe( BorderLayout) containing panel at the center surrounded with JScrollPane. The panel contains one more JPanel in it.
    On click of a button i need to resize both the panel.
    in the event handler method, Im caling setPreferedSize() and setSize() for both the panels.
    Only outer panel gets resized for the first click and for the second click inner panel gets resized...
    how can i solve this problem...?

    There is no way of knowing where the problem is without the code, however, you said you have called the setPreferedSize() and setSize() methods in the event handler.
    This should get called when you press the button, one thing you must do is to make sure that they are both inside the same block of code. If you are using an if statement.
    if(buttonPressed()){
    setPreferedSize();
    setSize();
    }Or you could post a simple version to help us solve the problem.

  • Weird Audio bleed problem on PCs only beginning at new year.

    Here is my test page showing the issue:
    http://jeanmarzollo.com/march10/TEST/
    At the new year, suddenly my animated children's books (built with one book page per scene mostly, all of which wait for the child to click the "next" button to turn the page) suddenly on windows PCs, each page would stop visually as usual, but continue to play the following page's audio (just one next page).  The audio definitely is not hidden on that scene, it's the NEXT scene's audio.  Can't understand why that would happen.
    I did a work-around fix by adding a "stop all sounds" action in addition to the "stop" at the end of each scene, but it can cause weird little issues. On this test page I made you'll see the earlier versions of the ebooks at the top of the page which worked fine before the new year and now show the issue that began at the new year (only on a windows machine). You have to go to past the cover page to see the problem (you can use the little lightning bolt arrow to avoid waiting through the whole intro).  My fixed versions are below.
    I just thought it was an odd little glitch that people might want to be aware of... I AM using Action Script 2.0... These are very simple little animations to match the child-like illustration style.... I do like Jean's painty illustrations to animate with.  Even though it can't resize, I think it's worth it.  (Jean Marzollo is the author/illustrator, and if you have little kids, they'll love all the free stuff on her site http://www.jeanmarzollo.com)
    Does anyone know why this could have happened?  Is it a windows operating system change (it happens to the movies whether they are served through IE or Firefox)?  Is anybody else experiencing any weird things with previously working movies that suddenly developed glitches after the new year?
    Thanks!
    Erika Wood

    Hello sbentley
    Welcome to the HP Forums!
    I will definitely assist you with the computer's issue regarding bleeding sound. Before anything else is done, please make sure you try every step in this thread: Troublesho​oting Guide: Audio does not Work after a Certain Period of Time
    If every step does not help, please provide the following information:
    1. The computer's model number. If you require assistance locating this information, please reference this website: Guide to finding your notebook product number
    2. The computer's operating system. If you require assistance locating this information, please reference this website to determine your Windows operating system.
    3. Does this occur on certain programs, or all programs?
    4. Have you installed any new software or drivers on this computer, before the issue appeared?
    5. What steps have been attempted from my first post on this thread, and what were the results?
    Mario
    I worked on behalf of HP.

Maybe you are looking for

  • In need of column type given a table and column.

    Hello, Currently I'm using in JDBC the following query to get the column's type (via ResultSetMetaData Java object): "select "+aColumnName+" from "+aTableName+" WHERE ROWNUM < 0" When the column is a Spatial column I'm getting the following exception

  • Lightning to USB camera adapter.

    I recently purchased an IPAD MINI and a Lightning to USB Camera adapter.  I went to plug my Sony Cyber Shot digital camera into my Ipad Mini via the adapter and it says "USB DEVICE REQUIRES TOO MUCH POWER.  Yet, when I plugged in my big Nikon D5000 S

  • How to make Folder Action work on file, subfolder content change?

    Hi! I looking for information in how to make a Folder Action, Work Flow or any action from Automator to work on file change and not only on deletion, moving or insertion. What I want to know is if it's possible to trigger some script or app while mon

  • How do I disable or delete the country code prefix

    I'm in Mexico and want to call another Mexican city ant skype keeps adding 52 before my number. Apparently it thinks I'm in the States and will need this code. How on earth do I just type in a phone number without a code? I don't need a country code

  • Transferring profiles between computers via time machine

    This may be a dumb question, but I'll ask anyway.  My new MBPR is one of the ones with a faulty battery in the 100k+ thread below, and Apple agreed to send me a brand new one.  The problem is, they're not sending it until they receive the defective o