Extending JPanel bug?

Hi,
I have built a custom panel by extending JPanel. I have then set the layout of my custom panel to BorderLayout, and added 2 more panels: one in the center, one in the west. The one on the west has a button on it, the one in the center is empty, so that sub classes can add their own widgets to it. Whenever I create a new instance of either this panel or one of the sub classes I have created, and add it to another JPanel (with layout set to null), it only displays the custom panel and the background and border of it: it does not display the other panels that I have added to it. However when you resize the frame which holds the GUI (by clicking and dragging it at the edges), it displays the custom panel correctly.
I am calling repaint method after adding the custom panel to the other one (the one with layout set to null). Is this display a bug in Java? If so, is their a way round it? Or is my code wrong?
Thanks in advance for any advice.
silverwatch.

Yes layouting is often a headache.
In general one adds components and calls pack in the JFrame to layout things. It seems you must call validate (invalidate?) before your repaint. A repaint(ms_delay) might be in order, if you are "in the message loop."

Similar Messages

  • Problem using extended JPanel

    Hi, I'm using JDeveloper 10.1.3.3. I've extended JPanel and named it TestPanel, and then have added few textboxes, one checkbox and one combobox. It was created as runnable panel. When I run that panel, everything worked fine. I used it in custom JFrame instead of dataPanel:
    TestPanel dataPanel = new TestPanel();
    Whatever I did, I couldn't see components on that custom panel. I tried to rebuild, run frame, I couldn't see it.
    Then I've tried to create another panel in original dataPanel (JPanel, BorderLayout), and use TestPanel that way. Didn't work. Does anyone know what might be the problem?

    Colleague helped me.
    Created custom panel is placed in Components View as ADF Swing Regions -> view.TestPanel, so it can be dragged and dropped.
    If creating panel in code, after creating custom JPanel
    TestPanel dataPanel = new TestPanel();
    There must be this line in jbInit() method:
    testPanel1.bindNestedContainer(panelBinding.findNestedPanelBinding("TestPanelPageDef1"));

  • Extended JPanel not rendering correctly

    I am using a split pane. One pane is a JScrollPane with a JTree attached, the second is a JScrollPane with a JPanel attached. The idea is to show different panels in the second pane depending on which node of the tree is selected.
    My problem is that I when I select a node on my tree in the first panel, my second panel shows only a small grey square.
    My extended JPanel class is:
    public class onePanel extends JPanel {
    public void onePanel() {
    JLabel jLabel1 = new JLabel();
    jLabel1.setText("Node One");
    add(jLabel1);
    In my main I am calling:
    JPanel info = new JPanel();
    JScrollPane myScrollPane = new JScrollPane(info);
    onePanel op = new onePanel();
    info.removeAll();
    info.add(op);
    info.revalidate();
    Any help on this matter would be much appreciated. Let me know if you need more information. Thanks.
    Fox

    My boss helped me with this one as well as bharatchhajer . I'll post the answer for future reference:
    I made the change suggested by bharatchhajer to leave out the intermediate info panel and just deal directly with the JScrollPane.
    In the subclass, instead of using the default constructor OnePanel(), I passed the parent. In this case, OnePanel(myScrollPane).
    I added this to the subclass:
    myScrollPane.add(this);
    Also, instead of myScrollPane.add(info); I used:
    OnePanel op = new OnePanel();
    op.OnePanel(myScrollPane);
    myScrollPane.setViewportView(op);
    So the main problem was that my subclass had no idea about what to attach to. The handle or parent had to be passed to it.
    Fox

  • Access to buttons in a extended JPanel!!

    I'm making a GUI and my problem is that I can not access buttons in an extended JPanel from the GUI class.
    I want to have access to these buttons so that when one click on them, they can perform some event to the components in the GUI class.

    I have a a GUI that contains a splitpane. In one of these panels I have a JTable MyJTable that contains a panel MyJPanel with buttons ( edit and remove buttons).
    When I click on one of these buttons, the rightpanel in the splitpane is going to change to a different panel.
    The problem is that the MyJPanel inside the MyJTable has to extend JPanel. The result of this is that I can not change panels in the rightPanel. This is because MyJPanel inside MyJTable does not contain any reference to the rightPanel.
    I have put a the rightpanel in the constructor like this: MyJTable( rightPanel, .., ..) but I think it gets a little bit messy..
    It is a bit hard to explain, but I hope you will understand it.

  • Unwanted space within an extended JPanel

    Hello JDC
    I subclass the Jpanel and I draw an image inside. The problem is that I receive unwanted empty space in the canvas bounds. I tried to set the mini,maxi and preferred size of both the jframe and the canvas but its doesnt help.
    public class ImageCanvas extends JPanel{
      static Image thisImg=null;
      static URL url=null;
      static Toolkit tool=null;
      public static final String DEFAULTADDRESS = "http://127.0.0.1/image/def.gif";
      public static final  boolean PRINTLN=true;
      public  static void p(String out){
        if(PRINTLN)
          System.out.println(out);
      // constructs a
      public ImageCanvas(String filepath){
         setLayout(new BorderLayout());
         try{
          url = new URL(filepath);
        }catch(Exception e){
          System.out.println("problem with creating url :" + e.toString());
        thisImg = Toolkit.getDefaultToolkit().getImage(url);
      public ImageCanvas(){
        try{
          url = new URL(DEFAULTADDRESS);
        }catch(Exception e){
          System.out.println("problem with creating url :" + e.toString());
        thisImg = Toolkit.getDefaultToolkit().getImage(url);
        repaint();
      public void setPic(Image x){
        //System.out.println("ImageCanvas > setPit(Image) invoked");
        thisImg = x;
        repaint();
      public static Image makeImage(String path){
        try{
          url = new URL(path);
        }catch(Exception e){
          System.out.println("problem with creating url :" + e.toString());
        Image img = Toolkit.getDefaultToolkit().getImage(url);
        return img;
      public void paintComponent(Graphics g){
        g.drawImage(thisImg,0,0,this);
    public void update(Graphics g){
        paint(g);
      public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.getContentPane().add(new ImageCanvas());
          frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
              System.exit(0);
        frame.pack();
        frame.setVisible(true);
    }the image dimension 100x100
    Any replies will by imprecated
    Shay Gaghe

    You could try using JLabel instead of subclassing JPanel. Just set the label's icon and don't set any text.
    I also agree that GridBagLayout is the most useful layout. When I was new to Java programming it was the most confusing. In order to do complicated graphical interfaces I use to have to use a lot of nested panels with different layouts. Even then I had problems because I couldn't specify exactly which component should expand etc. Now, two years later and after becoming a Sun certified programmer for the Java 2 platform, I use GridBagLayouts almost always and it give me the most flexibility. It allows me to make some really professional gui programs. I recommend spending some time getting used to using GridBagLayout more.

  • Class extends JPanel ? help

    i have a class that extends JPanel and i have all my buttons , textfields created on it.
    so how do i call the class to display the panel on a frame?
    asuming class is the class that extends JPanel
    class newPanel = new class();
    f.contentPane.add(newPanel);
    is this the right way?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Yeah... that works fine, just call f.show(). Mind your LayoutManager....

  • Can any one change this Applet into a class that extends Jpanel.....

    Hi,
    I need this applet as a class that extends JPanel, I will be very very thankful to you if any one kindly change this Applet code into a class that extends JApplet.
    I will be very thankful to you if some one can reserve few minutes & do this favor early.
    Thanks a lot for any help.
         My Pong Code
    import java.applet.*;
    import java.awt.*;
    import java.io.*;
    import java.awt.event.*;
    public class Class1 extends Applet implements Runnable
    {     private final int APPLET_WIDTH = 900;
         private final int APPLET_HEIGHT = 600;
         private int px = 15;
         private final int py = 560;
         private final int ph = 10;
         private final int pw = 75;
         private int old_px = px;
         private int bx = 450;
         private int by = 15;
         private final int bh = 20;
         private final int bw = 20;
         private int move_x = 2;
         private int move_y = 2;
         private boolean done = false;
         Thread t;
         private final int delay = 25;
         public void init()
         {     setBackground(Color.black);
              setSize(APPLET_WIDTH, APPLET_HEIGHT);
              requestFocus();
              addKeyListener(new DirectionKeyListener());
             (t = new Thread(this)).start();
         public void run()      {
        try      {     while((t == Thread.currentThread()) && (done == false))           {     
                   if ((bx < 15) || (bx > APPLET_WIDTH-30))                     move_x = -move_x;                                if ((by < 15) ||                    ((by > APPLET_HEIGHT-60)&&                     ((px<=bx)&&(bx<=px+pw))))
                        move_y = -move_y;
                   if (by > APPLET_HEIGHT)
                        done = true;
                                   bx = bx + move_x;
                   by = by + move_y;                                                repaint();
                   t.sleep(delay);
         catch(Exception e)      {}
         }//end run
         /*public void move_paddle(int amount)
              old_px = px;
              //if (amount > 0)
                //if (px <= APPLET_WIDTH-15)
                   px = px + amount;
              //else if (amount < 0)
               // if (px >= 15)
                   px = px + amount;
         public void paint(Graphics page)
              //     page.setColor(Color.black);
              //     page.drawRect(old_px, py, pw, ph);
                   page.setColor(Color.blue);
                   page.drawRect(px, py, pw, ph);
                   page.setColor(Color.white);
                   page.drawOval(bx, by, bw, bh);
                   if ((done == true) && (by > APPLET_HEIGHT))
                        page.drawString("LOSER!!!", APPLET_WIDTH/2, APPLET_HEIGHT/2);
                   else if (done == true)
                        page.drawString("Game Over, Man!", APPLET_WIDTH/2-10, APPLET_HEIGHT/2);
         private class DirectionKeyListener implements KeyListener               
              public void keyPressed (KeyEvent event)
                   switch (event.getKeyCode())
                   case KeyEvent.VK_LEFT:
                        old_px = px;
                        if (px >=15)
                             px -=10;
                        break;
                   case KeyEvent.VK_RIGHT:
                        old_px = px;
                        if (px+pw <= APPLET_WIDTH-15)
                             px += 10;
                        break;
                   case KeyEvent.VK_Q:
                        done = true;
                   default:
                   }  //end switch
                   repaint();
              }//end keyPressed
              public void keyTyped (KeyEvent event)
              public void keyReleased (KeyEvent event)
         }  //end class 
    }

    thank you sir for your advice.
    Its not like that I without any attempt, just past code here & asked for its conversion. I spent about 5 hours on it, can say spoil whole day but to no avail. You then just guide me, give some hint so that I do it. I will most probably wanted to do it by myself but asked for help when was just disappointed.
    I try to put all init() in default constructor of identical copy of this applet that extends JPanel. Problem.....ball tend to fell but pad not moving. Also out out was not getting ant color input. That was like my best effort.....other tried that I found by search like just do nothing only extend panel OR frame in spite of applet, start applet from within main of another class.... these are few I remember what I tried.
    I will be very very thankful to you if you can help/guide me how can I do it. Behavior of the Applet is like a normal PONG game with on pad controlled by arrow keys, & one ball colliding with walls of boundary & falling down.
    Thanks a lot again for your attention & time.

  • JEditorPane (or subclasses) and a class that extends JPanel

    hello to all,
    i'm realizing an application with Swing.
    i have realized a class that extends JPanel(called "PanelLayer") and, other to draw a ruler as Office 2003, it must contain an other subclass of JPanel (called "PanelLayer") that, in turn, will contain a JEditorPane.
    the problem is strange: i should continue in moviment the mouse to look well the JEditorPane (or subclasses)
    the URL is a image of the result that i get...
    URL : http://phantom89.helloweb.eu/img/img.jpg
    codes:
    public class Layer extends JPanel implements ComponentListener{
        private static final long serialVersionUID = 1L;
        private Rectangle2D.Double areaCentrale = new Rectangle2D.Double(100,100,850,1285);
        private double larghFoglio = 21.0*50;
        private double altFoglio = 29.7*50;
        private double zoom = 1.0;
        private JScrollPane sp = new JScrollPane(this);
        private Rectangle2D.Double posFoglio = new Rectangle2D.Double();
        private int lastX,lastY;
        private PanelLayer pl;
        private Point mouse = null;
        private JEditorPane text;
        public Layer(PanelLayer pl){
            this.setLayout(null);
            this.pl = pl;
            this.setPreferredSize(new Dimension((int)(40+larghFoglio*zoom), (int)(100+altFoglio*zoom)));
            areaCentrale = new Rectangle2D.Double(100*zoom,100*zoom,850*zoom,1285*zoom);
                sp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
            sp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
            //try{
                text = new JEditorPane();
                text.setBounds(50,50,200,200);
                this.add(text);
            //}catch(IOException e){}
            lastX = sp.getHorizontalScrollBar().getValue();
            lastY = sp.getVerticalScrollBar().getValue();
            this.addComponentListener(this);
            this.addMouseListener(this);
            this.addMouseMotionListener(this);
        public void paintComponent(Graphics g){
            if(posFoglio.height + posFoglio.width == 0){
                this.posFoglio = new Rectangle2D.Double((this.getWidth()-larghFoglio*zoom)/2,50,larghFoglio*zoom,altFoglio*zoom);       
            Graphics2D g2d = (Graphics2D)g;
            g2d.setPaint(Color.lightGray);
            g2d.fillRect(0,0,this.getWidth(),this.getHeight());
            g2d.translate((this.getWidth()-larghFoglio*zoom)/2,50);
            g2d.setPaint(Color.black);
            g2d.draw(new Rectangle2D.Double(0,0,larghFoglio*zoom,altFoglio*zoom));
            g2d.setPaint(Color.white);
            g2d.fill(new Rectangle2D.Double(1,1,larghFoglio*zoom-1,altFoglio*zoom-1));
            g2d.setPaint(Color.blue);
            g2d.draw(areaCentrale);
        public JScrollPane getJScrollPane(){
            return sp;
        public Rectangle2D.Double getDimFoglio(){       
            return this.posFoglio;
        public double getCmWidth(){
            return larghFoglio*zoom/50+((larghFoglio*zoom/50)%1 <= getIncr() ? 0 : getIncr());
        public double getCmHeight(){
            return altFoglio*zoom/50+((altFoglio*zoom/50)%1 <= getIncr() ? 0 : getIncr());
        public Point getPointMouse(){
            return mouse;
        public void refresh(){
            lastX = sp.getHorizontalScrollBar().getValue();
            posFoglio.x = (this.getWidth()-larghFoglio*zoom)/2-lastX;
        public double getIncr(){
            return zoom/2;
        public void mouseClicked(MouseEvent e) {}
        public void mouseEntered(MouseEvent e) {}
        public void mouseExited(MouseEvent e) {}
        public void mousePressed(MouseEvent e) {}
        public void mouseReleased(MouseEvent e) {}
        public void mouseDragged(MouseEvent e) {}
        public void mouseMoved(MouseEvent e) {
            mouse = e.getPoint();
            mouse.x -= sp.getHorizontalScrollBar().getValue();
            mouse.y -= sp.getVerticalScrollBar().getValue();
            pl.repaint();
        public void componentHidden(ComponentEvent e) {}
        public void componentMoved(ComponentEvent e) {
            lastX = sp.getHorizontalScrollBar().getValue();
            posFoglio.x = (this.getWidth()-larghFoglio*zoom)/2-lastX;
            lastY = sp.getVerticalScrollBar().getValue();
            posFoglio.y = 50-lastY;
            pl.repaint();
        public void componentResized(ComponentEvent e) {
            this.repaint();
            pl.repaint();
        public void componentShown(ComponentEvent e) {}
    public class PanelLayer extends JPanel implements MouseWheelListener,MouseInputListener{
        private static final long serialVersionUID = 1L;
        private Layer layer;
        private JScrollPane sp = null;
        private boolean visualizzaMouse = false;
        public PanelLayer(){
            this.setLayout(null);
            layer = new Layer(this);
            layer.addMouseListener(this);
            layer.addMouseMotionListener(this);
        public void paintComponent(Graphics g){
            if(layer.getDimFoglio().getWidth()+layer.getDimFoglio().getHeight() == 0){
                layer.setSize(50,50);
            if(sp == null){
                sp = layer.getJScrollPane();
                sp.addMouseWheelListener(this);
                sp.setBounds(30,30,this.getWidth()-30,this.getHeight()-30);
                this.add(sp);
            }else{
                layer.refresh();
            sp.setBounds(30,30,this.getWidth()-30,this.getHeight()-30);
            Graphics2D g2d = (Graphics2D)g;
            g2d.setPaint(new Color(153,255,153));
            g2d.fill(new Rectangle2D.Double(0,0,this.getWidth(),30));
            g2d.fill(new Rectangle2D.Double(0,0,30,this.getHeight()));
            g2d.setPaint(Color.black);
            g2d.drawLine(0,0,this.getWidth(),0);
            g2d.drawLine(0,30,this.getWidth(),30);
            g2d.drawLine(0,0,0,this.getHeight());
            g2d.drawLine(30,0,30,this.getHeight());
            for(double i=0,j=0;i<=layer.getCmWidth();i+=layer.getIncr(),j++){
                if(j%2==0){
                    g2d.drawLine((int)(layer.getDimFoglio().x+31+i*50), 15,(int)(layer.getDimFoglio().x+31+i*50), 30);
                    g2d.drawString(String.valueOf((int)(j/2)), (float)(layer.getDimFoglio().x+31+i*50), 13);               
                }else{
                    g2d.drawLine((int)(layer.getDimFoglio().x+31+i*50), 22,(int)(layer.getDimFoglio().x+31+i*50), 30);
            for(double i=0,j=0;i<=layer.getCmHeight();i+=layer.getIncr(),j++){
                if(j%2==0){
                    g2d.drawLine(15, (int)(layer.getDimFoglio().y+31+i*50),30,(int)(layer.getDimFoglio().y+31+i*50));
                    g2d.drawString(String.valueOf((int)(j/2)),5,(float)(layer.getDimFoglio().y+31+i*50));
                }else{
                    g2d.drawLine(22, (int)(layer.getDimFoglio().y+31+i*50),30,(int)(layer.getDimFoglio().y+31+i*50));
            if((layer.getPointMouse() != null)&&(visualizzaMouse)){
                g2d.drawLine(layer.getPointMouse().x+30,0,layer.getPointMouse().x+30,30);
                g2d.drawLine(0,layer.getPointMouse().y+30,30,layer.getPointMouse().y+30);
            g2d.setPaint(new Color(153,255,153));
            g2d.fillRect(1,1,29,29);
            int largh = layer.getJScrollPane().getVerticalScrollBar().getWidth();
            g2d.fillRect(this.getWidth()-largh, 1, largh, 29);
            g2d.fillRect(1, this.getHeight()-largh, 29, largh);
        public void mouseWheelMoved(MouseWheelEvent e) {
            JScrollBar vsb = layer.getJScrollPane().getVerticalScrollBar();
            vsb.setValue(vsb.getValue()+20*e.getWheelRotation());
        public void refresh(){
            if((layer != null)&&(sp != null)){
                layer.setSize(this.getWidth()-30,this.getHeight()-30);
                sp.setViewportView(layer);
                this.repaint();
        public void mouseClicked(MouseEvent e) {}
        public void mouseEntered(MouseEvent e) {
            visualizzaMouse = true;
            repaint();
        public void mouseExited(MouseEvent e) {
            visualizzaMouse = false;
            repaint();
        public void mousePressed(MouseEvent e) {}
        public void mouseReleased(MouseEvent e) {}
        public void mouseDragged(MouseEvent e) {}
        public void mouseMoved(MouseEvent e) {}
    }(my english isn't very good)

    Don't really understand what the posted code does and I can't execute the code so I don't have much to offer.
    But I did notice that you don't invoke super.paintComponent(...) which means you may have garbage being painted on the panels.
    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)", that demonstrates the incorrect behaviour.
    http://homepage1.nifty.com/algafield/sscce.html

  • Xml Serializing a class that extends JPanel

    Alright I am getting an Exception saying java.
    java.lang.reflect.InvocationTargetException
    Continuing ...
    java.lang.Exception: XMLEncoder: discarding statement XMLEncoder.writeObject(JpanelScreen);
    Continuing ...
    is anyone familiar with this... It ocurrs when I try to Serialize my class object that extends JPanel...

    any examples of how to do this?
    try {
    java.beans.XMLEncoder out = new java.beans.XMLEncoder( new BufferedOutputStream( new java.io.FileOutputStream(getFilename())));
    out.writeObject(Screen);
    out.close();
    }catch (Exception exc) {System.err.println(exc.getMessage());}

  • Closing a class that extends JPanel

    Hi, i have a class that extends JPanel(lets call it class A). In that class, if the user click the logout button, i want class A to close and display class B that extends JFrame. right now, i am able to call class B, but i cannot close class A.
    I uses remove() to close class A, but it doesnt work... could u tell me what to do??
    I put this code in class A...
    if (e.getSource() == logoutButton)     {
         remove(this);
         new Rest_Login1();
         String [] ar = null;
         Rest_Login1.main(ar);
    } Thx

    so i want to remove the CustomerPanel3 and display the Rest_Login1...
    some of my code look like this.
    thx
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class CustomerPanel3 extends JPanel implements ActionListener
    // some JButton, JLabel n etc
         public void actionPerformed (ActionEvent e)
              if (e.getSource() == logoutButton)     {
                   remove(this);
                   new Rest_Login1();
                   String [] ar = null;
                   Rest_Login1.main(ar);
    public class Rest_Login1 {
         public static void main(String args[])
              JFrame login1 = new JFrame("Login User Interface");
              JFrame.setDefaultLookAndFeelDecorated(true);
              RestaurantLogin userpan = new RestaurantLogin();
              login1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              login1.setSize(600, 250);
              login1.setLocation(230,192);
              login1.getContentPane().add(userpan);
              login1.setVisible(true);
    }

  • Problem extending JPanel

    Hi,
    What is the best format to have a class with a JFrame and a number of JPanels, one of which needs to be painted on using Graphics.
    class Demo extends JPanel{
    public JFrame frame;
    public JPanel panel1;
    public JPanel panel2;
    public JPanel panel3;
       Demo(){
          // initialise JFrame
          frame = new JFrame();
          // initialise a few JPanels
          panel1 = new JPanel();
          panel2 = new JPanel();
          panel3 = new JPanel();
          // refer to the JPanel I'm painting on
          frame.getContentPane(this);   // Is this correct?
         public void paint(Graphics g)     {
              g.drawString("Click below", 50, 50);               
                  // now this method should paint over one of the JPanels only, the one I'm extending..
    }Any thought appreciated.

    Thanks for the pointers Haynese ,
    I understand what I should be doing.
    I have another issue with this now, maybe its constructed badly...
    I can get the graphics objects on the JPanel to display but not the JButton or label I add. If I click in the region of the button and hit it, it appears. Any ideas?
    public class GraphEditor extends JPanel implements MouseListener
    public JButton button;
    public JLabel label5;
         public GraphEditor(){
              //  JPanel Button, displays if clicked on.
              button = new JButton("JPanel Button, displays if clicked on...");
              this.add(button);
                                             //  This should display but never does
              label5 = new JLabel("This should display but never does");
              add(label5);
              setSize(50,50);
              setVisible(true);
         public void paint(Graphics g)     {
                                            // This displays fine
              g.drawString("This displays fine", 5, 5);               
    }and:
    public class SystemWindow extends JFrame {     
    public JButton button;
    public JPanel topPanel;
    public JPanel bottomPanel;
    public JPanel mainPanel;
    public JLabel topPanelLabel;
    public JLabel bottomPanelLabel;
    public JButton getPathButton;
    private GraphEditor mainMap = new GraphEditor(this);
         SystemWindow(){     
             topPanel = new JPanel();
              bottomPanel = new JPanel();
              mainPanel = new JPanel();
              // 10 is horizontal
                                               // 01 is vertical
              getContentPane().setLayout(new GridLayout(0,1));
              getContentPane().add(mainPanel);
              mainPanel.add(topPanel);
              mainPanel.add(bottomPanel);
              topPanelLabel = new JLabel("Top Panel");
              topPanel.add(topPanelLabel);
              bottomPanelLabel = new JLabel("Bottom Panel");
              bottomPanel.add(bottomPanelLabel);
              button = new JButton("Save");
              //button.addActionListener(this);
              bottomPanel.add(button);
              getPathButton = new JButton("Get");
              //getPathButton.addActionListener(this);
              bottomPanel.add(getPathButton);
              getContentPane().add(mainMap);
              setTitle("App Title");          
              setSize(500,300);          
              setLocation(100,100);     
              mainPanel.setVisible(true);
              topPanel.setVisible(true);
             bottomPanel.setVisible(true);
             setVisible(true);
         }          Any suggestions welcome.

  • Extends JPanel

    Hi.
    I have a Class ATable that extends Panel. It is working good and draw the table.
    But, I need to convert this class to make it extends JPanel not Panel but it is not draw the table unless I change the frame size.
    So what is the problem please?
    this is my Class :
    =========================================================
    import java.awt.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.*;
    public class ATable extends JPanel
    implements TableDataModelListener, ColumnModelListener
    public static int OUTSIDE_TABLE = -1;
    TableCellRenderer tableCellRenderer;//interface for ---> Cell getTableCell(ATable atable, Object obj, int i, int j)
    TableDataModel tableDataModel; //interface
    ColumnModel columnModel; //class
    int cellOffsetY[];
    int rowHeight;
    int rowPadding;
    Point tableOffset;
    Point textOffset;
    Color gridLinesColor;
    Color tableBackground;
    ATableHeader tableHeader;
    static class _cls1 extends WindowAdapter
    public void windowClosing(WindowEvent e)
    System.exit(0);
    _cls1()
    public ATable()
    rowPadding = -1;
    tableCellRenderer = new DefaultTableCellRenderer();
    tableDataModel = new DefaultTableDataModel();
    columnModel = new ColumnModel();
    initColumnModel();
    setLayout(new BorderLayout());
    tableHeader = new ATableHeader(this, columnModel, new DefaultHeaderCellRenderer());
    add("North", tableHeader);
    initATable();
    public ATable(TableDataModel tableDataModel, ColumnModel columnModel, TableCellRenderer tableCellRenderer, TableCellRenderer headerCellRenderer)
    rowPadding = -1;
    this.tableCellRenderer = tableCellRenderer;
    this.tableDataModel = tableDataModel;
    this.columnModel = columnModel;
    setLayout(new BorderLayout());
    tableHeader = new ATableHeader(this, columnModel, headerCellRenderer);
    add("North", tableHeader);
    initATable();
    void initColumnModel()
    for(int i = 0; i < tableDataModel.getColumnsCount(); i++)
    TableColumn tableColumn = new TableColumn("Header " + i, i, 70);
    columnModel.addColumn(tableColumn);
    void calTextOffset()
    FontMetrics fm = getFontMetrics(getFont());
    textOffset.x = fm.charWidth('0');
    textOffset.y = fm.getAscent();
    void adjustColumnHeight()
    FontMetrics fm = getFontMetrics(getFont());
    rowHeight = fm.getAscent() + fm.getDescent() + 1;
    tableOffset.y = tableHeader.getPreferredSize().height + rowPadding;
    void initATable()
    gridLinesColor = new Color(50, 50, 50);
    tableBackground =new Color(155, 175, 202);
    textOffset = new Point();
    tableOffset = new Point();
    int fontSize = 12;
    Font font = new Font("Dialog", 0, fontSize);
    setFont(font);
    calTextOffset();
    adjustColumnHeight();
    calBeanDimensions();
    calCellsOffsetY();
    columnModel.addColumnModelListener(this);
    void calCellsOffsetY()
    if(cellOffsetY == null || cellOffsetY.length != tableDataModel.getRowsCount())
    cellOffsetY = new int[tableDataModel.getRowsCount()];
    int y = tableOffset.y;
    for(int i = 0; i < cellOffsetY.length; i++)
    cellOffsetY[i] = y;
    y += rowHeight + rowPadding;
    public void setFontAndAdjustDim(Font font)
    tableHeader.setFontAndAdjustDim(font);
    setFont(font);
    calTextOffset();
    adjustColumnHeight();
    calBeanDimensions();
    FontMetrics fm = getFontMetrics(getFont());
    int colWidth[] = new int[columnModel.getColumnsCount()];
    for(int i = 0; i < columnModel.getColumnsCount(); i++)
    TableColumn tableColumn = columnModel.getColumn(i);
    int dataModelIndex = tableColumn.getDataModelIndex();
    int max = fm.stringWidth(tableColumn.getHeaderValue());
    for(int j = 0; j < tableDataModel.getRowsCount(); j++)
    int current = fm.stringWidth(tableDataModel.getValueAt(j, dataModelIndex).toString());
    if(current > max)
    max = current;
    colWidth[i] = max + textOffset.x + textOffset.x;
    columnModel.setColumnsWidth(colWidth);
    calCellsOffsetY();
    doLayout();
    public void setFont(Font font)
    super.setFont(font);
    calTextOffset();
    void drawCell(Graphics g, int row, int col)
    TableColumn tableColumn = columnModel.getColumn(col);
    int x = tableColumn.getX();
    int width = tableColumn.getWidth();
    int y = cellOffsetY[row];
    int dataModelIndex = tableColumn.getDataModelIndex();
    Object value = tableDataModel.getValueAt(row, dataModelIndex);
    Cell cell = tableCellRenderer.getTableCell(this, value, row, col);
    drawCell(g, cell, x, y, width);
    void drawCell(Graphics g, Cell cell, int x, int y, int width)
    g.setClip(x, y, width, rowHeight);
    Color oldColor = g.getColor();
    g.setColor(gridLinesColor);
    g.drawRect(x, y, width - 1, rowHeight - 1);
    g.setColor(cell.getBGColor());
    g.fillRect(x + 1, y + 1, width - 2, rowHeight - 2);
    g.setColor(cell.getTextColor());
    g.setClip(x + 1, y + 1, width - 2, rowHeight - 2);
    g.drawString(cell.getValue(), x + textOffset.x, y + textOffset.y);
    if(cell.getHighlight() != null)
    g.setColor(cell.getHighlight());
    g.drawRect(x + 1, y + 1, width - 3, rowHeight - 3);
    g.setColor(oldColor);
    public int convertColumnIndexToModel(int columnIndex)
    TableColumn tableColumn = columnModel.getColumn(columnIndex);
    return tableColumn.getDataModelIndex();
    public int convertColumnIndexToView(int modelColumnIndex)
    int size = columnModel.getColumnsCount();
    for(int i = 0; i < size; i++)
    TableColumn tableColumn = columnModel.getColumn(i);
    if(tableColumn.getDataModelIndex() == modelColumnIndex)
    return i;
    return -1;
    public void hideColumn(int columnIndex)
    columnModel.removeColumn(columnIndex);
    public void addColumn(TableColumn tableColumn)
    columnModel.addColumn(tableColumn);
    public void moveColumn(int columnIndex, int newColumnIndex)
    columnModel.moveColumn(columnIndex, newColumnIndex);
    public int getColumnIndexFromPixel(int x)
    TableColumn tableColumn = columnModel.getColumn(columnModel.getColumnsCount() - 1);
    int edgeX = (tableColumn.getX() + tableColumn.getWidth()) - 1;
    if(x > edgeX || x < textOffset.x)
    return OUTSIDE_TABLE;
    for(int i = columnModel.getColumnsCount() - 1; i >= 0; i--)
    if(x > columnModel.getColumn(i).getX())
    return i;
    return OUTSIDE_TABLE;
    public int getRowFromPixel(int y)
    int edgeY = ((cellOffsetY.length == 0 ? 0 : cellOffsetY[cellOffsetY.length - 1]) + rowHeight) - 1;
    if(y > edgeY || y < tableOffset.y)
    return OUTSIDE_TABLE;
    for(int i = cellOffsetY.length - 1; i >= 0; i--)
    if(y > cellOffsetY)
    return i;
    return -1;
    public Dimension getPreferredSize()
    int width=0;
    int height=0;
    TableColumn tableColumn = columnModel.getColumn(columnModel.getColumnsCount() - 1);
    try
    height = cellOffsetY[cellOffsetY.length - 1] + rowHeight;
    width = tableColumn.getX() + tableColumn.getWidth();
    catch(Exception exp)
    height = 0;
    width = 0;
    return new Dimension(width, height);
    public Dimension getMinimumSize()
    TableColumn tableColumn = columnModel.getColumn(columnModel.getColumnsCount() - 1);
    int height = cellOffsetY[cellOffsetY.length - 1] + rowHeight;
    int width = tableColumn.getX() + tableColumn.getWidth();
    return new Dimension(width, height);
    public void updateAll()
    int rowsCount = tableDataModel.getRowsCount();
    update(0, tableDataModel.getRowsCount() - 1, 0, columnModel.getColumnsCount() - 1);
    public void update(int firstRowIndex, int lastRowIndex, int firstColIndex, int lastColIndex)
    if(firstRowIndex > lastRowIndex || firstColIndex > lastColIndex)
    return;
    try
    TableColumn firstColumn = columnModel.getColumn(firstColIndex);
    TableColumn lastColumn = columnModel.getColumn(lastColIndex);
    int width = (lastColumn.getX() + lastColumn.getWidth()) - firstColumn.getX();
    int height = (cellOffsetY[lastRowIndex] + rowHeight) - cellOffsetY[firstRowIndex];
    Image offScreen = createImage(width, height);
    Graphics og = offScreen.getGraphics();
    og.translate(-1 * firstColumn.getX(), -1 * cellOffsetY[firstRowIndex]);
    for(int i = firstRowIndex; i <= lastRowIndex; i++)
    for(int j = firstColIndex; j <= lastColIndex; j++)
    drawCell(og, i, j);
    getGraphics().drawImage(offScreen, firstColumn.getX(), cellOffsetY[firstRowIndex], null);
    catch(ArrayIndexOutOfBoundsException e)
    calCellsOffsetY();
    repaint();
    System.out.println(e);
    e.printStackTrace();
    public void paint(Graphics g)
    tableHeader.repaint();
    updateAll();
    public void setGridLinesColor(Color gridLinesColor)
    this.gridLinesColor = gridLinesColor;
    tableHeader.setGridLinesColor(gridLinesColor);
    repaint();
    public void setTableBackground(Color tableBackground)
    this.tableBackground = tableBackground;
    repaint();
    public void tableDataModelChanged(TableDataModelEvent e)
    if(e.getType() == TableDataModelEvent.UPDATE)
    update(e.getFirstRow(), e.getLastRow(), 0, columnModel.getColumnsCount() - 1);
    else
    if(e.getType() == TableDataModelEvent.INSERT)
    calCellsOffsetY();
    update(e.getFirstRow(), e.getLastRow(), 0, columnModel.getColumnsCount() - 1);
    } else
    calCellsOffsetY();
    repaint();
    void calBeanDimensions()
    public void cellDataChanged(int row, int col)
    col = convertColumnIndexToView(col);
    if(col < 0)
    return;
    } else
    TableColumn column = columnModel.getColumn(col);
    int width = column.getWidth();
    int height = rowHeight;
    Image offScreen = createImage(width, height);
    Graphics og = offScreen.getGraphics();
    og.translate(-1 * column.getX(), -1 * cellOffsetY[row]);
    drawCell(og, row, col);
    getGraphics().drawImage(offScreen, column.getX(), cellOffsetY[row], null);
    return;
    public void columnAdded(ColumnModelEvent e)
    calBeanDimensions();
    repaint();
    public void columnMoved(ColumnModelEvent e)
    repaint();
    public void columnRemoved(ColumnModelEvent e)
    calBeanDimensions();
    repaint();
    public void columnWidthChanged(ColumnModelEvent e)
    calBeanDimensions();
    repaint();
    public ATableHeader getHeader()
    return tableHeader;
    public ColumnModel getColumnModel()
    return columnModel;
    public static void main(String args[])
    throws Exception
    ATable aTable = new ATable();
    Frame f = new Frame();
    f.addWindowListener(new _cls1());
    f.add(aTable);
    Dimension dim = aTable.getPreferredSize();
    f.setVisible(true);
    f.pack();

    thank you for reply.
    I removed the setFont function and the class works good and showing the table.
    But when I put this table in JFrame not in Frame the table disappeared. I mean if I changed the Main class to the following :
    ================================================
    public static void main(String args[])
    throws Exception
    ATable aTable = new ATable();
    JFrame f = new JFrame();
    f.addWindowListener(new _cls1());
    f.getContentPane.add(aTable);
    Dimension dim = aTable.getPreferredSize();
    f.setVisible(true);
    f.pack();

  • Extending JPanel changes JPanel behavior

    All,
    I am trying to center a JPanel in the middle of my JFrame. Below is the code I use to center the JPanel. What is confusing me is that when the panel in question, actionPnl, is declared as a JPanel, the centering code works beautifully. When I declare it as a CanvasPanel (see code below) it does not show up at all. Now, I thought that when you use �Extends� that the class you are creating inherits all attributes of the class you are extending however this behavior suggests otherwise. Am I overlooking some fundamental ingredient?
    //private CanvasPanel actionPnl = new CanvasPanel();
    private JPanel actionPnl = new JPanel();
    private Box xp = Box.createHorizontalBox();
    private Box yp = Box.createVerticalBox();
    private void center()
      xp.add(Box.createHorizontalGlue());
      xp.add(actionPnl);
      xp.add(Box.createHorizontalGlue());
      yp.add(Box.createVerticalGlue());
      yp.add(xp);
      yp.add(Box.createVerticalGlue());
    }//end center()
    public class CanvasPanel extends JPanel
      private Image image;
    public CanvasPanel()
       setBackground (Color.WHITE);
       setPreferredSize(new Dimension(600, 100));
    }//end constructor CanvasPanel()
    public void paintComponent(Graphics g)
       g.drawImage(image, 0, 0, null);
       g.dispose();
    public void setImage(Image inImage)
       image = inImage;
    }

    We never want to see you entire program. We only want
    to see the code that demonstrates the incorrect
    behaviourI pieced this together and it has the same behavior. It is what I would call "hack code" and does not follow good practices. But it gets the point across. Just toggle which actionPnl declaration to comment out to see the difference.
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Image;
    import javax.swing.JPanel;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.image.BufferedImage;
    import java.awt.Graphics;
    public class test extends JFrame
    Container c;
    boolean btnControl = false;
    /******** toggle these two *********/
    //private CanvasPanel actionPnl = new CanvasPanel();
    private JPanel actionPnl = new JPanel();
    private Box xp = Box.createHorizontalBox();
    private Box yp = Box.createVerticalBox();
    public test()
    //container
    c = getContentPane();
    c.setBackground(Color.BLACK);
    c.setLayout(new BorderLayout());
    //construction
    buildActionPnl();
    //add to JFrame
    c.add(yp, BorderLayout.CENTER);
    setSize(1200, 950);
    setVisible(true);     
    }//end constructor balance()
    private void buildActionPnl()
      center();
    }//end buildActionPnl()
    private void center()
      xp.add(Box.createHorizontalGlue());
      xp.add(actionPnl);
      xp.add(Box.createHorizontalGlue());
      yp.add(Box.createVerticalGlue());
      yp.add(xp);
      yp.add(Box.createVerticalGlue());
    }//end center()
    public static void main(String args[])
      test t = new test();
    t.addWindowListener(
                new WindowAdapter(){
                     public void windowClosing(WindowEvent we){
                          System.exit(0);
    public class CanvasPanel extends JPanel
      private Image image;
    public CanvasPanel()
       setBackground (Color.WHITE);
       setPreferredSize(new Dimension(600, 100));
    }//end constructor CanvasPanel()
    public void paintComponent(Graphics g)
       g.drawImage(image, 0, 0, null);
       g.dispose();
    }I will research your suggested LayoutManager information and get back with how it works for me. At the moment I do not have code to control where each image is painted, that is what I am trying to take on.
    Thanks for the help, it is appreciated!

  • Extending JPanel or JComponent?

    Hi,
    just a short question: when should my class, which uses a paintComponent method, extends JPanel and when JComponent?
    Thanks!

    All custom components in Swing extend JComponent.
    JPanel extends JComponent. The basic functionality it adds it the painting of the background.
    So since you are doing custom painting I would suggest you don't need to extend JPanel for that feature, you can add that support yourself. Then when you create your object its more efficient since the JVM doesn't need to create a JPanel object.

  • Extending JPanel

    i made a class that extends JPanel and i overrided the paintComponent method so i could create my own graphics. I tried adding my component to a JScrollPane but it didn't work. How could i create a ScrollPane for my component.

    did you override getPreferredSize() on the panel subclass to return a size? or call setPreferredSize() early on (in the constructor or somewhere) on the panel subclass?
    the best way to deal with scrolling panels, however, is to use something like this handy class as the base class... It handles drag-scrolling and lets you set the scroll unit size to whatever. When you want to change the size, call setPreferredSize() and it'll notify the scrollpane of the change. (Generally, you want to leave the ScrollableTracksViewportWidth/Height as false, BTW.)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    * <code>ScrollablePanel</code> is a <code>JPanel</code> subclass which
    * supports scrolling via the <code>Scrollable</code> interface. 
    public class ScrollablePanel extends JPanel implements Scrollable, MouseMotionListener {
          * The scroll unit size. 
         private int unitSize = 5;
          * Flag to indicate if a viewport should always force the width of this
          * <code>Scrollable</code> to match the width of the viewport.
         private boolean scrollableTracksViewportWidth = false;
          * Flag to indicate if a viewport should always force the height of this
          * <code>Scrollable</code> to match the height of the viewport.
         private boolean scrollableTracksViewportHeight = false;
          * Creates a new <code>ScrollablePanel</code>. 
         public ScrollablePanel() {
              super();
              setAutoscrolls(true); // enable synthetic drag events
              addMouseMotionListener(this); // handle mouse drags
          * Handles mouse moved events.  Does nothing. 
          * @param  e  the mouse event
         public void mouseMoved(MouseEvent e) {
          * Handles mouse dragged events.  Tracks dragging for autoscrolling. 
          * @param  e  the mouse event
         public void mouseDragged(MouseEvent e) {
              scrollRectToVisible(new Rectangle(e.getX(), e.getY(), 1, 1));
          * Sets the preferred size of the panel.  This also calls
          * <code>revalidate()</code> to notify the viewport parent
          * of the change. 
          * @param  size  the preferred size of the panel
         public void setPreferredSize(Dimension size) {
              super.setPreferredSize(size);
              revalidate();
              repaint();
          * Returns the preferred size of the viewport for a view component. 
          * @return  the preferred size of the viewport
         public Dimension getPreferredScrollableViewportSize() {
              return getPreferredSize();
          * Components that display logical rows or columns should compute the
          * scroll increment that will completely expose one new row or column,
          * depending on the value of orientation.
          * @param  visibleRect  the visible area
          * @param  orientation  the orientation
          * @param  direction    the scroll direction
          * @return  the unit increment
         public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
              int currentPosition = 0;
              if(orientation == SwingConstants.HORIZONTAL) {
                   currentPosition = visibleRect.x;
              } else {
                   currentPosition = visibleRect.y;
              // return the number of pixels between currentPosition and the
              // nearest unit size increment in the indicated direction.
              if(direction < 0) {
                   int newPosition = currentPosition - (currentPosition / unitSize) * unitSize;
                   return (newPosition == 0) ? unitSize : newPosition;
              } else {
                   return ((currentPosition / unitSize) + 1) * unitSize - currentPosition;
          * Components that display logical rows or columns should compute the
          * scroll increment that will completely expose one block of rows or
          * columns, depending on the value of orientation.
          * @param  visibleRect  the visible area
          * @param  orientation  the orientation
          * @param  direction    the scroll direction
          * @return  the block increment
         public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
              if(orientation == SwingConstants.HORIZONTAL) {
                   return visibleRect.width - unitSize;
              } else {
                   return visibleRect.height - unitSize;
          * Return true if a viewport should always force the width of this
          * <code>Scrollable</code> to match the width of the viewport.
          * @return  the tracks viewport width mode
         public boolean getScrollableTracksViewportWidth() {
              return this.scrollableTracksViewportWidth;
          * Sets if a viewport should always force the width of this
          * <code>Scrollable</code> to match the width of the viewport.
          * @param  b  true if the tracks viewport width mode
         public void setScrollableTracksViewportWidth(boolean b) {
              this.scrollableTracksViewportWidth = b;
          * Return true if a viewport should always force the height of this
          * <code>Scrollable</code> to match the height of the viewport.
          * @return  the tracks viewport height mode
         public boolean getScrollableTracksViewportHeight() {
              return this.scrollableTracksViewportHeight;
          * Sets if a viewport should always force the height of this
          * <code>Scrollable</code> to match the height of the viewport.
          * @param  b  true if the tracks viewport height mode
         public void setScrollableTracksViewportHeight(boolean b) {
              this.scrollableTracksViewportHeight = b;
          * Gets the scroll unit size. 
          * @return  the scroll unit size
         public int getUnitSize() {
              return this.unitSize;
          * Sets the scroll unit size. 
          * @param  us  the scroll unit size
         public void setUnitSize(int us) {
              unitSize = us;
    }

Maybe you are looking for

  • How do I print images from Aperture to the Canon MG6150?

    I have recently installed (i think correctly) a Canon MG6150 printer on my iMac but am having difficulty making it work correctly when photo printing (the wireless connection seems OK).  When printing from Aperture I can cause a print to be made but

  • HP Pavilion Dv6 7078CA Recovery without recovery disc

    Hello!! i have an Hp Pavilion Dv6 - 7078ca, and after just 6 months of use, the Hard Drive just died. because i live in Brazil, and brought the Computer back home, i couldnt use the warrant, since the warrant is for canada only. so i changed by my ow

  • Can't connect using wpa_supplicant [SOLVED]

    When I was first setting up (latest netinstall iso, x86_64) I was using wpa_passphrase and wpa_supplicant just fine in fetching new packages and the like. I did this about 2 weeks ago (Jan 27). Some time ago when I updated and restarted, I noticed th

  • MPB 17" Student backpack

    Ok, I just got my MBP 17" and I leave for college in August. I need a laptop backpack. But, I need one that lets me carry a couple books as well. I've looked on the site and a couple reviews say most of them are hard to fit the MBP in without pulling

  • How to Stop the process chain if it in the middle of the process?

    Hi, Is there anyway that i can stop the process chain if it is in the middle of the process already? Raj