JPanels and SplitPanes difficulty

Hi there, I am playing around with swing at the moment, and am having some difficulty with JPanels and split panes.
What I would like to get eventually is a JFrame split up like this:
|             |            |
|             | -----------|
|             |            |
|             |            | 
|             |            |
|             | -----------|
----------------------------Just in case that v poor diagram does not suffice - The JFrame should be split roughly in half with a vertical line, then the right hand panel should be split into thirds (roughly) with two horizontal lines.
The code that I have is this:
import javax.swing.JFrame;
import java.awt.*;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
     public class ccssc  {
          private JPanel jsp2;
          private JPanel jsp1;
          private JPanel jsp3;
          private JPanel jsp4;
          private JLabel jl = new JLabel("HELLO JLABEL");
          public ccssc(){
               JFrame.setDefaultLookAndFeelDecorated(true);
          JFrame frame = new JFrame("Self Contained Example");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setPreferredSize(new Dimension(1200, 900));
          //init
          jsp2 = new JPanel();
          jsp1 = new JPanel();
          jsp3 = new JPanel();
          jsp4 = new JPanel();
          jsp3.setSize(350, 50);
          jsp4.setSize(350, 50);
          jsp1.setSize(900, 1000);
          jsp3.add(jl); //Frame with the JLabel on it.
          jsp1.setBackground(Color.BLUE);
          jsp2.setBackground(Color.BLACK);
          jsp3.setBackground(Color.RED);
          jsp4.setBackground(Color.GREEN);
          JSplitPane splitPane2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
                 true, jsp3, jsp2);
          JSplitPane splitPane3 = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
                 true, splitPane2, jsp4 );
          JSplitPane splitPane1 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
                 true, jsp1, splitPane2);
         splitPane2.setDividerLocation(50);
         splitPane3.setDividerLocation(700);
         splitPane1.setDividerLocation(850);
         frame.add(splitPane3);
         frame.add(splitPane1);
         frame.setResizable(true);
         frame.pack();
          frame.setVisible(true);
          public static void main(String[] args) throws Exception{
               new ccssc();
     }My thinking is that the JSplitPane3 should have as its top half JSplitPane2, and as its bottom half, the new JPanel (jsp4) however, this does not work, it runs fine, but only displays the first 3 JPanels, and only the JSplitPanes 1 and 2.
I am confused, is there something I am missing here?
Thanks for your time,
beccy

Two issues with your code:
You know that you are adding components to JFrame twice without specifying where. When doing this, you are actually adding components to the JFrame's contentPane, and the default layout for the contentPane is a BorderLayout. Thus when you add two things without specifying a location, both are added to the BorderLayout.CENTER position, and thus the second component will completely obscure the first one added.
The other issue is that the API for the JSplitPane.setDividerLocation( ) method states that it only will have an effect after the split pane is correctly realized and on the screen. This will only occur after setVisible(true) has been called. You may want to move these method calls to after the frame has been set visible. If done correctly, you won't have to call setSize on the JPanels (somethiing that shouldn't be done anyways). Something like so:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.SwingUtilities;
class MyCcssc2 extends JPanel
    public static final Dimension PANEL_SIZE = new Dimension(800, 650);
    private static final long serialVersionUID = 1L;
    private JPanel leftPanel = new JPanel();
    private JPanel rightTopPanel = new JPanel();
    private JPanel rightMidPanel = new JPanel();
    private JPanel rightBottomPanel = new JPanel();
    private JSplitPane rightBottomSP = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
            rightMidPanel, rightBottomPanel);
    private JSplitPane rightSP = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
            rightTopPanel, rightBottomSP);
    private JSplitPane mainSP = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
            leftPanel, rightSP);
    MyCcssc2()
        setLayout(new BorderLayout());
        setPreferredSize(PANEL_SIZE);
        leftPanel.setBackground(Color.blue);
        rightTopPanel.setBackground(Color.red);
        rightMidPanel.setBackground(Color.black);
        rightBottomPanel.setBackground(Color.green);
        add(mainSP);
    public void setDividerLocation()
        mainSP.setDividerLocation(0.5);
        rightSP.setDividerLocation(0.3333);
        rightBottomSP.setDividerLocation(0.3333);
    private static void createAndShowGUI()
        JFrame frame = new JFrame("Swing Application");
        MyCcssc2 ccssc2 = new MyCcssc2();
        frame.getContentPane().add(ccssc2);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        ccssc2.setDividerLocation();
    public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable()
            public void run()
                createAndShowGUI();
}Also, try to use variable names that are more meaningful. It will make your code that much easier for us to read. Good luck!
Edited by: Encephalopathic on Dec 26, 2007 7:42 AM

