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.

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"));

  • Extending JPanel to contain a JRootPane - problems with scroll panes

    I am trying to write a JPanel subclass that contains a JRootPane, similar to the way that JFrame contains a JRootPane. The reason that I am doing this is that I would like to be able to intercept mouse events using the JGlassPane facility, but adding the glasspane to the JFrame is problematic since it then intercepts mouse events over all components in the JFrame, including the menu bar. It seems simpler to me to have the JRootPane owned by a JPanel, to give me better control over intercepting events. I've got an implementation working with the JFrame case, but have had to handle many small "gotchas", and at least one more exists. I'm hoping to simplify things by moving away from this way of doing things.
    I wrote a straightforward RootPanePanel class that extends JPanel and implements RootPaneContainer, delegating all of the add methods to the JRootPane's content pane. Here's the constructor for RootPanePanel:
    public RootPanePanel (LayoutManager layout) {
            rootPane = new JRootPane ();
            rootPane.setOpaque(true);
            rootPane.getContentPane().setLayout(layout);
            super.add (rootPane);
    }RootPanePanel also delegates calls like getContentPane/setContentPane to the JRootPane.
    To test my implementation, I wrote a main method that looks like the following:
    public static void main (String[] args) {
      SwingUtilities.invokeLater(new Runnable () {
        public void run () {
          try {
            JEditorPane editorPane = new JEditorPane ("http://www.archives.gov/exhibits/charters/print_friendly.html?page=declaration_transcript_content.html&title=NARA%20%7C%20The%20Declaration%20of%20Independence%3A%20A%20Transcription");
            JScrollPane scrollPane = new JScrollPane (editorPane);
            JFrame frame = new JFrame ("Test RootPanePanel");
            RootPanePanel panel = new RootPanePanel ();                    
            panel.add(scrollPane);
            frame.add(panel, BorderLayout.CENTER);
            scrollPane.setPreferredSize(new Dimension(800, 600));
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize (640, 480);
            frame.pack ();
            frame.setVisible(true);
          } catch (Exception e) {
            e.printStackTrace();
      });Note that I'm not actually using JEditorPane in my application, but it is the simplest component that displays the problem I'm encountering.
    When this code runs, it is fine, as long as the JFrame is big enough to display the scrollbars for the JScrollPane. If the JFrame is made small enough, the scrollbars are not displayed.
    If I instead add the JScrollPane to the JFrame directly, it behaves as you would expect.
    Is this a problem of mixing heavyweight and lightweight components? It doesn't seem like it should be; in both cases the JScrollPane is handling the same client component, the JEditorPane.
    Any suggestions/ideas are welcome!

    Here's the full RootPanePanel class in case people want to try it out
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.HeadlessException;
    import java.awt.LayoutManager;
    import java.io.IOException;
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JLayeredPane;
    import javax.swing.JPanel;
    import javax.swing.JRootPane;
    import javax.swing.JScrollPane;
    import javax.swing.RootPaneContainer;
    import javax.swing.SwingUtilities;
    public class RootPanePanel extends JPanel implements RootPaneContainer {
         private JRootPane rootPane;
         public RootPanePanel () {
              this (new BorderLayout());
         public RootPanePanel (LayoutManager layout) {
              rootPane = new JRootPane ();
              rootPane.setOpaque(true);
              rootPane.getContentPane().setLayout(layout);
              super.add (rootPane);
         public Container getContentPane() {
              return rootPane.getContentPane();
         public Component getGlassPane() {
              return rootPane.getGlassPane();
         public JLayeredPane getLayeredPane() {
              return rootPane.getLayeredPane();
         public void setContentPane(Container arg0) {
              rootPane.setContentPane(arg0);
         public void setGlassPane(Component arg0) {
              rootPane.setGlassPane(arg0);
         public void setLayeredPane(JLayeredPane arg0) {
              rootPane.setLayeredPane(arg0);
         @Override
         protected void addImpl(Component comp, Object constraints, int index)
              if (comp == rootPane) {
                   super.addImpl(comp, constraints, index);
              else {
                   getContentPane().add(comp, constraints, index);
         @Override
         public Component add(Component comp, int index) {
              return rootPane.getContentPane().add(comp, index);
         @Override
         public void add(Component comp, Object constraints, int index) {
              rootPane.getContentPane().add(comp, constraints, index);
         @Override
         public void add(Component comp, Object constraints) {
              rootPane.getContentPane().add(comp, constraints);
         @Override
         public Component add(Component comp) {
              return rootPane.getContentPane().add(comp);
         @Override
         public Component add(String name, Component comp) {
              return rootPane.getContentPane().add(name, comp);
         public static void main (String[] args) {
              SwingUtilities.invokeLater(new Runnable () {
                   public void run () {
                        try {
                             JEditorPane editorPane = new JEditorPane ("http://www.archives.gov/exhibits/charters/print_friendly.html?page=declaration_transcript_content.html&title=NARA%20%7C%20The%20Declaration%20of%20Independence%3A%20A%20Transcription");
                             JScrollPane scrollPane = new JScrollPane (editorPane);
                             JFrame frame = new JFrame ("Test RootPanePanel");
                             RootPanePanel panel = new RootPanePanel ();                    
                             panel.add(scrollPane);
                             frame.add(panel, BorderLayout.CENTER);
                             scrollPane.setPreferredSize(new Dimension(800, 600));                                                                                                                                                 
                             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                             frame.setSize (640, 480);
                             frame.pack ();
                             frame.setVisible(true);                                                                                                    
                        } catch (HeadlessException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
                        } catch (IOException e) {
                             // TODO Auto-generated catch block
                             e.printStackTrace();
         public JRootPane getRootPane() {
              return rootPane;
    }

  • Problem with JPanel and/or Thread

    Hello all,
    I have the following problem.
    I have a JFrame containing to JPanels. The JPanels are placed
    via BorderLayout.
    JPanel #1 is for moving a little rectangle (setDoubleBufferd), it is
    a self defined object extending JPanel.
    The paint methon in JPanel #1 has been overwritten to do the drawings.
    JPanel #2 contains 4 JButtons, but they have no effect at the
    moment. It is an "original" JPanel.
    The class extending JFrame implemented the interface Runnable and
    is started in its own thread.
    After starting the programm everthing looks fine.
    But if I press a Button in the second JPanel this button is painted in
    the top left corner of my frame. It changes if I press another button.
    Any help would be appreciated.
    Thanks.
    Ralf

    I have a JFrame containing to JPanels. The JPanels are
    placed
    via BorderLayout.The type of Layout does not seem to be relevant
    >
    JPanel #1 is for moving a little rectangle
    (setDoubleBufferd), it is
    a self defined object extending JPanel.
    The paint methon in JPanel #1 has been overwritten to
    do the drawings.
    JPanel #2 contains 4 JButtons, but they have no effect
    at the
    moment. It is an "original" JPanel.
    The class extending JFrame implemented the interface
    Runnable and
    is started in its own thread.
    After starting the programm everthing looks fine.
    But if I press a Button in the second JPanel this
    button is painted in
    the top left corner of my frame. It changes if I press
    another button.
    I noticed you solved this by painting the whole JFrame.
    Yeh Form time to time I get this problem too......
    Especially if the screen has gone blank - by going and having a cup of tea etc -
    Text from one Panel would be drawn in another.. annoying
    At first it was because I changed the state of some Swing Components
    not from the Event Thread.
    So make sure that your new Thread doesn't just blithely call repaint() or such like cos that leads to problems
    but rather something like
    SwingUtilities.invokeLater( new Runnable()
       public void run()
          MyComponent.repaint();
    });However I still get this problem using JScrollPanes, and was able to fix it by using the slower backing store method for the JScrollPane
    I could not see from my code how something on one JPanel can get drawn on another JPanel but it was happening.
    Anyone who could totally enlighten me on this?

  • Problem with JPanel, JMenuBar

    Hi, I'm new here so I'm not even sure if I'm posting in the correct forum ^^
    I usually don't have problems when building a JFrame and adding items into it but now I'm confused.
    When the JFrame is "built", I get a NullPointerException from the Panel's paintComponent method when it's trying to draw an image (g.drawImage())
    This is the whole JPanel class
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class PanneauDe extends JPanel
      private static final String [] TAB_IMAGE = { "De1.GIF", "De2.GIF", "De3.GIF",
                                                   "De4.GIF", "De5.GIF", "De6.GIF" };
      private static final int [] TAB_FREQUENCE = {0,0,0,0,0,0};
      private static final int SIDE = 100;
      private De unDe;
      private ImageIcon imageDe;
      private boolean aFirstTime;
      private int aX, aY; 
      public PanneauDe()
        unDe = new De();
        aX = aY = 0;
        aFirstTime = true;  
        addMouseListener(new EcouteurSouris());   
      public String getStats()
        String statsMsg = "";
        for ( int iPos = 0; iPos < TAB_FREQUENCE.length; iPos ++ )
          statsMsg += "Face " + (iPos + 1) + " : " + TAB_FREQUENCE[iPos] + " fois\n\n";
        return statsMsg;
      public String getTotal()
        int total = 0;
        for ( int iPos = 0; iPos < TAB_FREQUENCE.length; iPos ++ )
          total += TAB_FREQUENCE[iPos];
        return "Le d� a �t� lanc� " + total + " fois";
      public void throwDice()
        unDe.throwAgain();
        TAB_FREQUENCE[unDe.getFace() - 1] ++;   
      public void paintComponent (Graphics g) 
        super.paintComponent(g);
        g.drawImage (imageDe.getImage(), aX, aY, null); // <---- THIS GENERATES THE NULLPOINTEREXCEPTION
      class EcouteurSouris extends MouseAdapter
        public void mouseClicked (MouseEvent pMouseEvent)
          aX = pMouseEvent.getX();
          aY = pMouseEvent.getY();
          throwDice();
          imageDe = new ImageIcon(TAB_IMAGE[unDe.getFace() - 1]);
          repaint();
    }When I click in the windows, a picture of a dice (different side, randomly generated by the method throwDice() ), when I click again the first image dissapear and another one appears... and I make statistics about the results.
    I tried ...
      public void paintComponent (Graphics g) 
        super.paintComponent(g);
        //g.drawImage (imageDe.getImage(), aX, aY, null);
      class EcouteurSouris extends MouseAdapter
        public void mouseClicked (MouseEvent pMouseEvent)
          aX = pMouseEvent.getX();
          aY = pMouseEvent.getY();
          throwDice();
          imageDe = new ImageIcon(TAB_IMAGE[unDe.getFace() - 1]);
          Graphics g = getGraphics();
          g.drawImage (imageDe.getImage(), aX, aY, null);
          g.dispose();
        }Everything works correctly, no more NullPointerException, but the images don't dissapear when I click again. They just stay there.
    I'm not completly familiar with the repaint/dispose/paintComponent but I really don't understand why i get this NullPointerException error :\
    If you see some weird words in the code, it's because i'm canadian-frenchy! :)
    Full program is here

    The real question is why are you trying to override the paintComponent() method. Just add the image to a JLabel and add the label to a panel.
    However, the problem is that the paintComponent() method is invoked when the frame is shown and since you don't create the image until you do a mouseClick, the image in null.

  • Problem with jpanel size

    Hi I want to add a view port to a JPanel
    the main problem is that the Jpanel change size as the frame.
    how can i make it independent from the frame so having it; own w, h
    thanks
    package help;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.FlowLayout;
    import java.awt.GridLayout;
    import javax.swing.*;
    public abstract class MyFrame extends JFrame {
    private static final long serialVersionUID = 1L;
    private static JButton drawCircle, drawRectangle, drawSquare, drawStar, start, clear,quit,back, screenshoot;
    static final int FPS_MIN = 0;
    static final int FPS_MAX = 150;
    static final int FPS_INIT = 0;
    static int fps;
    double x1,x2;
    double y1,y2;
    int dr =1;
    int dy= 1;
    int Selection=0;
    boolean click=true; //check if start has been clicked
    int width = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;  // screen width
    int height = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height;     //screen higth
    protected static int count;
    int R,G,B;  //color
    Cursor c;                    //cursor object
    private static ShapePanel bpnl;
    public MyFrame()
            R=G=B=0;
            int width = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;
            int height = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height-100;
            JFrame frame=new JFrame();
            BorderLayout layout=new BorderLayout();
            frame.setLayout(layout);
            frame.setTitle("Game");
            //panel to hold buttons
            JPanel upPanel = new JPanel();
            upPanel.setLayout(new FlowLayout());
            upPanel.setSize(width, height/5);
            //panel to hold SLIDERS
            JPanel leftPanel = new JPanel();
            leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
            leftPanel.setSize(50, height);
            //initialize buttons and add to the upPanel
            drawCircle=new JButton("Draw Circle");
            upPanel.add(drawCircle);
            drawStar=new JButton("Draw Star");
            upPanel.add(drawStar);
            drawRectangle=new JButton("Draw Rectangle");
            upPanel.add(drawRectangle);
            drawSquare=new JButton("Draw Square");
            upPanel.add(drawSquare);
            start=new JButton("Start");
            start.setBackground(Color.GREEN);
            //upPanel.add(start);
            clear=new JButton("Clear");
            upPanel.add(clear);
            back=new JButton("Back");
            upPanel.add(back);
            quit=new JButton("Quit");
            quit.setBackground(Color.red);
            upPanel.add(quit);  
            screenshoot=new JButton("ScreenShoot");
            c = new Cursor (Cursor.CROSSHAIR_CURSOR);     //Change cursor to cross hair
         this.setCursor (c);
            //new object spanel to hold TIMER
            JPanel spanel=new JPanel();
                spanel.setLayout(new GridLayout());
                //slider dimension construction
                JSlider sDimension = new JSlider(JSlider.HORIZONTAL,FPS_MIN, FPS_MAX, FPS_INIT);
                sDimension.setMajorTickSpacing(30);
                sDimension.setMinorTickSpacing(3);
                sDimension.setPaintTicks(true);
                sDimension.setPaintLabels(true);
                Font font = new Font("Serif", Font.ITALIC, 15);
                sDimension.setFont(font);
                sDimension.setBorder(BorderFactory.createTitledBorder("Shape Dimension"));
                //slider speed construction
                int FPS_MIN_s = 0;
                int FPS_MAX_s = 60;
                int FPS_INIT_s = 0;    //initial frames per second
                JSlider sSpeed = new JSlider(JSlider.HORIZONTAL,FPS_MIN_s, FPS_MAX_s, FPS_INIT_s);
                sSpeed.setBorder(BorderFactory.createTitledBorder("Shape Speed"));
             ////////////////////////// // slider colors////////////////////////////////////////////////////
                int FPS_MIN_C = 0;
                int FPS_MAX_C = 250;
                int FPS_INIT_C = 0;  
                JSlider sliderR= new JSlider(JSlider.HORIZONTAL,FPS_MIN_C, FPS_MAX_C, FPS_INIT_C);
                sliderR.setBorder(BorderFactory.createTitledBorder("Red Channel"));
                JSlider sliderG= new JSlider(JSlider.HORIZONTAL,FPS_MIN_C, FPS_MAX_C, FPS_INIT_C);
                sliderG.setMajorTickSpacing(50);
                sliderG.setMinorTickSpacing(25);
                sliderG.setPaintTicks(true);
                sliderG.setPaintLabels(true);
                sliderG.setFont(font);
                sliderG.setBorder(BorderFactory.createTitledBorder("Green Channel"));
                JSlider sliderB= new JSlider(JSlider.HORIZONTAL,FPS_MIN_C, FPS_MAX_C, FPS_INIT_C);
                sliderB.setBorder(BorderFactory.createTitledBorder("Blue Channel"));
              //     spanel.add(sSpeed,BorderLayout.EAST);
                  frame.add(upPanel,BorderLayout.NORTH);
                  frame.add(leftPanel,BorderLayout.WEST);
                  bpnl = new ShapePanel(3000,3000);
                        System.out.println("panel width = "+bpnl.getWidth() +"  heigth = " + bpnl.getHeight());
                        bpnl.setFocusable(true);
                  upPanel.setBackground(Color.DARK_GRAY);
                  upPanel.setBorder(BorderFactory.createLineBorder(Color.white));
            frame.add(spanel,BorderLayout.SOUTH);       
            frame.add(bpnl, BorderLayout.CENTER);
            frame.setSize(width, height);
            frame.setVisible(true);               
               leftPanel.add(sliderR);
               leftPanel.add(sliderB);
               leftPanel.add(sliderG);
               leftPanel.add(sDimension,BorderLayout.WEST); 
                 System.out.println("panel width = "+bpnl.getWidth() +"  heigth = " + bpnl.getHeight());
              public static  int getPanelWidth()
                  System.out.println("panel width   "+bpnl.getWidth());
                  return bpnl.getWidth();
              public static  int getPanelHeigth()
                  System.out.println("Panel heigth  " +bpnl.getHeight());
                  return bpnl.getHeight();
              public static void main(String args[])
                  new MyFrame() {};
    package help;
    import java.awt.Cursor;
    import java.awt.Graphics;
    import javax.swing.JPanel;
    class ShapePanel extends JPanel  {
         private static final long serialVersionUID = 1L;
         private javax.swing.Timer animationTmr;
         private float heigth;
         private float width;
         private Cursor c;
         public ShapePanel(int w, int h) {
                    int W=w;
                    int H=h;
                    c = new Cursor (Cursor.CROSSHAIR_CURSOR);     //Change cursor to cross hair
                    this.setCursor (c); 
                    this.setPreferredSize(3000,3000);
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              g.fillRect(0, 0, this.getWidth(), this.getHeight());
        private void setPreferredSize(int i, int i0) {
        thanks

    sorry i hope this is better
    package help;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public abstract class MyFrame extends JFrame {
    private static final long serialVersionUID = 1L;
    int dr =1;
    int dy= 1;
    int Selection=0;
    int width = java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;  // screen width
    int height = java.awt.Toolkit.getDefaultToolkit().getScreenSize().height-100;     //screen higth
    private static ShapePanel bpnl;
    public MyFrame()
            JFrame frame=new JFrame();
            BorderLayout layout=new BorderLayout();
            frame.setLayout(layout);
            bpnl = new ShapePanel(3000,3000);
            System.out.println("panel width = "+bpnl.getWidth() +"  heigth = " + bpnl.getHeight());
            bpnl.setFocusable(true);
              frame.add(bpnl);
            frame.setSize(width, height);
               pack();
            frame.setVisible(true);               
    System.out.println("panel width = "+bpnl.getWidth() +"  heigth = " + bpnl.getHeight());
              public static  int getPanelWidth()
                  System.out.println("panel width   "+bpnl.getWidth());
                  return bpnl.getWidth();
              public static  int getPanelHeigth()
                  System.out.println("Panel heigth  " +bpnl.getHeight());
                  return bpnl.getHeight();
              public static void main(String args[])
                  new MyFrame() {};
    package help;
    import java.awt.Cursor;
    import java.awt.Graphics;
    import javax.swing.JPanel;
    class ShapePanel extends JPanel  {
         private static final long serialVersionUID = 1L;
         private Cursor c;
         public ShapePanel(int w, int h) {
                    int W=w;
                    int H=h;
                    c = new Cursor (Cursor.CROSSHAIR_CURSOR);     //Change cursor to cross hair
                    this.setCursor (c); 
                    this.setPreferredSize(3000,3000);
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              g.fillRect(0, 0, this.getWidth(), this.getHeight());
        private void setPreferredSize(int i, int i0) {
       

  • Problem with JPanel.updateUI()

    Hello,
    i have a problem with updateUI(), here's a simple example what's wrong. just compile and run the following piece of code and look what happens after 2 seconds: the left panel will be decrease its width after calling updateUI(), but why? is it a bug of updateUI() or is it my fault?
    import java.awt.*;
    import javax.swing.*;
    public class Test extends JPanel
            private JList m_list;
            private DefaultListModel m_listModel;
            private JPanel m_buttons;
            public static GridBagConstraints creategbc (int x, int y, int w, int h, int wx, int wy, int f)
                    GridBagConstraints gbc = new GridBagConstraints();
                    gbc.gridx = x;
                    gbc.gridy = y;
                    gbc.gridwidth = w;
                    gbc.gridheight = h;
                    gbc.weightx = wx;
                    gbc.weighty = wy;
                    gbc.fill = f;
                    gbc.insets = new Insets(5, 5, 5, 5); // kleinen Rahmen ziehen
                    return gbc;
            public Test ()
                    GridBagLayout gbl = new GridBagLayout();
                    setLayout(gbl);
                    GridBagConstraints gbc;
                    initButtons();
                    gbc = creategbc(0, 0, 1, 1, 20, 100, GridBagConstraints.NONE);
                    gbc.anchor = GridBagConstraints.NORTH;
                    gbl.setConstraints(m_buttons, gbc);
                    add(m_buttons);
                    initList();
                    JScrollPane sp = new JScrollPane(m_list);
                    gbc = creategbc(1, 0, 1, 1, 100, 100, GridBagConstraints.BOTH);
                    gbl.setConstraints(sp, gbc);
                    add(sp);
            public void addItem (String item)
                    m_listModel.addElement(item);
            public void initList ()
                    m_listModel = new DefaultListModel();
                    m_list = new JList(m_listModel);
            public void initButtons ()
                    m_buttons = new JPanel();
                    m_buttons.setLayout(new GridLayout(4, 1, 0, 20));
                    m_buttons.add(new JButton("Neu"));
                    m_buttons.add(new JButton("Bearbeiten"));
                    m_buttons.add(new JButton("L�schen"));
                    m_buttons.add(new JButton("Abfrage"));
            public static void main (String[] args)
                    JFrame f = new JFrame();
                    Test t = new Test();
                    f.setContentPane(t);
                    f.setSize(600, 450);
                    f.setVisible(true);
                    try
                            Thread.sleep(2000);
                    catch (Exception e)
                    t.addItem("Hallo");
                    t.updateUI();

    Hello,
    i have a problem with updateUI(), here's a simple
    example what's wrong. just compile and run the
    following piece of code and look what happens after 2
    seconds: the left panel will be decrease its width
    after calling updateUI(), but why? is it a bug of
    updateUI() or is it my fault?updateUI() its called when the L&F is changed, there is
    rarely a case when you need to call updateUI().
    Why do you call updateUI() if you remove the call to updateUI()
    everything will work OK.
    merry xmas

  • Problem with jpanel and revalidate()

    i have made a calendar. on click on jlabel you can switch month/year and there is the problem. for example when i switch from february to march and back again, then the panel don�t update. but why?
    i hope you understand what i mean.(I am german and can�t englisch)
    here is the code(i have mixed german in english in the code, i hope you understand even so.)
    package organizer.gui;
    import organizer.*;
    import java.text.SimpleDateFormat;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class Kalender extends JPanel {
    private Calendar calendar;
    private JPanel days;
    private JLabel monthLabel;
    private SimpleDateFormat monthFormat = new SimpleDateFormat("dd MMM yyyy");
    private TerminManager manger;
    public Kalender(TerminManager manager) {
       super();
       this.manger=manager;
       this.calendar=Calendar.getInstance();
       this.initializeJPanel();
       this.updatePanel();
    protected void updatePanel() {
       monthLabel.setText(monthFormat.format(calendar.getTime()));
       if(days!=null) {
         days.removeAll();
       }else {
         days = new JPanel(new GridLayout(0, 7));
       days.setOpaque(true);
       for (int i = 1; i <=7; i++) {
         int dayInt = ( (i + 1) == 8) ? 1 : i + 1;
         JLabel label = new JLabel();
         label.setHorizontalAlignment(JLabel.CENTER);
         if (dayInt == Calendar.SUNDAY) {
           label.setText("Son");
         else if (dayInt == Calendar.MONDAY) {
           label.setText("Mon");
         else if (dayInt == Calendar.TUESDAY) {
           label.setText("Die");
         else if (dayInt == Calendar.WEDNESDAY) {
           label.setText("Mit");
         else if (dayInt == Calendar.THURSDAY) {
           label.setText("Don");
         else if (dayInt == Calendar.FRIDAY) {
           label.setText("Fre");
         else if (dayInt == Calendar.SATURDAY) {
           label.setText("Sam");
         days.add(label);
       Calendar setupCalendar = (Calendar) calendar.clone();
       setupCalendar.set(Calendar.DAY_OF_MONTH, 1);
       int firstday = setupCalendar.get(Calendar.DAY_OF_WEEK);
       for (int i = 1; i < (firstday - 1); i++) {
         days.add(new JLabel(""));
       for (int i = 1; i <=setupCalendar.getActualMaximum(Calendar.DAY_OF_MONTH); i++) {
         int day = setupCalendar.get(Calendar.DAY_OF_MONTH);
         final Date d = setupCalendar.getTime();
         final JLabel label = new JLabel(String.valueOf(day));
         label.setOpaque(true);
         if(this.manger.isTerminAtDay(d)) {
           String s="<html><center>" + day + "<br>";
           if(this.manger.isBirthdayAtDay(d)) {
             s+="Geburtstag<br>";
           if(this.manger.isOtherTerminAtDay(d)) {
             s+="Termin";
           label.setText(s);
           label.addMouseListener(new MouseListener() {
              * mouseClicked
              * @param e MouseEvent
             public void mouseClicked(MouseEvent e) {
               Termin[] t = Kalender.this.manger.getTermineAtDay(d);
               if (t.length == 1) {
                 new TerminDialog(null, t[0]);
               else {
                 new TerminAuswahlDialog(null, t, d);
              * mouseEntered
              * @param e MouseEvent
             public void mouseEntered(MouseEvent e) {
              * mouseExited
              * @param e MouseEvent
             public void mouseExited(MouseEvent e) {
              * mousePressed
              * @param e MouseEvent
             public void mousePressed(MouseEvent e) {
              * mouseReleased
              * @param e MouseEvent
             public void mouseReleased(MouseEvent e) {
         final Color background=label.getBackground();
         final Color foreground=label.getForeground();
         label.setHorizontalAlignment(JLabel.CENTER);
         label.addMouseListener(new MouseAdapter() {
           public void mouseEntered(MouseEvent e) {
             label.setBackground(Color.BLUE);
             label.setForeground(Color.RED);
           public void mouseExited(MouseEvent e) {
             label.setBackground(background);
             label.setForeground(foreground);
         days.add(label);
         setupCalendar.roll(Calendar.DAY_OF_MONTH,true);
       this.add(days, BorderLayout.CENTER);
       this.revalidate();
    private JLabel createUpdateButton(final int field,final int amount) {
       final JLabel label = new JLabel();
       final Border selectedBorder = new EtchedBorder();
       final Border unselectedBorder = new EmptyBorder(selectedBorder
           .getBorderInsets(new JLabel()));
       label.setBorder(unselectedBorder);
       label.addMouseListener(new MouseAdapter() {
         public void mouseReleased(MouseEvent e) {
           calendar.add(field, amount);
           Kalender.this.updatePanel();
         public void mouseEntered(MouseEvent e) {
           label.setBorder(selectedBorder);
         public void mouseExited(MouseEvent e) {
           label.setBorder(unselectedBorder);
       return label;
    private void initializeJPanel() {
       JPanel header = new JPanel();
       JLabel label;
       label = this.createUpdateButton(Calendar.YEAR, -1);
       label.setText("<<");
       header.add(label);
       label = this.createUpdateButton(Calendar.MONTH, -1);
       label.setText("<");
       header.add(label);
       monthLabel=new JLabel("");
       header.add(monthLabel);
       label = this.createUpdateButton(Calendar.MONTH, 1);
       label.setText(">");
       header.add(label);
       label = this.createUpdateButton(Calendar.YEAR, 1);
       label.setText(">>");
       header.add(label);
       this.setLayout(new BorderLayout());
       this.add(header, BorderLayout.NORTH);
    }

    I got you code to compile and run and made a single change to get it to work; adding a call to repaint at the end of the updatePanel method.
            this.add(days, BorderLayout.CENTER);
            this.revalidate();
            repaint();
        }Whenever you change the size of a containers components or add/remove components you must ask the container to run through its component hierarchy and check the size requirements of all its children and lay them out again, ie, do a new layout. The JComponent method for this isrevalidate. If you are working in the AWT you must use the Component/(overridden in)Container method validate, sometimes preceded by a call to the invalidate method. Some people prefer the validate method over revalidate. These are methods used to update guis by asking for a renewed layout. For economy you can call one (sometimes with invalidate, but rarely) of these methods on the smallest component/container that includes all the containers needing the renewed layout, ie, keep the action as localized as possible.
    When the rendering of components has changed, things like colors, borders and text, we need to ask the components to repaint themselves. The easy way to do this is to call repaint on the gui. For economy you can call repaint on the smallest component that contains all the components needing repainting. Some classes like those in the JTextComponent group have their own internal repainting calls so they will repaint themselves when changes are made.
    In making guis, especially elaborate ones, it seems to take some playful experimentation to find out what is needed to get what you want. Sometimes it is a call to revalidate, sometimes a call to repaint, sometimes both. You just have to experiment.

  • Weird problem with jpanel vs jframe

    I'm using jmathplot.jar from JMathTools which lets me do 3d plotting. I used a JFrame to get some code to work and it worked fine. Here's the code that worked for a JFrame:
    public class View extends JFrame
        private Model myModel;
        private Plot3DPanel myPanel;
        // ... Components
        public View(Model m)
            myModel = m; 
            // ... Initialize components
            myPanel = new Plot3DPanel("SOUTH");
            myPanel.addGridPlot("Test",myModel.getXRange(),myModel.getYRange(),myModel.getZValues());
            setSize(600, 600);
            setContentPane(myPanel);
            setVisible(true);
    }Here's the class that starts everything:
    public class TestApplet extends JApplet
        public void init()
            //Execute a job on the event-dispatching thread; creating this applet's GUI.
            try
                SwingUtilities.invokeAndWait(new Runnable()
                    public void run()
                        createGUI();
            catch (Exception e)
                e.printStackTrace();
        private void createGUI()
            System.out.println("Creating GUI");
            Model model = new Model();
            View view = new View(model);
    }And here's the Model:
    public class Model
        private double[] myXRange,myYRange;
        private double[][] myZValues;
        public Model()
            createDataSet();
        public double[] getXRange()
            return myXRange;
        public double[] getYRange()
            return myYRange;
        public double[][] getZValues()
            return myZValues;
        private void createDataSet()
            myXRange = new double[10];
            myYRange = new double[10];
            myZValues = new double[10][10];
            for(double i=0;i<10;i++)
                for(double j=0;j<10;j++)
                    double x = i/10;
                    double y = j/10;
                    myXRange[(int) i] = x;
                    myYRange[(int) j] = y;
                    myZValues[(int) i][(int) j]= Math.cos(x*Math.PI)*Math.sin(y*Math.PI);
    }However, as you can see, my main class is a JApplet because ideally I want View to be a JPanel that I add to the applet. All I did was change "extends JFrame" to "extends JApplet" and changed:
    setSize(600, 600);
    setContentPane(myPanel);
    setVisible(true);to
    this.add(myPanel);and added these two lines to createGUI():
            view.setOpaque(true);
            setContentPane(view);When I run it however, it appears really really small. It seems like its drawing the panel to the default size of the applet viewer and doesn't resize it when I resize the applet. I don't know if it's a problem with the library or if I'm doing something wrong in my applet.

    However, as you can see, my main class is a JApplet because ideally I want View to be a JPanel that I add to the applet. All I did was change "extends JFrame" to "extends JApplet" and (...)What do you mean? View extends JApplet? I thought View was meant to extend JPanel in the end...
    When I run it however, it appears really really small. It seems like its drawing the panel to the default size of the applet viewer and doesn't resize it when I resize the applet.Or, the panel has its preferred size, and this latter is too small. Actually the panel has the size its container's layout manager awards it (taking or not the panel's preferred, minimum, and maximum sizes into account). See the tutorial on [layout managers|http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html] .
    In particular, this line adds the myPanel to a parent panel (presumably, it is in class View which extends JPanel, whose default layout is FlowLayout):
    this.add(myPanel);
    I don't know if it's a problem with the library or if I'm doing something wrong in my applet.Likely not (presumably the library interfers only in how it computes the Plot3DPanel's preferred size). There's an easy way to tell: try to layout correctly a custom JPanel of yours, containing only e.g. a button with an icon. Once you understand the basics of layout management, revisit the example using ther 3rd-party library.
    N.B.: there are a lot of "likely" and "presumably" in my reply: in order to avoid hardly-educated guesses especially on what is or isn't in your actual code, you'd better provide an SSCCE , which means reproducing the problem without the 3rd party library.

  • Display problem in JPanel

    Hi,
    I am facing a probelm of displaying an image in JPanel in the following code. I want to display "displayImage" in "CenterPanel as shown in the program. The problem I am facing is that the image displyed on this panel is momentairly and then it disappears. Can anyone help me with this out??
    <Code>
    //Author @ Jaikishan Jalan;
    //Date @ September 29,2005;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.Graphics.*;
    import java.awt.image.*;
    import java.awt.image.BufferedImage;
    import javax.imageio.*;
    import java.io.*;
    import javax.swing.JOptionPane;
    import java.util.Random;
    //This is the main class to achieve the desired objective;
    public class Task3 extends JFrame{
    JFrame frame;
         public Task3(){
         frame = new JFrame("Cryptography Demo");
         //mainpanel is the panel designed to generate the layout for the main frame;
    frame.setContentPane(new mainpanel(this));
         frame.setSize(1000,700);
    frame.setVisible(true);
         frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
    public static void main(String args[]){
         new Task3();
    //This class corresponds to mainpanel class;
    //It contains a Label named as string, a textfield named as stringp and a button named as submit;
    //Their name clearly indicates what are they used for;
    class mainpanel extends JPanel implements ActionListener{
    JFrame temp;
    JTextField stringp;
    JPanel centerPanel;
    protected static final int b = Color.black.getRGB();
    protected static final int w = Color.white.getRGB();
    static int pixels[];
    int string_length=0;
    Image displayImage= null;
    RenderedImage originalimg=null;
    Image img1=null,img2=null,img3=null;
    public mainpanel(JFrame x){ // setLayout(new BorderLayout());
              temp = x ;
              setLayout(new BorderLayout());
              JPanel southPanel = new JPanel();
              southPanel.setBackground(Color.GRAY);
              JPanel eastPanel=new JPanel();
              centerPanel=new JPanel();
              centerPanel.setBackground(Color.lightGray);
              eastPanel.setBackground(Color.GRAY);
              eastPanel.setLayout(new BoxLayout(eastPanel, BoxLayout.Y_AXIS));
              eastPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              JLabel string = new JLabel("String : ");
    stringp = new JTextField("Enter String",14);
    JButton submit = new JButton("Submit");
         JButton close = new JButton("Close Window");
         JButton share_1 = new JButton("Share 1");
              JButton share_2 = new JButton("Share 2");
              JButton original = new JButton("Original Image");
              JButton combine = new JButton("Combine Share");
    southPanel.add(string);
    southPanel.add(stringp);
    southPanel.add(submit);
         southPanel.add(close);
              eastPanel.add(Box.createVerticalGlue());
              eastPanel.add(original);
              eastPanel.add(Box.createRigidArea(new Dimension(0,10)));
              eastPanel.add(share_1);
              eastPanel.add(Box.createRigidArea(new Dimension(0,10)));
              eastPanel.add(share_2);
              eastPanel.add(Box.createRigidArea(new Dimension(0,10)));
              eastPanel.add(combine);
              eastPanel.add(Box.createVerticalGlue());
              eastPanel.setBorder(BorderFactory.createEtchedBorder());
              southPanel.setBorder(BorderFactory.createEtchedBorder());
              add(southPanel, BorderLayout.SOUTH);
              add(eastPanel, BorderLayout.EAST);
              centerPanel.setBorder(BorderFactory.createEtchedBorder());
         add(centerPanel, BorderLayout.CENTER);
    stringp.addActionListener(this);     
         submit.addActionListener(this);
         close.addActionListener(this);
         original.addActionListener(this);
              share_1.addActionListener(this);
              share_2.addActionListener(this);
              combine.addActionListener(this);
         setVisible(true);
              repaint();
    public void actionPerformed(ActionEvent e) {
    String str= e.getActionCommand();
         string_length = stringp.getText().length();
         if(str.equals("Submit")){
              if((string_length<4)|(string_length>14))
              {JOptionPane.showMessageDialog(null,"String size should be in between 4 and 14","Error",JOptionPane.OK_OPTION); }
              else
                   JOptionPane.showConfirmDialog(null,"Are you sure you want to submit","Confirm",JOptionPane.YES_NO_OPTION);
              if(JOptionPane.YES_OPTION==0){
                   String name = new String(stringp.getText());
                   Canvas cn = new Canvas();
              originalimg= new BufferedImage(256,256,BufferedImage.TYPE_BYTE_GRAY);
    Graphics cg = ((BufferedImage)originalimg).getGraphics();
              cg.setColor(Color.WHITE);
              cg.fillRect(0,0,256,256);
              cg.setColor(Color.BLACK);
              cg.setFont(new Font("",Font.BOLD,25));
              FontMetrics fm = cg.getFontMetrics();
              int x = (256- fm.stringWidth(name))/2;
              int y = (fm.getAscent()+(256-(fm.getAscent()+fm.getDescent()))/2);
    cg.drawString (name,x,y);
                        //Some algorthim which produces img1, img2 , img3 from "originalimg"
                             img1 = createImage(new MemoryImageSource(column*2,row,block1,0,column*2));
                             img2 = createImage(new MemoryImageSource(column*2,row,block2,0,column*2));
                             for(int t=0;t<row*column*2;t++){
                             if((block1[t] == w) & (block2[t] ==w))
                                  comb[t] = w;
                                  else comb[t] = b;
                             img3 = createImage(new MemoryImageSource(column*2,row,comb,0,column*2));
                   displayImage = (Image)originalimg;
                   repaint();     
         else if(str.equals("Close Window")){
              System.exit(0);}
         else if(str.equals("Original Image"))
         { displayImage = (Image)originalimg;
              repaint();
         else if(str.equals("Share 1")){
              displayImage = img1;
              repaint();
         else if(str.equals("Share 2")){
              displayImage = img2;
              repaint();
         else if(str.equals("Combine Share")){
              displayImage = img3;
              repaint();
    public Insets getInsets(){return new Insets(10,10,10,10);}
    public void paint(Graphics g){
         super.paint(g);
         if(displayImage != null) {
              try{ MediaTracker m = new MediaTracker(this);
                        m.addImage(displayImage,0);
                        m.waitForID(0);
              centerPanel.getGraphics().drawImage(displayImage,(centerPanel.getWidth()-displayImage.getWidth(null))/2,(centerPanel.getHeight()-displayImage.getHeight(null))/2,this);
         }catch(InterruptedException ie){System.out.println(ie);};
    }

    Do you want me to use Image Icon componenet to display the image in a JPanel? ImageIcon is not a component and cannot be directly added to a JPanel.
    I want you to:
    a) read the tutorial
    b) run the examples
    c) understand how the examples work
    d) use the information from above and make the changes to your code.

  • 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.

  • 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

Maybe you are looking for