How to dispose a JPanel ?

Hi,
i want to know, how to dispose or close the JPanel from the application as well as from the memory?.
In Simple,
for JFrame or JInternalFrame we have .dispose(), which will remove the component from view as well as from allocated memory.
What is the equivalant method for that in JPanel.
Thanks in advance.
** Subbu **

yeah, u r right.
i want to remove the JPanel from the JInternalFrame which is inside the JFrame.
well, whenever i am clicking the MenuItems i will open a new JPanel in the Internal frame.
In order to close that panel and open a new one , i made that as JPanel.setVisible(false) and creating a new instance for the second JPanel.
When the panel count is increasing, i should make all the opened panels as setVisible as false. i don't want to do like this.
i don't want to hide that JPanel. I want that to be removed entirely from the application.
Whenever i need that again, i will create a fresh instance for that.
can u able understand my problem?
--Subbu                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Similar Messages

  • How to make a JPanel selectable

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

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

  • How to dynamically resize JPanel at runtime??

    Hello Sir:
    I met a problem, I need to resize a small JPanel called panel within a main Control JPanel (with null Layout) if I click the mouse then I can Drag and Resize this small JPanel Border to the size I need at runtime, I know I can use panel.setSize() or panel.setPreferredSize() methods at design time,
    But I have no idea how to do it even I search this famous fourm,
    How to dynamically resize JPanel at runtime??
    Can any guru throw some light or good example??
    Thanks

    Why are you using a null layout? Wouldn't having a layout manager help you in this situation?

  • How to place a JPanel at the center of another JPanel?

    Can anyone tell me how to place a JPanel inside another JPanel? The first JPanel consists of three JPanels each consisting of a label&textfield and are placed using BoxLayout. The second JPanel is a big blank screen. So, i would like to put the first JPanel at the center of second JPanel(horizontally & vertically). The problem is that i don't have any other component. So,if i try to use FlowLayout, i am able to put it at the center(horizontally, not vertically) only on the top edge. I tried to use BoxLayout. But, i couldn't(as i don't have any other elements). I tried to create some blank elements. But, they are messing up the elements of my JPanel. Any cluesssssssss??????????

    import java.awt.*;
    import javax.swing.*;
    public class CenteredLayout
        private JPanel getPanel()
            GridBagLayout gridbag = new GridBagLayout();
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            JPanel p = new JPanel(gridbag);
            addComponents(new JLabel("label 1"), new JTextField(8), p, gbc);
            addComponents(new JLabel("label 2"), new JTextField(8), p, gbc);
            addComponents(new JLabel("label 3"), new JTextField(8), p, gbc);
            JPanel panel = new JPanel(gridbag);
            panel.setBackground(Color.pink);
            gbc.anchor = GridBagConstraints.CENTER;
            gbc.insets = new Insets(0,0,0,0);
            panel.add(p, gbc);
            return panel;
        private void addComponents(Component c1, Component c2, Container c,
                                   GridBagConstraints gbc)
            gbc.anchor = GridBagConstraints.EAST;
            gbc.gridwidth = GridBagConstraints.RELATIVE;
            c.add(c1, gbc);
            gbc.anchor = GridBagConstraints.WEST;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            c.add(c2, gbc);
        public static void main(String[] args)
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new CenteredLayout().getPanel());
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • How to repaint a JPanel in bouncing balls game?

    I want to repaint the canvas panel in this bouncing balls game, but i do something wrong i don't know what, and the JPanel doesn't repaint?
    The first class defines a BALL as a THREAD
    If anyone knows how to correct the code please to write....
    package fuck;
    //THE FIRST CLASS
    class CollideBall extends Thread{
        int width, height;
        public static final int diameter=15;
        //coordinates and value of increment
        double x, y, xinc, yinc, coll_x, coll_y;
        boolean collide;
        Color color;
        Rectangle r;
        bold BouncingBalls balls; //A REFERENCE TO SECOND CLASS
        //the constructor
        public CollideBall(int w, int h, int x, int y, double xinc, double yinc, Color c, BouncingBalls balls) {
            width=w;
            height=h;
            this.x=x;
            this.y=y;
            this.xinc=xinc;
            this.yinc=yinc;
            this.balls=balls;
            color=c;
            r=new Rectangle(150,80,130,90);
        public double getCenterX() {return x+diameter/2;}
        public double getCenterY() {return y+diameter/2;}
        public void move() {
            if (collide) {
            x+=xinc;
            y+=yinc;
            //when the ball bumps against a boundary, it bounces off
            //bounce off the obstacle
        public void hit(CollideBall b) {
            if(!collide) {
                coll_x=b.getCenterX();
                coll_y=b.getCenterY();
                collide=true;
        public void paint(Graphics gr) {
            Graphics g = gr;
            g.setColor(color);
            //the coordinates in fillOval have to be int, so we cast
            //explicitly from double to int
            g.fillOval((int)x,(int)y,diameter,diameter);
            g.setColor(Color.white);
            g.drawArc((int)x,(int)y,diameter,diameter,45,180);
            g.setColor(Color.darkGray);
            g.drawArc((int)x,(int)y,diameter,diameter,225,180);
            g.dispose(); ////////
        ///// Here is the buggy code/////
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.canvas.repaint();
    //THE SECOND CLASS
    public class BouncingBalls extends JFrame{
        public Graphics gBuffer;
        public BufferedImage buffer;
        private Obstacle o;
        private List<CollideBall> balls=new ArrayList();
        private static final int SPEED_MIN = 0;
        private static final int SPEED_MAX = 15;
        private static final int SPEED_INIT = 3;
        private static final int INIT_X = 30;
        private static final int INIT_Y = 30;
        private JSlider slider;
        private ChangeListener listener;
        private MouseListener mlistener;
        private int speedToSet = SPEED_INIT;
        public JPanel canvas;
        private JPanel p;
        public BouncingBalls() {
            super("fuck");
            setSize(800, 600);
            p = new JPanel();
            Container contentPane = getContentPane();
            final BouncingBalls xxxx=this;
            o=new Obstacle(150,80,130,90);
            buffer=new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_RGB);
            gBuffer=buffer.getGraphics();
            //JPanel canvas start
            final JPanel canvas = new JPanel() {
                final int w=getSize().width-5;
                final int h=getSize().height-5;
                @Override
                public void update(Graphics g)
                   paintComponent(g);
                @Override
                public void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    gBuffer.setColor(Color.ORANGE);
                    gBuffer.fillRect(0,0,getSize().width,getSize().height);
                    gBuffer.draw3DRect(5,5,getSize().width-10,getSize().height-10,false);
                    //paint the obstacle rectangle
                    o.paint(gBuffer);
                    g.drawImage(buffer,0,0, null);
                    //gBuffer.dispose();
            };//JPanel canvas end
            addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            addButton(p, "Start", new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    CollideBall b = new CollideBall(canvas.getSize().width,canvas.getSize().height
                            ,INIT_X,INIT_Y,speedToSet,speedToSet,Color.BLUE,xxxx);
                    balls.add(b);
                    b.start();
            contentPane.add(canvas, "Center");
            contentPane.add(p, "South");
        public void addButton(Container c, String title, ActionListener a) {
            JButton b = new JButton(title);
            c.add(b);
            b.addActionListener(a);
        public boolean collide(CollideBall b1, CollideBall b2) {
            double wx=b1.getCenterX()-b2.getCenterX();
            double wy=b1.getCenterY()-b2.getCenterY();
            //we calculate the distance between the centers two
            //colliding balls (theorem of Pythagoras)
            double distance=Math.sqrt(wx*wx+wy*wy);
            if(distance<b1.diameter)
                return true;
            return false;
        synchronized void repairCollisions(CollideBall a) {
            for (CollideBall x:balls) if (x!=a && collide(x,a)) {
                x.hit(a);
                a.hit(x);
        public static void main(String[] args) {
            JFrame frame = new BouncingBalls();
            frame.setVisible(true);
    }  And when i press start button:
    Exception in thread "Thread-2" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-3" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-4" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    and line 153 is: balls.canvas.repaint(); in Method run() in First class.
    Please help.

    public RepaintManager manager;
    public BouncingBalls() {
            manager = new RepaintManager();
            manager.addDirtyRegion(canvas, 0, 0,canvas.getSize().width, canvas.getSize().height);
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.manager.paintDirtyRegions(); //////// line 153
       but when push start:
    Exception in thread "Thread-2" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-3" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at fuck.CollideBall.run(CollideBall.java:153)
    i'm newbie with Concurrency and i cant handle this exceptons.
    Is this the right way to do repaint?

  • How to make a JPanel transparent? Not able to do it with setOpaque(false)

    Hi all,
    I am writing a code to play a video and then draw some lines on the video. For that first I am playing the video on a visual component and I am trying to overlap a JPanel for drawing the lines. I am able to overlap the JPanel but I am not able to make it transparent. So I am able to draw lines but not able to see the video. So, I want to make the JPanel transparent so that I can see the video also... I am posting my code below
    import javax.media.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import java.lang.Math;
    import javax.media.control.FramePositioningControl;
    import javax.media.protocol.*;
    import javax.swing.*;
    class MPEGPlayer2 extends JFrame implements ActionListener,ControllerListener,ItemListener
         Player player;
         Component vc, cc;
         boolean first = true, loop = false;
         String currentDirectory;
         int mediatime;
         BufferedWriter out;
         FileWriter fos;
         String filename = "";
         Object waitSync = new Object();
         boolean stateTransitionOK = true;
         JButton bn = new JButton("DrawLine");
         MPEGPlayer2 (String title)
              super (title);
              addWindowListener(new WindowAdapter ()
                   public void windowClosing (WindowEvent e)
                            dispose ();
                            public void windowClosed (WindowEvent e)
                         if (player != null)
                         player.close ();
                         System.exit (0);
              Menu m = new Menu ("File");
              MenuItem mi = new MenuItem ("Open...");
              mi.addActionListener (this);
              m.add (mi);
              m.addSeparator ();
              CheckboxMenuItem cbmi = new CheckboxMenuItem ("Loop", false);
              cbmi.addItemListener (this);
              m.add (cbmi);
              m.addSeparator ();
              mi = new MenuItem ("Exit");
              mi.addActionListener (this);
              m.add (mi);
              MenuBar mb = new MenuBar ();
              mb.add (m);
              setMenuBar (mb);
              setSize (500, 500);
              setVisible (true);
         public void actionPerformed (ActionEvent ae)
                        FileDialog fd = new FileDialog (this, "Open File",FileDialog.LOAD);
                        fd.setDirectory (currentDirectory);
                        fd.show ();
                        if (fd.getFile () == null)
                        return;
                        currentDirectory = fd.getDirectory ();
                        try
                             player = Manager.createPlayer (new MediaLocator("file:" +fd.getDirectory () +fd.getFile ()));
                             filename = fd.getFile();
                        catch (Exception exe)
                             System.out.println(exe);
                        if (player == null)
                             System.out.println ("Trouble creating a player.");
                             return;
                        setTitle (fd.getFile ());
                        player.addControllerListener (this);
                        player.prefetch ();
         }// end of action performed
         public void controllerUpdate (ControllerEvent e)
              if (e instanceof EndOfMediaEvent)
                   if (loop)
                        player.setMediaTime (new Time (0));
                        player.start ();
                   return;
              if (e instanceof PrefetchCompleteEvent)
                   player.start ();
                   return;
              if (e instanceof RealizeCompleteEvent)
                   vc = player.getVisualComponent ();
                   if (vc != null)
                        add (vc);
                   cc = player.getControlPanelComponent ();
                   if (cc != null)
                        add (cc, BorderLayout.SOUTH);
                   add(new MyPanel());
                   pack ();
         public void itemStateChanged(ItemEvent ee)
         public static void main (String [] args)
              MPEGPlayer2 mp = new MPEGPlayer2 ("Media Player 2.0");
              System.out.println("111111");
    class MyPanel extends JPanel
         int i=0,j;
         public int xc[]= new int[100];
         public int yc[]= new int[100];
         int a,b,c,d;
         public MyPanel()
              setOpaque(false);
              setBorder(BorderFactory.createLineBorder(Color.black));
              JButton bn = new JButton("DrawLine");
              this.add(bn);
              bn.addActionListener(actionListener);
              setBackground(Color.CYAN);
              addMouseListener(new MouseAdapter()
                             public void mouseClicked(MouseEvent e)
                   saveCoordinates(e.getX(),e.getY());
         ActionListener actionListener = new ActionListener()
              public void actionPerformed(ActionEvent aae)
                        repaint();
         public void saveCoordinates(int x, int y)
                    System.out.println("x-coordinate="+x);
                    System.out.println("y-coordinate="+y);
                    xc=x;
              yc[i]=y;
              System.out.println("i="+i);
              i=i+1;
         public Dimension getPreferredSize()
    return new Dimension(500,500);
         public void paintComponent(Graphics g)
    super.paintComponent(g);
              Graphics2D g2D = (Graphics2D)g;
              //g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
              g2D.setColor(Color.GREEN);
              for (j=0;j<i;j=j+2)
                   g2D.drawLine(xc[j],yc[j],xc[j+1],yc[j+1]);

    camickr wrote:
    "How to Use Layered Panes"
    http://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.html
    Add your video component to one layer and your non-opaque panel to another layer.Did you try that with JMF? It does not work for me. As I said, the movie seems to draw itself always on top!

  • How to draw a JPanel in an offscreen image

    I am still working on painting a JPanel on an offline image
    I found the following rules :
    - JPanel.setBounds shall be called
    - the JPanel does not redraw an offline image, on should explicitly override paint()
    to paint the children components
    - the Children components do not pain, except if setBounds is called for each of them
    Still with these rules I do not master component placement on the screen. Something important is missing. Does somebody know what is the reason for using setBounds ?
    sample code :
    private static final int width=512;
    private static final int height=512;
    offScreenJPanel p;
    FlowLayout l=new FlowLayout();
    JButton b=new JButton("Click");
    JLabel t=new JLabel("Hello");
    p=new offScreenJPanel();
    p.setLayout(l);
    p.setPreferredSize(new Dimension(width,height));
    p.setMinimumSize(new Dimension(width,height));
    p.setMaximumSize(new Dimension(width,height));
    p.setBounds(0,0,width,height);
    b.setPreferredSize(new Dimension(40,20));
    t.setPreferredSize(new Dimension(60,20));
    p.add(t);
    p.add(b);
    image = new java.awt.image.BufferedImage(width, height,
    java.awt.image.BufferedImage.
    TYPE_INT_RGB);
    Graphics2D g= image.createGraphics();
    // later on
    p.paint(g);
    paint method of offScreenPanel :
    public class offScreenJPanel extends JPanel {
    public void paint(Graphics g) {
    super.paint(g);
    Component[] components = getComponents();
    for (int i = 0; i < components.length; i++) {
    JComponent comp=(JComponent) components;
    comp.setBounds(0,0,512,512);
    components[i].paint(g);

    Unfortunately using pack doesn't work, or I didn't use it the right way.
    I made a test case, eliminated anything not related to the problem (Java3D, applet ...). In the
    test case if you go to the line marked "// CHANGE HERE" and uncomment the jf.show(), you have
    an image generated in c:\tmp under the name image1.png with the window contents okay.
    If you replace show by pack you get a black image. It seems there still something.
    simplified sample code :[b]
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import com.sun.j3d.utils.applet.*;
    import com.sun.j3d.utils.image.*;
    import com.sun.j3d.utils.universe.*;
    import java.io.*;
    import java.awt.image.*;
    import javax.imageio.*;
    public class test {
    private static final int width=512;
    private static final int height=512;
    public test() {
    JPanel p;
    BorderLayout lay=new BorderLayout();
    java.awt.image.BufferedImage image;
    // add a JPanel with a label and a button
    p=new JPanel(lay);
    p.setPreferredSize(new Dimension(width,height));
    JLabel t=new JLabel("Hello");
    t.setPreferredSize(new Dimension(60,20));
    p.add(t,BorderLayout.NORTH);
    p.setDebugGraphicsOptions(DebugGraphics.LOG_OPTION );
    // show the panel for debug
    JFrame jf=new JFrame();
    jf.setSize(new Dimension(width,height));
    jf.getContentPane().add(p);
    [b]
    // CHANGE HERE->
    jf.pack();
    //jf.show();
    // create an off screen image
    image = new java.awt.image.BufferedImage(width, height,
    java.awt.image.BufferedImage.TYPE_INT_RGB);
    // paint JPanel on off screen image
    Graphics2D g= image.createGraphics();
    g.setClip(jf.getBounds());
    System.err.println("BEFORE PAINT");
    jf.paint(g);
    System.err.println("AFTER PAINT");
    // write the offscreen image on disk for debug purposes
    File outputFile = new File("c:\\tmp\\image1.png");
    try {
    ImageIO.write(image, "PNG", outputFile);
    } catch (Exception e) {
    System.err.println(e.getMessage());
    g.dispose();
    jf.dispose();
    public static void main(String[] args) {
    test t=new test();
    }

  • How to update a JPanel in a JApplet

    Hi All,
    I'm trying to make my own sudoku JApplet. JApplet uses a BorderLayout() adding the sudoku Puzzle in the center, JButtons for New Games in a JPanel in the west and a GridLayout(3,3) to select the number to put in the puzzle in the east.
    The problem is: how can i update the sudoku puzzle in the center by clicking the "new game" JButton in the west?
    I use JButtons to represent numbers in the puzzle. this is how i create the JButton and set its ActionListener().
         public static JButton casella(String[] casella) {
              final JButton b = new JButton(casella[0]);
              b.setFont(new Font("SansSerif",Font.BOLD,33));
              if(casella[3].equals("1"))
                   b.setBorder(BorderFactory.createLineBorder(Color.orange));
              if(casella[3].equals("2"))
                   b.setBorder(BorderFactory.createLineBorder(Color.red));
              else
                   b.setBorder(BorderFactory.createLineBorder(Color.black));
              b.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        if(Sudoku.NUMERO_CORRENTE>=0)
                             b.setText(String.valueOf(Sudoku.NUMERO_CORRENTE));
                        else
                             b.setText("_");
              return b;
         }this is the main class:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Sudoku extends JApplet {
         static String[][][] MATRICE = MatriceCompleta.sudoku().getArrayMatrice();
         static JPanel PANNELLO_NUMERICO = OggettiGrafici.pannelloNumerico();
         static JPanel PANNELLO_EAST = new JPanel(new GridLayout(3,1));
         static JPanel PANNELLO_WEST = new JPanel(new GridLayout(6,1));
         static JPanel PANNELLO_CASELLE = new JPanel(new GridLayout(3,3));
         static JPanel PANNELLO = new JPanel(new BorderLayout());
         static int POSIZIONE_CASELLA_X = 0;
         static int POSIZIONE_CASELLA_Y = 0;
         static int NUMERO_CORRENTE = 0;
         static JLabel LABEL_NUMERO_CORRENTE = new JLabel(String.valueOf(NUMERO_CORRENTE), JLabel.CENTER);
         static JLabel LABEL_PARTITA = new JLabel("",JLabel.CENTER);
         static JLabel LABEL_NUOVA_PARTITA = new JLabel("NUOVA PARTITA",JLabel.CENTER);
         static JButton FACILE = new JButton("Livello Facile");
         static JButton NORMALE = new JButton("Livello Medio");
         static JButton DIFFICILE = new JButton("Livello Difficile");
         static JButton CONTROLLA_ERRORI = new JButton("Controlla Errori");
         static JButton CANCELLA_NUMERO = new JButton("Cancella Numero");
         static String DIFFICOLTA = "NORMALE";
         static int i, j, k;
         public void init() {
              String[][][][] divisaInPannelli = ComandiUtili.divisioneInPannelli(MATRICE);
              JPanel p0 = new JPanel(new GridBagLayout());
              JPanel p1 = new JPanel(new GridBagLayout());
              JPanel p2 = new JPanel(new GridBagLayout());
              JPanel p3 = new JPanel(new GridBagLayout());
              JPanel p4 = new JPanel(new GridBagLayout());
              JPanel p5 = new JPanel(new GridBagLayout());
              JPanel p6 = new JPanel(new GridBagLayout());
              JPanel p7 = new JPanel(new GridBagLayout());
              JPanel p8 = new JPanel(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.fill = GridBagConstraints.BOTH;
                    // creating the sudoku puzzle panel using JButtons
              for(i=0;i<9;i++) {
                   for(j=0;j<3;j++) {
                        for(k=0;k<3;k++) {
                             JButton b = OggettiGrafici.casella(divisaInPannelli[i][k][j]);
                             c.gridx = j;
                             c.gridy = k;
                             c.ipadx = 42;
                             c.ipady = 12;
                             if(i==0)
                                  p0.add(b,c);
                             else if(i==1)
                                  p1.add(b,c);
                             else if(i==2)
                                  p2.add(b,c);
                             else if(i==3)
                                  p3.add(b,c);
                             else if(i==4)
                                  p4.add(b,c);
                             else if(i==5)
                                  p5.add(b,c);
                             else if(i==6)
                                  p6.add(b,c);
                             else if(i==7)
                                  p7.add(b,c);
                             else if(i==8)
                                  p8.add(b,c);
              PANNELLO_CASELLE.add(p0);
              PANNELLO_CASELLE.add(p1);
              PANNELLO_CASELLE.add(p2);
              PANNELLO_CASELLE.add(p3);
              PANNELLO_CASELLE.add(p4);
              PANNELLO_CASELLE.add(p5);
              PANNELLO_CASELLE.add(p6);
              PANNELLO_CASELLE.add(p7);
              PANNELLO_CASELLE.add(p8);
              PANNELLO_EAST.add(PANNELLO_NUMERICO);
              PANNELLO_EAST.add(LABEL_NUMERO_CORRENTE);
              PANNELLO_EAST.add(LABEL_PARTITA);
              PANNELLO_WEST.add(LABEL_NUOVA_PARTITA);
              PANNELLO_WEST.add(FACILE);
              PANNELLO_WEST.add(NORMALE);
              PANNELLO_WEST.add(DIFFICILE);
              PANNELLO_WEST.add(CONTROLLA_ERRORI);
              PANNELLO_WEST.add(CANCELLA_NUMERO);
              PANNELLO.add(PANNELLO_CASELLE, BorderLayout.CENTER);
              PANNELLO.add(PANNELLO_EAST, BorderLayout.EAST);
              PANNELLO.add(PANNELLO_WEST, BorderLayout.WEST);
              add(PANNELLO);
         public void paint(Graphics g) {
              super.paint(g);
    }How can i update the sudoku puzzle (JPanel with 9x9 JButtons) by clicking on a "new game" JButton?
    Thank You very much in advance!

    Hi SD,
    How are you drawing the image on the JPanel?
    Are you using JLabel with image and adding it to Panel or using
    drawImage to get the image on the panel (Only jpeg and gif formats are supported here).
    DrawImage should automatically refresh, if not call repaint().
    That should refresh the Screen.
    Regards
    Chandra Mohan

  • How to put a JPanel in a JTable

    I have been having problems with using a JPanel in each cell in a column of a JTable. I have a class "myPanel" which extends JPanel and has an overridden paint() function. In each row I want the "myPanel" to be displayed in the cell.
    I've read all the documentation(that I could find online), and have searched for a while, but have not found the right way to do this.
    I currently have defined myPanel like this:
    class myPanel extends JPanel implements TableCellRenderer{
    public Component getTableCellRendererComponent( ... ) {
    repaint();
    public void paint(Graphics g) { ... }
    So, In my paint function I am not sure which cell(in the table) needs to be painted, but in the getTableCellRendererComponent, I know the cell to be rendered but I can't actually paint anything(I dont have a Graphics object to paint on).
    SO either I get my graphics painted into every cell in the column identically, or I don't see anything in the cells. How do I paint differently in different cells.
    Should I be using the object passed into getTableCellRendererComponent directly?
    And I don't think there is a default renderer for a panel which would display the panel.
    Any hints would be wonderful, as I can't get this to work.

    You should use your myPanel with the params row and column as if the panel in that row and that column is the one to paint and return it from the method getCellRendererComponent, like in this code.
    public Component getTableCellRendererComponent(...){
    //....set the properties of your panel/CellRenderer as needed
    //for displaiing the cell located in the row and column you get as //parameters,
    //even adding or removing buttons or other stuffs from your panel
    return this;
    // you return the CEllRenderer itself !!! The table will do the painting work !!
    That's it !!!
    Do not use paint or repaint, you don't need it !!!
    Bye Massimo

  • How to make a JPanel containing buttons  take up the width of the window?

    I'm creating a GUI and I have a button group that I want to be the width of the window. I have another JPanel on the same window that doesn't have a button group in it and it takes up the width of the window. I don't think I'm doing anything differently creating the two, but I need consistency.
    The best way I can explain this is with code, so I created an example of what I am doing here:
    import java.awt.*;
    import javax.swing.*;
    public class test extends JFrame {
         public test() {
              JPanel win = new JPanel();
              JPanel buttonsPanel = new JPanel();
              JPanel statusPanel = new JPanel();
              win.setLayout(new BoxLayout(win, BoxLayout.Y_AXIS));
              buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.Y_AXIS));
              statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.Y_AXIS));
    //          createRadioButtonsPanel
              ButtonGroup buttons = new ButtonGroup();
              JRadioButton currentMap = new JRadioButton("option1", true);
              JRadioButton newMap = new JRadioButton("option2");
              JRadioButton noMap = new JRadioButton("option3");
              buttons.add(currentMap);
              buttons.add(newMap);
              buttons.add(noMap);
              buttonsPanel.add(currentMap);
              buttonsPanel.add(newMap);
              buttonsPanel.add(noMap);
              buttonsPanel.setBorder(
                        BorderFactory.createTitledBorder("Create: "));
    //           createStatusPanel
              JLabel statusLabel = new JLabel("Loading...");
              statusLabel.setBorder(BorderFactory.createLoweredBevelBorder());
              statusLabel.setPreferredSize(new Dimension(400,20));
              statusLabel.setMinimumSize(new Dimension(400,20));
              statusLabel.setMaximumSize(new Dimension(400,20));
              statusPanel.add(statusLabel);
              JPanel statusButtons = new JPanel(new FlowLayout(FlowLayout.RIGHT));
              JButton pauseSearch = new JButton("Pause");
              JButton cancelSearch = new JButton("Cancel");
              statusButtons.add(pauseSearch);
              statusButtons.add(cancelSearch);
              statusPanel.add(statusButtons);
              statusPanel.setBorder(BorderFactory.createTitledBorder("Status: "));
              win.add(buttonsPanel);
              win.add(statusPanel);
              getContentPane().add(win);
              pack();
              setVisible(true);
         public static void main(String args[]) {
              test s = new test();
    }When I compile and run this class I get this window:
    http://img136.imageshack.us/img136/1538/exampleek5.png
    You see how on the bottom, "Status" JPanel takes up the entire width of the window? When the window is resized, the border is also resized. I would love to have the top "Create" JPanel have the same behavior. How do I do this?
    Thanks in advance!

    It can get confusing when using the BoxLayout. The box layout takes into consideration the X alignment of the components as well as the minimum and maximum lengths.
    So I suggest you read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/layout/box.html]How to Use Box Layout for examples and explanations on how these values are used in the layout process.
    It may be easier to use a BorderLayout for the high level layout manger, since it will resize a components width when added to the NORTH, CENTER or SOUTH.

  • How to add a JPanel with label and border line

    hi,
    I want a Jpanel with label and border line like this.Inside it i need to have components.Is there a resuable component to bring this directly??
    Any solution in this regards.???
    Label-----------------------------------------------------------
    | |
    | |
    | |
    | |
    | |
    |________________________________________ |

    [url http://java.sun.com/docs/books/tutorial/uiswing/misc/border.html]How to Use Borders

  • How to senter a JPanel on a parent container

    Hi,
    I have a fixed sized JPanel that I want to add to the center of a container. I would like my JPanel's center to be fixed to the center of the container.
    I have tried to use GridBagLayout with a GridbagConstraint like follows:
    GridBagLayout gridbag = new GridBagLayout();
    getContentPane().setLayout(gridbag);
    GridBagConstraints c = new GridBagConstraints();
    c.fill = c.CENTER;
    SubPanel subPanel = new SubPanel();
    gridbag.setConstraints(subPanel, c);
    getContentPane().add(subPanel);
    setSize(400, 500);
    setVisible(true);
    But this results in the upper left corner of my JPanel being put in the center of the container. Does anyone know how to get the center of my JPanel being placed in the center?
    Best regards
    // Johan

    how about flowlayout?
    this.setLayout( new Flowlayout( Flowlayout.CENTER ) );
    this.add( subPanel );
    This might put it at the center at the top though.
    Another way would be to use GridLayout and set the grids, when you add your panel it Should size the cells equal to your largest component which would be the JPanel, then just add blank JLabels to the other cells and add your subpanel to the center cell, that my work better.

  • How to extend a jpanel

    hi
    this might sound like a beginers question
    i have a main class which extends jframe i called the frame graphicsframe i have also decleared, a jpanel inside
    this class.
    but how do i extend that JPanel in another class i know you can use graphicsframe.panel to change the methods. but then i have to declear all of the methods using graphicsframe.panel.

    to extend a JPanel you simply, ... extend it:
    public class MyPanel extends JPanel
      // you'll need a constructor or a few in here plus any override and new methods
    }I try to avoid extending JPanels, JFrames, and whatnot unless I'm going to change the basic behavior of the component, most commonly to override the paintComponent of a JPanel so I can draw in it.
    By the way, what is to "declear"?
    One more point: you probably should post Swing questions in the Swing forum (but please don't do this now. Continue on with this thread and please don't cross-post).

  • How to Serialize a JPanel which is inside a JApplet

    Hi..
    I have a JApplet where i have a JPanel which contains some JLabels and JTextFields,now i have to Serialize that full Panel so that i can retrived it later on with the labels and textfields placed in the same order,for that i tried serializing the full panel on to a file but it is giving me NotSerializeException,i dont know how to tackel it..
    public SaveTemplate(JPanel com) {
    try {
    ObjectOutputStream os=new ObjectOutputStream(new FileOutputStream("Temp1.temp"));
    os.writeObject(com);
    catch(Exception e) {
    e.printStackTrace();
    This is the code..plz help me with that..

    Actually its forming a Template which client will generate and that has to saved on the serverside..So what i thought that once when the client has designed a template,i can save the full template which is a panel into a file and later on when he want to open the template i just have to read the file and create an object of JPanel and add to the frame,so i dont need to apply much effort for that...But now serialization in Applet is giving problem.

  • How to refresh a JPanel/JTextArea

    My main problem is that I don't know how to correctly refresh a JTextArea in an Applet. I have an Applet with 2 internal frames. Each frame is comprised of a JPanel.
    The first internal frame calls the second one as shown below:
    // Set an internal frame for Confirmation and import the Confirm class into it//
    Container CF = nextFrame.getContentPane();
    //<Jpanel>
    confirmation = new Confirmation( );
    CF.add ( confirmation, BorderLayout.CENTER );
    mFrameRef.jDesktopPane1.add(nextFrame,JLayeredPane.MODAL_LAYER);
    currentFrame.setVisible(false); // Hide this Frame
    nextFrame.setVisible(true); // Show Next Frame/Screen of Program
    confirmation (Jpanel) has a JTextArea in it. When it's called the first time it displays the correct information (based on choices from the first frame). If a user presses the back button (to return to first frame) and changes something, it doesn't refresh in the JTextArea when they call the confirmation(Jpanel) again. I used System.out.println (called right after jtextareas code), and it shows the info has indeed changed...I guess I don't know how to correctly refresh a JTextArea in an Applet. Here is the relevent code for the 2nd Internal Frame (confirmation jpanel):
    // Gather Info to display to user for confirmation //
    final JTextArea log = new JTextArea(10,35);
    log.setMargin(new Insets(5,5,5,5));
    log.setEditable(false);
    log.append("Name: " storeInfoRef.getFirstName() " "
    +storeInfoRef.getLastName() );
    log.append("\nTest Project: " +storeInfoRef.getTestProject() );
    JScrollPane logScrollPane = new JScrollPane(log);

    Here is the relevant code that I am having the problem with...
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    public class Confirmation extends JPanel {
    // Variables declaration
    private StoreInfo storeInfoRef; // Reference to StoreInfo
    private MFrame mFrameRef; // Reference to MFrame
    private Progress_Monitor pmd; // Ref. to Progress Monitor
    private JLabel ConfirmMessage; // Header Message
    private JButton PrevButton;                // Navigation Button btwn frames
    private JInternalFrame prevFrame, currentFrame; // Ref.to Frames
    // End of variables declaration
    public Confirmation(MFrame mFrame, StoreInfo storeInfo) {
    mFrameRef = mFrame; // Reference to MFrame
    storeInfoRef = storeInfo; // Reference to Store Info
    prevFrame = mFrameRef.FileChooserFrame; // Ref. to Previous Frame
    currentFrame = mFrameRef.ConfirmationFrame; // Ref. to this Frame
    initComponents();
    // GUI for this class //
    private void initComponents() {
    ConfirmMessage = new JLabel();
    PrevButton = new JButton();
    UploadButton = new JButton();
    setLayout(new GridBagLayout());
    GridBagConstraints gridBagConstraints1;
    ConfirmMessage.setText("Please confirm that the information "
    +"entered is correct");
    add(ConfirmMessage, gridBagConstraints1);
    // Gather Info to display to user for confirmation //
    final JTextArea log = new JTextArea(10,35);
    log.setMargin(new Insets(5,5,5,5));
    log.setEditable(false);
    log.append("Name: " storeInfoRef.getFirstName() " "
    +storeInfoRef.getLastName() );
    log.append("\nTest Project: " +storeInfoRef.getTestProject() );
    log.append("\nTest Director: " +storeInfoRef.getTestDirector() );
    log.append("\nTest Location: " +storeInfoRef.getTestLocation() );
    log.append("\nDate: " +storeInfoRef.getDate() );
    String fileOutput = "";
    Vector temp = new Vector( storeInfoRef.getFiles() );
    for ( int v=0; v < temp.size(); v++ )
    fileOutput += "\n " +temp.elementAt(v);  // Get File Names
    log.append("\nFile: " +fileOutput );
    // log.repaint();
    // log.validate();
    // log.revalidate();
    JScrollPane logScrollPane = new JScrollPane(log);
    System.out.println("Name: " storeInfoRef.getFirstName() " " +storeInfoRef.getLastName() );
    System.out.println("Test Project: " +storeInfoRef.getTestProject() );
    System.out.println("Test Director: " +storeInfoRef.getTestDirector() );
    System.out.println("Test Location: " +storeInfoRef.getTestLocation() );
    System.out.println("Date: " +storeInfoRef.getDate() );
    System.out.println("File: " +fileOutput );
    // End of Gather Info //
    add(logScrollPane, gridBagConstraints1);
    PrevButton.addMouseListener(new java.awt.event.MouseAdapter() {
    public void mouseClicked(java.awt.event.MouseEvent evt) {
    PrevButtonMouseClicked(evt);
    PrevButton.setText("Back");
    JPanel Buttons = new JPanel();
    Buttons.add(PrevButton);
    add(Buttons, gridBagConstraints1);
    // If User Presses 'Prev' Button //
    private void PrevButtonMouseClicked(java.awt.event.MouseEvent evt) {
    try
    currentFrame.setVisible(false); // Hide this Frame
    prevFrame.setVisible(true); // Show Next Frame/Screen of Program
    catch ( Throwable e ) // If A Miscellaneous Error
    System.err.println( e.getMessage() );
    e.printStackTrace( System.err );
    }// End of Confirmation class

Maybe you are looking for