Similar Messages

  • Canvas3D JPanel and Behavior

    Hello,
    I am a student’s geomatic and I do my memory on 3D object implementation in a data base.
    To do that, I have a 3D graphic interface. I use Java 3D and Swing.
    Now, my program load only 3D points. There are 3 parts:
    - a 3D viewer,
    - a table,
    - buttons for the actions.
    I would like to get the 3D mouse coordinates in my 3D world.
    I succeed in a first program’s version. There were two windows JFrame, one included the Canevas3D and the other the table with the buttons.
    For the mouse’s action, I modify this source code :
    http://deven3d.free.fr/telechargements/fichiers/java3d/chap07/SimpleBehavior/SimpleBehavior.java
    Then, I put the Canevas3D in a JPanel (and neither in a separate window). And I add this JPanel to the JFram (those contain the table and the buttons for the actions).
    And after that my class Behavior don’t work.
    I think it’s due to my ActionListener (it’s use to catch the buttons’ press) who intercept the mouse action.
    This is my class Behavior :
    import java.awt.AWTEvent;
    import java.awt.Point;
    import java.awt.event.*;
    import java.util.Enumeration;
    import javax.media.j3d.*;
    import javax.vecmath.Point3d;
    public class InterGraph3d extends Behavior {
           // Condition qui va declencher le stimulus
           private WakeupCondition wakeupCondition =
                new WakeupOnAWTEvent(MouseEvent.MOUSE_PRESSED);
           private Canvas3D caneva;
           InterGraph3d (Canvas3D cane){
                   this.caneva = cane;
         public void initialize() {
             this.wakeupOn(wakeupCondition);
         public void processStimulus(Enumeration criteria) {
              WakeupCriterion critere;
             AWTEvent[] events;
             MouseEvent evt;
             // On boucle sur les critères ayant declenche le comportement
             while (criteria.hasMoreElements()) {
               // On recupere le premier critere de l'enumeration
               critere = (WakeupCriterion)criteria.nextElement();
               // On ne traite que les criteres correspondant a un evenement AWT
               if (critere instanceof WakeupOnAWTEvent) {
                 // On récupère le tableau des evements AWT correspondant au critere
                 events = ((WakeupOnAWTEvent)critere).getAWTEvent();
                 if (events.length > 0) {
                   // On récupère l'événement
                   evt = (MouseEvent)events[events.length-1];
                   // Traitement au cas par cas selon la touche pressée
                   switch(evt.getButton()) {
                   // Obtenir les coordonnées 3D du point cliqué
                     case MouseEvent.BUTTON1: // clic gauche
                     // pour avoir les coordonnées du point cliqué dans l'univers en 3D
                     // on déclare un point 3D
                     Point3d ptSourie = new Point3d();
                     // on utilise la fonction pour avoir les coordonnées de la sourie en 3D.
                     ptSourie = obtenirPointSourieCaneva(caneva, evt.getPoint());
                     // ici faire une liaison avec l'interface graphique
                     System.out.println("Coor sourie");
                       System.out.println(ptSourie.x);
                       System.out.println(ptSourie.y);
                       System.out.println(ptSourie.z);
                       break;
              // Une fois le stimulus traite, on réinitialise le comportement
             this.wakeupOn(wakeupCondition);
         // fonction pour récupérer les coordonnées de la sourie dans le
         public Point3d obtenirPointSourieCaneva(Canvas3D myCanvas, Point clickPos)
              Point3d mousePos = new Point3d();
              //pixel value in image-plate coordinates and copies that value into the object provided.
             myCanvas.getPixelLocationInImagePlate(clickPos.x, clickPos.y, mousePos);
              //This block of code converts our image plate coordinates out to virtual world coordinates
              Transform3D motion = new Transform3D();
              myCanvas.getImagePlateToVworld(motion);
              //We do this convertion the mouse position.
              motion.transform(mousePos);
              return mousePos;
    }

    The ScrollDemo uses the column and row header as well as the corner to create the rulerIt adds a component to the colum and row header and the corner. That component may or may not be a JPanel, or JComponent which they have used for custom painting.
    Can I change the ScrollDemo to use a JPanel instead?Makes no sense. There are 9 areas to add a Component. Any of those 9 areas can hold a JPanel.
    Does a JPanel provide the same elements A panel uses a LayoutManager to place components. Check the scroll pane source code to see what LayoutManager it uses.

  • Array of JPanel and Array of JTextField?

    Hi,
    I try to create array of jpanel and inizialize it in "for" , but when run it give me this error message:
    "Exception in thread "main" java.lang.NullPointerException"
    at the row: "panInsCantante.add(panInsNCC);"
    why?
    (ps. i tried in another code to create array of jtextfield and it give me same error message..)
    here part of code :
          JPanel [] panInsCantante = new JPanel[3];
          for(int i=0;i<=N;i++){
               JPanel panInsNCC= new JPanel();
               panInsNCC.setLayout( new GridLayout(3,1) );
               panInsNCC.add(campoTesto1);
               panInsNCC.add(campoTesto2);
               panInsNCC.add(campoTesto3);
               //panInsCantante[i] = new JPanel();
               //panInsCantante.setLayout( new GridLayout(1,1) );
         panInsCantante[i].add(panInsNCC);

    a question (theoric...)A VERY important question I may add.
    what's the difference between ..
    this instance :
    JPanel [] panInsCantante = new
    JPanel[3];This declares and initializes the array itself, nothing more. No JPanels have been initialized as yet, just the array. It's as if you have now built the shelves to hold the books, but you have no books up there yet...
    and this instance of panInsCantante? :
    panInsCantante[i] = new JPanel();and this initializes each JPanel in the array as you loop through the array. .... and now you have filled the shelves with the books and can use the books.
    You will need them both.
    In all likelihood, the reason for your confusion is that all of your previous arrays were arrays of primative types: int, double, float, and char. In this situation, you don't need to go through the step of initializing the variable.
    But now you are faced for the first time with an array of reference type, an array of Objects. This is a different situation and requires the steps that we have gone through.
    Message was edited by:
    petes1234

  • Drawning text/images in a JPanel and then resizing/moving it with the mouse

    Hello ebverybody!
    I need to be able to draw some text objects in a JPanel and then resize/move it with the mouse... How could I do that!? Same for some images loaded from jpg files...
    Should I just paint the text and then repaint when the mouse selects it? How to do this selection?! Or should use something like a jLabel and then change it`s font metrics?!
    I need to keep track of the upper left corner of the text/image, as well as the width/height of it. This will be recorded in a file.
    The text/images need to smoothly move around the panel as the mouse drags when selectin an entity.. not just "click the entity, then click another point and the entity appears there as if by magic...":)
    Please, tell the best way to do that!
    Thanks everybody!
    Message was edited by:
    cassio.marques

    I know what you mean! This happened to me as well!
    And one thing that I found useful is, if you want to directly select a layer without selecting from the layers pallete and without having autoselect enabled, just hold Ctrl and click on in directly in the image. This saved me a lot of time!

  • Displaying image in JPanel and scroll it through JScrollpanel

    Can any one will help me,
    I need to draw a image in a JPanel and, this JPanel is attached with a Jscrollpanel.
    I need to scroll the this JPanel to view the image.

    Here is my code for that
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class PicPanel extends javax.swing.JPanel implements WindowListener{
    /** Creates new form PicPanel */
    public PicPanel() {
    initComponents();
    // this.setOpaque(true);
    JFrame myFrame = new JFrame("Panel Tiler");
    myFrame.addWindowListener( this );
    myFrame.setSize(new Dimension(1000,300));
    setPreferredSize(new Dimension(1000,300));
    Container cp = myFrame.getContentPane();
    cp.add( this, BorderLayout.CENTER );
    tk = Toolkit.getDefaultToolkit();
    im =tk.getImage("smple.jpg");
         jPanel1.im=im;
    // jPanel1.setSize(new Dimension(1000,300));
    myFrame.pack();
    myFrame.show();
    jPanel1.repaint();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    private void initComponents() {
    java.awt.GridBagConstraints gridBagConstraints;
         jPanel1=new JPanelC();
    jScrollPane1 = new javax.swing.JScrollPane(jPanel1);
    setLayout(new java.awt.GridBagLayout());
    jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    jScrollPane1.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    jScrollPane1.setOpaque(false);
         gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.gridwidth = 2;
    gridBagConstraints.gridheight = 3;
    gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
    gridBagConstraints.ipadx = 378;
    gridBagConstraints.ipady = 298;
    gridBagConstraints.weightx = 1.0;
    gridBagConstraints.weighty = 1.0;
    gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
    add(jScrollPane1, gridBagConstraints);
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.ipadx = 372;
    gridBagConstraints.ipady = 280;
    gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
    add(jPanel1, gridBagConstraints);
    public static void main(String[] args)
    new PicPanel();
    public void windowOpened(WindowEvent e) {}
    public void windowClosing(WindowEvent e)
    // myFrame.dispose();
    System.exit(0);
    public void windowClosed(WindowEvent e) {}
    public void windowIconified(WindowEvent e) {}
    public void windowDeiconified(WindowEvent e) {}
    public void windowActivated(WindowEvent e) {}
    public void windowDeactivated(WindowEvent e) {}
    private JPanelC jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private Icon iiBackground;
    private Toolkit tk;
    private Image im;
    class JPanelC extends javax.swing.JPanel{
    public Image im;
    public void paintComponent(Graphics g){
              //super.paintComponent(g);
    if(im!=null)
                   imageobserver io = new imageobserver();
         System.out.println(im.getHeight(io));
         if(im.getHeight(io)!=-1)
    setSize(im.getWidth(io), im.getHeight(io));
    g.drawImage(im,0,0,null);
         // setOpaque(false);
    super.paintComponent(g);
    class imageobserver implements java.awt.image.ImageObserver{
    public boolean imageUpdate(Image img, int infoflags, int x, int y,int width, int height) {
              if ((infoflags & java.awt.image.ImageObserver.ALLBITS) != 0) {
    repaint();
    return false;
    //repaint();
    return true;
    Here i need to scroll the image in the panel but it is not working out.

  • About JPanel and JTabbedPane

    I have a JPanel and i want to know how any tab buttons it contain.
    We have a method in JTabbedPane to find it out ,so how can i type cast the JPanel to JTabbedPane.
    Thanks

    JTabbedPane does not extend JPanel, so you can't cast JPanel to JTabbedPane.
    A JPanel does not contain any tabs.
    I think you might need to rephrase the question.

  • Help me to solve it, JPanel and object reference

    Hi, friends,
    please help to solve this problem
    I have array of objects, let's say
    JLabel a[][] = new JLabel[4][4];then i add them into a JPanel(new GridLayout(4,4));
    public void buildLayout(){
       lfMouse lf = new lfMouse(); //MouseListener
          for(int i=0;i<4;i++){
         for(int j=0;j<4;j++){
                             lbl[i][j] = new JLabel(i*10+j+"");
             lbl[i][j].addMouseListener(lf);
             pane.add(lbl[i][j]);
    }What i need is when user click the label, the label will change to another JLabel's object, and the panel can immediately update itself.
    Here's my assumption:
    class lfMouse extends MouseAdapter{
            public void mouseClicked(MouseEvent e){
                      JLabel temp = (JLabel)e.getSource(); //get the clicked object
                       temp = new JLabel("Hihi"); //change its address to other    
                                                                        //object's reference
                       pane.revalidate();
    }But it didn't work...can anyone help me to understand object reference concept in Java? And how can i update the UI of JPanel immediately?
    I don't use setText(), because i need to change to another object...
    All i can do is to remove all the label in JPanel, and add the label to JPanel again..but i think it's not the effective way...
    please help me to solve it....
    Thanks for your help.... :)

    Creating a new Object does not add the Object to the panel. Its just an Object sitting in memory.
    I don't use setText(), because i need to change to another object...setText(...) is the obvious solution
    If you need to keep the original text String in your array then your array should be an array of Strings. Then you would build your JLabels using the Strings contained in the array. This way when you update the text of the label you are not touching the original array String values.
    All i can do is to remove all the label in JPanel, and add the label to JPanel again..but i think it's not the effective way...Its the only other way if you don't want to use setText(...);

  • Painting JPanels and graphics

    I have a JPanel into which want to display boxes of data connected by lines. The boxes are JPanels (with a ScrollPane and JList) and the lines simply Graphics2D objects. I have overridden the paint(g) method of the enclosing panel to call super.paint(g) followed by my graphics calls. This works fine on start-up and repaint (from maximizing), but when I resize the main panel, the middle of the panel doesn't show the graphics (the inner panels display fine). I think I see the graphics being drawn then erased, but I'm not sure. Reviewing the Painting in AWT and Swing articles hasn't helped. I've tried various versions of paintComponent(), paintChildren(), etc. as alternatives, but the problem remains (or I never see the graphics at all). This seems like a timing and clipping problem but I can't figure it out. Can anyone explain what resize is doing that is different than a normal paint? How should one combine JPanels and graphics?Thanks.

    Unfortunately, overriding paintComponent() causes the graphics to be completely over-written for some reason. The problem is apparently when the inner Panels are written (I guess by paintChildren()). I'm following the directions in Doing Without a Layout Manager in the Java Tutorial: setting the outer JPanel's layout to null, explicitly setting the bounds of the inner JPanels and overwriting paint() with super.paint() (which paints the inner panels correctly) followed by my graphics code. All is well until I resize.
    Now the Doing Without a Layout Manager page states "However, creating containers with absolutely positioned containers can cause problems if the window containing the container is resized." Guess they're right ;-) Anyone know how to get around this problem?

  • TabbedPane and SplitPane in javafx 1.2

    Hi there,
    I have some problems finding the TabbedPane and SplitPane package in javafx 1.2.
    I´m new to javafx and doing some Tutorials. Now i got a Project which requires Tabs and some sort of Window splitting.
    For example, the tutorial: MyTabbedPane
    in Netbeans 6.5.1 with javafx 1.2 installed, theres always the error message "Could not find Symbol" at the "TabbedPane" expression.
    I hope you can help, i´m quite frustrated at the moment.
    Thanks in advance for any help.

    I have some problems finding the TabbedPane and SplitPane package in javafx 1.2.No wonder, they don't exist (yet!).
    The article you link to isn't a tutorial but a demo.
    At the bottom of the article, there a link to the source of this implementation: mytabbedpane

  • Quickest way to clone a JPanel and its components?

    Is there a quick method to clone a JPanel and its components?

    This has been tried before and not work.
    JVM reports errors :
    clone() has protected access in java.lang.Object.

  • Height of JPanel in SplitPane can only get bigger?

    Hi,
    I've got a JPanel in the bottom part of a JSplitPane. In the PaintComponent I use the height of the panel in some calculations (to make sure what i want to draw stays visible). So I take the height of the JPanel (getHeight). When I change the dividerlocation by hand, the height of the JPanel does get bigger, but when I move it in the other direction, it doesn't get smaller again. I am confused.
    How is that possible? And any ideas to get the "real" size ("real" being the size of what i can see in the splitpane)?
    Regards,
    Ren�

    If you right click on the image on the page in the context menu select photo box alignment and then select one of scale to fit {centered, Left-aligned, Right-aligned}
    That should do what you are loking for.

  • Hot to get components to adjust size & fill Jpanel when splitPane is moved

    HI, i am developing a small app that makes heavy use of swing. in the main JFrame, i need to have a a horizontal split bar dividing it into a top and a bottom
    area and in the bottom area another vertical one diving it into 2, left and right. in the right area i need to put a lot of visual controls such as labels, textboxes....
    the thing is that i need them to stretch and shrink in size everytime the splitpane is moved. i use a JPanel to hold these controls.
    how can it be done?
    thank you

    DarrylBurke wrote:
    _steve wrote:
    i know how to use layout managers i just don't know which yields the desired behavior, the one i want.Hence the nudge towards the relevant tutorial, where you can find what you need to know.
    i am not an expert swing developer and i don't intend to become one today.Ah, ok. Good luck finding another job, then.
    thank youYou're welcome, I'm sure.
    dbthank yourself, typical. if you don't have any positive input to contribute with, please do not enter the discussion and save yourself the frustration.
    not having time, not needing swing is something and not willing to work is something else.you are no better developer, that i am sure of, too.

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

  • Problem with jpanel and image

    i have a jinternalframe with gridbaglayout which has several jpanels. one of the jpanels has to display an image.
    i have searched through the forum and i have made a method to draw the image,
    but the problem is that when i added to the jpanel the last (jpanel) gets much bigger and as a result to break down the layout.
    any help is appreciated!

    i have searched through the forum and i have made a method to draw the image,Just add the image to a JLabel.
    when i added to the jpanel the last (jpanel) gets much bigger[url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]How to Use Layout Managers

Maybe you are looking for

  • Code for radio button is not working plz help

    checkboxes are working fine but when i put radio code submit button does nothing plz help thanks in advance <%@ page language="java" contentType ="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" import= "java.sql.*,java.io.*,com.anaghan.MyBe

  • Accessing Multiple Observers in an Observable class

    Hi! I have 2 Observers added via: this.addObserver() on my 1 Observable class. The 1st Observer works fine when i call: setChanged(); notifyObservers("SomeArgument");However, when i pass a different argument to the 2nd Observer that i added, it still

  • Photo stream in referenced mode?

    I'd like to have my photo stream show up in referenced mode in Aperture.  Anyone know how to do this?

  • My ibook won't start mac osx

    Hi! I was trying to download a program and install it but when restart my ibook it show the massage "Starting Mac OSX" for a few seconds with uncomplete load. And the display becomes blue forever.I counldn't even shut down. Please help! sakdanuwat Th

  • BW infoprovider ABAP

    Hi Experts, I need to extract, insert and update data directly to the infoprovider (multiprovider and infocube) through an ABAP program; please advice for possible function modules and BAPIs that I can use in the program. Some tricks and pointers wil