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.

Similar Messages

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

  • 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

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

  • 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

  • Problem with JPanel and JDesktopPane

    Hi,
    I am having a problem with my app and I wonder if someone can see what I am doing wrong. I have a class that extends JFrame that holds a centered JPanel to draw on. There are also 3-4 other JInternalFrames that are in use.
    From what I have read to use JDesktopPane to organize the JInternalFrames, all you do is add the JInternalFrames to the JDesktopPane and setContentPane to be the JdesktopPane:
            Jpanel panel = new JPanel();
            JDesktopPane dm = new JDesktopPane();
            setContentPane(dm);
            dm.add(panel, BorderLayout.CENTER);
            dm.add(internalFrame1);
            dm.add(internalFrame2);
            dm.add(internalFrame3);But as soon as I add the panel to the JDesktopPane then my JPanel doesnt show up. As I had it before I was adding the panel to the content pane of the Jframe, and adding the JinternalFrames to the layeredPane like this:
            getContentPane().add(panel, BorderLayout.CENTER);
            lp = getLayeredPane();
            lp.add(internalFrame1);
            lp.add(internalFrame2);
            lp.add(internalFrame3);and this worked but the JInternalFrames behaved badly, not getting focus or moving to the top frame when clicked, which I guess is what JDesktopPane is supposed to do. But how do I get my original JPanel in my JFrame to show up when added to the JDesktopPanel?
    Am I missing something here?
    Thanks,
    Paul

    Thanks for your response. I will try that when I get home, although I will be surprised if that works because I am already using setPreferredSize() . It seemed to me that once a Jframe's content pane gets assigned to a JDesktopPane, then the JPanel no longer has anywhere to draw itself, as according to the Sun documentation, you can only add a JInternalFrame to a JDesktopPane.
    So I am thinking its not possible to have a JPanel as the content pane of a JFrame while having a JDesktopPane containing my JInternalFrames. Is this indeed the case?
    Thanks,
    Paul

  • Problem with JFrame, JPanel and getInsets()...

    hi, this is my problem:
    I have a JFrame and I want add a JPanel to its ContentPan, I need to know the JFrame's getInsets values to set (with setBounds()) the right dimensions of the JPanel, but if I call getInsets() before of setVisible(true) I obtain all 0 values, if I call setVisible(true) before of add() I obtain the right values, but the JPanel is not showed.
    By now I have solved with this sequence:
    new panel();
    contpan.add(panel);
    getInsets();
    panel.setBounds();but I would pass the bounds values to my panel constructor, something like this:
    new panel(getInsets(););
    contpan.add(panel);Could someone help me?

    I have just found this post:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=302473
    And the first way seems to be the only way to solve the problem... :(
    Now the question is, does it exist a way to refresh a JFrame after that I have uset setVisible(true)?
    If it does exist I could have something like this:
    setVisible(true)
    new panel(getInsets(););
    contpan.add(panel);
    REFRESH();

  • An Image JPanel, A semi-transparent JPanel, and non-opaque components

    This is a more intelligent re-asking of the question I posed here: http://forum.java.sun.com/thread.jspa?threadID=579298&tstart=50.
    I have a class called ImagePane, which is basically a JPanel with an image background. The code is much like the ImagePanel posted by camickr, discussed in this topic: http://forum.java.sun.com/thread.jspa?forumID=57&threadID=316074 (except mine only draws the image, it does not tile or scale it).
    On top of my ImagePane, I can place another component, TransparentContainer. This again extends JPanel, only a color is specified in the constructor, and it is drawn at about 70% opacity. This component is meant to help increase the readability of text components that blend with the background image, without blocking out the background image completely.
    This works very well, until I need to add a component, like, say, a non-opaque JRadioButton in a ButtonGroup. When you select a new JRadioButton at runtime, the semi-transparent JPanel fills with a combination of a completely opaque color (the one specifies to the TransparentContainer) and garbage from the non-opaque component being redrawn.
    I have noticed that the UI is restored to being non-messed up if you place another application window on top of it and then move it. So apparently, one solution is to redraw the entire UI, or just the part that has the JRadioButton on it, every time the radio button is clicked. However, this seems unnecessarily complicated. It seems to me that I am missing something in my TransparentContainer's paintComponent() method. Does anyone have any ideas?
    Here is my TransparentContainer code, if it will help:
    import java.awt.AlphaComposite;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import javax.swing.JPanel;
    public final class TransparentContainer extends JPanel
         /* Private Fields: For use only by this class.
          *  These fields hold information needed by more
          *  than one method of this class.
         private boolean fullTransparencyEnabled;
         private Color baseColor;
         private Color outerBorderColor;
         private Color innerBorderColor;
         private int obw;
         private int ibw;
         private int cbw;
         /* -- START OF METHODS -- */
         /* public TransparentContainer(Color color, boolean fullTrans)
          *   Initiallizes the transparent container object
          *   with 'color' as its base color.
         public TransparentContainer(Color color, boolean fullTrans)
              fullTransparencyEnabled = fullTrans;
              baseColor = color;
              Color borders[] = findBorderColors();
              outerBorderColor = borders[0];
              innerBorderColor = borders[1];
              obw = 3;
              ibw = 1;
              cbw = obw + ibw;
         /* private Color[] findBorderColors(Color base)
          *   Calculates the colors for the outer and inner
          *   borders of the object based on the base color.
         private Color[] findBorderColors()
              Color borders[] = new Color[2];
              int colorData[] = new int[9];
              colorData[0] = getBaseColor().getRed();
              colorData[1] = getBaseColor().getGreen();
              colorData[2] = getBaseColor().getBlue();
              colorData[3] = colorData[0] - 50;          // outerBorder red
              colorData[4] = colorData[1] - 45;          // outerBorder green
              colorData[5] = colorData[2] - 35;          // outerBorder blue
              colorData[6] = colorData[0] + 30;          // innerBorder red
              colorData[7] = colorData[1] + 30;          // innerBorder green
              colorData[8] = colorData[2] + 20;          // innerBorder blue
              /* Make sure the new color data is not out of bounds: */
              for (int i = 3; i < colorData.length; i++)
                   if (colorData[i] > 255)
                        colorData[i] = 255;
                   else if (colorData[i] < 0)
                        colorData[i] = 0;
              borders[0] = new Color(colorData[3], colorData[4], colorData[5]);
              borders[1] = new Color(colorData[6], colorData[7], colorData[8]);
              return borders;
         /* public Color getBaseColor()
          *   Returns the baseColor of this object.
         public Color getBaseColor()
              return baseColor;
         /* public Color getOuterColor()
          *   Returns the outerBorderColor of this object.
         public Color getOuterColor()
              return outerBorderColor;
         /* public Color getInnerColor()
          *   Returns the innerBorderColor of this object.
         public Color getInnerColor()
              return innerBorderColor;
         /* public boolean getFullTransEnabled()
          *   Returns whether or not this object will render
          *   with all of its transparency effects.
         public boolean getFullTransEnabled()
              return fullTransparencyEnabled;
         /* protected void paintComponent(Graphics g)
          *   Paints the component with the borders and colors
          *   that were set up in above methods.
         protected void paintComponent(Graphics g)
              Graphics2D g2d = (Graphics2D) g;
              AlphaComposite alphaComp;
              g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
              g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
              g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
                                            RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
              g2d.setColor(getBaseColor());
              /* Draw the main body of the component */
              if (getFullTransEnabled())
                   alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f);
                   g2d.setComposite(alphaComp);
              else
                   alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);
                   g2d.setComposite(alphaComp);
              g2d.fillRect(cbw, cbw, super.getWidth() - 2 * cbw, super.getHeight() - 2 * cbw);
              alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f);
              g2d.setComposite(alphaComp);
              /* Draw the inner border: */
              g2d.setColor(getInnerColor());
              g2d.fillRect(obw, obw, ibw, super.getHeight() - obw * 2); // left border
              g2d.fillRect(obw, obw, super.getWidth() - obw, ibw); // top border
              g2d.fillRect(super.getWidth() - cbw, obw, ibw, super.getHeight() - obw * 2); // right border
              g2d.fillRect(obw, super.getHeight() - cbw, super.getWidth() - obw * 2, ibw); // bottom border
              /* Draw the outer border: */
              g2d.setColor(getOuterColor());
              g2d.fillRect(0, 0, obw, super.getHeight()); // left border
              g2d.fillRect(0, 0, super.getWidth() + obw, obw); // top border
              g2d.fillRect(super.getWidth() - obw, 0, obw, super.getHeight()); // right border
              g2d.fillRect(0, super.getHeight() - obw, super.getWidth(), obw); // bottom border
              alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);
              g2d.setComposite(alphaComp);
              g2d.dispose();
    }

    I added the main method to your TransparentContainer class ...
         public static void main(String[] args) {
              JFrame f = new JFrame("test transparent container");
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              TransparentContainer tc = new TransparentContainer(Color.RED, true);
              JLabel label = new JLabel("Hello, World!");
              tc.add(label);
              f.getContentPane().add(tc);
              f.setSize(800, 600);
              f.setVisible(true);
         }...using the code you posted the label was not shown. I modified your paintComponent(Graphics g) method and I did this (see the areas in bold):
         /* protected void paintComponent(Graphics g)
          *   Paints the component with the borders and colors
          *   that were set up in above methods.
         protected void paintComponent(Graphics g)
              // Call super so components added to this panel are visible
              super.paintComponent(g);
              Graphics2D g2d = (Graphics2D) g;
              AlphaComposite alphaComp;
              g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
              g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
              g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION,
                                            RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
              g2d.setColor(getBaseColor());
              /* Draw the main body of the component */
              if (getFullTransEnabled())
                   alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f);
                   g2d.setComposite(alphaComp);
              else
                   alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);
                   g2d.setComposite(alphaComp);
              g2d.fillRect(cbw, cbw, super.getWidth() - 2 * cbw, super.getHeight() - 2 * cbw);
              alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f);
              g2d.setComposite(alphaComp);
              /* Draw the inner border: */
              g2d.setColor(getInnerColor());
              g2d.fillRect(obw, obw, ibw, super.getHeight() - obw * 2); // left border
              g2d.fillRect(obw, obw, super.getWidth() - obw, ibw); // top border
              g2d.fillRect(super.getWidth() - cbw, obw, ibw, super.getHeight() - obw * 2); // right border
              g2d.fillRect(obw, super.getHeight() - cbw, super.getWidth() - obw * 2, ibw); // bottom border
              /* Draw the outer border: */
              g2d.setColor(getOuterColor());
              g2d.fillRect(0, 0, obw, super.getHeight()); // left border
              g2d.fillRect(0, 0, super.getWidth() + obw, obw); // top border
              g2d.fillRect(super.getWidth() - obw, 0, obw, super.getHeight()); // right border
              g2d.fillRect(0, super.getHeight() - obw, super.getWidth(), obw); // bottom border
              alphaComp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f);
              g2d.setComposite(alphaComp);
              // Do not dispose the graphics
              // g2d.dispose();          
         }...seems to work fine now. Perhaps you should also add methods or additional constructors so the user can easily change the transparency level...and add some javadoc comments to your constructors ...at a first glance I did not know what fullTrans was
    public TransparentContainer(Color color, boolean fullTrans)good luck!!

Maybe you are looking for

  • AnyConnect 3.1 - removing Security Warning: Untrusted VPN Server Certificate!

    Hi guys, Is there a way to disable the warning generated from using self signed certs? I would like to make the process as seamless as possible. AnyConnect 3.1 ASA 8.4(2) Thanks.

  • Cannot get on the internet no ip address

    My computer stopped connecting to the Internet. Airport says there is no ip address. How can I fix it?

  • -24994 runtime environment error while starting MAXDB J2E instance

    Hello, I have a SAPDB installation on my Windows XP machine that came along with SAP WAS 640 SP12. I was trying to explore the dbmcli commands basically to shrink the log files. Its strange but when I went to SAPMMC and checked the database, it went

  • Huawei e17 USB modem

    Hi, I have one annoying trouble with my huawei e17 USB modem (connected to MacBook Pro): • Internet connection works fine when I log in but once I log out and my wife log's in the internet connection just hangs...tries to connect but hangs. Only solu

  • Changing Movie to Music Video On 5th Generation

    I just bought a 5th Generation iPod and I am having a trouble changing music videos to music video in iTunes. I can right click on a single file and under options change Video Type to Music Video from Movie the problem is I have slightly over 1,000 m