JPanel & JFrame

Hello,
I made an Application that uses a JFrame that contains several JPanels. In addtion my application requires a wizard-like operaton, I did that by removing and adding JPanels and components as needed.
But it turns out malfunction after some add's and remove's, do you have an idea about that.
Thanks

Thanks My friend
It is difficult to show the code, but what I meant is that in my application I made different Jpanels with each having different set of button. When the user presses certain button, the program remove the JPanel and add another one.
But after some time the program starts to show panel on top of each others, and the GUI is not clear.
I hope this clearifies the thing
Thanks.

Similar Messages

  • Help: JPanel/JFrame display complexities, wrong size

    I am trying to make a simple game of worms.I wan't to draw a rectangle in the center of the window where in the middle the game is played and on the outside score, lives and other such things are displayed. The problem is the rectangle won't draw properly because the window is the wrong size and I don't know if it is something I am doing wrong with the panel or frame.
    import javax.swing.*;
    import java.awt.*;
    public class DemoWormPanel extends JPanel implements Runnable{
        private static final int WIDTH = 600, HEIGHT = 400;
        private Graphics dbG;
        private Image dbImage;
        private Thread animator;
        private boolean running = false;
        private Rectangle walls;
        public DemoWormPanel() {
            super();
            setSize(WIDTH,HEIGHT);
        public void startGame() {
            if (animator == null) {
                animator = new Thread(this);
                animator.start();
            running = true;
            //defining game walls at 50 pixels within panel border
            walls = new Rectangle(50, 50, WIDTH - 50, HEIGHT - 50);
        public void gameRender() {
            if (dbImage == null) {
                dbImage = createImage(WIDTH, HEIGHT);
                if (dbImage == null) {
                    System.out.println("Error creating double buffer");
                    System.exit(0);
                dbG = dbImage.getGraphics();
            dbG.setColor(Color.black);
            dbG.fillRect(0,0,WIDTH,HEIGHT);
            dbG.setColor(Color.white);
            dbG.drawRect(walls.x, walls.y, walls.width, walls.height);
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(dbImage, 0, 0, this);
            g.dispose();
        public void update(Graphics g){
            paint(g);
        public void run() {
            while (running) {
                gameRender();
                repaint();
                try {
                    Thread.sleep(1000/50);
                } catch (InterruptedException e) {}
            System.exit(0);
        public static void main(String[] args) {
            DemoWormPanel wp = new DemoWormPanel();
            JFrame f = new JFrame();
            f.setTitle("Worms");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(wp);
            f.setSize(WIDTH, HEIGHT);
            f.setVisible(true);
            wp.startGame();
    }Somewhere in there is my problem.
    What happens is that the right and bottom walls of the Rectangle are cut off of the screen because the window is not the right size. I changed the code to determine if the coordinates of the walls were accurate every iteration and they were. I also made it check the width and height every iteration by printing out this.getWidth() and this.getHeight() and found that instead of a 600 x 400 window, I have a 584 x 364. I also tried changing the panel and frame's size methods to make a new dimension instead of setting it directly from my constants and it had no effect. I also added directly to those constants to make it precisely 600 x 400 but the rectangle is still cut off, so maybe I also have a graphics issue. The only other potential issue I can think of is that I have Vista but I looked around here and searched google and found no similar issues to this.
    I am not new to java but I am also not advanced. I just started using java again after about 6 months and I have made a pong game before without this problem, on another computer though.I am at my wits end. I'll check for responses tomorrow and thank you for any help or insight you can offer.

    the problem is here
    walls = new Rectangle(50, 50, WIDTH - 50, HEIGHT - 50);
    at best the right/bottom walls will equal the frame's dimensions. try it as
    walls = new Rectangle(50, 50, WIDTH - 100, HEIGHT - 100);
    but this won't get you exactly what you want, due to the titlebar height (30?)
    slightly different version
    import javax.swing.*;
    import java.awt.*;
    class DemoWormPanel extends JPanel {
        private static final int WIDTH = 600, HEIGHT = 400;
        public DemoWormPanel() {
            setBackground(Color.BLACK);
            setPreferredSize(new Dimension(WIDTH-100,HEIGHT-100));
        public static void main(String[] args) {
            DemoWormPanel wp = new DemoWormPanel();
            JFrame f = new JFrame();
            f.setLayout(new GridBagLayout());
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(wp,new GridBagConstraints());
            f.setSize(WIDTH, HEIGHT);
            f.setVisible(true);
    }

  • JPanel/JFrame refresh

    I am writing an application which removes a JPanel and replaces it when you perform certain actions, this usually works but when I add a new row (3 buttons, 3 textfield) to the JPanel you need to minimize and maximize the window to get it to refresh properly.
    Does anyone know what methods I need to call in order to force this refresh without the user having to minimize the window? It would be the same method(s) implicitly called when a jframe is minimized/maximised. Thanks.

    there is no revalidate() on the Container object but i tried the validate() method which seems to work - thanks.

  • Why doesn't the Card show up from the CardLayout:used JPanel,JFrame

    hello guys,
    this is a question regarding. As I did not get nice responses i am posting again today.
    http://forum.java.sun.com/thread.jsp?forum=57&thread=235761
    Hi, I would like to re-arrange my question and put it in a simpler way. I have a frame(mainframes.java) with border layout. There is a panel on the west(borderlayout.west) which has a few buttons. The center panel(borderlayout.center) has a cardlayout and needless to mention that it contains a deck of panels. When I click on a button in the left panel, an appropriate panel in the deck should be displayed in the center panel. It's all simple so far, but here comes the real problem. I have designed my application in such a way that I have each of my panels in a separate class(each of which extend JPanel) and I am trying to integrate them all in my frame. When I click on the button on the left panel(p.s.:this panel is also in a separate class), then the appropriate panel should be displayed in the frame(i.e. in the center deck).
    mainframes.java:-
    //This is the local method which takes an argument from the invoking panel and displays the corresponding card in the deck.
    void showpanel(String p1)
    this.cardLayout2.show(CENTERPANEL,p1);
    System.out.println("Inside showpanel "+ p1);
    leftpanel.java:-
    void B_LOGIN_actionPerformed(ActionEvent e) {
    new mainframes().showpanel("lp");
    // I am trying to display the card "lp" when I click on a button in the leftpanel, but I can only get the console output as "Inside showpanel lp". This shows that the method showpanel(String lp) is getting invoked but the required card is not being displayed. i.e. this.cardLayout2.show(CENTERPANEL,p1) seems to be not working.
    Thanks for your time. Mail me, if you want to access the complete code, at [email protected]

    I'd check to make sure 3 things...
    1) You have added your Panels to the CardLayout Panel
    2) You have added the CardLayoutPanel to the center of your BorderLayout JPanel
    3) Try giving calls to validate()/invalidate() on the JPanel containing the CardLayoutPanel
    void showpanel(String p1)
    ... invalidate()
    this.cardLayout2.show(CENTERPANEL,p1);
    System.out.println("Inside showpanel "+ p1);
    ... validate()
    Otherwise, I may just need to check your source code, you can send to [email protected]

  • How to add JPanel,JFrame to JSP Page so that it does'nt popup

    i have added a JPanel jp1
    which is as follows
    <%JPanel jp1 = new JPanel();%>
    i am getting a error in the page in webbrowser
    javax.swing.JPanel[,0,0,0x0,invalid,layout=java.awt.FlowLayout,alignmentX=null,alignmentY=null,border=,flags=9,maximumSize=,minimumSize=,preferredSize=]
    also i have added a frame as follows
    <%adminlog adllogz = new adminlog();%>
    <%adllogz.setVisible(true);%>
    so these two lines of code make a poop up window of adminlog
    from a webbrowser
    what i want is that these two lines of code should not do
    a pop up but come inside a webbrowserPlease tell asap

    The problem is that you used position:absolute, my post talked about using position:fixed.
    Also your image does not need to be inside the adBox, just use adImage by itself with this CSS:
    #adImage{
    background-color: #FF0000;
    position:fixed;
    bottom:0px;
    right:0px;
    width:100px;
    height: 100px;
    will fix adImage to bottom right 0 px from the edge of window. If you want a little separation, just change
    bottom:0px;
    right:0px;
    to 5 or 10 px or so.
    No jQuery needed.
    Best wishes,
    Adninjastrator

  • JFRAME- JPANEL question

    I have a JFrame that holds a JPanel. If that JPanel needs to contact the JFrame how do I get access to parent? I tried panelname.getParent, when I did I got a
    java.lang.ClassCastException
    Any help would be great.
    Brock

    i think you have to buid your own JPanel class lyke this:
    public class MyJPanel extends JPanel{
    JFrame parent;
    public MyJPanel(JFrame p){
    parent = p;
    // here you have access to the parent JFrame in your JPanel
    public JFrame getParentFrame(){
    return parent;
    // here you return the parent of the JPanel
    so in your JFrame class you add the JPanel like this:
    getContentPane().add(new MyJpanel(this));
    i hope it helps you. :)

  • 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 call a private method in a JFrame

    I have a Frame which has some properties like its size, bgcolor plus other parameters, as instance variables. There is a button on the Frame with the caption : "set properties". When one clicks on that button, a new frame should appear via which a user can change the values of the parameters of the main Frame (i.e size, bgcolor,..etc). The user would input the new values in the textfields or radio buttons that are on the new frame, and then click a submit button, which has to exist on the same NFrame. How can I do that so that when the submit button is pressed, the parameters values are updated and so is the display view ?
    I made it this way : I created 2 classes, the main frame and the new Frame. I made the new Frame an instance variable of the main Frame. When the user clicks the " set properties" button on the main Frame, the new Frame is shown. The user enters new values for some of the parameters and clicks submit. The parameters in the new Frame are updated. UP TO HERE EVERYTHING WENT JUST FINE. Now, there is a private method in the main frame that changes the color, size, ...etc of the main frame according to the values stored in the instance variables color, size,...etc. THE QUESTION IS: How can the new Frame display the changes after the values have been updated ? That is, how can it call the "private" method in the main class?? Should the new class be a child class of the main class to be able to access it's private methods ??

    import java.awt.*;
    import java.awt.event.*;
    import java.util.Random;
    import javax.swing.*;
    public class CallingHome
        SkinMod skinMod;
        JPanel panel;
        public CallingHome()
            // send reference so SkinMod can call methods in this class
            skinMod = new SkinMod(this);
            JButton change = new JButton("change properties");
            change.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    skinMod.showDialog();
            JPanel north = new JPanel();
            north.add(change);
            panel = new JPanel();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(north, "North");
            f.getContentPane().add(panel);
            f.setSize(300,100);
            f.setLocation(200,200);
            f.setVisible(true);
        public void setBackground(Color color)
            panel.setBackground(color);
            panel.repaint();
        public static void main(String[] args)
            new CallingHome();
    class SkinMod
        CallingHome callHome;
        Random seed;
        JDialog dialog;
        public SkinMod(CallingHome ch)
            callHome = ch;
            seed = new Random();
            createDialog();
        public void showDialog()
            if(!dialog.isShowing())
                dialog.setVisible(true);
        private void createDialog()
            JButton change = new JButton("change background");
            change.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    callHome.setBackground(getColor());
                    dialog.dispose();
            JPanel p = new JPanel();
            p.add(change);
            dialog = new JDialog();
            dialog.getContentPane().add(p);
            dialog.setSize(200,100);
            dialog.setLocation(525,200);
        private Color getColor()
            return new Color(seed.nextInt(0xffffff));
    }

  • Embed an applet into jpanel

    I have a unique problem. I have an application built on swing f/w with xml used for design and maven used for build.
    I have an applet that is independent of this application. Now i dont have a clue how to embed that applet into a jpanel or into that application. Anything of that will help me immensely. Please suggest if anybody has a clue.
    Thanks in advance.
    Regards,
    Ashish

    >
    I have a unique problem. >Big claim since..
    >
    ..I have an application built on swing f/w with xml used for design and maven used for build.
    I have an applet that is independent of this application. Now i dont have a clue how to embed that applet into a jpanel or into that application. >..the AppletViewer has been Swing based since around 1.3 or before. ;-)
    In any case, if you control the source of the applet, or can recreate it, the best solution has already been given on the first reply.
    If not, and it actually makes sense to embed an Applet or JApplet in a Swing JPanel(/JFrame), then it becomes more complicated.
    Here is one of the most simplistic [examples of embedding an applet in a JFrame|http://forums.sun.com/thread.jspa?messageID=10259860#10259860]. If it becomes necessary to pass parameters to the applet, allow it to share input streams, or implment the showStatus() showDocument() methods as I did in Appleteer, it becomes more complex again. So far I have found no practical way to mimic Applet/JavaScript interaction.
    Edit 1:
    And noting you are yet another multi-poster. No that is not unique, just very irritating, and a great disincentive for others to help.
    Edited by: AndrewThompson64 on Jul 1, 2009 1:40 AM

  • Strange delay in modifying JPanel

    Hi
    Once the "Login" button is pressed, I want my JPanel to show the string "Connecting..." so I added a simple card panel to show either "Welcome" or "connecting...".
    When the button is pressed, the code flows as expected, except that the card does not change until the Oracle database connection (from the checkUser method) returns. So basically, it only says "connecting..." after trying to connect. It's as if the JPanel/JFrame is not allowing any updates until the checkUser returns. checkUser just as a try block attempting to connect to a db.
    Any ideas?
    public void actionPerformed(ActionEvent ae) {
           // char array to store the password
              char[] charInputPassword;
           // Set the Panel to show "Connecting..."
              ((CardLayout)cardPanel.getLayout()).show(cardPanel, CONNPANE);
           // The text below appears in CMD window when logingButton button is pressed
           // but the card panel doesn't not change until the checkUser
           // procedure has completed. ???
           TextIO.putln("Panel should now show CONNPANE");
             if(ae.getSource() == loginButton) {
                inputUsername = usernameField.getText();
                charInputPassword = passwordField.getPassword();
             inputPassword = new String(charInputPassword);
             TextIO.putln("OK Pressed - Username is " + inputUsername);
             try {
               checkUser();
             } catch(Exception e) {
                  TextIO.putln("CheckUser error: " + e.getMessage());
         }

    Your action listener is invoked on the event dispatching thread, so until your method returns, that thread is blocked. In other words, by the time Swing gets a chance to update the GUI, it is too late.
    An easy workaround is to wrap all the code following the modification of the GUI in a call to EventQueue.invokeLater(). Something like this:
    public void actionPerformed(ActionEvent ae) {
        // Set the Panel to show "Connecting..."
        ((CardLayout)cardPanel.getLayout()).show(cardPanel, CONNPANE);
        if (ae.getSource() == loginButton) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    inputUsername = usernameField.getText();
                    charInputPassword = passwordField.getPassword();
                 inputPassword = new String(charInputPassword);
    }Geoff

  • Help with calling up a JPanel

    I posted a simular problem to this earlier, but got tottally muddled up in what i was writing. I have been stuck on this now for quite a while and its problably really straight forward. Basically i have a class called Meet which extends a JPanel as it is using JTabbedPane and i followed a sun tutorial. Now this JPanel gets added to a JFrame in my code through
           JFrame frame = new JFrame("MEET_dataTable");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new Meet(), BorderLayout.CENTER);
            frame.pack();
            frame.setVisible(true);Now this class all works great when run alone. But then in another class which extends a JFrame, one of the buttons should be calling up the above Meet class. So i declared Meet meet; and i created the CreateAtlDatabase_actionPerformed method.
         private void CreateAtlDatabase_actionPerformed()
              meet = new Meet();
                    this.dispose();
              } But everytime this button is pressed, the whole program crashes. I have also tried different ways, for instance i removed the JFrame code from my Meet class and placed it in my CreateAtlDatabase_actionPerformed method, so that the frame is created on request, but then i have problems disposing of the gui in my Meet class. The circle continues. Any advise on what i can do would be great.

    But everytime this button is pressed, the whole program crashes.By this i mean when i press the button, the whole application just freezes, and then after quite a long time my command line displays
    Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError: Java heap spa
    ce
            at javax.swing.plaf.basic.BasicTabbedPaneUI.createScrollButton(BasicTabb
    edPaneUI.java:305)
            at javax.swing.plaf.basic.BasicTabbedPaneUI$ScrollableTabSupport.createB
    uttons(BasicTabbedPaneUI.java:3253)
            at javax.swing.plaf.basic.BasicTabbedPaneUI$ScrollableTabSupport.<init>(
    BasicTabbedPaneUI.java:3238)
            at javax.swing.plaf.basic.BasicTabbedPaneUI.installComponents(BasicTabbe
    dPaneUI.java:258)
            at javax.swing.plaf.basic.BasicTabbedPaneUI.installUI(BasicTabbedPaneUI.
    java:206)
            at javax.swing.plaf.basic.BasicTabbedPaneUI$Handler.propertyChange(Basic
    TabbedPaneUI.java:3521)
            at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSup
    port.java:339)
            at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSup
    port.java:276)
            at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSup
    port.java:297)
            at java.awt.Component.firePropertyChange(Component.java:7908)
            at javax.swing.JComponent.firePropertyChange(JComponent.java:4454)
            at javax.swing.JTabbedPane.setTabLayoutPolicy(JTabbedPane.java:536)
            at Meet.<init>(Meet.java:264)
            at Meet.<init>(Meet.java:268)
            at Meet.<init>(Meet.java:268)
            at Meet.<init>(Meet.java:268)
            at Meet.<init>(Meet.java:268)
            at Meet.<init>(Meet.java:268)
            at Meet.<init>(Meet.java:268)
            at Meet.<init>(Meet.java:268)
            at Meet.<init>(Meet.java:268)
            at Meet.<init>(Meet.java:268)
            at Meet.<init>(Meet.java:268)
            at Meet.<init>(Meet.java:268)
            at Meet.<init>(Meet.java:268)
            at Meet.<init>(Meet.java:268)
            at Meet.<init>(Meet.java:268)
            at Meet.<init>(Meet.java:268)
            at Meet.<init>(Meet.java:268)
            at Meet.<init>(Meet.java:268)
            at Meet.<init>(Meet.java:268)
            at Meet.<init>(Meet.java:268)I then took this code out of my Meet class(class which extends the JPanel)
            JFrame frame = new JFrame("MEET_dataTable");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new Meet(), BorderLayout.CENTER);
            frame.pack();
            frame.setVisible(true);And i place it in the action event of the class that calls up the JPanel.
         private void CreateAtlDatabase_actionPerformed()
            JFrame frame = new JFrame("MEET_dataTable");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new Meet(), BorderLayout.CENTER);
            frame.pack();
            frame.setVisible(true);
            this.dispose();
              } Now that seems to do the trick, i just wasnt sure if it was allowed. But in doing this another problem is created. In my Meet class, i have a go back button which should return the user to the JFrame gui and dispose of the JPanel gui. But of course you cannot use this.dispose() on a JPanel and i no longer have the JFrame to which the panel is added in this class, which means i cant dispose of its JFrame. I have tried using System.exit(0) but this closes everything, and my last attempt has been
    private void back_actionPerformed() 
            this.getParent().setVisible(false);
            CreateAtlDatabase data = new CreateAtlDatabase();
      Which removes the JPanel but leaves an empty JFrame. Now this is where i am stuck, how can i dispose of this? and of course is the moving of my JFrame to my other class ok?
    cheers

  • Movie file from JFrame ?

    I've created a Java3D app in a Canvas3D > JPanel > JFrame and now want to be able to record what's happening in the frame into a .mov or other movie file for later playback (with some start recording / stop recording controls)
    Should I be trying to set up a QTHandleRef for the graphics in my frame, somehow convert the 3DCanvas in my frame to a QTCanvas, use some other Quicktime tool, or forget Quicktime and use the much easier method with source code you're about to give me ?
    with thanks,
    Jon

    i suppose u will need some more programming in java.
    download JMF or Java Media FrameWork
    thats apt for your need...
    it can make image files into a movie and
    then u can even save them as u like in format...

  • Adding video in jframe?

    help please.. how can i add a video in a jframe? is it possible?

    how? i cant understand it. plesae teach me........T_TYou can do this. You just need JMF. Check out this code
    import javax.swing.*;
    import javax.media.*;
    import java.net.*;
    import java.io.*;
    public class JMFVideo1
         public static void main(String args[]) throws Exception
              Player player;
              JFrame jframe=new JFrame();
              jframe.setSize(300,300);
              JPanel jpanel=new JPanel();
              jpanel.setLayout(new BoxLayout(jpanel,BoxLayout.Y_AXIS));
              player=Manager.createRealizedPlayer(new MediaLocator(new File("G:/java files1/jmf/love.mpg").toURL()));
              player.setMediaTime(new Time(30.0));
              jpanel.add(player.getVisualComponent());
              Control controls[]=player.getControls();
              CachingControl cc=null;
              for(int i=0;i<controls.length;i++)
                   if(controls[i] instanceof CachingControl)
                        cc=(CachingControl) controls;
                        jpanel.add(cc.getProgressBarComponent());     
                        System.out.println("Found CachingControl");
              if(player.getControlPanelComponent()==null)
                   System.out.println("Null");
              else
                   jpanel.add(player.getControlPanelComponent());
              jframe.setContentPane(jpanel);
              jframe.setVisible(true);
              player.start();

  • JPanel getSize()

    I have JPanel inside another JPanel/JFrame and the getSize(), getDimension(), and getBounds() all return 0.
    How to get the dimension and location of JPanel inside
    another JPanel/JFrame?

    The panels must be already visible. Also the panel must contain something (if using a layoutmanager or constraints which doesn't stretch the components...)

  • JScrollPane in JPanel???

    Hi !!!
    I want to add a JScrollPane to a JPanel, but it's doesn't work.
    class Planche extends JPanel
    JFrame f;
    public Planche(JFrame f)
    this.f = f;
    this.setLayout(null);
    JPanel p_tousGraphique = new JPanel();
    p_tousGraphique.setLayout(null);
    JScrollPane scrollPane = new JScrollPane(p_tousGraphique, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    p_tousGraphique.setBounds(10,10,1800,1600);
    this.add(scrollPane);
    Thanks by advance!!!

    Thanks for your answer, it's help to find the solution. The script display the scrollpane in the panel. But I have a problem. I want to put some componement in the jpanel and I do disable the layour manager
    p_tousGraphique.setLayout(null);
    But when I remove this line the scrollbar work fine, but my componement doesn't display like I want. So I disable the layour manager. The scrollbar display in jpanel but it doesn't scroll, dispite I have some componement that I don't see in my eye.
    Thanks by advance !!!
    My script that I do:
    this.setLayout(new BorderLayout());
    p_tousGraphique.setLayout(null);
    JScrollPane scrollPane = new JScrollPane(p_tousGraphique, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    scrollPane.setPreferredSize(new Dimension(p_tousGraphique.getWidth(),p_tousGraphique.getHeight()));
    this.add(scrollPane);
    this is my principale JPanel

Maybe you are looking for