Component - validate, invalidate

What's the proper way to use the Component validate and invalidate methods?
Quick background: I've extended JPanel to draw an image as it's background. The image can be scaled and what i want to do is set the preferred size of the panel to reflect that of the scaled image size.
I've placed some zoom in/out buttons in a frame along with the panel but i can't get them to work as i would expect. The code below does what i want it to do but i don't understand why i need to set both the preferred size and the size, then why i need to call invalidate and then validate on the parent.
Any ideas/guidance on the proper way of resizing components and getting the parents to re-layout with the new sizes?
Thanks
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JPanel;
public class ImagePanel extends JPanel {
     /** Original image */
     private Image image;
     /** Scaled version */
     private Image zoomedImage;
     /** Scaled width */
     private int imageZoomWidth;
     /** Scaled height */
     private int imageZoomHeight;
     @Override
     protected void paintComponent(Graphics g) {
          g.clearRect(0, 0, getWidth(), getHeight());
          g.drawImage(zoomedImage, 0, 0, this);
     public void setImage(Image image) {
          this.image = image;
          imageZoomWidth = image.getWidth(this);
          zoom(0);
     public void zoom(int delta) {
          imageZoomWidth += delta;
          zoomedImage = image.getScaledInstance(imageZoomWidth, -1,
                    Image.SCALE_FAST);
          imageZoomHeight = zoomedImage.getHeight(this);
          // Both these are needed?
          setPreferredSize(new Dimension(imageZoomWidth, imageZoomHeight));
          setSize(getPreferredSize());
          // invalidate to force re-layout of parents
          invalidate();
          // Why is this is needed too ?
          if (getParent() != null) {
               getParent().validate();
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class ImagePanelTest {
     public static void main(String[] args) throws FileNotFoundException,
               IOException {
          JFrame frame = new JFrame("Image Panel Test");
          JButton zoomInButton = new JButton("Larger");
          JButton zoomOutButton = new JButton("Smaller");
          final ImagePanel imgPanel = new ImagePanel();
          imgPanel.setImage(ImageIO.read(new FileInputStream(
                    "image09-07-14_12-34-57-99.jpg")));
          imgPanel.setBorder(BorderFactory.createLineBorder(Color.black));
          zoomInButton.addActionListener(new ActionListener() {
               @Override
               public void actionPerformed(ActionEvent e) {
                    imgPanel.zoom(50);
          zoomOutButton.addActionListener(new ActionListener() {
               @Override
               public void actionPerformed(ActionEvent e) {
                    imgPanel.zoom(-50);
          Container container = frame.getContentPane();
          JPanel panel = new JPanel();
          panel.setLayout(new FlowLayout());
          panel.add(zoomOutButton);
          panel.add(imgPanel);
          panel.add(zoomInButton);
          container.add(new JScrollPane(panel));
          frame.setSize(800, 600);
          frame.addWindowListener(new WindowAdapter() {
               public void windowClosing(WindowEvent we) {
                    System.exit(0);
          frame.setVisible(true);
}

You're playing the role of the RepaintManager with that code. Just change your zoom method to this,
public void zoom(int delta) {
    imageZoomWidth += delta;
    zoomedImage = image.getScaledInstance(imageZoomWidth, -1,
            Image.SCALE_FAST);
    imageZoomHeight = zoomedImage.getHeight(this);
    setPreferredSize(new Dimension(imageZoomWidth, imageZoomHeight));
    revalidate();
    repaint();
}and all will be well.

Similar Messages

  • Problem with doLayout() / validate() / invalidate()

    Hi, Java developers!!!
    Ok, this is my current situation:
    My application is as follows:
    ....................................Frame
    ...............................(BorderLayout)
    .........................................|
    ................./----------------+-----------------\
    ................|.......................|.........................|
    ............NORTH:...............CENTER:..............SOUTH:
    ............Canvas.................Panel................TextField
    .................................(BorderLayout)
    .........................................|
    .........................../---------+---------\
    ..........................|.............................|
    ....................CENTER:.......................EAST:
    ......................Panel..........................Panel
    ................(BorderLayout).............(BorderLayout)
    ........................|..................................|
    .........|..............|............|..............|..............|
    .....SOUTH:....CENTER:....EAST:......CENTER:......EAST:
    ....Scrollbar....Canvas....Scrollbar.....Canvas......Scrollbar
    .(Horizontal)................(Vertical)........(X).......(Vertical)
    The Canvas component marked as (X) has special code
    that makes it's width resizable. In fact, what I did was:
    public Dimension getPreferredSize()
    Dimension sd;
    Dimension cd;
    sd = parentFrame.getSize();
    cd = new Dimension(super.getPreferredSize());
    cd.width = (int)(((double)sd.width) * widthPercent);
    return cd;
    Here, widthPercent is a global variable that indicates how
    wide must be the component, related to the containing
    frame's width.
    When I change widthPercent, I do the following:
    widthPercent = newWidthPercent;
    invalidate();
    repaint();
    Well, it turns out that, when invoked, the component
    does NOT change it's width immediately, but until the
    next time I >resize< the Frame. I know the code above
    is being executed, since the Frame is seen to be redrawing, but the layout does NOT change. I've tested
    with almost everything I could:
    doLayout();
    validate(); invalidate();
    getParent().doLayout();
    getParent().validate(); getParent().invalidate();
    parentFrame.doLayout();
    parentFrame.validate(); parentFrame.invalidate();
    etc. but it doesn't seem to work!!! No one changes the layout of the components until I resize the window!!!
    Any ideas, please?
    - Heriberto Delgado
    ([email protected])

    Sorry for the long delay. I was just preparing the application for posting. The original one was somewhat large, with a lot of stuff that could hide the true problem. I narrowed it the most I could, while still showing the behavior I mentioned before. Here it is:
    (The panel at the right is the resizable one. It's supposed to resize with the black stripe between the
    right & left panels, which it does, but it shows up only until the window is resized.)
    import java.awt.*;
    import java.awt.event.*;
    public class MainAppTest extends Frame
         class MapViewer extends Canvas
              public MapViewer()
                   super();
                   setBackground(Color.white);
         class SpriteViewer extends Canvas
              double widthPercent;
              Cursor resizeCursor;
              int initDraggedPosX;
              Frame parentFrame;
              public SpriteViewer(Frame newParentFrame)
                   super();
                   setBackground(Color.lightGray);
                   setFont(new Font("SansSerif",Font.PLAIN,12));
                   parentFrame = newParentFrame;
                   widthPercent = 0.2;
                   resizeCursor = Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR);
                   enableEvents(MouseEvent.MOUSE_CLICKED |
                   MouseEvent.MOUSE_MOVED |
                   MouseEvent.MOUSE_DRAGGED);
              public void processMouseEvent(MouseEvent e)
                   int i,m;
                   super.processMouseEvent(e);
                   switch(e.getID())
                        case MouseEvent.MOUSE_CLICKED:
                             if(e.getX() < 5)
                                  initDraggedPosX = e.getX();
                             break;
              public void processMouseMotionEvent(MouseEvent e)
                   Dimension fd;
                   Dimension cd;
                   Cursor newCursor;
                   int newWidth;
                   double newWidthPercent;
                   super.processMouseMotionEvent(e);
                   switch(e.getID())
                        case MouseEvent.MOUSE_MOVED:
                             if(e.getX() < 5)
                                  newCursor = resizeCursor;
                             } else
                                  newCursor = Cursor.getDefaultCursor();
                             if(!(newCursor.equals(getCursor())))
                                  setCursor(newCursor);
                             break;
                        case MouseEvent.MOUSE_DRAGGED:
                             if(getCursor().equals(resizeCursor))
                                  fd = parentFrame.getSize();
                                  cd = getSize();
                                  newWidth = cd.width + initDraggedPosX - e.getX();
                                  if(fd.width!=0)
                                       newWidthPercent = ((double)newWidth)
                                       / ((double)fd.width);
                                       if(newWidthPercent<0.05)
                                            newWidthPercent = 0.05;
                                       if(newWidthPercent>0.9)
                                            newWidthPercent = 0.9;
                                       if(widthPercent != newWidthPercent)
                                            widthPercent = newWidthPercent;
                                            parentFrame.invalidate();
                                            parentFrame.validate();
                                            parentFrame.repaint();
                             break;
              public Dimension getPreferredSize()
                   Dimension sd;
                   Dimension cd;
                   sd = parentFrame.getSize();
                   cd = new Dimension(super.getPreferredSize());
                   cd.width = (int)(((double)sd.width) * widthPercent);
                   return cd;
              public void paint(Graphics g)
                   Dimension cd;
                   cd = getSize();
                   g.setColor(Color.black);
                   g.fillRect(0,0,
                   5,cd.height - 1);
                   g.setColor(Color.lightGray);
                   g.fillRect(5,0,
                   cd.width - 6,cd.height - 1);
         MapViewer CurrentMapViewer;
         Scrollbar HorizMapScrollbar;
         Scrollbar VertMapScrollbar;
         SpriteViewer CurrentSpriteViewer;
         Scrollbar VertSpriteScrollbar;
         Panel StatusBar;
         public MainAppTest(String[] args)
              super("Test");
              AppStart();
         public void AppStart()
              Class c;
              Panel p,p2,p3;
              Dimension sd;
              GridBagLayout gbl;
              GridBagConstraints gbc;
              TextField tf;
              setLayout(new BorderLayout(0,0));
              p = new Panel(new BorderLayout(0,0));
              CurrentMapViewer = new MapViewer();
              p.add(BorderLayout.CENTER,CurrentMapViewer);
              HorizMapScrollbar = new Scrollbar(Scrollbar.HORIZONTAL);
              p.add(BorderLayout.SOUTH,HorizMapScrollbar);
              VertMapScrollbar = new Scrollbar(Scrollbar.VERTICAL);
              p.add(BorderLayout.EAST,VertMapScrollbar);
              p2 = new Panel(new BorderLayout(0,0));
              CurrentSpriteViewer = new SpriteViewer(this);
              p2.add(BorderLayout.CENTER,CurrentSpriteViewer);
              VertSpriteScrollbar = new Scrollbar(Scrollbar.VERTICAL);
              p2.add(BorderLayout.EAST,VertSpriteScrollbar);
              p3 = new Panel(new BorderLayout(0,0));
              p3.add(BorderLayout.CENTER,p);
              p3.add(BorderLayout.EAST,p2);
              add(BorderLayout.CENTER,p3);
              StatusBar = new Panel();
              StatusBar.setBackground(Color.lightGray);
              gbl = new GridBagLayout();
              gbc = new GridBagConstraints();
              StatusBar.setLayout(gbl);
              gbc.weightx = 1;
              gbc.weighty = 1;
              gbc.insets = new Insets(0,0,0,0);
              gbc.fill = GridBagConstraints.BOTH;
              gbc.anchor = GridBagConstraints.CENTER;
              gbc.gridwidth = GridBagConstraints.REMAINDER;
              gbc.gridheight = 1;
              tf = new TextField();
              gbl.setConstraints(tf,gbc);
              StatusBar.add(tf);
              add(BorderLayout.SOUTH,StatusBar);
              addWindowListener
                   new WindowAdapter()
                        public void windowClosing(WindowEvent e)
                             AppStop();
              pack();
              sd = getToolkit().getScreenSize();
              setSize(sd.width * 8 / 10, sd.height * 8 / 10);
              show();
              CurrentSpriteViewer.requestFocus();
         public void AppStop()
              System.exit(0);
         public static final void main(String[] args)
              new MainAppTest(args);

  • Calendar component validate and valueChange events in creator 2_1

    Hi, I have a very simple test scenario for calendar component -
    two textfields + one calendar. When value changed (either via manually enter or select date from popup calendar), I want to see if validate and valueChange events get fired.
    ( similar to this post http://developers.sun.com/jscreator/reference/code/samplecomps/2004q2/calendar/calendar_component.pdf)
    So, in page1, I have:
    public void calendar1_validate(FacesContext context, UIComponent component, Object value) {
    // TODO: Replace with your code
    textField2.setValue("validate visit:"+calendar1.getValue());
    public void calendar1_processValueChange(ValueChangeEvent event) {
    // TODO: Replace with your code
    textField1.setValue("valuechange visit:"+calendar1.getValue());
    In the calendar property, I have:
    validate: lengthValidator1.validate()
    valueChange: calendar1_processValueChange
    valueChangeListener: #{Page1.calendar1_processValueChange}
    However, nothing happens when a date, valid or not, was entered or a new date was selected from popup.
    I have a message attached to calendar1 and it shows nothing.
    I set break points in functions above and there is not break.
    Question:
    1. Where can I look for clues of what events get fired?
    2. Any simple thing that I missed using calender? simple property setting...etc.
    System: vista + creator 2_1
    Thanks in advance for your suggestions

    There may be a couple of things going on here.
    First, is the page being submitted?
    Second, I think custom validators have to be registered. Have you registered the validator?

  • Component.validate() leaves invalidated

    Hello,
    I have the following problem:
    nodeComp.validate();
    if (!nodeComp.isValid())
         System.err.println("Component is invalid!!!");It keeps printing that the component is invalid.
    I am using a JComponent as a stamp (same as in JTable) so my component is not really added to any container.
    PS: bsampieri are you there?

    yeah...
    Did you read the API docs on what validate() and isValid() means? I don't believe, from reading them just now, that they are that closely related.
    validate() -- Ensures that this component has a valid layout. This method is primarily intended to operate on instances of Container.
    isValid() -- Determines whether this component is valid. A component is valid when it is correctly sized and positioned within its parent container and all its children are also valid.
    What's the real problem? That it says it's valid or not shouldn't matter. If you call setSize() and validate(), after that you should be able to call paint() on the component with another graphics object to draw that component on the graphics.

  • Programatically validate/invalidate cache for specific query

    Hi,
    I am looking to programatically invalidate and re-instantiate the cache for a specific query.
    I know how to perform this manually via RSRT, RSRT1/2....etc. What I am looking for is a way to schedule this and programatically control caching on specific query.
    Any help would be wonderful!!
    Thanks!

    hi Dong Suk Choi ,
    the technical information which u have furnished clearly says that the settings
    that u have made does not enable the query to use cache.
    u can enhance cache by customizing the inforovider or in the transaction rsrt
    even if the concerned query does not have required settings u can make them in rsrt tcode.
    goto rsrt set the read mode and cache mode as u wish, however default settings would give optimum performance.
    and run the query.
    in the rsrt screen a push button execute + debug enter that and unmark the check box do not use cache.
    hope this helps.
    reward points if helpful.
    bye.
    under properties tab u can give the query settingMessage was edited by:
            Rakesh Elangovan

  • Resizing component in JScrollPane

    Hi!
    I want to do the following: when the button pressed, resize the component(JPanel) inside the JScrollPane.
    I tried the following code:
    jPanel1.setPreferredSize(new Dimension(400, 300));
    jScrollPane1.getViewport().add(jPanel1, null);
    void jButton1_actionPerformed(ActionEvent e)
    jPanel1.setPreferredSize(new Dimension(4000, 3000));
    When I press the button, nothing happens.
    Please help.

    Thank you, Stas, but it didn't work. Now my code is:
    void jButton1_actionPerformed(ActionEvent e)
    jPanel1.setPreferredSize(new Dimension(4000, 3000));
    ((Component)jScrollPane1).invalidate();
    jScrollPane1.validate();
    jScrollPane1.repaint();
    I expected my horizontal and vertical bars to change ( the sign that the panel's size changed), but they didn't.

  • Qt heavy weight component

    Hi guys,
    Im using the QT java api and have hit some problems with their AWT video window component. The reason I'm posting here rather than the QT forums is that I believe this problem is common to all heavy weight components in Java.
    Ok, the QT api offers a factory method for creating what they call QTComponent (awt heavy weight component - extends java.awt.component) which I add to a dedicated JPanel.
    I need to be able to set the visibility of the video window so I do;
    parent_panel.setVisible(value)
    parent_panel.repaint();
    parent_panel.invalidate();
    parent_panel.validate();
    which sets the parent JPanel visibility to hidden but does not hide the child video window. (note: this is called from the event dispatch thread).
    I have tried validate, invalidate, repaint (you name it), on both the parent JPanel and the java.awt.component itself, but this still doesn't fix the problem.
    One thing to note is that if I resize or minimize then maximize the container JFrame the video window disappears. So i'm guessing the handlers for these events execute routines I need to in my 'setvisible' method.
    If anyone could help that would be great.
    Many thanks,
    Alex

    Athlon1600 wrote:
    that heavy-weight component is JDIC web browser. It's the only cross-platform browser I know and it's one of the main controls in my GUI. can't change thatCan't help you there.
    JInternalFrame descends from JComponent? yes?Yep. So it's lightweight.
    Well, I'm not smart enough yet to mix lightweight and heavyweight components, but fortunately Google is: [Mixing Heavy and Light Components|http://java.sun.com/products/jfc/tsc/articles/mixing/]
    ~{color:gray}the first hit by the way{color}~

  • Paint Component

    Hi all
    i have four classes plot , plot3d, plotsurface and test
    plot is derived from JPanel and plot3d and plotsurface extend plot class
    i am trying to do a very simple operation . just making a tool bar with 2 buttons to switch between plots .
    the 2 plot classes plot3d and plotsurface just draw a line on the screen
    problem is that when the user clicks one button it doesnot show up on the screen but when the window is resized it does call paint component of the corresponding class
    can Any one explain why this is happening......
    package test;
    import javax.swing.*;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    public abstract class plot extends JPanel {
    plot()
    public void paintComponent(Graphics g)
    Graphics2D graphics2D=(Graphics2D)g;
    super.paintComponent(g);
    package test;
    import javax.swing.*;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    public class plot3d extends plot {
    plot3d(boolean resizable)
    public void paintComponent(Graphics g)
    Graphics2D graphics2D=(Graphics2D)g;
    super.paintComponent(g);
    graphics2D.drawLine(200,200,320,320);
    package test;
    import javax.swing.*;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    public class plotsurface extends plot {
    plotsurface(boolean resizable)
    public void paintComponent(Graphics g)
    Graphics2D graphics2D=(Graphics2D)g;
    super.paintComponent(g);
    graphics2D.drawLine(120,120,140,140);
    package test;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.Graphics2D.*;
    import java.applet.*;
    public class Test extends javax.swing.JApplet {
    private Container container;
    public Rectangle rect;
    JPanel toolBar;
    JButton contourButton;
    JButton surfaceButton;
    JPanel toolPanel;
    public Graphics g;
    public test.plot3d graph3D;
    public test.plotsurface graphSurface;
    private int plotType=0;
    private void graph3D(Graphics2D g2)
    graph3D=new plot3d(false);
    public void graphSurface(Graphics2D g2)
              graphSurface=new plotsurface(false);
    private void changeplottoContour()
    if(plotType==0)
    return;
    plotType=0;
    g=container.getGraphics();
    Graphics2D g2=(Graphics2D)g;
    container.removeAll();
    repaint();
    graphSurface=null;
    System.gc();
    graph3D(g2);
    container.add(toolPanel,BorderLayout.NORTH);
    container.add(graph3D,BorderLayout.CENTER);
    private void changeplottoSurface()
    if(plotType==1)
    return;
    plotType=1;
    g=container.getGraphics();
    Graphics2D g2=(Graphics2D)g;
    container.removeAll();
    repaint();
    graph3D=null;
    System.gc();
    graphSurface(g2);
    container.add(toolPanel,BorderLayout.NORTH);
    container.add(graphSurface,BorderLayout.CENTER);
    private void surfaceButtonActionPerformed(java.awt.event.ActionEvent evt)
         changeplottoSurface();
         repaint();
    private void contourButtonActionPerformed(java.awt.event.ActionEvent evt)
         changeplottoContour();
         repaint();
    public void init()
         container=getContentPane();
    g=container.getGraphics();
    Graphics2D g2=(Graphics2D)g;
    Rectangle r1= new Rectangle();
    rect=new Rectangle();
    //r1=container.getBounds();
    toolPanel= new JPanel(new BorderLayout());
    toolBar = new JPanel();
    contourButton = new JButton("Contour");
    toolBar.add(contourButton);
    contourButton.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    contourButtonActionPerformed(evt);
    surfaceButton = new JButton("Surface Plot");
    toolBar.add(surfaceButton);
    surfaceButton.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    surfaceButtonActionPerformed(evt);
    toolBar.setBackground(Color.white);
    toolPanel.add(toolBar,BorderLayout.NORTH);
    container.add(toolPanel,BorderLayout.NORTH);
    Rectangle r2= toolPanel.getBounds();
    Dimension appletSize = this.getSize();
    int appletHeight= appletSize.height;
    int appletWidth= appletSize.width;
              rect.setBounds(0,(int)r2.getHeight(),appletWidth,appletHeight-(int)r2.getHeight());
    plotType=0;
         graph3D(g2);
         container.add(graph3D,BorderLayout.CENTER);

    in your button action listeneres (e.g. contourButtonActionPerformed()) don't only call repaint(), but update(this.getGraphics());
    this should help in most cases. other refreshing methods are:
    java -Dsun.java2d.noddraw=true HelloWorld
    java.awt.Component.repaint()
    java.awt.Component.update(Graphics) (e.g. c.update(c.getGraphics());)
    java.awt.Component.validate()
    javax.swing.JComponent.revalidate()
    javax.swing.JComponent.updateUI()
    javax.swing.SwingUtilities.updateComponentTreeUI(java.awt.Component)

  • Quicktime heavy weight components

    Hi guys,
    Im using the QT java api and have hit some problems with their AWT video window component. The reason I'm posting here rather than the QT forums is that I believe this problem is common to all heavy weight components in Java.
    Ok, the QT api offers a factory method for creating what they call QTComponent (awt heavy weight component - extends java.awt.component) which I add to a dedicated JPanel.
    I need to be able to set the visibility of the video window so I do;
    parent_panel.setVisible(value)
    parent_panel.repaint();
    parent_panel.invalidate();
    parent_panel.validate();
    which sets the parent JPanel visibility to hidden but does not hide the child video window. (note: this is called from the event dispatch thread).
    I have tried validate, invalidate, repaint (you name it), on both the parent JPanel and the java.awt.component itself, but this still doesn't fix the problem.
    One thing to note is that if I resize or minimize then maximize the container JFrame the video window disappears. So i'm guessing the handlers for these events execute routines I need to in my 'setvisible' method.
    If anyone could help that would be great.
    Many thanks,
    Alex

    Lightweight components are components whose printed
    sources weigh less than 200 grams.Is a paper and a print face required?

  • Pack() vs. frame.pack()..??

    Hey guys.
    I'm just starting to create a GUI. The code is below:
    public MyFrame() {
            frame = new JFrame("Take A Seat");
            frame.setBounds(100,100, 300, 200);
            //frame.setResizable(false);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Display frame
            //initComponents();  
            pack();
            frame.setVisible(true);
        }What is the difference between calling pack() and frame.pack()?? I find that when I call "frame.pack()" and I'm trying to display ONLY an empty frame, it only shows the TitleBar. However, if I call "pack()", it shows the full (blank,grey) frame with my bounds.
    The thing is, Netbeans creates a method called initComponents() that calls pack() and setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    But this EXIT_ON_CLOSE doesn't work for my frame. It only works if I use:
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Can anyone explain this to me please? I would just like to know what's running, what's happening etc...
    ...DJVege...

    I think your MyFrame is exteneded from JFrame
    pack() validates the components.
    You can use validate or revalidate also.
    To create a splash screen you can try
    frame=new JFrame();
    frame.setUndecorated(true);
    pack adds the components in the frame and something
    like adjust them to the max component size.
    If you add a button to frame and pack it
    then the frame size will be of button (packed).
    If you don't add anything in the frame then
    obviously only titlebar will be visible.
    I think you should study validate,invalidate,revalidate and pack

  • Rubber stamp table cell renderers performance

    One never stops to learn...
    http://java.sun.com/javase/6/docs/api/javax/swing/table/DefaultTableCellRenderer.html
    +“...So this class overrides the validate, invalidate, revalidate, repaint, and firePropertyChange methods to be no-ops and override the isOpaque method solely to improve performance. If you write your own renderer, please keep this performance consideration in mind.”+
    Hm. This was quite a revelation for me. However, I’m having troubles implementing it. I have rather complex cell renderers… To be exact: I have complex cell editors, for example one containing two textfields and two buttons (key & description textfields plus zoom & search buttons) inside a JPanel. The JPanel is the cell editor component. Because I want the buttons on exactly the same location in the renderer as in the editor, I have an editor-to-renderer wrapper.
    I cannot disable the mentioned methods on the JPanel that is the renderer, then its contents isn’t painted anymore. Invalidate and validate must stay.
    Now, I can easily build a simple text based renderer using DefaultTableCellRenderer aka JLabel. However, what if a table must show more than trivial stuff? Are there any good guides on how to build complex cell renderers?
    Again: I often use the editor-as-renderer wrapper in order to not have to code stuff twice. At all works just fine, but appearantly is very slow (my tables are slow indeed)... Any way to do this correctly?

    Ok, here you are with two SSCCE's! :-)
    The first test only shows a regular complex renderer (2x textfield, 2x button). According to the specs the component must have certain methods disabled, so they are overridden in the jpanel that holds all these components. Run, and then try again with the two methods uncommented.
    The second test is how I normally do it; I do not want to write separate editors and renderers, so I only write the editor and use an editor-to-renderer wrapper. In order to fulfill the requirement, I wrap the editor component in a second jpanel that overrides the required methods. Again, run and then try again with the two methods uncommented.
    package test;
    import java.awt.Component;
    import java.awt.GridLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    * Test1: use a complex cell renderer and follow the specs in
    * http://java.sun.com/javase/6/docs/api/javax/swing/table/DefaultTableCellRenderer.html
    public class CellRendererTest
          * @param args
         public static void main(String[] args)
              SwingUtilities.invokeLater(new Runnable()
                   @Override
                   public void run()
                        JTable lJTable = new JTable(new DefaultTableModel(new String[][]{{"a1","b1"},{"a2","b2"}}, new String[]{"A","B"}));
                        lJTable.setDefaultRenderer(Object.class, new ComplexCellRenderer());
                        JFrame lJFrame = new JFrame();
                        lJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        lJFrame.add(lJTable);
                        lJFrame.setSize(500,100);
                        lJFrame.setVisible(true);
         // =============================================================================
         static class ComplexCellRenderer implements TableCellRenderer
              JTextField iKey = new JTextField(5);
              JButton iSearch = new JButton("?");
              JButton iGoto = new JButton(">");
              JTextField iDescription = new JTextField(20);
              JPanel iJPanel = new JPanel()               
    //               @Override public void validate() {}
    //               @Override public void invalidate() {}
                   @Override public void revalidate() {}
                   @Override public void repaint() {}
                   @Override public void firePropertyChange(String propertyName, Object oldValue, Object newValue) {}
                   @Override public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {}
                   @Override public void firePropertyChange(String propertyName, int oldValue, int newValue) {}
              public ComplexCellRenderer()
                   iKey.setBorder(null);
                   iDescription.setBorder(null);
                   iDescription.setEnabled(false);
                   iJPanel.setLayout(new GridLayout());
                   iJPanel.add(iKey);
                   iJPanel.add(iSearch);
                   iJPanel.add(iGoto);
                   iJPanel.add(iDescription);
              @Override
              public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
                   iKey.setText( value == null ? "" : value.toString() );
                   iDescription.setText( value == null ? "" : value.toString() + "..." );
                   return iJPanel;
    }Test 2:
    package test;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.GridLayout;
    import javax.swing.AbstractCellEditor;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellEditor;
    import javax.swing.table.TableCellRenderer;
    * Test2: usually when have complex cell renderers, it actually means you have complex cell editors.
    * You want the renderer to look 100% like the editor, so it is practical to implement a wrapper.
    * Naturally the wrapped editor must adhere to the specs in: 
    * http://java.sun.com/javase/6/docs/api/javax/swing/table/DefaultTableCellRenderer.html
    * So the idea is the wrap it in a special panel, this is what the "useAsRenderer" method is for.
    public class CellRendererTest2
          * @param args
         public static void main(String[] args)
              SwingUtilities.invokeLater(new Runnable()
                   @Override
                   public void run()
                        JTable lJTable = new JTable(new DefaultTableModel(new String[][]{{"a1","b1"},{"a2","b2"}}, new String[]{"A","B"}));
                        lJTable.setDefaultEditor(Object.class, new ComplexCellEditor());
                        lJTable.setDefaultRenderer(Object.class, new UseTableCellEditorAsTableCellRenderer(new ComplexCellEditor().useAsRenderer()));
                        JFrame lJFrame = new JFrame();
                        lJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        lJFrame.add(lJTable);
                        lJFrame.setSize(500,100);
                        lJFrame.setVisible(true);
         // =============================================================================
         // The editor
         static class ComplexCellEditor extends AbstractCellEditor  implements TableCellEditor
              JTextField iKey = new JTextField(5);
              JButton iSearch = new JButton("?");
              JButton iGoto = new JButton(">");
              JTextField iDescription = new JTextField(20);
              JPanel iJPanel = new JPanel();
              public ComplexCellEditor()
                   super();
                   iKey.setBorder(null);
                   iDescription.setBorder(null);
                   iDescription.setEnabled(false);
                   iJPanel.setLayout(new GridLayout());
                   iJPanel.add(iKey);
                   iJPanel.add(iSearch);
                   iJPanel.add(iGoto);
                   iJPanel.add(iDescription);
              @Override
              public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
                   iKey.setText( value == null ? "" : value.toString() );
                   iDescription.setText( value == null ? "" : value.toString() + "..." );
                   return iJPanel;
              @Override
              public Object getCellEditorValue()
                   return iKey.getText();
              public ComplexCellEditor useAsRenderer()
                   JPanel lJPanel = new JPanel()
    //                    @Override public void validate() {}
    //                    @Override public void invalidate() {}
                        @Override public void revalidate() {}
                        @Override public void repaint() {}
                        @Override public void firePropertyChange(String propertyName, Object oldValue, Object newValue) {}
                        @Override public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {}
                        @Override public void firePropertyChange(String propertyName, int oldValue, int newValue) {}
                   lJPanel.setLayout(new BorderLayout());
                   lJPanel.add(iJPanel);
                   iJPanel = lJPanel;
                   return this;
         // ==========================================================================================
         // Simplified version of the wrapper (normally this wrapper takes care of the special JPanel)
         static class UseTableCellEditorAsTableCellRenderer implements TableCellRenderer
              public UseTableCellEditorAsTableCellRenderer(TableCellEditor tableCellEditor)
                   iTableCellEditor = tableCellEditor;
              private TableCellEditor iTableCellEditor = null;
              @Override
              public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
                  // we use the editor as the renderer
                  Component lEditor = iTableCellEditor.getTableCellEditorComponent(table, value, isSelected, row, column);
                  return lEditor;
    }

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

  • JTree custom renderer setting selection background color problem

    Hi,
    I have a JTree with a custom icon renderer that displays an icon. The JTree is part of a TreeTable component. Iam having a problem setting the selection background uniformly for the entire row. There is no problem when there is no row selected in the JTable.
    My present code looks like this:
    Iam overriding paint in my renderer which extends DefaultCellRenderer.
           super.paint(g);
            Color bColor = null;
            if(!m_selected) {
                 if(currRow % 2 == 0) {
                      bColor = Color.WHITE;
                 } else {
                                                    bColor = backColor;
            } else {
                 bColor = table.getSelectionBackground();                  bColor = getRowSelectionColor();
         if(bColor != null) {
                           g.setColor(bColor);
             if(!m_selected) {
                   g.setXORMode(new Color(0xFF, 0xFF, 0xFF));
             } else {
                 g.setXORMode(new Color(0x00, 0x00, 0x00));
                  I have a color I arrive at using some algorithm that I want using method getRowSelectionColor(). The other cells in the row have this color. But the cell containing the tree node shows different color. Iam not able to arrive at the right combination of the color to set and the xor color so my tree node also looks like the other cells in the row.
    It is not a problem really as the table still looks good. Its just that the tree node looks like it has been highlighted and this might cause a problem when a table cell is highlighed later on in the application ( two cells in the row would be highlighted causing confusion).
    Any help would be appreciated.
    Regards,
    vidyut

    Hi Camickr,
    Thanks for the reply. Iam sorry I didn't include the sources the first time around. There were too many of them. I have created a small, self-contained, compilable program that demonstrates the problem and including it herewith. Still there's quite many files but they are all needed Iam afraid. The only one you will have to concern yourself fior this problem is the file IconRenderer.java. The treenode background and the other cells background are not in sync when table row is not selected in this example though. But they are in my real program. I just need them to be in sync i.e have the same background color when the row is selected.
    Your help would be very much appreciated.
    These are the files that are included below:
    1. AbstractTreeTableModel.java
    2. Bookmarks.java
    3. BookmarksModel.java
    4. DynamicTreeTableModel.java
    5. IconRenderer.java
    6. IndicatorRenderer.java
    7. JTreeTable.java
    8. TreeTableExample3.java (contains main)
    9. TreeTableModel.java
    10. TreeTableModelAdapter.java
    The copyright and javadocs information has been stripped for clarity.
    cheers,
    vidyut
    // AbstractTreeTableModel.java BEGIN
    import javax.swing.tree.*;
    import javax.swing.event.*;
    public abstract class AbstractTreeTableModel implements TreeTableModel {
        protected Object root;    
        protected EventListenerList listenerList = new EventListenerList();
        public AbstractTreeTableModel(Object root) {
            this.root = root;
        // Default implementations for methods in the TreeModel interface.
        public Object getRoot() {
            return root;
        public boolean isLeaf(Object node) {
            return getChildCount(node) == 0;
        public void valueForPathChanged(TreePath path, Object newValue) {}
        // This is not called in the JTree's default mode:
        // use a naive implementation.
        public int getIndexOfChild(Object parent, Object child) {
            for (int i = 0; i < getChildCount(parent); i++) {
             if (getChild(parent, i).equals(child)) {
                 return i;
         return -1;
        public void addTreeModelListener(TreeModelListener l) {
            listenerList.add(TreeModelListener.class, l);
        public void removeTreeModelListener(TreeModelListener l) {
            listenerList.remove(TreeModelListener.class, l);
        protected void fireTreeNodesChanged(Object source, Object[] path,
                                            int[] childIndices,
                                            Object[] children) {
            // Guaranteed to return a non-null array
            Object[] listeners = listenerList.getListenerList();
            TreeModelEvent e = null;
            // Process the listeners last to first, notifying
            // those that are interested in this event
            for (int i = listeners.length-2; i>=0; i-=2) {
                if (listeners==TreeModelListener.class) {
    // Lazily create the event:
    if (e == null)
    e = new TreeModelEvent(source, path,
    childIndices, children);
    ((TreeModelListener)listeners[i+1]).treeNodesChanged(e);
    protected void fireTreeNodesInserted(Object source, Object[] path,
    int[] childIndices,
    Object[] children) {
    // Guaranteed to return a non-null array
    Object[] listeners = listenerList.getListenerList();
    TreeModelEvent e = null;
    // Process the listeners last to first, notifying
    // those that are interested in this event
    for (int i = listeners.length-2; i>=0; i-=2) {
    if (listeners[i]==TreeModelListener.class) {
    // Lazily create the event:
    if (e == null)
    e = new TreeModelEvent(source, path,
    childIndices, children);
    ((TreeModelListener)listeners[i+1]).treeNodesInserted(e);
    protected void fireTreeNodesRemoved(Object source, Object[] path,
    int[] childIndices,
    Object[] children) {
    // Guaranteed to return a non-null array
    Object[] listeners = listenerList.getListenerList();
    TreeModelEvent e = null;
    // Process the listeners last to first, notifying
    // those that are interested in this event
    for (int i = listeners.length-2; i>=0; i-=2) {
    if (listeners[i]==TreeModelListener.class) {
    // Lazily create the event:
    if (e == null)
    e = new TreeModelEvent(source, path,
    childIndices, children);
    ((TreeModelListener)listeners[i+1]).treeNodesRemoved(e);
    protected void fireTreeStructureChanged(Object source, Object[] path,
    int[] childIndices,
    Object[] children) {
    // Guaranteed to return a non-null array
    Object[] listeners = listenerList.getListenerList();
    TreeModelEvent e = null;
    // Process the listeners last to first, notifying
    // those that are interested in this event
    for (int i = listeners.length-2; i>=0; i-=2) {
    if (listeners[i]==TreeModelListener.class) {
    // Lazily create the event:
    if (e == null)
    e = new TreeModelEvent(source, path,
    childIndices, children);
    ((TreeModelListener)listeners[i+1]).treeStructureChanged(e);
    // Default impelmentations for methods in the TreeTableModel interface.
    public Class getColumnClass(int column) { return Object.class; }
    public boolean isCellEditable(Object node, int column) {
    return getColumnClass(column) == TreeTableModel.class;
    public void setValueAt(Object aValue, Object node, int column) {}
    // Left to be implemented in the subclass:
    * public Object getChild(Object parent, int index)
    * public int getChildCount(Object parent)
    * public int getColumnCount()
    * public String getColumnName(Object node, int column)
    * public Object getValueAt(Object node, int column)
    // AbstractTreeTableModel.java END
    // Bookmarks.java BEGIN
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import javax.swing.text.html.parser.*;
    public class Bookmarks {
    /** The root node the bookmarks are added to. */
    private BookmarkDirectory root;
    * Creates a new Bookmarks object, with the entries coming from
    * <code>path</code>.
    public Bookmarks(String path) {
         root = new BookmarkDirectory("Bookmarks");
         if (path != null) {
         parse(path);
    * Returns the root of the bookmarks.
    public BookmarkDirectory getRoot() {
         return root;
    protected void parse(String path) {
         try {
         BufferedReader reader = new BufferedReader(new FileReader
                                       (path));
         new ParserDelegator().parse(reader, new CallbackHandler(), true);
         catch (IOException ioe) {
         System.out.println("IOE: " + ioe);
         JOptionPane.showMessageDialog(null, "Load Bookmarks",
                             "Unable to load bookmarks",
                             JOptionPane.ERROR_MESSAGE);
    private static final short NO_ENTRY = 0;
    private static final short BOOKMARK_ENTRY = 2;
    private static final short DIRECTORY_ENTRY = 3;
    private class CallbackHandler extends HTMLEditorKit.ParserCallback {
         /** Parent node that new entries are added to. */
         private BookmarkDirectory parent;
         /** The most recently parsed tag. */
         private HTML.Tag tag;
         /** The last tag encountered. */
         private HTML.Tag lastTag;
         * The state, will be one of NO_ENTRY, DIRECTORY_ENTRY,
    * or BOOKMARK_ENTRY.
         private short state;
         * Date for the next BookmarkDirectory node.
         private Date parentDate;
         * The values from the attributes are placed in here. When the
         * text is encountered this is added to the node hierarchy and a
    * new instance is created.
         private BookmarkEntry lastBookmark;
         * Creates the CallbackHandler.
         public CallbackHandler() {
         parent = root;
         lastBookmark = new BookmarkEntry();
         // HTMLEditorKit.ParserCallback methods
         * Invoked when text in the html document is encountered. Based on
         * the current state, this will either: do nothing
    * (state == NO_ENTRY),
         * create a new BookmarkEntry (state == BOOKMARK_ENTRY) or
    * create a new
         * BookmarkDirectory (state == DIRECTORY_ENTRY). If state is
    * != NO_ENTRY, it is reset to NO_ENTRY after this is
    * invoked.
    public void handleText(char[] data, int pos) {
         switch (state) {
         case NO_ENTRY:
              break;
         case BOOKMARK_ENTRY:
              // URL.
              lastBookmark.setName(new String(data));
    parent.add(lastBookmark);
    lastBookmark = new BookmarkEntry();
              break;
         case DIRECTORY_ENTRY:
              // directory.
              BookmarkDirectory newParent = new
                   BookmarkDirectory(new String(data));
              newParent.setCreated(parentDate);
              parent.add(newParent);
              parent = newParent;
              break;
         default:
              break;
    state = NO_ENTRY;
         * Invoked when a start tag is encountered. Based on the tag
         * this may update the BookmarkEntry and state, or update the
         * parentDate.
         public void handleStartTag(HTML.Tag t, MutableAttributeSet a,
                        int pos) {
         lastTag = tag;
         tag = t;
         if (t == HTML.Tag.A && lastTag == HTML.Tag.DT) {
    long lDate;
              // URL
              URL url;
              try {
              url = new URL((String)a.getAttribute(HTML.Attribute.HREF));
              } catch (MalformedURLException murle) {
              url = null;
              lastBookmark.setLocation(url);
              // created
              Date date;
              try {
    lDate = Long.parseLong((String)a.getAttribute("add_date"));
    if (lDate != 0l) {
    date = new Date(1000l * lDate);
    else {
    date = null;
              } catch (Exception ex) {
              date = null;
              lastBookmark.setCreated(date);
              // last visited
              try {
    lDate = Long.parseLong((String)a.
    getAttribute("last_visit"));
    if (lDate != 0l) {
    date = new Date(1000l * lDate);
    else {
    date = null;
              } catch (Exception ex) {
              date = null;
              lastBookmark.setLastVisited(date);
              state = BOOKMARK_ENTRY;
         else if (t == HTML.Tag.H3 && lastTag == HTML.Tag.DT) {
              // new node.
              try {
              parentDate = new Date(1000l * Long.parseLong((String)a.
                                  getAttribute("add_date")));
              } catch (Exception ex) {
              parentDate = null;
              state = DIRECTORY_ENTRY;
         * Invoked when the end of a tag is encountered. If the tag is
         * a DL, this will set the node that parents are added to the current
         * nodes parent.
         public void handleEndTag(HTML.Tag t, int pos) {
         if (t == HTML.Tag.DL && parent != null) {
              parent = (BookmarkDirectory)parent.getParent();
    public static class BookmarkDirectory extends DefaultMutableTreeNode {
         /** Dates created. */
         private Date created;
         public BookmarkDirectory(String name) {
         super(name);
         public void setName(String name) {
         setUserObject(name);
         public String getName() {
         return (String)getUserObject();
         public void setCreated(Date date) {
         this.created = date;
         public Date getCreated() {
         return created;
    public static class BookmarkEntry extends DefaultMutableTreeNode {
         /** User description of the string. */
         private String name;
         /** The URL the bookmark represents. */
         private URL location;
         /** Dates the URL was last visited. */
         private Date lastVisited;
         /** Date the URL was created. */
         private Date created;
         public void setName(String name) {
         this.name = name;
         public String getName() {
         return name;
         public void setLocation(URL location) {
         this.location = location;
         public URL getLocation() {
         return location;
         public void setLastVisited(Date date) {
         lastVisited = date;
         public Date getLastVisited() {
         return lastVisited;
         public void setCreated(Date date) {
         this.created = date;
         public Date getCreated() {
         return created;
         public String toString() {
         return getName();
    // Bookmarks.java END
    // BookmarksModel.java BEGIN
    import java.util.Date;
    public class BookmarksModel extends DynamicTreeTableModel {
    * Names of the columns.
    private static final String[] columnNames =
    { "Name", "Location", "Last Visited", "Created" };
    * Method names used to access the data to display.
    private static final String[] methodNames =
    { "getName", "getLocation", "getLastVisited","getCreated" };
    * Method names used to set the data.
    private static final String[] setterMethodNames =
    { "setName", "setLocation", "setLastVisited","setCreated" };
    private static final Class[] classes =
    { TreeTableModel.class, String.class, Date.class, Date.class };
    public BookmarksModel(Bookmarks.BookmarkDirectory root) {
         super(root, columnNames, methodNames, setterMethodNames, classes);
    public boolean isCellEditable(Object node, int column) {
         switch (column) {
         case 0:
         // Allow editing of the name, as long as not the root.
         return (node != getRoot());
         case 1:
         // Allow editing of the location, as long as not a
         // directory
         return (node instanceof Bookmarks.BookmarkEntry);
         default:
         // Don't allow editing of the date fields.
         return false;
    // BookmarksModel.java END
    // DynamicTreeTableModel.java BEGIN
    import java.lang.reflect.*;
    import javax.swing.tree.*;
    public class DynamicTreeTableModel extends AbstractTreeTableModel {
    /** Names of the columns, used for the TableModel getColumnName method. */
    private String[] columnNames;
    private String[] methodNames;
    private String[] setterMethodNames;
    /** Column classes, used for the TableModel method getColumnClass. */
    private Class[] cTypes;
    public DynamicTreeTableModel(TreeNode root, String[] columnNames,
                        String[] getterMethodNames,
                        String[] setterMethodNames,
                        Class[] cTypes) {
         super(root);
         this.columnNames = columnNames;
         this.methodNames = getterMethodNames;
         this.setterMethodNames = setterMethodNames;
         this.cTypes = cTypes;
    public int getChildCount(Object node) {
         return ((TreeNode)node).getChildCount();
    public Object getChild(Object node, int i) {
         return ((TreeNode)node).getChildAt(i);
    public boolean isLeaf(Object node) {
         return ((TreeNode)node).isLeaf();
    public int getColumnCount() {
         return columnNames.length;
    public String getColumnName(int column) {
         if (cTypes == null || column < 0 || column >= cTypes.length) {
         return null;
         return columnNames[column];
    public Class getColumnClass(int column) {
         if (cTypes == null || column < 0 || column >= cTypes.length) {
         return null;
         return cTypes[column];
    public Object getValueAt(Object node, int column) {
         try {
         Method method = node.getClass().getMethod(methodNames[column],
                                  null);
         if (method != null) {
              return method.invoke(node, null);
         catch (Throwable th) {}
         return null;
    * Returns true if there is a setter method name for column
    * <code>column</code>. This is set in the constructor.
    public boolean isCellEditable(Object node, int column) {
    return (setterMethodNames != null &&
         setterMethodNames[column] != null);
    // Note: This looks up the methods each time! This is rather inefficient;
    // it should really be changed to cache matching
    // methods/constructors
    // based on <code>node</code>'s class, and code>aValue</code>'s
    //class.
    public void setValueAt(Object aValue, Object node, int column) {
         boolean found = false;
         try {
         // We have to search through all the methods since the
         // types may not match up.
         Method[] methods = node.getClass().getMethods();
         for (int counter = methods.length - 1; counter >= 0; counter--) {
              if (methods[counter].getName().equals
              (setterMethodNames[column]) && methods[counter].
              getParameterTypes() != null && methods[counter].
              getParameterTypes().length == 1) {
              // We found a matching method
              Class param = methods[counter].getParameterTypes()[0];
              if (!param.isInstance(aValue)) {
                   // Yes, we can use the value passed in directly,
                   // no coercision is necessary!
                   if (aValue instanceof String &&
                   ((String)aValue).length() == 0) {
                   // Assume an empty string is null, this is
                   // probably bogus for here.
                   aValue = null;
                   else {
                   // Have to attempt some sort of coercision.
                   // See if the expected parameter type has
                   // a constructor that takes a String.
                   Constructor cs = param.getConstructor
                   (new Class[] { String.class });
                   if (cs != null) {
                        aValue = cs.newInstance(new Object[]
                                       { aValue });
                   else {
                        aValue = null;
              // null either means it was an empty string, or there
              // was no translation. Could potentially deal with these
              // differently.
              methods[counter].invoke(node, new Object[] { aValue });
              found = true;
              break;
         } catch (Throwable th) {
         System.out.println("exception: " + th);
         if (found) {
         // The value changed, fire an event to notify listeners.
         TreeNode parent = ((TreeNode)node).getParent();
         fireTreeNodesChanged(this, getPathToRoot(parent),
                        new int[] { getIndexOfChild(parent, node) },
                        new Object[] { node });
    public TreeNode[] getPathToRoot(TreeNode aNode) {
    return getPathToRoot(aNode, 0);
    private TreeNode[] getPathToRoot(TreeNode aNode, int depth) {
    TreeNode[] retNodes;
         // This method recurses, traversing towards the root in order
         // size the array. On the way back, it fills in the nodes,
         // starting from the root and working back to the original node.
    /* Check for null, in case someone passed in a null node, or
    they passed in an element that isn't rooted at root. */
    if(aNode == null) {
    if(depth == 0)
    return null;
    else
    retNodes = new TreeNode[depth];
    else {
    depth++;
    if(aNode == root)
    retNodes = new TreeNode[depth];
    else
    retNodes = getPathToRoot(aNode.getParent(), depth);
    retNodes[retNodes.length - depth] = aNode;
    return retNodes;
    // DynamicTreeTableModel.java END
    // IconRenderer.java BEGIN
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.plaf.basic.BasicTreeUI;
    class IconRenderer extends DefaultTreeCellRenderer
    // Color backColor = new Color(0xD0, 0xCC, 0xFF);
    Color backColor = new Color(0xF0, 0xF0, 0xE0);
    String tipText = "";
    JTree tree;
    int currRow = 0;
    boolean m_selected;
    JTable table;
    public IconRenderer(JTree tree, JTable table) {
    this.table = table;
    // setBackground(backColor);
    setBackground(Color.GREEN);
    setForeground(Color.black);
         this.tree = tree;
    public Component getTreeCellRendererComponent(JTree tree, Object value,
    boolean selected,
    boolean expanded, boolean leaf,
    int row, boolean hasFocus) {
         Object node = null;
         super.getTreeCellRendererComponent(
    tree, value, selected,
    expanded, leaf, row,
    hasFocus);
         TreePath treePath = tree.getPathForRow(row);
    if(treePath != null)
              node = treePath.getLastPathComponent();
    currRow = row;
    m_selected = selected;
    DefaultMutableTreeNode itc = null;
    if (node instanceof DefaultMutableTreeNode) {
    itc = (DefaultMutableTreeNode)node;
         setClosedIcon(closedIcon);
    setOpenIcon(openIcon);
    return this;
    /* Override the default to send back different strings for folders and leaves. */
    public String getToolTipText() {
    return tipText;
    * Paints the value. The background is filled based on selected.
    public void paint(Graphics g) {
         super.paint(g);
         Color bColor = null;
         if(!m_selected) {
              System.out.println(" iconren not sel currRow " + currRow);
              if(currRow % 2 == 0) {
                   bColor = Color.WHITE;
              } else {
              bColor = backColor;
         } else {
              bColor = table.getSelectionBackground();
              System.out.println("in else selbg = " + bColor);           
              bColor = new Color(0xF0, 0xCC, 0x92);
              System.out.println(" bColor aft = " + bColor);           
         int imageOffset = -1;
         if(bColor != null) {
         imageOffset = getLabelStart();
         g.setColor(bColor);
         if(!m_selected) {
              System.out.println(" not sel setting white ");
              g.setXORMode(new Color(0xFF, 0xFF, 0xFF));
         } else {
    //          g.setXORMode(new Color(0xCC, 0xCC, 0x9F));
              g.setXORMode(new Color(0x00, 0x00, 0x00));
              System.out.println(" using color = " + g.getColor());           
         if(getComponentOrientation().isLeftToRight()) {
         g.fillRect(imageOffset, 0, getWidth() - 1 - imageOffset,
                   getHeight());
         } else {
         g.fillRect(0, 0, getWidth() - 1 - imageOffset,
                   getHeight());
    private int getLabelStart() {
         Icon currentI = getIcon();
         if(currentI != null && getText() != null) {
         return currentI.getIconWidth() + Math.max(0, getIconTextGap() - 1);
         return 0;
    // IconRenderer.java END
    // IndicatorRenderer.java BEGIN
    // import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import javax.swing.table.*;
    import javax.swing.table.*;
    import javax.swing.plaf.basic.*;
    import java.awt.event.*;
    import java.util.EventObject;
    import java.text.NumberFormat;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.StringTokenizer;
    import java.util.Arrays;
    class IndicatorRenderer extends DefaultTableCellRenderer {
    /** Makes sure the number of displayed in an internationalized
    * manner. */
    protected NumberFormat formatter;
    /** Row that is currently being painted. */
    protected int lastRow;
    protected int reloadRow;
    protected int reloadCounter;
    protected TreeTableModel treeTableModel;
    protected TreeTableModelAdapter treeTblAdapter;
    protected JTable table;
    Component renderer = null;
    Color backColor = new Color(0xF0, 0xF0, 0xE0);
    IndicatorRenderer(TreeTableModelAdapter treeTblAdapter, TreeTableModel treeTableModel) {
         setHorizontalAlignment(JLabel.RIGHT);
         setFont(new Font("serif", Font.BOLD, 12));
         this.treeTableModel = treeTableModel;
         this.treeTblAdapter = treeTblAdapter;
    * Invoked as part of DefaultTableCellRenderers implemention. Sets
    * the text of the label.
    public void setValue(Object value) {
    /* setText((value == null) ? "---" : formatter.format(value)); */
         setText((value == null) ? "---" : (String) value.toString());
    * Returns this.
    public Component getTableCellRendererComponent(JTable table,
    Object value, boolean isSelected, boolean hasFocus,
    int row, int column) {
         renderer = super.getTableCellRendererComponent(table, value, isSelected,
    hasFocus, row, column);
         lastRow = row;
         this.table = table;
              if(isSelected) {
                   doMask(hasFocus, isSelected);
              } else
              setBackground(table.getBackground());
    return renderer;
    * If the row being painted is also being reloaded this will draw
    * a little indicator.
    public void paint(Graphics g) {
         super.paint(g);
    private void doMask(boolean hasFocus, boolean selected) {
              maskBackground(hasFocus, selected);
    private void maskBackground(boolean hasFocus, boolean selected) {
              Color seed = null;
              seed = table.getSelectionBackground();
              Color color = seed;
              if (color != null) {
                   setBackground(
    new Color(0xF0, 0xCC, 0x92));
    // IndicatorRenderer.java END
    // JTreeTable.java BEGIN
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import java.util.EventObject;
    public class JTreeTable extends JTable {
    /** A subclass of JTree. */
    protected TreeTableCellRenderer tree;
    protected IndicatorRenderer indicatorRenderer = null;
    public JTreeTable(TreeTableModel treeTableModel) {
         super();
         // Creates the tree. It will be used as a renderer and editor.
         tree = new TreeTableCellRenderer(treeTableModel);
         TreeTableModelAdapter tdap = new TreeTableModelAdapter(treeTableModel, tree);
         // Installs a tableModel representing the visible rows in the tree.
         super.setModel(tdap);
         // Forces the JTable and JTree to share their row selection models.
         ListToTreeSelectionModelWrapper selectionWrapper = new
         ListToTreeSelectionModelWrapper();
         tree.setSelectionModel(selectionWrapper);
         setSelectionModel(selectionWrapper.getListSelectionModel());
         // Installs the tree editor renderer and editor.
         setDefaultRenderer(TreeTableModel.class, tree);
         setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor());
         indicatorRenderer = new IndicatorRenderer(tdap, treeTableModel);     
         // No grid.
         setShowGrid(false);
         // No intercell spacing
         setIntercellSpacing(new Dimension(0, 0));     
         // And update the height of the trees row to match that of
         // the table.
         //if (tree.getRowHeight() < 1) {
         // Metal looks better like this.
         setRowHeight(20);
    public TableCellRenderer getCellRenderer(int row, int col) {
              if(col == 0)
              return tree;
              else
              return indicatorRenderer;     
    public void updateUI() {
         super.updateUI();
         if(tree != null) {
         tree.updateUI();
         // Do this so that the editor is referencing the current renderer
         // from the tree. The renderer can potentially change each time
         // laf changes.
         setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor());
         // Use the tree's default foreground and background colors in the
         // table.
    LookAndFeel.installColorsAndFont(this, "Tree.background",
    "Tree.foreground", "Tree.font");
    public int getEditingRow() {
    return (getColumnClass(editingColumn) == TreeTableModel.class) ? -1 :
         editingRow;
    private int realEditingRow() {
         return editingRow;
    public void sizeColumnsToFit(int resizingColumn) {
         super.sizeColumnsToFit(resizingColumn);
         if (getEditingColumn() != -1 && getColumnClass(editingColumn) ==
         TreeTableModel.class) {
         Rectangle cellRect = getCellRect(realEditingRow(),
                             getEditingColumn(), false);
    Component component = getEditorComponent();
         component.setBounds(cellRect);
    component.validate();
    public void setRowHeight(int rowHeight) {
    super.setRowHeight(rowHeight);
         if (tree != null && tree.getRowHeight() != rowHeight) {
    tree.setRowHeight(getRowHeight());
    public JTree getTree() {
         return tree;
    public boolean editCellAt(int row, int column, EventObject e){
         boolean retValue = super.editCellAt(row, column, e);
         if (retValue && getColumnClass(column) == TreeTableModel.class) {
         repaint(getCellRect(row, column, false));
         return retValue;
    public class TreeTableCellRenderer extends JTree implements
         TableCellRenderer {
         /** Last table/tree row asked to renderer. */
         protected int visibleRow;
         /** Border to draw around the tree, if this is non-null, it will
         * be painted. */
         protected Border highlightBorder;
         public TreeTableCellRenderer(Tr

  • Inserting Records in an Array and using a constructor with it

    I badly need help on this! Please please please! I have been studying java for a short time only.
    Anyway, here goes: My project requires the following:
    Employee inputs the no. of video in the shelf. They have four classifications: Drama, Comedy, Action, and Thriller. Each video classification has different rates. The employee creates a video record containing the following information: 1. video ID number, 2. video classification, and 3. Price.
    The employee should display the classifications of videos available and the price. Only the available video tapes would be displayed according to the customer's chosen classification. When the customer chooses the video he wants to rent, the program will register and attach the name of the customer to the video number.
    I only need to use arrays, and NOT database to record the information.

    is it ok i i declare the drama_rate outside the video class?
    i have a list of variables on my videoupdate classYes. It's probably best to declare it static & then you can access it directly:
    public static float drama_rate = 100.0;
    rate = <the class name>.drama_rate;
    so, i should also include a customer no. both in the video and customer class.I would. You may want to list a bunch of videos and who currently has them. This way you don't have to search the customers AND the videos to do this.
    thanks =) i don't know either why we had to validate/invalidate,\
    but our applet doesnt refresh when >it is supposed to, so
    we just used this method. It wouldnt slow down the application, would it?Could you just revalidate()?
    the use of arrays. i havent finished with the program yet.
    i have the design already, i just couldnt put it in code.
    im not familiar with the use of multidimensional arrays-
    can i use this for the video and customer records i will need to store?Not sure what you're using arrays for, but here's an example of something I might do. Maybe it will be useful to you.
    Have you looked at HashMaps? You could use "Customer" as the key and then use an ArrayList of checked out Videos as the value:
    HashMap customers = new HashMap();
    ArrayList videos = new ArrayList();
    //Add the checked out videos to the list
    videos.add(video);
    <etc>
    // Add this customer and the list of videos he has checked out.
    customers.put(customer,videos);
    [\code]

  • Validating xml in pipeline - if not valid drop file in invalid folder

    My goal is to receive an xml file through a customized pipeline so I can validate it.  If it's valid I drop it in 'valid' folder.  Then my orchestration will pick it from that location and do whatever it will do with it.  This works fine.
     But if the xml file is NOT valid I want to drop it in a an 'INVALID' folder and have a different orchestration pick it up and send an email to me.  Is this possible?  In my pipeline I don't have a dissambler, just an XMLValidator with the appropriate
    schema in the document schemas collection.  When I do drop in an 'invalid' xml file according to the schema, the pipeline is suspended.  How can I drop that invalid xml file into a folder?
    I've been learning/working with BizTalk for about 3 months.  I'm trying to keep this simple and avoid doing any custom c# code until I'm more comfortable with BizTalk.
    thank you in advance for your expert advice.
    Jean Stiles

    Hi Jean,
    Your validation pipeline should promote the "MessageType" property of the message (if the orchestration doesn't have any other filters and if the orchestration's receive shape has a message type pointing to specific message). Its seems that when your validation
    component validate any incoming message, after its process it shall promote the message type property of the message. Other wise you would not have any subscriber for the message published. The error "The published message could not be routed because no subscribers
    were found" is due to this issue. i.e your orchestration subscription doesn't match to the message outputted by your custom vaidation component.
    Not sure what is the full functionality of your custom validation component. if its simply validating the message, you can still get this functionality by using XML-Receive pipeline and set the property "Validate Document" to "True" and by specifying the
    "DocumentSpecNames" to the schema which you want to validate the incoming message against.
    If you're using custom pipeline to do standard validation, then follow like this:
    Receive Port (with Enable routing for Failed Messages enabled)  Receive Location with XML-Receive pipeline  (Validate Document" to "True" and by specifying the "DocumentSpecNames" to the schema which you want to validate )
    Bind the Receive Port to Orchestration - Do your process as normal
    Create a send port with above filter for ErrorReport and configure this send port to send the invalid message to your invalid folder.
    If you're using custom pipeline to something more than standard validation of XML-Receive pipeline , then follow like this:
    Receive Port (with Enable routing for Failed Messages enabled)  Receive Location with Your custom validation pipeline component.
    Ensure your custom pipeline component promotes the message type property as
    string systemPropertyNS = @”http://schemas.microsoft.com/BizTalk/2003/system-properties”;
    outboundMsg.Context.Promote(“MessageType”, systemPropertyNS, “http://NameSpace#RootNode”);
    replace the outboundMsg to the outbound message you output in your custom validation component. And message type to relevant value as yours. Or by some means ensure your custom pipeline output the message with matces to subcription expected by your Orchestration.
    Bind the Receive Port to Orchestration - Do your process as normal
    Create a send port with above filter for ErrorReport and configure this send port to send the invalid message to your invalid folder.
    If this answers your question please mark it accordingly. If this post is helpful, please vote as helpful by clicking the upward arrow mark next to my reply.

Maybe you are looking for

  • The computer has rebooted from a bugcheck. The bugcheck was: 0x0bad1001

    I would like to know how to troubleshoot this issue. The computer has rebooted from a bugcheck.  The bugcheck was: 0x0bad1001 (0x00000000000d04fd, 0xffffd00022fb6388, 0xffffd00022fb5b90, 0xfffff803552f9916). A dump was saved in: C:\WINDOWS\MEMORY.DMP

  • Using Java.io Package in JSP

    Hi all, I want to use java.io package in a JSP and read one htm file. the program is giving me exception that the file say index.htm does not exists. I don't know how to solve this error. If any one can help me then it would be great. I don't want to

  • Ipod touch wont unlock and reloads

    My ipod touch turns on and goes to the lock screen but once i start to unlock it, it goes black with a little white circle moving around like its reloading. It constantly does this and it won't let me unlock my screen because of it. Please help.

  • Save custom prefrence in MDS DB

    Hi I want to save basic user level preferences like show/hide text field, field length etc into MDS repository. These preferences will basically be a key value pair. Is there any MDS api which i could make use of to store these values at user level?

  • Can anyone help me find live chat??!

    I got an email saying I cancelled my subscrption, which I did not. Now I can't find a way to contact skype. Been going in circles! Can anyone send me the link to the live chat button?