Implementing a Scrollable JPanel

Does anyone have any suggestions for making a JPanel scrollable? Apparently, simply placing the JPanel inside a JScrollPane doesn't work, since JPanel does not implement Scrollable. I guess the solution would be to implement a custom JScrollablePanel. Has anyone else come across this problem?
Thanks.

Ok - I figured it out - It's the FlowLayout that I'm
using for the JPanel. It doesn't support wrapping.hmm, no, that's not it. FlowLayout is actually a simple/limited layout manager - it's preferred size is always calculated as though it should be on one line, but it will wrap if the panel's actual width is too small and it's height can accomodate more than 1 row. When you put a JPanel in a JScrollPane, the panel's preferred-size is used to size the panel, hence, a single line that goes on forever. The best solution is to subclass your JPanel and implement Scrollable - that is the whole reason that Scrollable exists, so that you can tell the JScrollPane how to scroll. Here's a sample that obviously only works with FlowLayout: import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ScrollablePanel extends JPanel implements Scrollable {
     public ScrollablePanel() {
          this(FlowLayout.LEFT);
     public ScrollablePanel(int flowLayoutType) {
          super(new FlowLayout(flowLayoutType));
     public ScrollablePanel(int flowLayoutType, int hgap, int vgap) {
          super(new FlowLayout(flowLayoutType, hgap, vgap));
     public Dimension getPreferredSize() {
          if (getParent() == null)
               return getPreferredSize();
                // calculate the preferred size based on the flow of components
          FlowLayout flow = (FlowLayout)getLayout();
          int w = getParent().getWidth();
          int h = flow.getVgap();
          int x = flow.getHgap();
          int rowH = 0;
          Dimension d;
          Component[] comps = getComponents();
          for (int i = 0; i < comps.length; i++) {
               if (comps.isVisible()) {
                    d = comps[i].getPreferredSize();
                    if (x + d.width > w && x > flow.getHgap()) {
                         x = flow.getHgap();
                         h += rowH;
                         rowH = 0;
                         h += flow.getVgap();
                    rowH = Math.max(d.height, rowH);
                    x += d.width + flow.getHgap();
          h += rowH;
          return new Dimension(w, h);
     public Dimension getPreferredScrollableViewportSize() {
          return getPreferredSize();
     public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
          // shift the view so that you see the next logical page
          if (orientation == SwingConstants.HORIZONTAL) {
               // this won't happen in this case since we never scroll horizontally
               return visibleRect.width;
          return visibleRect.height;
     public boolean getScrollableTracksViewportHeight() {
          // only force the height if the preferred size is too short to fill the viewport
          return getPreferredSize().height < getParent().getHeight();
     public boolean getScrollableTracksViewportWidth() {
          // always force this panel's width to the viewport's width
// this effectively disables horizontal scrolling
          return true;
     public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
          return 10;
     private static JScrollPane scroller;
     private static ScrollablePanel sp;
     public static void main(String[] args) {
          try {
               SwingUtilities.invokeAndWait(new Runnable() {
                    public void run() {
                         sp = new ScrollablePanel(FlowLayout.LEFT, 20, 20);
                         scroller = new JScrollPane(sp);
                         final JButton button = new JButton("Add Label");
                         button.addActionListener(new ActionListener() {
                              public void actionPerformed(ActionEvent e) {
                                   sp.add(new JLabel("HELLO"));
                                   scroller.validate();
                         JPanel content = new JPanel(new BorderLayout());
                         content.add(button, BorderLayout.NORTH);
                         content.add(scroller);
                         JFrame f = new JFrame("Test");
                         f.setContentPane(content);
                         f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                         f.setSize(600, 400);
                         f.setLocationRelativeTo(null);
                         f.setVisible(true);
          catch (Exception e) { e.printStackTrace(); }

Similar Messages

  • Implementing a scrollable component w custom drawing

    Hi! I'm currently trying to implement a component, that does some custom drawing, and is scrollable, but if I add the drawing component
    on a JScrollPane, nothing shows up, no scrollbars, no custom drawing.
    If i just add the component with the custom drawing to a JFrame, it looks fine.
    http://www.iit.uni-miskolc.hu/~kovacs29/Painter.java
    Can you tell me what am i doing wrong?

    The problem with drawing was that I forgot to draw the background :)
    Here is the source code if anyone views this topic later:
    import java.awt.*;
    import javax.swing.*;
    public class Painter extends JComponent implements Scrollable {
         private static final long serialVersionUID = 1L;
         public Painter() {
              setMinimumSize(new Dimension(800, 500));
              setMaximumSize(new Dimension(800, 500));
              setPreferredSize(new Dimension(800, 500));
              setOpaque(true);
         public Dimension getPreferredScrollableViewportSize() {
              return getPreferredSize();
         public int getScrollableUnitIncrement(Rectangle visibleRect,
                   int orientation, int direction) {
              return 10;
         public int getScrollableBlockIncrement(Rectangle visibleRect,
                   int orientation, int direction) {
              return 25;
         public boolean getScrollableTracksViewportWidth() {
              return false;
         public boolean getScrollableTracksViewportHeight() {
              return false;
         protected void paintComponent(Graphics graphics) {
              Graphics g = graphics.create();
              // It wasnt drawing things right when scrolling because the next 2 lines were missing :)
              g.setColor(getBackground());
              g.fillRect(0, 0, getWidth(), getHeight());
              g.setColor(Color.RED);
              g.drawLine(0, 0, getWidth(), getHeight());
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        JFrame f = new JFrame();
                        Painter p = new Painter();
                        JScrollPane sp = new JScrollPane();
                        f.setLayout(new BorderLayout());
                        //sp.add(p)
                        //This was here instead of setViewPortView()
                        sp.setViewportView(p);
                        f.add(sp, BorderLayout.CENTER);
                        f.setSize(400, 300);
                        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        f.setVisible(true);
    }

  • JScrollPane, JPanel & Scrollable interface

    Hello,
    I recently did a little programming with a JPanel and mistakenly implemented the Scrollable interface with a JPanel when I did not need to. In the process I discovered something that has sparked my curiosity. I added a group of JLabels in a GridLayout to this Scrollable JPanel. I also set the horizontalalignment of the JLabels in the panel. When this was set the JPanel by itself rendered the Labels according to the alignment I had set. However when I put the panel in a JScrollPane, The alignment of the Labels was not rendered as I expected. The elements in the JPanel were always flush to the left, no matter what alignment I had constructed the label with.
    Does anyone know why if you descended from a JPanel and implemented the Scrollable interface with that object, when you pass the object into a JScrollPane why you would lose the alignments of the JLabels in that Scrollable JPanel?
    This is not pivotal information to me, but I am curious. If anyone knows the answer to this please let me know.
    Thanks,
    Dan Hughes

    Dan,
    I have no idea why this happens. I do know however that it is a great source of insanity when you really need to get a JScrollPane to behave itself. If ever you need to make a JPanel the client of a JScrollPane use null layout and absolute positioning, also setPreferredSize of the JPanel before adding components. When all components are added to the JPanel make the JPanel the client of a JScrollPane. Also at the very end of your code you will need this code to make the layout the scrollBars behave:
    SwingUtilities.invokeLater(new Runnable()
    public void run()
    getViewport().setViewPosition(new Point(0,0));
    JScrollPAINS were not named PAINS for no reason. This information probably seems mostly irrelevant, but if you are curious, or intend on programming in future with JScrollPane it is probably wise to keep this near by.

  • URGENT! Need help with scrolling on a JPanel!

    Hello Guys! I guess there has been many postings about this subject in the forum, but the postings I found there.... still couldn't solve my problem...
    So, straight to the problem:
    I am drawing some primitive graphic on a JPanel. This JPanel is then placed in a JScrollPane. When running the code, the scrollbars are showing and the graphic is painted nicely. But when I try to scroll to see the parts of the graphics not visible in the current scrollbarview, nothing else than some flickering is happening... No movement what so ever...
    What on earth must I do to activate the scroll functionality on my JPanel??? Please Help!
    And yes, I have tried implementing the 'Scrollable' interface... But it did not make any difference...
    Code snippets:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import java.util.*;
    public class FilterComp extends JPanel {//implements Scrollable {
      protected DefaultMutableTreeNode root;
      protected Image buffer;
      protected int lastW = 0;
      protected int origoX = 0;
      protected final StringBuffer sb = new StringBuffer();
    //  protected int maxUnitIncrement = 1;
      protected JScrollPane scrollpane = new JScrollPane();
       *  Constructor for the FilterComp object
       *@param  scrollpane  Description of the Parameter
      public FilterComp(JScrollPane scrollpane) {
        super();
    //    setPreferredSize(new Dimension(1000, 500));
        this.setBackground(Color.magenta);
    //    setOpaque(false);
        setLayout(
          new BorderLayout() {
            public Dimension preferredLayoutSize(Container cont) {
              return new Dimension(1000, 600);
        this.scrollpane = scrollpane;
        scrollpane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        scrollpane.setPreferredSize( new Dimension( 500, 500 ) );
        scrollpane.getViewport().add( this, null );
    //    scrollpane.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
        repaint();
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        int w = getSize().width;
        if (w != lastW) {
          buffer = null;
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        if (root != null) {
          int h = getHeight(root);
          if (buffer == null) {
            buffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
            Graphics2D g3 = (Graphics2D) buffer.getGraphics();
            g3.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g3.setColor(Color.black);
            g3.setStroke(new BasicStroke(2));
            paint(g3, (w / 2) + origoX, 10, w / 2, root); 
          lastW = w;
          AffineTransform old = g2.getTransform();
          AffineTransform trans = new AffineTransform();
          trans.translate((w / 2) + origoX, (getHeight() - (h * 40)) / 2);
          g2.setTransform(trans);
          g2.drawImage(buffer, (-w / 2) + origoX, 0, null);
          g2.setTransform(old);
        updateUI();
       *  Description of the Method
       *@param  g  Description of the Parameter
      public void update(Graphics g) {
        // Call paint to reduce flickering
        paint(g);
       *  Description of the Method
       *@param  g2    Description of the Parameter
       *@param  x     Description of the Parameter
       *@param  y     Description of the Parameter
       *@param  w     Description of the Parameter
       *@param  node  Description of the Parameter
      private void paint(Graphics2D g2, int x, int y, int w, DefaultMutableTreeNode node) {
        if (node.getChildCount() == 2) {
          DefaultMutableTreeNode c1 = (DefaultMutableTreeNode) node.getChildAt(0);
          DefaultMutableTreeNode c2 = (DefaultMutableTreeNode) node.getChildAt(1);
          if (c1.getChildCount() == 0 && c2.getChildCount() == 0) {
            String s = c1.getUserObject().toString() + " " + node.getUserObject() + " " + c2.getUserObject();
            paint(g2, x, y, s);
          } else {
            g2.drawLine(x - (w / 2), y, x + (w / 2), y);
            Font f = g2.getFont();
            g2.setFont(new Font(f.getName(), Font.BOLD | Font.ITALIC, f.getSize() + 2));
            paint(g2, x, y, node.getUserObject().toString());
            g2.setFont(f);
            g2.drawLine(x - (w / 2), y, x - (w / 2), y + 40);
            g2.drawLine(x + (w / 2), y, x + (w / 2), y + 40);
            paint(g2, x - (w / 2), y + 40, w / 2, c1);
            paint(g2, x + (w / 2), y + 40, w / 2, c2);
        } else if (node.getChildCount() == 0) {
          paint(g2, x, y, node.getUserObject().toString());
       *  Description of the Method
       *@param  g2  Description of the Parameter
       *@param  x   Description of the Parameter
       *@param  y   Description of the Parameter
       *@param  s   Description of the Parameter
      private void paint(Graphics2D g2, int x, int y, String s) {
        y += 10;
        StringTokenizer st = new StringTokenizer(s, "\\", false);
        if (s.indexOf("'") != -1 && st.countTokens() > 1) {
          int sh = g2.getFontMetrics().getHeight();
          while (st.hasMoreTokens()) {
            String t = st.nextToken();
            if (st.hasMoreTokens()) {
              t += "/";
            int sw = g2.getFontMetrics().stringWidth(t);
            g2.drawString(t, x - (sw / 2), y);
            y += sh;
        } else {
          int sw = g2.getFontMetrics().stringWidth(s);
          g2.drawString(s, x - (sw / 2), y);
       *  Sets the root attribute of the FilterComp object
       *@param  root  The new root value
      public void setRoot(DefaultMutableTreeNode root) {
        this.root = root;
        buffer = null;
       *  Gets the root attribute of the FilterComp object
       *@return    The root value
      public DefaultMutableTreeNode getRoot() {
        return root;
       *  Gets the height attribute of the FilterComp object
       *@param  t  Description of the Parameter
       *@return    The height value
      private int getHeight(TreeNode t) {
        int h = 1;
        int c = t.getChildCount();
        if (c > 0) {
          if (c > 1) {
            h += Math.max(getHeight(t.getChildAt(0)), getHeight(t.getChildAt(1)));
          } else {
            h += getHeight(t.getChildAt(0));
        return h;
       *  Sets the x attribute of the FilterComp object
       *@param  x  The new x value
      public void setX(int x) {
        origoX = x;
       *  Gets the x attribute of the FilterComp object
       *@return    The x value
      public int getX() {
        return origoX;
       *  Gets the preferredScrollableViewportSize attribute of the FilterComp
       *  object
       *@return    The preferredScrollableViewportSize value
    //  public Dimension getPreferredScrollableViewportSize() {
    //    return getPreferredSize();
       *  Gets the scrollableBlockIncrement attribute of the FilterComp object
       *@param  r            Description of the Parameter
       *@param  orientation  Description of the Parameter
       *@param  direction    Description of the Parameter
       *@return              The scrollableBlockIncrement value
    //  public int getScrollableBlockIncrement(Rectangle r, int orientation, int direction) {
    //    return 10;
       *  Gets the scrollableTracksViewportHeight attribute of the FilterComp object
       *@return    The scrollableTracksViewportHeight value
    //  public boolean getScrollableTracksViewportHeight() {
    //    return false;
       *  Gets the scrollableTracksViewportWidth attribute of the FilterComp object
       *@return    The scrollableTracksViewportWidth value
    //  public boolean getScrollableTracksViewportWidth() {
    //    return false;
       *  Gets the scrollableUnitIncrement attribute of the FilterComp object
       *@param  r            Description of the Parameter
       *@param  orientation  Description of the Parameter
       *@param  direction    Description of the Parameter
       *@return              The scrollableUnitIncrement value
    //  public int getScrollableUnitIncrement(Rectangle r, int orientation, int direction) {
    //    return 10;
    }

    The Scrollable interface should be implemented by a JPanel set as the JScrollPane's viewport or scrolling may not function. Although it is said to be only necessary for tables, lists, and trees, without it I have never had success with images. Even the Java Swing Tutorial on scrolling images with JScrollPane uses the Scrollable interface.
    I donot know what you are doing wrong here, but I use JScrollPane with a JPanel implementing Scrollable interface and it works very well scrolling images drawn into the JPanel.
    You can scroll using other components, such as the JScrollBar or even by using a MouseListener/MouseMotionListener combination, but this is all done behind the scenes with the use of JScrollPane/Scrollable combination.
    You could try this approach using an ImageIcon within a JLabel:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Test extends JFrame {
         BufferedImage bi;
         Graphics2D g_bi;
         public Test() {
              super("Scroll Test");
              makeImage();
              Container contentPane = getContentPane();
              MyView view = new MyView(new ImageIcon(bi));
              JScrollPane sp = new JScrollPane(view);
              contentPane.add(sp);
              setSize(200, 200);
              setVisible(true);
         private void makeImage() {
              bi = new BufferedImage(320, 240, BufferedImage.TYPE_INT_ARGB);
              g_bi = bi.createGraphics();
              g_bi.setColor(Color.white);
              g_bi.fillRect(0,0,320,240);
              g_bi.setColor(Color.black);
              g_bi.drawLine(0,0,320,240);
         public static void main(String args[]) {
              Test test = new Test();
    class MyView extends JLabel {
         ImageIcon icon;
         public MyView(ImageIcon ii) {
              super(ii);
              icon = ii;
         public void paintComponent(Graphics g) {
              g.drawImage(icon.getImage(),0,0,this);
    }Robert Templeton

  • ScrollPane not validating correctly when scaling a JPanel

    I am drawing on a JPanel which I would like to be able to zoom on, im using the 2D graphics for zooming. When I scale the scaling seems to work correctly, but when the JPanel gets bigger then the size it had when I added it to the ScrollPane, the graphics starts to "leave" the viewing area. I would like to know what I can do about this. I am currently using the revalidate method before my paint, and I can se that ssize of the JPanel is changing, but not totally to what i set the PreferedSize to, why not is beyond my understanding.
    Im making the JPanel, which is a class extending JPanel , then the ScrollPane, adding the scrollPane to my frame and im not using layoutmanagers AFAIK anyway.
    Code to edit the JPanel and create scrollPane in the frame class
            //Editing the scrollable JPanel
            workSpace.setPreferredSize(new Dimension(800, 800));
            workSpace.setOriginalHeight(800);
            workSpace.setOriginalWidth(800);
            workSpace.setLayout(null);
            //Creating and adding the scrollPane
            scrollPane = new JScrollPane(workSpace);
            scrollPane.setBounds(new Rectangle(285, 155, 685, 455));
            contentPane.add(scrollPane, null);
    The paint method
        public void paintComponent(Graphics _g) {
            super.paintComponent(_g);
            //do rendering as offscreen, to avoid "flicker".
            Image offscreen = createImage(this.getWidth(), this.getHeight()); //make an image
            Graphics2D g2d = (Graphics2D) offscreen.getGraphics(); //get the graphics object from the image
            g2d.scale(scale, scale);
            //clear contents
            g2d.setPaint(DS_Data.getBGColor());
            g2d.fillRect(0, 0, this.getWidth(), this.getHeight());
            String[] dxfList = EntityListHandler.getListNames(); //get a list of names
            if (dxfList.length > 0) {
                //System.out.println("<WorkSpace.paint> Drawing - restraints x: " + this.getWidth() + "  y: " + this.getHeight());
                Block drawBlock; //block object
                for (int i = 0; i < dxfList.length; i++) {
                    drawBlock = EntityListHandler.getTopLevelBlock(dxfList);
    if (drawBlock != null) {
    drawBlock.doDraw(g2d, this.getWidth(), this.getHeight(), 0,
    0, 0, -3, false); //brug ALTID -3 til at kalde doDraw p� blokke, det fort�ller det er f�rste block
    g2d.drawLine(this.getWidth(), 0, this.getWidth(), this.getHeight());
    g2d.drawLine(0, this.getHeight(), this.getWidth(), this.getHeight());
    g2d.dispose(); //dispose of the graphics2d context when were done with it.
    _g.drawImage(offscreen, 0, 0, this);
    } else {
    System.out.println("<WorkSpace.paint> Listen er ikke klar .");
    g2d.drawString("No content loaded.", 200, 200);
    The zoom method controlled by the mouse wheel
        //Zoom method reacting on a mousewheel event
        public void this_mouseWheelMoved(MouseWheelEvent e) {
            if (e.getWheelRotation() == 1) {
                scale -= ZOOM_FACTOR;
            } else if (e.getWheelRotation() == -1) {
                scale += ZOOM_FACTOR;
            height = (int) (orig_height * scale);
            width = (int) (orig_width * scale);
            setPreferredSize(new Dimension(width, height));
            revalidate();
            repaint();
    Some set methods just to show that I have them.
        public void setOriginalHeight(int _orig_height) {
            orig_height = _orig_height;
        public void setOriginalWidth(int _orig_width) {
            orig_width = _orig_width;
        }TIA hope somebody is able to clarify some things for me.
    Kenneth

    Swing gives you doble buffering for free. Try this
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class ZoomScale extends JPanel implements MouseWheelListener {
        Block[] blocks;
        int origWidth, origHeight;
        double scale;
        final double ZOOM_FACTOR = 0.1;
        public ZoomScale() {
            scale = 1.0;
            addMouseWheelListener(this);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            if(blocks == null)
                initGraphics();
            int w = getWidth(), h = getHeight();
            g2.scale(scale, scale);
            for(int j = 0; j < blocks.length; j++)
                blocks[j].draw(g2);
            g2.setPaint(Color.red);
            g2.drawLine(w, 0, w, h);
            g2.setPaint(Color.blue);
            g2.drawLine(0, h, w, h);
        public void mouseWheelMoved(MouseWheelEvent e) {
            if (e.getWheelRotation() == 1) {
                scale -= ZOOM_FACTOR;
            } else if (e.getWheelRotation() == -1) {
                scale += ZOOM_FACTOR;
            System.out.println("scale = " + scale);
            revalidate();
            repaint();
        public Dimension getPreferredSize() {
            return new Dimension((int)(scale * origWidth), (int)(scale * origHeight));
        private void initGraphics() {
            origWidth  = getWidth();
            origHeight = getHeight();
            double w = origWidth;
            double h = origHeight;
            double r = Math.min(w,h)/4;
            blocks = new Block[4];
            blocks[0] = new Block(new Line2D.Double(w/16, h/16, w*15/16, h*15/16),
                                  Color.green.darker());
            blocks[1] = new Block(new Line2D.Double(w*15/16, h/16, w/16, h*15/16),
                                  Color.orange);
            blocks[2] = new Block(new Rectangle2D.Double(w/16, h/16, w*7/8, h*7/8),
                                  Color.blue);
            blocks[3] = new Block(new Ellipse2D.Double(w/2-r, h/2-r, 2*r, 2*r),
                                  Color.red);
        public static void main(String[] args) {
            ZoomScale zs = new ZoomScale();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(zs));
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    class Block {
        Shape s;
        Color color;
        Block(Shape s, Color color) {
            this.s = s;
            this.color = color;
        public void draw(Graphics2D g2) {
            g2.setPaint(color);
            g2.draw(s);
    }

  • How to make a JPanel selectable

    When extending a JPanel and overriding the paintComponent() method the custom JPanel can not be selected so that it gets for example KeyEvents.
    But if I make the new Class extend a JButton it gets of course selected and able to receive for example KeyEvents.
    My question is therefore; what does the JButton implement that a JPanel doesn&#8217;t so that a JButton gets selectable? Or in other words; how to make a JPanel selectable?
    Aleksander.

    Try this extended code. Only the first panel added can get the Focus.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Test extends JFrame
      public Test()
        setLocation(400,300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel panel1 = new JPanel(new BorderLayout());
        JPanel panel2 = new JPanel(new BorderLayout());
        ImagePanel imgPanel = new ImagePanel();
        panel1.setFocusable(true);
        panel2.setFocusable(true);
        panel1.setPreferredSize(new Dimension(0, 50));
        panel2.setPreferredSize(new Dimension(0, 50));
        panel1.setBorder(BorderFactory.createLineBorder(Color.RED,     4));
        panel2.setBorder(BorderFactory.createLineBorder(Color.CYAN,    4));
        imgPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 4));
        panel1.add(new JLabel("Panel 1"), BorderLayout.CENTER);
        panel2.add(new JLabel("Panel 2"), BorderLayout.CENTER);
        getContentPane().add(panel1, BorderLayout.NORTH);
        getContentPane().add(panel2, BorderLayout.SOUTH);
        getContentPane().add(imgPanel, BorderLayout.CENTER);   
        pack();
        panel1.addKeyListener(new KeyAdapter(){
            public void keyPressed(KeyEvent ke){
                System.out.println("Panel1");}});
        panel2.addKeyListener(new KeyAdapter(){
            public void keyPressed(KeyEvent ke){
                System.out.println("Panel2");}});
      public static void main(String[] args){new Test().setVisible(true);}
    class ImagePanel extends JPanel
      Image img;
      public ImagePanel()
        setFocusable(true);
        setPreferredSize(new Dimension(400,300));
        try{img = javax.imageio.ImageIO.read(new java.net.URL(getClass().getResource("Test.gif"), "Test.gif"));}
        catch(Exception e){/*handled in paintComponent()*/}
        addKeyListener(new KeyAdapter(){
          public void keyPressed(KeyEvent ke){
            System.out.println("ImagePanel");}});
      public void paintComponent(Graphics g)
        if(img != null)
          g.drawImage(img, 0,0,this.getWidth(),this.getHeight(),this);
        else
          g.drawString("This space for rent",50,50);
    }

  • Scrollable Cursor in Stored Procedure

    I am trying to implement a scrollable cursor that exists in a stored procedure. Here is my situation:
    o Oracle 9i (9.2.0.1.0) for both client and server.
    o OCI Interface in purely C++ environment
    o I am able to compile/link program with 9i client library, and successfully fetch data from a stored proc that contains a nonscrollable/forward only/traditional cursor without any problems.
    I have a stored proc that looks like this:
    procedure test(
    testcursor out cv_types.cv_fit_data
    ) as
    begin
    open testcursor
    for select data_id,
    text
    from data;
    end test;
    This is where I run into problems:
    First I allocate an OCIStmt handle and bind it to the proc. Then using the stmt handle that points to the proc, I bind a secondary handle that points to the cursor (testcursor above) by calling OCIBindByPos with type=SQLT_REF (See OCI ref manual on binding ref cursor). Next, I execute the proc via OCIStmtExecute with the mode=OCI_STMT_SCROLLABLE_READONLY using the statement handle that points to the procedure. Then I use that secondary stmt handle to fetch the rows via OCIStmtFetch2(). I am able to fetch the rows if I stick to OCI_FETCH_NEXT, but when I attempt to use any scrollable features such as OCI_FETCH_ABSOLUTE, it bails with an ORA-24391 error. Upon further investigation, I found out that this error occurs when the stmt is not executed with mode=OCI_STMT_SCROLLABLE_READONLY. The clincher is that I did execute in that mode... Has anyone been faced with a similar situation? Am I tackling this the wrong way? Any help, even pointers to any docs I missed on the subject, is greatly appreciated.
    Thanks,
    Bryan
    I am using OCI in C++ to fetch the data via OCIStmtFetch2(...) method.

    vaidyanathanraja wrote:
    4. If there is a logical error, the same procedure should not generate data when it is rerun. Behaviour should be the same at all times.Incorrect. Something like NLS settings for example can make the same code, behave differently. E.g. a date string is passed and implicitly converted to a date. And this will work for most dates from different session using different NLS settings (e.g. yyyy/mm/dd versus yyyy/dd/mm). And these sessions will provide different results using the same parameters calling the same application code.
    There are a number of such run-time factors that influences code.
    5. Failed means it didn't generate the expected output. Which means that there is a problem with that SQL being executed the way it is, with the parameters used. You need to isolate the problem further.
    6. Parameter values are right.Have you proved that by using a test case that runs the very same SQL via a test proc, using the same parameter, via a job? Ran that test case interactively via sqlplus?
    You need to pop the hood and isolate the problem.
    7. I came across one blog saying different behaviour for REF CURSOR between oracle 10g and 11g and he says it is oracle bug. I don't know whether it is applicable for this case also.Bahumbug. There are many Oracle bugs. As there is in all software. However, you have not provided any evidence of a bug.
    Application code is behaving inconsistently. That is the symptom. Oracle system code is not relevant until you can prove that the inconsistency is not in the application code, but lower down the call stack.

  • Adding and displaying a new JPanel -- not working as expected

    I'm starting my own new thread that is based on a problem discussed in another person's thread that can be found here in the New to Java forum titled "ActionListener:
    http://forum.java.sun.com/thread.jspa?threadID=5207301
    What I want to do: press a button which adds a new panel into another panel (the parentPane), and display the changes. The Actionlistener-derived class (AddPaneAction) for the button is in it's own file (it's not an internal class), and I pass a reference to the parentPane in the AddPaneAction's constructor as a parameter argument.
    What works: After the button is clicked the AddPaneAction's actionPerformed method is called without problem.
    What doesn't work: The new JPanel (called bluePanel) is not displayed as I thought it would be after I call
            parentPane.revalidate();  // this doesn't work
            parentPane.repaint(); 
    What also doesn't work: So I obtained a reference to the main app's JFrame (I called it myFrame) by recursively calling component.getParent( ), no problem there, and then tried (and failed to show the bluePanel with) this:
            myFrame.invalidate();  // I tried this with and without calling this method here
            myFrame.validate();  // I tried this with and without calling this method here
            myFrame.repaint();
    What finally works but confuses me: I got it to work but only after calling this:
            myFrame.pack(); 
            myFrame.repaint();But I didn't think that I needed to call pack to display the panel. So, what am I doing wrong? Why are my expectations not correct? Here's my complete code/SSCCE below. Many thanks in advance.
    Pete
    The ParentPane class:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class ParentPane extends JPanel
        private JButton addPaneBtn = new JButton("Add new Pane");
        public ParentPane()
            super();
            setLayout(new BorderLayout());
            setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
            setBackground(Color.yellow);
            JPanel northPane = new JPanel();
            northPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
            northPane.setBackground(Color.yellow);
            northPane.add(addPaneBtn);
            add(northPane, BorderLayout.NORTH);
            // add our actionlistener object and pass it a reference
            // to the main class which happens to be a JPanel (this)
            addPaneBtn.addActionListener(new AddPaneAction(this));
        public static void main(String[] args)
            javax.swing.SwingUtilities.invokeLater(new Runnable()
                public void run()
                    createAndShowGUI();
        private static void createAndShowGUI()
            JFrame frame = new JFrame("test add panel");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(new ParentPane());
            frame.pack();
            frame.setVisible(true);
    } the AddPaneAction class:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingConstants;
    public class AddPaneAction implements ActionListener
        private JPanel parentPane;
        private JFrame myFrame;
        public AddPaneAction(JPanel parentPane)
            this.parentPane = parentPane;
         * recursively get the JFrame that holds the parentPane panel.
        private JFrame getJFrame(Component comp)
            Component parentComponent = comp.getParent();
            if (parentComponent instanceof JFrame)
                return (JFrame)parentComponent;
            else
                return getJFrame(parentComponent);
        public void actionPerformed(ActionEvent arg0)
            JPanel bluePanel = new JPanel(new BorderLayout());
            bluePanel.setBackground(Color.blue);
            bluePanel.setPreferredSize(new Dimension(400, 300));
            JLabel myLabel = new JLabel("blue panel label");
            myLabel.setForeground(Color.LIGHT_GRAY);
            myLabel.setVerticalAlignment(SwingConstants.CENTER);
            myLabel.setHorizontalAlignment(SwingConstants.CENTER);
            bluePanel.add(myLabel, BorderLayout.CENTER);
            parentPane.add(bluePanel);
            myFrame = getJFrame(parentPane);
            //parentPane.revalidate();  // this doesn't work
            //parentPane.repaint(); 
            //myFrame.invalidate(); // and also this doesn't work
            //myFrame.validate();
            //myFrame.repaint();
            myFrame.pack();  // but this does!?
            myFrame.repaint();
    }

    For me (as it happens I'm using JDK 1.5.0_04) your code appears to work fine.
    It may be that we're seeing the same thing but interpreting it differently.
    1. When I run your application with your "working" code, and press the button then the JFrame resizes and the blue area appears.
    2. When I run your application with your "not working" code and press the button then the JFrame does not resize. If I manually resize it then the blue area is there.
    3. When I run your application with your "not working" code, resize it first and then press the button then the JFrame then the blue area is there.
    I interpret all of this as correct behaviour.
    Is this what you are seeing too?
    Are you expecting revalidate, repaint, invalidate or validate to resize your JFrame? I do not.
    As an aside, I do remember having problems with this kind of thing in earlier JVMs (e.g. various 1.2 and 1.3), but I haven't used it enough recently to know if your code would manifest one of the previous problems or not. Also I don't know if they've fixed any stuff in this area.

  • Use extends and implements or not?

    What is considered a better way of implementing classes? with the use of extends and/or implements or not?
    ex:
    public class TabPanel extends JPanel implements ActionListeneror have it return the needed Type
    ex:
    public class TabPanel implements ActionListener
    public JPanel TabPanel()
    JPanel jp = new JPanel();
    jp.add(new JLabel("Test"));
    return jp;
    }

    To extend or not to extend, that is a question. Defenitely, you must subclass when you need to override some method. You want to subclass to reuse the customized class. You want to implement an interface when you need a class implementing it.
    Regarding your example:
    public class TabPanel implements ActionListener {
         public JPanel TabPanel() {
              JPanel jp = new JPanel();
              jp.add(new JLabel("Test"));
              return jp;
    }Are you sure it will work? IMO, you do not have to specify result type and must not return anything in the constructors. Why to bother with TabPanel class? If you like to hide the scope, use {} braces in the code.
    JPanel panel = new JPanel();
    jp.add(new JLabel("Test"));
    public class NonAnanymousListener implements ActionListener {

  • Drawing in JPanel within JApplet

    Hi, having problems drawing in jpanel that is within japplet.
    My code follows:
    * TestApplet.java
    * @author WhooHoo
    //<applet code="TestApplet.class" width="400" height="250"></applet>
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.Graphics;
    import javax.swing.JButton;
    public class TestApplet extends javax.swing.JApplet implements ActionListener {
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel1;
    private Graphics g;
    private javax.swing.JButton btnTest;
    /** Creates new form Cafe */
    public TestApplet() {
    public void init() {
    jPanel1 = new javax.swing.JPanel();
    btnTest = new javax.swing.JButton();
    jPanel2 = new javax.swing.JPanel();
    btnTest.setText("test");
    jPanel1.add(btnTest);
    getContentPane().add(jPanel1, java.awt.BorderLayout.NORTH);
    jPanel2.setBorder(new javax.swing.border.TitledBorder("Draw"));
    getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);
    btnTest.addActionListener(this);
    jPanel2.setOpaque(false);
    g=jPanel2.getGraphics();
    /** Invoked when an action occurs.
    public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equalsIgnoreCase("test"))
    System.out.println("test");
    g.setColor(java.awt.Color.BLACK);
         g.drawString("testing",50,50);
         g.drawString("testing",50,100);
         g.drawString("testing",50,150);
         g.drawString("testing",50,200);
         g.drawString("testing",50,250);
    public void destroy()
    g.dispose();
    When this code is run the applet seems to run fine but when the button is pressed, nothing is drawn in jpanel. Can anyone see what the problem is and suggest a fix. I need to be able to pass graphics obj around to other methods to draw in the other methods also. Testing will not dispaly anywhere in applet or frame.
    plz email or post any suggestions.

    but if I can get this to workYou can get this to work, here is the working code:
    import java.awt.event.*;
    import java.awt.Graphics;
    import javax.swing.*;
    import java.awt.*;
    public class TestApplet extends JApplet implements ActionListener {
         private JPanel jPanel2,jPanel1;
         private javax.swing.JButton btnTest;
         String string1 = "";
         public TestApplet() {
         public void init() {
              jPanel1 = new JPanel();
              btnTest = new JButton();
              jPanel2 = new JPanel(){
                   public void paintComponent(Graphics g) {
                        g.setColor(java.awt.Color.BLACK);
                        g.drawString(string1,50,50);
                        g.drawString(string1,50,100);
                        g.drawString(string1,50,150);
                        g.drawString(string1,50,200);
                        g.drawString(string1,50,250);
              btnTest.setText("test");
              jPanel1.add(btnTest);     
              getContentPane().add(jPanel1, BorderLayout.NORTH);
              jPanel2.setBorder(new javax.swing.border.TitledBorder("Draw"));
              getContentPane().add(jPanel2, BorderLayout.CENTER);
              btnTest.addActionListener(this);
              jPanel2.setOpaque(false);
         public void actionPerformed(ActionEvent e) {
              if (e.getActionCommand().equalsIgnoreCase("test"))
                   System.out.println("test");
                   string1 = "testing";
                   jPanel2.repaint();
         public void destroy(){}
    }Unfortunately all painting to a component must happen inside the paint method. I don't know if what you ask is possible. I try to figure it out. Maybe someone else has an answer.
    Pandava

  • Send Scrollable Frame to Back

    I'm trying to implement a scrollable frame in a layout, so that it appears to be pulled out from behind a stationary graphic. It always shows up on my iPad in front of the graphic. I've tried to put it on its own layer which is at the bottom, but it still goes to the top. Is what I am trying to do possible?

    They're called overlays for a reason. You cannot have static content on top.
    Convert the image to an MSO, set to auto play once and that should do
    the trick.
    Bob

  • Implementing 3D Object

    Implementing 3D Object
    Hi, I am taking an introductory Java course at school, and I need some help with implementing one class to another.
    I am trying to put Kuma.java (3D object) into KumaPanel.java (above the buttonPanel), but I have no clue how. Would it be easier if I just write one class instead of trying to link these two together?
    Here are my codes:
    Kuma.java:
    import java.awt.Frame;
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import com.sun.j3d.utils.applet.MainFrame;
    import com.sun.j3d.utils.behaviors.vp.OrbitBehavior;
    import com.sun.j3d.utils.geometry.*;
    import com.sun.j3d.utils.universe.*;
    import javax.media.j3d.*;
    import javax.vecmath.*;
    import com.sun.j3d.loaders.objectfile.ObjectFile;
    import com.sun.j3d.loaders.*;
    public class Kuma extends Applet
        static boolean application = false;
           public static void main(String[] args)
                application = true;
             Frame frame = new MainFrame(new Kuma(), 640, 480);
         public void init()
              setLayout(new BorderLayout());
              Canvas3D c = new Canvas3D(SimpleUniverse.getPreferredConfiguration());
             add("Center", c);
             SimpleUniverse universe= new SimpleUniverse(c); // setup the SimpleUniverse, attach the Canvas3D
             BranchGroup scene = createSceneGraph();
             universe.getViewingPlatform().setNominalViewingTransform();
            scene.compile();
            universe.addBranchGraph(scene); //add your SceneGraph to the SimpleUniverse
              //Rotate the cube
              OrbitBehavior cameraRotate = new OrbitBehavior(c);
              cameraRotate.setSchedulingBounds(new BoundingSphere());
              universe.getViewingPlatform().setViewPlatformBehavior(cameraRotate);
        public BranchGroup createSceneGraph()
             BranchGroup root = new BranchGroup();
             TransformGroup tg = new TransformGroup();
            Transform3D t3d = new Transform3D();
                try
                    Scene s = null;
                    ObjectFile f = new ObjectFile ();
                  f.setFlags (ObjectFile.RESIZE | ObjectFile.TRIANGULATE | ObjectFile.STRIPIFY);
                   if (application == false)
                        java.net.URL neuron = new java.net.URL (getCodeBase(), "walk.obj");
                        s = f.load (neuron);
                        tg.addChild (s.getSceneGroup ());
                   else
                        String s1 = "walk.obj";
                        s = f.load (s1);
                        tg.addChild (s.getSceneGroup ());
               catch (java.net.MalformedURLException ex){
               catch (java.io.FileNotFoundException ex){
               // create an ambient light
               BoundingSphere bounds = new BoundingSphere (new Point3d (0.0, 0.0, 0.0), 100.0);
               Color3f ambientColor = new Color3f (1.0f, 1.0f, 1.0f);
               AmbientLight ambientLightNode = new AmbientLight (ambientColor);
               ambientLightNode.setInfluencingBounds (bounds);
               root.addChild (ambientLightNode);
               root.addChild(tg);
              t3d.setTranslation(new Vector3f(100.0f, 0.0f, -100.0f));
               return root;
    KumaPanel.java:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.FlowLayout;
    import java.awt.Font;
    import java.awt.image.BufferedImage;
    import javax.imageio.ImageIO;
    import java.io.File;
    import java.io.IOException;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class KumaPanel extends JFrame implements ActionListener, KeyListener{
         JPanel buttonPanel = new JPanel();
         public static int WIDTH = 800;
         public static int HEIGHT = 600;
         KumaPanel()
              ///Create a Content Window
              setSize(WIDTH, HEIGHT); //setting the size of the window
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//for closing the window
              setTitle("Nazo Nazo"); //title of the window
              Container contentPane = getContentPane();
              contentPane.setBackground(Color.blue); //background color of the panel
              ///Create a White Button Panel
              contentPane.setLayout(new BorderLayout());
              buttonPanel.setLayout(new FlowLayout()); //set layout type to FlowLayout
              buttonPanel.setBackground(Color.black); //background to white
              contentPane.add(buttonPanel,BorderLayout.SOUTH); //add buttonPanel on contentPanel
              ///Create First Button with Kuma Ranger on it
              ImageIcon smiley1 = new ImageIcon("kuma.jpg");
              JButton firstButton = new JButton("kuma");
              firstButton.setIcon(smiley1);
              firstButton.setBackground(Color.white);
              buttonPanel.add(firstButton);          //add button to buttonPanel
              firstButton.addActionListener(this);
              ///Create First Button with Mrs.Smile on it
              ImageIcon smiley2 = new ImageIcon("inu.jpg");
              JButton secondButton = new JButton("inu");
              secondButton.setIcon(smiley2);
              secondButton.setBackground(Color.white);
              buttonPanel.add(secondButton);          //add button to buttonPanel
              secondButton.addActionListener(this);
              ///Create First Button with Mrs.Smile on it
              ImageIcon smiley3 = new ImageIcon("usa.jpg");
              JButton thirdButton = new JButton("usa");
              thirdButton.setIcon(smiley3);
              thirdButton.setBackground(Color.white);
              buttonPanel.add(thirdButton);          //add button to buttonPanel
              thirdButton.addActionListener(this);
         public static void main(String[] args)
              KumaPanel iDemo = new KumaPanel();
              iDemo.setVisible(true);
         public void actionPerformed(ActionEvent e) {
              Container contentPane = getContentPane(); //getting the contentPane of the window
              if (e.getActionCommand().equals("inu")) {
                   contentPane.setBackground(Color.green);
                   System.out.println("I have pressed the GREEN smiley...");
              else if (e.getActionCommand().equals("kuma")) {
                   contentPane.setBackground(Color.red);
                   System.out.println("I have pressed the RED smiley...");
              else if (e.getActionCommand().equals("usa")) {
                   contentPane.setBackground(Color.yellow);
                   System.out.println("I have pressed the YELLOW smiley...");
              else
                   System.out.println("There is an error.");
         @Override
         public void keyPressed(KeyEvent e) {
              // TODO Auto-generated method stub
         @Override
         public void keyReleased(KeyEvent e) {
              // TODO Auto-generated method stub
         @Override
         public void keyTyped(KeyEvent e) {
              // TODO Auto-generated method stub
    }Thank you!

    cider wrote:
    I am trying to put Kuma.java (3D object) Not exactly. It's an Applet, and this distinction is important.
    into KumaPanel.java (above the buttonPanel), and this is a JFrame, another important distinction.
    but I have no clue how. Would it be easier if I just write one class instead of trying to link these two together?In general, no. You want to keep things that are logically distinct in their own classes and files. BUT, combining what you have posted here unfortunately is like combining oil and water. Since Kuma is an Applet, it uses AWT GUI components which don't mesh well with KumaPanel's Swing components. Also, an Applet is Root container as is a JFrame. Both of them are sort of like final destinations for components and don't readily "go in" to something else. You need to combine something that is compatible with the other and easily goes into something else. For instance if Kuma where a JPanel, it would be be easy to put it into a JFrame somewhere.
    I suggest that you go through the Java Swing tutorials to get a better appreciation of java GUI programming before trying to tackle something like what you are trying to do here.

  • How a JPanel is updated?

    Hello,
    I have the following problem: When I add controls to a JPanel at runtime, they don't show up at once. I need to resize the frame manually using my mouse. I suspect that I have to call some kind of repaint on the content pane, but that doesn't work. Any idea? Here is the code:
    public class GUITest extends JFrame implements ActionListener
    private JPanel panel;
    public GUITest()
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    panel = new JPanel();
    panel.add(new JLabel("One"));
    panel.add(new JLabel("Two"));
    JButton b = new JButton("And...");
    b.addActionListener(this);
    panel.add(b);
    Container cont = getContentPane();
    cont.add(panel);
    pack();
    setVisible(true);
    public void actionPerformed(ActionEvent e)
    panel.add(new JLabel("Three"));
    // Simulate event, cause panel is usually in another class with no pointer to the parent
    NotifyListeners();
    public void NotifyListeners()
    // TODO: What to do here to make the button click result in a repaint too?
    Container cont = getContentPane();
    cont.repaint();
    public static void main(String[] args)
    GUITest t = new GUITest();
    }

    Ok, found it myself :) Sorry for posting. It was of course cp.validate(), where validate is kindof repaint if you change the content of a container.

  • Scrollable

    Why does JTable implement the scrollable interface, if when I set the preferredScrollableViewportSize, nobody pays attention???
    I searched through stack traces and class files to try and find some class that actually cared what preferredScrollableViewportSize my JTable set, and there are none. Anyone know why?
    Only way I get respect is to
    JScrollPane.setPreferredSize(jtable.getPreferredScrollableViewportSize());If I have to do this manually, why did they bother to implement the scrollable interface on jtable??

    This is great! I'll work on implementing it tomorrow. Thanks.
    And I'll consider that in the future. Sorry, kind of new to the forums and haven't had time to look around. I was flustered and found the first semi-applicable location and fired my question.

  • Auto-resize the components of JTabbedPane with JPanels

    Hi,
    We have swing window with tabbed pane having two JPanels. There are couple of components (button/text
    fields/JXTable/Jtree ..etc)added to each panel. so far, every thing is working fine.
    Issue is, when we try to expand the winodw size, the components of each panel are static. The size of components
    are not changing accorning to window size. All the components are center alligned with increasing the window size. It would be great help, if you can help on this.
    Following is the sample code used to prepare  swing window.
    public class SOS extends JFrame implements TreeWillExpandListener,
                                               TreeExpansionListener,
        JPanel firstPanel = new JPanel(new GridBagLayout());
        JPanel secondPanel = new JPanel(new GridBagLayout());
        public SOS() throws SQLException, ParserConfigurationException,
                            SAXException, IOException, XPathExpressionException {
            //EHDD Tabbed Pane
            nehObjectTypelist = new JList((createObjectsListData()).toArray());
            nehObjectTypelist.setFont(font);
            nehObjectTypelist.setCellRenderer(new CheckListRenderer());
            nehObjectTypelist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            nehObjectTypelist.setBorder(new EmptyBorder(0, 4, 0, 0));
            nehObjectTypelist.addMouseListener(new MouseAdapter() {
            JScrollPane nehObjTypeSP = new JScrollPane(nehObjectTypelist);
            nehObjTypeSP.setSize(200, 200);
            nehOwmerslist = new JList((createOwnersListData()).toArray());
            nehOwmerslist.setFont(font);
            nehOwmerslist.setCellRenderer(new CheckListRenderer());
            nehOwmerslist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            nehOwmerslist.setBorder(new EmptyBorder(0, 4, 0, 0));
            nehOwmerslist.addMouseListener(new MouseAdapter() {
            JScrollPane sp = new JScrollPane(nehOwmerslist);
            sp.setSize(200, 200);
            //JTree with checkbox
            DefaultMutableTreeNode root = createFirstLevel();
            final DefaultTreeModel model = new DefaultTreeModel(root);
            nehTree = new JTree(root);
            QuestionCellRenderer renderer = new QuestionCellRenderer();
            nehTree.setCellRenderer(renderer);
            QuestionCellEditor editor = new QuestionCellEditor();
            nehTree.setCellEditor(editor);
            nehTree.setEditable(true);
            nehTree.addTreeWillExpandListener(this);
            nehTree.setShowsRootHandles(true);
            nehTree.setModel(model);
            nehTree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
            JScrollPane scroll = new JScrollPane(nehTree);
            scroll.setPreferredSize(new Dimension(200, 180));
            scroll.setFont(font);
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(1, 1, 1, 1);
            gbc.gridx = 0;
            gbc.gridy = 0;
            //gbc.gridwidth = 2;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            //gbc.anchor = GridBagConstraints.LINE_START;
            JLabel nehHeading =
                new JLabel("Select your criteria and click the Fetch Topics by Criteria button");
            nehHeading.setFont(font);
            firstPanel.add(nehHeading, gbc);
            gbc.insets = new Insets(1, 1, 1, 1);
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.gridx = 0;
            gbc.gridy = 1;
            gbc.gridwidth = 1;
            JLabel nehDocType = new JLabel("Type");
            nehDocType.setFont(font);
            firstPanel.add(nehDocType, gbc);
            gbc.gridx = 1;
            gbc.gridy = 1;
            JLabel nehDocOwner = new JLabel("Owner");
            nehDocOwner.setFont(font);
            firstPanel.add(nehDocOwner, gbc);
            gbc.gridx = 2;
            gbc.gridy = 1;
            JLabel nehProdTree = new JLabel("Tree");
            nehProdTree.setFont(font);
            firstPanel.add(nehProdTree, gbc);
            gbc.weightx = 0;
            gbc.weighty = 0;
            gbc.gridx = 0;
            gbc.gridy = 2;
            firstPanel.add(nehObjTypeSP, gbc);
            gbc.gridx = 1;
            gbc.gridy = 2;
            firstPanel.add(sp, gbc);
            gbc.gridx = 2;
            gbc.gridy = 2;
            firstPanel.add(scroll, gbc);
            gbc.fill = GridBagConstraints.VERTICAL;
            gbc.anchor = GridBagConstraints.FIRST_LINE_START;
            gbc.weightx = 0;
            gbc.weighty = 0;
            gbc.gridheight = 1;
            gbc.gridheight = 1;
            gbc.gridx = 0;
            gbc.gridy = 21;
            JButton fetchButton = new JButton("Fetch");
            fetchButton.setFont(font);
            fetchButton.setSize(new Dimension(175, 35));
            firstPanel.add(fetchButton, gbc);
            fetchButton.addActionListener(new ActionListener() {
            gbc.gridx = 0;
            gbc.gridy = 22;
            JLabel nehOR = new JLabel("- OR -");
            nehOR.setFont(font);
            firstPanel.add(nehOR, gbc);
            JButton searchButton = new JButton("Fetch by Title");
            searchButton.setToolTipText("Enter title search criteria");
            searchButton.setFont(font);
            gbc.gridheight = 1;
            gbc.gridx = 0;
            gbc.gridy = 23;
            gbc.anchor = GridBagConstraints.LINE_START;
            JLabel nehOpenBySVNIdLabel = new JLabel("Open by ID");
            nehOpenBySVNIdLabel.setFont(font);
            firstPanel.add(nehOpenBySVNIdLabel, gbc);
            gbc.gridheight = 1;
            gbc.gridx = 1;
            gbc.gridy = 23;
            gbc.anchor = GridBagConstraints.WEST;
            findTextField.setColumns(20);
            firstPanel.add(findTextField, gbc);
            gbc.gridheight = 1;
            gbc.gridx = 2;
            gbc.gridy = 23;
            gbc.anchor = GridBagConstraints.WEST;
            JButton openButton = new JButton("Open");
            openButton.setFont(font);
            openButton.setPreferredSize(searchButton.getPreferredSize());
            System.out.println("Button Size" + openButton.getSize());
            firstPanel.add(openButton, gbc);
            openButton.addActionListener(new ActionListener() {
            gbc.gridheight = 1;
            gbc.gridx = 0;
            gbc.gridy = 24;
            gbc.anchor = GridBagConstraints.LINE_START;
            JLabel searchLabel =
                new JLabel("Search the repository by title word(s)");
            searchLabel.setToolTipText("Enter title search criteria");
            searchLabel.setFont(font);
            firstPanel.add(searchLabel, gbc);
            gbc.gridheight = 1;
            gbc.gridx = 1;
            gbc.gridy = 24;
            gbc.anchor = GridBagConstraints.WEST;
            searchTextField = new JTextField("", 20);
            searchTextField.setColumns(20);
            searchTextField.setEditable(true);
            firstPanel.add(searchTextField, gbc);
            gbc.gridheight = 1;
            gbc.gridx = 2;
            gbc.gridy = 24;
            gbc.anchor = GridBagConstraints.WEST;
            firstPanel.add(searchButton, gbc);
            searchButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
            gbc.anchor = GridBagConstraints.FIRST_LINE_START;
            gbc.gridwidth = 4;
            gbc.gridx = 0;
            gbc.gridy = 28;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            tableScrollPane.setPreferredSize(new Dimension(200, 200));
            firstPanel.add(tableScrollPane, gbc);
            gbc.fill = GridBagConstraints.NONE;
            gbc.gridheight = 1;
            JRadioButton reviewButton = new JRadioButton("Review");
            reviewButton.setFont(font);
            reviewButton.setMnemonic(KeyEvent.VK_B);
            reviewButton.setSelected(true);
            JRadioButton testButton = new JRadioButton("Test");
            testButton.setFont(font);
            testButton.setMnemonic(KeyEvent.VK_B);
            JRadioButton prodButton = new JRadioButton("Production");
            prodButton.setFont(font);
            prodButton.setMnemonic(KeyEvent.VK_B);
            nehGroup.add(reviewButton);
            nehGroup.add(testButton);
            nehGroup.add(prodButton);
            gbc.gridx = 2;
            gbc.gridy = 30;
            firstPanel.add(reviewButton, gbc);
            gbc.gridx = 2;
            gbc.gridy = 31;
            firstPanel.add(testButton, gbc);
            gbc.gridx = 2;
            gbc.gridy = 32;
            firstPanel.add(prodButton, gbc);
            gbc.gridx = 2;
            gbc.gridy = 33;
            JButton printButton = new JButton("Print");
            printButton.setFont(font);
            firstPanel.add(printButton, gbc);
            printButton.addActionListener(new ActionListener() {
            gbc.fill = GridBagConstraints.NORTHEAST;
            gbc.gridx = 0;
            gbc.gridy = 30;
            JButton openTopicsButton = new JButton("Open Selection");
            openTopicsButton.setFont(font);
            firstPanel.add(openTopicsButton, gbc);
            openTopicsButton.addActionListener(new ActionListener() {
            gbc.gridx = 0;
            gbc.gridy = 32;
            JButton mapLinks = new JButton("Insert");
            mapLinks.setFont(font);
            JButton relatedLinks = new JButton("Insert Links");
            relatedLinks.setFont(font);
            relatedLinks.setPreferredSize(mapLinks.getPreferredSize());
            firstPanel.add(relatedLinks, gbc);
            relatedLinks.addActionListener(new ActionListener() {
            gbc.gridx = 0;
            gbc.gridy = 33;
            firstPanel.add(mapLinks, gbc);
            mapLinks.addActionListener(new ActionListener() {
            tabbedPane.add("NEH", firstPanel);
            //NEH Tabbed Pane
            tabbedPane.add("EHDD", secondPanel);
            add(tabbedPane);
            tabbedPane.addChangeListener(new ChangeListener() {
        public static void main(String[] args) throws SQLException,
                                                      ParserConfigurationException,
                                                      SAXException, IOException,
                                                      XPathExpressionException {
            SOS sos = new SOS();
            sos.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            sos.setTitle("SOS");
            sos.setSize(760, 680);
            sos.setVisible(true);
            sos.toFront();
            sos.setMinimumSize(new Dimension(760, 680));
    Thanks,
    MSR.

    I never use GridBagLayout.
    I suggest that you change to combinations of BorderLayout, GridLayout (without "Bag"!) and GroupLayout.
    bye
    TPD

Maybe you are looking for

  • SAME NUMBER RANGES FOR DOMESTIC AND EXPORT INVOICE

    Dear All, We have maintained Two objects separately for Exports and Domastic sales invoices which is inturn giving two different number ranges. But our client needs same number to be continued for both. For eg: 000001 .  000002 and 000003 is the numb

  • Discount Code for Single Product

    Is it possible to create a discount code for just a single product? I know I can do it for a single catalog - but hoping I can do it on single products, too.

  • Mouse acts twice when I click once

    I bought a G4 Quicksilver on Ebay when I retired my old identical G4, which I had used primarily on OS9.2. The "new" one works fine overall on OSX 10.4.11, but the mouse is crazy. I have to highlight a line 4-5 times because it keeps disappearing whe

  • How to deactivate another computer

    i cant find out how to deactivate a coumputer from my coumputer i have no idea what coumputer it is help me please

  • No logging event link-status on SG300

    How can I do it (no logging event link-status) on Cisco Small Business 300 Series Managed Switches (SG300)?