SetToolTipText in a JComboBox

ex:
JComboBox Scombo31 = new JComboBox();
Scombo31.addItem("S"); Scombo31.addItem("P");
Scombo31.setToolTipText("S=steel P=paper");
the addItem is OK but the ToolTipText don't appear.

JTextField textfield83 = new JTextField(" ",1);
textfield83.setToolTipText("AAAA-MM-DD");
System.out.println("ToolTip10"+ textfield83.getToolTipText().toString() ); //To see if it's assign
Works well, there
Scombo21.addItem("Y"); Scombo21.addItem("N");
Scombo21.setToolTipText("Y=RFP N=No");
System.out.println("ToolTip11"+ Scombo21.getToolTipText().toString() ); //To see if it's assign
Not works,
.addItem ok
ToolTiptext not appear
System.out. ... ok

Similar Messages

  • Programming a Pencil Tool on Paint?

    Here's my code for Scribble(a pencil tool) and its superclass Shape. Basically, my program remembers where the mouse has been and draws a line from the previous point to the current point. However, the scribble doesn't show up (occasionally you will see a small line at the very end) I think the problem is that each Scribble object only has one previous and one current. Therefore, there is only 1 line left at the end. How can I correct this?
    Thanks in advance!
    Note: this doesn't run since there are about 5 other classes needed. I guess can post them if you want? xD
    import java.awt.*;
    public class Scribble extends Shape{
         protected Point startpt, endpt;
         protected Point previous, current;
         int count = 0;
        public Scribble(Point start, DrawingCanvas dcanvas){
         super();
         System.out.println("SCRIBBLE CREATED!!!!!!!\n\n");
         startpt = start;
         current = start;
         endpt = start;
         canvas = dcanvas;
         bounds = new Rectangle(start);
        public void resize(Point anchor, Point end){
         super.resize(anchor, end);
         previous = current;
         startpt = anchor;
         current = end;
         endpt = end;
        public void translate(int dx, int dy){
         super.translate(dx, dy);
         previous.translate(dx, dy);
         current.translate(dx, dy);
         startpt.translate(dx, dy);
         endpt.translate(dx, dy);
        public void draw(Graphics g, Rectangle regionToDraw){
              count++;
              System.out.println(count);
         if (!bounds.intersects(regionToDraw)){
             return;
         g.setColor(super.getColor());
         g.drawLine((int)previous.getX(), (int)previous.getY(), (int)current.getX(), (int)current.getY());
         if (isSelected) { // if selected, draw the resizing knobs
                           // along the 4 corners
             Rectangle[] knobs = getKnobRects();
             for (int i = 0; i < knobs.length; i++)
              g.fillRect(knobs.x, knobs[i].y,
                   knobs[i].width, knobs[i].height);
    protected Rectangle[] getKnobRects(){
         Rectangle[] knobs = new Rectangle[2];
         knobs[0] = new Rectangle((int)startpt.getX() - KNOB_SIZE/2,
                        (int)startpt.getY() - KNOB_SIZE/2, KNOB_SIZE, KNOB_SIZE);
         knobs[1] = new Rectangle((int)endpt.getX() - KNOB_SIZE/2,
                        (int)endpt.getY()- KNOB_SIZE/2, KNOB_SIZE, KNOB_SIZE);
         return knobs;
    protected int getKnobContainingPoint(Point pt){
         if (!isSelected) return NONE;
         Rectangle[] knobs = getKnobRects();
         for (int i = 0; i < knobs.length; i++)
         if (knobs[i].contains(pt))
              return i;
         return NONE;
    }import java.awt.*;
    import java.util.*;
    import java.io.*;
    public abstract class Shape implements Serializable, Cloneable{
         private Color color;
    protected Rectangle bounds;
    protected boolean isSelected;
    public DrawingCanvas canvas;
    protected static final int KNOB_SIZE = 6;
    protected static final int NONE = -1;
    protected static final int NW = 0;
    protected static final int SW = 1;
    protected static final int SE = 2;
    protected static final int NE = 3;
         Shape(){
              color = Color.darkGray;
         public Color getColor(){
         return color;
         public Object clone(){
              try{
              Shape copy = (Shape)super.clone();
              copy.setBounds(bounds);
              return copy;
              catch(CloneNotSupportedException c){
                   return null;
         public void setColor(Color newColor){
         color = newColor;
         canvas.repaint();
         /** The "primitive" for all resizing/moving/creating operations that
         * affect the rect bounding box. The current implementation just resets
         * the bounds variable and triggers a re-draw of the union of the old &
         * new rectangles. This will redraw the shape in new size and place and
         * also "erase" if bounds are now smaller than before.
         protected void setBounds(Rectangle newBounds){
              Rectangle oldBounds = bounds;
              bounds = newBounds;
              updateCanvas(oldBounds.union(bounds));
         /** The resize operation is called when first creating a rect, as well as
         * when later resizing by dragging one of its knobs. The two parameters
         * are the points that define the new bounding box. The anchor point
         * is the location of the mouse-down event during a creation operation
         * or the opposite corner of the knob being dragged during a resize
         * operation. The end is the current location of the mouse.
         public void resize(Point anchor, Point end){
              Rectangle newRect = new Rectangle(anchor);
              // creates smallest rectange which
              // includes both anchor & end
              newRect.add(end);
              // reset bounds & redraw affected areas
              setBounds(newRect);
              canvas.repaint();
         /** The translate operation is called when moving a shape by dragging in
         * the canvas. The two parameters are the delta-x and delta-y to move
         * by. Note that either or both can be negative. Create a new rectangle
         * from our bounds and translate and then go through the setBounds()
         * primitive to change it.
         public void translate(int dx, int dy){
              Rectangle newRect = new Rectangle(bounds);
              newRect.translate(dx, dy);
              setBounds(newRect);
              canvas.repaint();
         /** Used to change the selected state of the shape which will require
         * updating the affected area of the canvas to add/remove knobs.
         public void setSelected(boolean newState){
              isSelected = newState;
              // need to erase/add knobs
              // including extent of extended bounds
              updateCanvas(bounds, true);
              canvas.repaint();
         /** The updateCanvas() methods are used when the state has changed
         * in such a way that it needs to be refreshed in the canvas to properly
         * reflect the new settings. The shape should take responsibility for
         * messaging the canvas to properly update itself. The appropriate AWT/JFC
         * way to re-draw a component is to send it the repaint() method with the
         * rectangle that needs refreshing. This will cause an update() event to
         * be sent to the component which in turn will call paint(), where the
         * real drawing implementation goes. See the paint() method in
         * DrawingCanvas to see how it is implemented.
         protected void updateCanvas(Rectangle areaOfChange, boolean enlargeForKnobs){
                   System.out.println("canvas2 updated");
              Rectangle toRedraw = new Rectangle(areaOfChange);
              if (enlargeForKnobs)
              toRedraw.grow(KNOB_SIZE/2, KNOB_SIZE/2);
              canvas.repaint(toRedraw);
         protected void updateCanvas(Rectangle areaOfChange){
                   System.out.println("canvas updated");
              updateCanvas(areaOfChange, isSelected);
              public Rectangle getBounds(){
                   return bounds;
         /** When the DrawingCanvas needs to determine which shape is under
         * the mouse, it asks the shape to determine if a point is "inside".
         * This method should returns true if the given point is inside the
         * region for this shape. For a rectangle, any point within the
         * bounding box is inside the shape.
         public boolean inside(Point pt){
              return bounds.contains(pt);
         /** When needed, we create the array of knob rectangles on demand. This
         * does mean we create and discard the array and rectangles repeatedly.
         * These are small objects, so perhaps it is not a big deal, but
         * a valid alternative would be to store the array of knobs as an
         * instance variable of the Shape and and update the knobs as the bounds
         * change. This means a little more memory overhead for each Shape
         * (since it is always storing the knobs, even when not being used) and
         * having that redundant data opens up the possibility of bugs from
         * getting out of synch (bounds move but knobs didn't, etc.) but you may
         * find that a more appealing way to go. Either way is fine with us.
         * Note this method provides a nice unified place for one override from
         * a shape subclass to substitute fewer or different knobs.
         protected Rectangle[] getKnobRects(){
                   System.out.println("knobs gotten");
              Rectangle[] knobs = new Rectangle[4];
              knobs[NW] = new Rectangle(bounds.x - KNOB_SIZE/2,
                             bounds.y - KNOB_SIZE/2, KNOB_SIZE, KNOB_SIZE);
              knobs[SW] = new Rectangle(bounds.x - KNOB_SIZE/2,
                             bounds.y + bounds.height - KNOB_SIZE/2,
                             KNOB_SIZE, KNOB_SIZE);
              knobs[SE] = new Rectangle(bounds.x + bounds.width - KNOB_SIZE/2,
                             bounds.y + bounds.height - KNOB_SIZE/2,
                             KNOB_SIZE, KNOB_SIZE);
              knobs[NE] = new Rectangle(bounds.x + bounds.width - KNOB_SIZE/2,
                             bounds.y - KNOB_SIZE/2,
                             KNOB_SIZE, KNOB_SIZE);
              return knobs;
         /** Helper method to determine if a point is within one of the resize
         * corner knobs. If not selected, we have no resize knobs, so it can't
         * have been a click on one. Otherwise, we calculate the knob rects and
         * then check whether the point falls in one of them. The return value
         * is one of NW, NE, SW, SE constants depending on which knob is found,
         * or NONE if the click doesn't fall within any knob.
         protected int getKnobContainingPoint(Point pt){
                   System.out.println("resize knobs");
              // if we aren't selected, the knobs
              // aren't showing and thus there are no knobs to check
              if (!isSelected) return NONE;
              Rectangle[] knobs = getKnobRects();
              for (int i = 0; i < knobs.length; i++)
              if (knobs[i].contains(pt))
                   return i;
              return NONE;
         /** Method used by DrawingCanvas to determine if a mouse click is starting
         * a resize event. In order for it to be a resize, the click must have
         * been within one of the knob rects (checked by the helper method
         * getKnobContainingPoint) and if so, we return the "anchor" ie the knob
         * opposite this corner that will remain fixed as the user drags the
         * resizing knob of the other corner around. During the drag actions of a
         * resize, that fixed anchor point and the current mouse point will be
         * passed to the resize method, which will reset the bounds in response
         * to the movement. If the mouseLocation wasn't a click in a knob and
         * thus not the beginning of a resize event, null is returned.
    public Point getAnchorForResize(Point mouseLocation){
              System.out.println("is it a resize?");
    int whichKnob = getKnobContainingPoint(mouseLocation);
    if (whichKnob == NONE) // no resize knob is at this location
    return null;
    Rectangle[] knobs = getKnobRects();
    whichKnob = Math.abs(whichKnob - (int)(knobs.length / 2));
    return (new Point(knobs[whichKnob].x + knobs[whichKnob].width /2,
    knobs[whichKnob].y + knobs[whichKnob].height/2));
    public abstract void draw(Graphics g, Rectangle regionToDraw);

    line left at the end. How can I correct this?java.awt.Polygon (or Polygon2D)
    Here are a few of my thoughts
    #1 There is a Shape interface in core java already, as well as plenty of very useful shapes (Rectangle, Ellipse2D, Area). Shape has some really nice features like contains(...) and intersects(...). By creating a separate class for your Shape objects, you ensure that the two will be incompatible.
    #2 As tempting as it is, it is a bad idea to include a Color with a shape. What if you want it to have more than one Color? What if you want the insides of the shape to be filled by an Image? I just created and posted a class on the java forums called Renderable, which combines a java.awt.Shape with a java.awt.Paint.
    #3 Below is my PaintArea class. It "scribbles" on an Image. Maybe this will give you some ideas. To compile it, you will either have to find my MathUtils class (which I've posted here before) or reimplement the distance and angle methods. There is also a reference to WIndowUtilities... find that or remove it and put the PaintArea in a Frame and do setVisible(true)
    You are welcome to use and modify this code, but please don't change the package and please make sure that you add attribution if you submit this in an academic setting.
    * Created on Jun 15, 2005 by @author Tom Jacobs
    package tjacobs.ui.ex;
    import java.awt.image.BufferedImage;
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.ImageIcon;
    import javax.swing.JComboBox;
    import javax.swing.JComponent;
    import javax.swing.JPanel;
    import javax.swing.JToolBar;
    import tjacobs.MathUtils;
    import tjacobs.ui.util.WindowUtilities;
    * PaintArea is a component that you can draw in similar to but
    * much simpler than the windows paint program.
    public class PaintArea extends JComponent {
         private static final long serialVersionUID = 0;
         BufferedImage mImg; //= new BufferedImage();
         int mBrushSize = 1;
         private boolean mSizeChanged = false;
         private Color mColor1, mColor2;
         static class PaintIcon extends ImageIcon {
              public static final long serialVersionUID = 0;
              int mSize;
              public PaintIcon(Image im, int size) {
                   super(im);
                   mSize = size;
         public PaintArea() {
              super();
              setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
              addComponentListener(new CListener());
              MListener ml = new MListener();
              addMouseListener(ml);
              addMouseMotionListener(ml);
              setBackground(Color.WHITE);
              setForeground(Color.BLACK);
         public void paintComponent(Graphics g) {
              if (mSizeChanged) {
                   handleResize();
              //g.drawImage(mImg, mImg.getWidth(), mImg.getHeight(), null);
              g.drawImage(mImg, 0, 0, null);
              //super.paintComponent(g);
              //System.out.println("Image = " + mImg);
              //System.out.println("Size: " + mImg.getWidth() + "," + mImg.getHeight());
         public void setBackground(Color c) {
              super.setBackground(c);
              if (mImg != null) {
                   Graphics g = mImg.getGraphics();
                   g.setColor(c);
                   g.fillRect(0, 0, mImg.getWidth(), mImg.getHeight());
                   g.dispose();
         public void setColor1(Color c) {
              mColor1 = c;
         public void setColor2(Color c) {
              mColor2 = c;
         public Color getColor1() {
              return mColor1;
         public Color getColor2() {
              return mColor2;
         class ToolBar extends JToolBar {
              private static final long serialVersionUID = 1L;
              ToolBar() {
                   final ColorButton fore = new ColorButton();
                   fore.setToolTipText("Foreground Color");
                   final ColorButton back = new ColorButton();
                   back.setToolTipText("Background Color");
                   JComboBox brushSize = new JComboBox();
                   //super.createImage(1, 1).;
                   FontMetrics fm = new FontMetrics(getFont()) {
                        private static final long serialVersionUID = 1L;};
                   //int ht = fm.getHeight();
                   int useheight = fm.getHeight() % 2 == 0 ? fm.getHeight() + 1 : fm.getHeight();
                   final BufferedImage im1 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   Graphics g = im1.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2, useheight / 2, 1, 1);
                   g.dispose();
                   //im1.setRGB(useheight / 2 + 1, useheight / 2 + 1, 0xFFFFFF);
                   final BufferedImage im2 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   g = im2.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2 - 1, useheight / 2 - 1, 3, 3);
                   g.dispose();
    //               im2.setRGB(useheight / 2 - 1, useheight / 2 - 1, 3, 3, new int[] {     0, 0xFFFFFF, 0,
    //                                                            0xFFFFFF, 0xFFFFFFF, 0xFFFFFF,
    //                                                            0, 0xFFFFFF, 0}, 0, 1);
                   final BufferedImage im3 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   g = im3.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2 - 2, useheight / 2 - 2, 5, 5);
                   g.dispose();
    //               im3.setRGB(useheight / 2 - 2, useheight / 2 - 2, 5, 5, new int[] {     0, 0, 0xFFFFFF, 0, 0, 
    //                                                            0, 0xFFFFFF, 0xFFFFFFF, 0xFFFFFF, 0,
    //                                                            0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF,
    //                                                            0, 0xFFFFFF, 0xFFFFFFF, 0xFFFFFF, 0,
    //                                                            0, 0, 0xFFFFFF, 0, 0}, 0, 1);
                   //JLabel l1 = new JLabel("1 pt", new ImageIcon(im1), JLabel.LEFT);
                   //JLabel l2 = new JLabel("3 pt", new ImageIcon(im2), JLabel.LEFT);
                   //JLabel l3 = new JLabel("5 pt", new ImageIcon(im3), JLabel.LEFT);
                   brushSize.addItem(new PaintIcon(im1, 1));
                   brushSize.addItem(new PaintIcon(im2, 3));
                   brushSize.addItem(new PaintIcon(im3, 5));
                   //brushSize.addItem("Other");
                   add(fore);
                   add(back);
                   add(brushSize);
                   PropertyChangeListener pl = new PropertyChangeListener() {
                        public void propertyChange(PropertyChangeEvent ev) {
                             Object src = ev.getSource();
                             if (src != fore && src != back) {
                                  return;
                             Color c = (Color) ev.getNewValue();
                             if (ev.getSource() == fore) {
                                  mColor1 = c;
                             else {
                                  mColor2 = c;
                   fore.addPropertyChangeListener("Color", pl);
                   back.addPropertyChangeListener("Color", pl);
                   fore.changeColor(Color.BLACK);
                   back.changeColor(Color.WHITE);
                   brushSize.addItemListener(new ItemListener() {
                        public void itemStateChanged(ItemEvent ev) {
                             System.out.println("ItemEvent");
                             if (ev.getID() == ItemEvent.DESELECTED) {
                                  return;
                             System.out.println("Selected");
                             Object o = ev.getItem();
                             mBrushSize = ((PaintIcon) o).mSize;
                   //Graphics g = im1.getGraphics();
                   //g.fillOval(0, 0, 1, 1);
                   //BufferedImage im1 = new BufferedImage();
                   //BufferedImage im1 = new BufferedImage();
         protected class MListener extends MouseAdapter implements MouseMotionListener {
              Point mLastPoint;
              public void mouseDragged(MouseEvent me) {
                   Graphics g = mImg.getGraphics();
                   if ((me.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
                        g.setColor(mColor1);
                   } else {
                        g.setColor(mColor2);
                   Point p = me.getPoint();
                   if (mLastPoint == null) {
                        g.fillOval(p.x - mBrushSize / 2, p.y - mBrushSize / 2, mBrushSize, mBrushSize);
                        //g.drawLine(p.x, p.y, p.x, p.y);
                   else {
                        g.drawLine(mLastPoint.x, mLastPoint.y, p.x, p.y);
                        //g.fillOval(p.x - mBrushSize / 2, p.y - mBrushSize / 2, mBrushSize, mBrushSize);
                        double angle = MathUtils.angle(mLastPoint, p);
                        if (angle < 0) {
                             angle += 2 * Math.PI;
                        @SuppressWarnings("unused")
                        double distance = MathUtils.distance(mLastPoint, p) * 1.5;
                        if (angle < Math.PI / 4 || angle > 7 * Math.PI / 4 || Math.abs(Math.PI - angle) < Math.PI / 4) {
                             for (int i = 0; i < mBrushSize / 2; i ++) {
                                  g.drawLine(mLastPoint.x, mLastPoint.y + i, p.x, p.y + i);
                                  g.drawLine(mLastPoint.x, mLastPoint.y - i, p.x, p.y - i);
    //                              System.out.println("y");
    //                              System.out.println("angle = " + angle / Math.PI * 180);
                        else {
                             for (int i = 0; i < mBrushSize / 2; i ++) {
                                  g.drawLine(mLastPoint.x + i, mLastPoint.y, p.x + i, p.y);
                                  g.drawLine(mLastPoint.x  - i, mLastPoint.y, p.x - i, p.y);
    //                              System.out.println("x");
    //                    System.out.println("new = " + PaintUtils.printPoint(p));
    //                    System.out.println("last = " + PaintUtils.printPoint(mLastPoint));
                        //System.out.println("distance = " + distance);
                        //Graphics2D g2 = (Graphics2D) g;
                        //g2.translate(mLastPoint.x + mBrushSize / 2, mLastPoint.y);
                        //g2.rotate(angle);
                        //g2.fillRect(0, 0, (int) Math.ceil(distance), mBrushSize);
                        //g2.rotate(-angle);
                        //g2.translate(-mLastPoint.x + mBrushSize / 2, -mLastPoint.y);
    //                    g.setColor(Color.RED);
    //                    g.drawRect(p.x, p.y, 1, 1);
                   mLastPoint = p;
                   g.dispose();
                   repaint();
              public void mouseMoved(MouseEvent me) {}
              public void mouseReleased(MouseEvent me) {
                   mLastPoint = null;
         private void handleResize() {
              Dimension size = getSize();
              mSizeChanged = false;
              if (mImg == null) {
                   mImg = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
                   Graphics g = mImg.getGraphics();
                   g.setColor(getBackground());
                   g.fillRect(0, 0, mImg.getWidth(), mImg.getHeight());
                   g.dispose();
              else {
                   int newWidth = Math.max(mImg.getWidth(),getWidth());
                   int newHeight = Math.max(mImg.getHeight(),getHeight());
                   if (newHeight == mImg.getHeight() && newWidth == mImg.getWidth()) {
                        return;
                   BufferedImage bi2 = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
                   Graphics g = bi2.getGraphics();
                   g.setColor(getBackground());
                   g.fillRect(0, 0, bi2.getWidth(), bi2.getHeight());
                   g.drawImage(mImg, mImg.getWidth(), mImg.getHeight(), null);
                   g.dispose();
                   mImg = bi2;
         public JToolBar getToolBar() {
              if (mToolBar == null) {
                   mToolBar = new ToolBar();
              return mToolBar;
         private ToolBar mToolBar;
         public static void main (String args[]) {
              PaintArea pa = new PaintArea();
              JPanel parent = new JPanel();
              parent.setLayout(new BorderLayout());
              parent.add(pa, BorderLayout.CENTER);
              pa.setPreferredSize(new Dimension(150, 150));
              parent.add(pa.getToolBar(), BorderLayout.NORTH);
              WindowUtilities.visualize(parent);
         protected class CListener extends ComponentAdapter {
              public void componentResized(ComponentEvent ce) {
                   mSizeChanged = true;
    }

  • GridBagLayout & Canvas question

    I hit a snag during my homework assignment. I am in the making of a RTS game, and want to draw on a Canvas, which I'm placing within a Panel that has a GridbagLayout using the following code:
    pane = new Panel(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    //pane.add(new Label(), c);
    c.gridx = 0;
    c.gridy = 0;
    c.fill = GridBagConstraints.BOTH;
    pane.add(field, c);As I understand this should place and size the field (Canvas) to fill out all the available space in the panel, but all I see is a big white nothing. http://users.hszk.bme.hu/~fm649/javasnag0.png The funny thing is that if I delete the comment tag before
    pane.add(new Label(), c);then I actually get what I wanted, the field (Canvas) is drawn correctly in the appropriate place and size (except for the label itself in the center of the window). http://users.hszk.bme.hu/~fm649/javasnag1.png Any ideas why is this happening?
    Thanks in advance, Mike

    the making of a RTS game, and want to draw on a
    Canvas, which I'm placing within a Panel that has aYou want to draw on a canvas? By default canvas is not equiped to do this. If you want a canvas you can draw on, check out my code below. If you are using AWT instead of swing you might have to modify this a little, but it shouldn't be too hard
    You are welcome to use and modify this code, but please do not change the package or take credit for it as your own work.
    tjacobs.ui.PaintArea.java
    ====================
    * Created on Jun 15, 2005 by @author Tom Jacobs
    package tjacobs.ui;
    import java.awt.image.BufferedImage;
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.ImageIcon;
    import javax.swing.JComboBox;
    import javax.swing.JComponent;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JToolBar;
    import javax.swing.SwingUtilities;
    import tjacobs.MathUtils;
    * PaintArea is a component that you can draw in similar to but
    * much simpler than the windows paint program.
    public class PaintArea extends JComponent {
         BufferedImage mImg; //= new BufferedImage();
         int mBrushSize = 1;
         private boolean mSizeChanged = false;
         private Color mColor1, mColor2;
         static class PaintIcon extends ImageIcon {
              int mSize;
              public PaintIcon(Image im, int size) {
                   super(im);
                   mSize = size;
         public PaintArea() {
              super();
              setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
              addComponentListener(new CListener());
              MListener ml = new MListener();
              addMouseListener(ml);
              addMouseMotionListener(ml);
              setBackground(Color.WHITE);
              setForeground(Color.BLACK);
         public void paintComponent(Graphics g) {
              if (mSizeChanged) {
                   handleResize();
              //g.drawImage(mImg, mImg.getWidth(), mImg.getHeight(), null);
              g.drawImage(mImg, 0, 0, null);
              //super.paintComponent(g);
              //System.out.println("Image = " + mImg);
              //System.out.println("Size: " + mImg.getWidth() + "," + mImg.getHeight());
         public void setBackground(Color c) {
              super.setBackground(c);
              if (mImg != null) {
                   Graphics g = mImg.getGraphics();
                   g.setColor(c);
                   g.fillRect(0, 0, mImg.getWidth(), mImg.getHeight());
                   g.dispose();
         public void setColor1(Color c) {
              mColor1 = c;
         public void setColor2(Color c) {
              mColor2 = c;
         public Color getColor1() {
              return mColor1;
         public Color getColor2() {
              return mColor2;
         class ToolBar extends JToolBar {
              ToolBar() {
                   final ColorButton fore = new ColorButton();
                   fore.setToolTipText("Foreground Color");
                   final ColorButton back = new ColorButton();
                   back.setToolTipText("Background Color");
                   JComboBox brushSize = new JComboBox();
                   //super.createImage(1, 1).;
                   FontMetrics fm = new FontMetrics(getFont()) {};
                   int ht = fm.getHeight();
                   int useheight = fm.getHeight() % 2 == 0 ? fm.getHeight() + 1 : fm.getHeight();
                   final BufferedImage im1 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   Graphics g = im1.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2, useheight / 2, 1, 1);
                   g.dispose();
                   //im1.setRGB(useheight / 2 + 1, useheight / 2 + 1, 0xFFFFFF);
                   final BufferedImage im2 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   g = im2.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2 - 1, useheight / 2 - 1, 3, 3);
                   g.dispose();
    //               im2.setRGB(useheight / 2 - 1, useheight / 2 - 1, 3, 3, new int[] {     0, 0xFFFFFF, 0,
    //                                                            0xFFFFFF, 0xFFFFFFF, 0xFFFFFF,
    //                                                            0, 0xFFFFFF, 0}, 0, 1);
                   final BufferedImage im3 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   g = im3.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2 - 2, useheight / 2 - 2, 5, 5);
                   g.dispose();
    //               im3.setRGB(useheight / 2 - 2, useheight / 2 - 2, 5, 5, new int[] {     0, 0, 0xFFFFFF, 0, 0, 
    //                                                            0, 0xFFFFFF, 0xFFFFFFF, 0xFFFFFF, 0,
    //                                                            0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF,
    //                                                            0, 0xFFFFFF, 0xFFFFFFF, 0xFFFFFF, 0,
    //                                                            0, 0, 0xFFFFFF, 0, 0}, 0, 1);
                   //JLabel l1 = new JLabel("1 pt", new ImageIcon(im1), JLabel.LEFT);
                   //JLabel l2 = new JLabel("3 pt", new ImageIcon(im2), JLabel.LEFT);
                   //JLabel l3 = new JLabel("5 pt", new ImageIcon(im3), JLabel.LEFT);
                   brushSize.addItem(new PaintIcon(im1, 1));
                   brushSize.addItem(new PaintIcon(im2, 3));
                   brushSize.addItem(new PaintIcon(im3, 5));
                   //brushSize.addItem("Other");
                   add(fore);
                   add(back);
                   add(brushSize);
                   PropertyChangeListener pl = new PropertyChangeListener() {
                        public void propertyChange(PropertyChangeEvent ev) {
                             Object src = ev.getSource();
                             if (src != fore && src != back) {
                                  return;
                             Color c = (Color) ev.getNewValue();
                             if (ev.getSource() == fore) {
                                  mColor1 = c;
                             else {
                                  mColor2 = c;
                   fore.addPropertyChangeListener("Color", pl);
                   back.addPropertyChangeListener("Color", pl);
                   fore.changeColor(Color.BLACK);
                   back.changeColor(Color.WHITE);
                   brushSize.addItemListener(new ItemListener() {
                        public void itemStateChanged(ItemEvent ev) {
                             System.out.println("ItemEvent");
                             if (ev.getID() == ItemEvent.DESELECTED) {
                                  return;
                             System.out.println("Selected");
                             Object o = ev.getItem();
                             mBrushSize = ((PaintIcon) o).mSize;
                   //Graphics g = im1.getGraphics();
                   //g.fillOval(0, 0, 1, 1);
                   //BufferedImage im1 = new BufferedImage();
                   //BufferedImage im1 = new BufferedImage();
         protected class MListener extends MouseAdapter implements MouseMotionListener {
              Point mLastPoint;
              public void mouseDragged(MouseEvent me) {
                   Graphics g = mImg.getGraphics();
                   if ((me.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
                        g.setColor(mColor1);
                   } else {
                        g.setColor(mColor2);
                   Point p = me.getPoint();
                   if (mLastPoint == null) {
                        g.fillOval(p.x - mBrushSize / 2, p.y - mBrushSize / 2, mBrushSize, mBrushSize);
                        //g.drawLine(p.x, p.y, p.x, p.y);
                   else {
                        g.drawLine(mLastPoint.x, mLastPoint.y, p.x, p.y);
                        //g.fillOval(p.x - mBrushSize / 2, p.y - mBrushSize / 2, mBrushSize, mBrushSize);
                        double angle = MathUtils.angle(mLastPoint, p);
                        if (angle < 0) {
                             angle += 2 * Math.PI;
                        double distance = MathUtils.distance(mLastPoint, p) * 1.5;
                        if (angle < Math.PI / 4 || angle > 7 * Math.PI / 4 || Math.abs(Math.PI - angle) < Math.PI / 4) {
                             for (int i = 0; i < mBrushSize / 2; i ++) {
                                  g.drawLine(mLastPoint.x, mLastPoint.y + i, p.x, p.y + i);
                                  g.drawLine(mLastPoint.x, mLastPoint.y - i, p.x, p.y - i);
    //                              System.out.println("y");
    //                              System.out.println("angle = " + angle / Math.PI * 180);
                        else {
                             for (int i = 0; i < mBrushSize / 2; i ++) {
                                  g.drawLine(mLastPoint.x + i, mLastPoint.y, p.x + i, p.y);
                                  g.drawLine(mLastPoint.x  - i, mLastPoint.y, p.x - i, p.y);
    //                              System.out.println("x");
    //                    System.out.println("new = " + PaintUtils.printPoint(p));
    //                    System.out.println("last = " + PaintUtils.printPoint(mLastPoint));
                        //System.out.println("distance = " + distance);
                        //Graphics2D g2 = (Graphics2D) g;
                        //g2.translate(mLastPoint.x + mBrushSize / 2, mLastPoint.y);
                        //g2.rotate(angle);
                        //g2.fillRect(0, 0, (int) Math.ceil(distance), mBrushSize);
                        //g2.rotate(-angle);
                        //g2.translate(-mLastPoint.x + mBrushSize / 2, -mLastPoint.y);
    //                    g.setColor(Color.RED);
    //                    g.drawRect(p.x, p.y, 1, 1);
                   mLastPoint = p;
                   g.dispose();
                   repaint();
              public void mouseMoved(MouseEvent me) {}
              public void mouseReleased(MouseEvent me) {
                   mLastPoint = null;
         private void handleResize() {
              Dimension size = getSize();
              mSizeChanged = false;
              if (mImg == null) {
                   mImg = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
                   Graphics g = mImg.getGraphics();
                   g.setColor(getBackground());
                   g.fillRect(0, 0, mImg.getWidth(), mImg.getHeight());
                   g.dispose();
              else {
                   int newWidth = Math.max(mImg.getWidth(),getWidth());
                   int newHeight = Math.max(mImg.getHeight(),getHeight());
                   if (newHeight == mImg.getHeight() && newWidth == mImg.getWidth()) {
                        return;
                   BufferedImage bi2 = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
                   Graphics g = bi2.getGraphics();
                   g.setColor(getBackground());
                   g.fillRect(0, 0, bi2.getWidth(), bi2.getHeight());
                   g.drawImage(mImg, mImg.getWidth(), mImg.getHeight(), null);
                   g.dispose();
                   mImg = bi2;
         public JToolBar getToolBar() {
              if (mToolBar == null) {
                   mToolBar = new ToolBar();
              return mToolBar;
         private ToolBar mToolBar;
         public static void main (String args[]) {
              PaintArea pa = new PaintArea();
              JPanel parent = new JPanel();
              parent.setLayout(new BorderLayout());
              parent.add(pa, BorderLayout.CENTER);
              pa.setPreferredSize(new Dimension(150, 150));
              parent.add(pa.getToolBar(), BorderLayout.NORTH);
              WindowUtilities.visualize(parent);
         protected class CListener extends ComponentAdapter {
              public void componentResized(ComponentEvent ce) {
                   mSizeChanged = true;
    MathUtils.java
    ===========
    * Created on Nov 7, 2004 by @author Tom Jacobs
    package tjacobs;
    import java.awt.Point;
    * Simple math routines spelled out. There's euclideanDistance, factorial,
    * combinations, distance.<p>
    * Pretty standard really.
    public class MathUtils {
         private MathUtils() {
              super();
         public static double euclideanDistance(Point p1, Point p2) {
              return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));
         public static int factorial(int x) {
              int pow = 1;
              while (x > 1) {
                   pow = pow * x;
                   x--;
              return pow;
         public static int getCombinations(int total, int picks, boolean replacing, boolean ordered) {
              int ans = 0;
              if (replacing && ordered) {
                   ans = (int)Math.pow(total, picks);
                   //total / Math.pow(totalpicks)
              else if (!replacing && ordered){
                   ans = factorial (total);
                   ans /= factorial(total - picks);
              } else if (replacing && !ordered) {
                   ans = factorial(total + picks - 1);
                   ans /= factorial(picks);
                   ans /= factorial(total - picks);
              else if (!replacing && !ordered) {
                   ans = factorial(total);
                   ans/= factorial(picks);
                   ans/= factorial(total - picks);               
              return ans;
         public static double distance (Point p1, Point p2) {
              return distance(p1.x, p1.y, p2.x, p2.y);
         public static double distance(double x1, double y1) {
              return distance(x1, y1, 0, 0);
         public static double distance (double x1, double y1, double x2, double y2) {
              return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
         public static double angle (Point p1, Point p2) {
              return angle(p1.x, p1.y, p2.x, p2.y);
         public static double angle (double x1, double y1, double x2, double y2) {
              double xdiff = x1 - x2;
              double ydiff = y1 - y2;
              double tan = xdiff / ydiff;
              double atan = Math.atan2(ydiff, xdiff);
              return atan;
         public static double reflectOff(double ray, double reflectOff) {
              return reflectOff + reflectOff - ray;
         //Testing only
    /*     public static void main(String args[]) {
              System.out.println(reflectOff(0, Math.PI / 4) / Math.PI);
              System.out.println(reflectOff(Math.PI / 2, Math.PI) / Math.PI);
              System.out.println(reflectOff(5 * Math.PI / 4, Math.PI / 2) / Math.PI);
              System.out.println(reflectOff(Math.PI, Math.PI / 2));
    WindowUtils.java
    ===============
    package tjacobs.ui;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.ImageIcon;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenuItem;
    import javax.swing.JPopupMenu;
    import javax.swing.Popup;
    import javax.swing.SwingUtilities;
    public abstract class WindowUtilities {
         public static final int RESIZE_MARGIN_SIZE = 4;
         private static Window sExitWindow = null;
         public static interface CreatePopupWindow {
              public JDialog createPopupWindow(Point p);
         * Returns an point which has been adjusted to take into account of the
         * desktop bounds, taskbar and multi-monitor configuration.
         * <p>
         * This adustment may be cancelled by invoking the application with
         * -Djavax.swing.adjustPopupLocationToFit=false
        public static Point adjustPopupLocationToFitScreen(Component popup, Component invoker, int xposition, int yposition) {
         Point p = new Point(xposition, yposition);
            if(//popupPostionFixDisabled == true ||
                        GraphicsEnvironment.isHeadless())
                return p;
            Toolkit toolkit = Toolkit.getDefaultToolkit();
            Rectangle screenBounds;
            Insets screenInsets;
            GraphicsConfiguration gc = null;
            // Try to find GraphicsConfiguration, that includes mouse
            // pointer position
            GraphicsEnvironment ge =
                GraphicsEnvironment.getLocalGraphicsEnvironment();
            GraphicsDevice[] gd = ge.getScreenDevices();
            for(int i = 0; i < gd.length; i++) {
                if(gd.getType() == GraphicsDevice.TYPE_RASTER_SCREEN) {
    GraphicsConfiguration dgc =
    gd[i].getDefaultConfiguration();
    if(dgc.getBounds().contains(p)) {
    gc = dgc;
    break;
    // If not found and we have invoker, ask invoker about his gc
    if(gc == null && invoker != null) {
    gc = invoker.getGraphicsConfiguration();
    if(gc != null) {
    // If we have GraphicsConfiguration use it to get
    // screen bounds and insets
    screenInsets = toolkit.getScreenInsets(gc);
    screenBounds = gc.getBounds();
    } else {
    // If we don't have GraphicsConfiguration use primary screen
    // and empty insets
    screenInsets = new Insets(0, 0, 0, 0);
    screenBounds = new Rectangle(toolkit.getScreenSize());
    int scrWidth = screenBounds.width -
    Math.abs(screenInsets.left+screenInsets.right);
    int scrHeight = screenBounds.height -
    Math.abs(screenInsets.top+screenInsets.bottom);
    Dimension size;
    size = popup.getPreferredSize();
    if( (p.x + size.width) > screenBounds.x + scrWidth )
    p.x = screenBounds.x + scrWidth - size.width;
    if( (p.y + size.height) > screenBounds.y + scrHeight)
    p.y = screenBounds.y + scrHeight - size.height;
    /* Change is made to the desired (X,Y) values, when the
    PopupMenu is too tall OR too wide for the screen
    if( p.x < screenBounds.x )
    p.x = screenBounds.x ;
    if( p.y < screenBounds.y )
    p.y = screenBounds.y;
    return p;
         public static MouseListener addAsPopup(final CreatePopupWindow cpw, Component owner) {
              if (cpw == null || owner == null) {
                   return null;
              MouseListener ml = new MouseAdapter() {
                   CreatePopupWindow create = cpw;
                   public void mousePressed(MouseEvent ev) {
                        testPopup(ev);
                   public void mouseReleased(MouseEvent ev) {
                        testPopup(ev);
                   private void testPopup(MouseEvent ev) {
                        if (ev.isPopupTrigger()) {
                             final JDialog pop = create.createPopupWindow(ev.getPoint());
                             //pop.setUndecorated(true);
                             if (pop == null) {
                                  return;
                             Window w = SwingUtilities.getWindowAncestor(ev.getComponent());
                             pop.setLocation(ev.getX() + w.getX(), ev.getY() + w.getY());
                             pop.pack();
                             pop.addWindowListener(new WindowAdapter() {
                                  public void windowDeactivated(WindowEvent we) {
                                       pop.dispose();
                             pop.setFocusableWindowState(true);
                             pop.setVisible(true);
                             pop.requestFocus();
                             //pop.show();
              owner.addMouseListener(ml);
              return ml;
         public static MouseListener addAsPopup(final JPopupMenu popup, Component owner) {
              if (popup == null || owner == null) {
                   return null;
              //popup.setUndecorated(true);
              MouseListener ml = new MouseAdapter() {
                   JPopupMenu pop = popup;
                   public void mousePressed(MouseEvent ev) {
                        testPopup(ev);
                   public void mouseReleased(MouseEvent ev) {
                        testPopup(ev);
                   private void testPopup(MouseEvent ev) {
                        if (ev.isPopupTrigger()) {
                             //pop.setLocation(ev.getPoint());
                             //pop.pack();
                             //pop.setVisible(true);
                             //JPopupMenu pop = new JPopupMenu();
                             //pop.add(new JMenuItem("Hi"));
                             pop.show(ev.getComponent(), ev.getX(), ev.getY());
              owner.addMouseListener(ml);
              return ml;
         public static MouseListener addAsPopup(final JDialog popup, Component owner) {
              if (popup == null || owner == null) {
                   return null;
              //popup.setUndecorated(true);
              MouseListener ml = new MouseAdapter() {
                   Window pop = popup;
                   public void mousePressed(MouseEvent ev) {
                        testPopup(ev);
                   public void mouseReleased(MouseEvent ev) {
                        testPopup(ev);
                   private void testPopup(MouseEvent ev) {
                        if (ev.isPopupTrigger()) {
                             pop.setLocation(ev.getPoint());
                             pop.pack();
                             pop.setVisible(true);
              owner.addMouseListener(ml);
              return ml;
         public static Point getBottomRightOfScreen(Component c) {
         Dimension scr_size = Toolkit.getDefaultToolkit().getScreenSize();
         Dimension c_size = c.getSize();
         return new Point(scr_size.width - c_size.width, scr_size.height - c_size.height);
         public static Window visualize(Component c) {
              return visualize(c, sExitWindow == null);
         public static Window visualize(Image im) {
              return visualize(new JLabel(new ImageIcon(im)));
         public static Window visualize (Component c, int width, int height) {
              return visualize(c, sExitWindow == null, width, height);
         public static Window visualize(Component c, boolean exit, int width, int height) {
              JFrame f;
              Window w;
              if (c instanceof Window) {
                   w = (Window) c;
              else {
                   f = new JFrame();
                   f.getContentPane().add(c);
                   w = f;
              // to be thread safe, this should be synchonized.
              // but it doesn't really matter in everyday situations
              if (sExitWindow == null) {
                   sExitWindow = w;
              w.setSize(width, height);
              w.setLocation(100, 100);
              if (exit) {
                   w.addWindowListener(new WindowClosingActions.Exit());
              w.setVisible(true);
              return w;          
         public void center(Window w) {
              Dimension dim = w.getSize();
              Dimension scr = Toolkit.getDefaultToolkit().getScreenSize();
              w.setLocation((scr.width - dim.width)/2, (scr.height - dim.height)/2);
         public static Window visualize(Component c, boolean exit) {
              JFrame f;
              Window w;
              if (c instanceof Window) {
                   w = (Window) c;
              else {
                   f = new JFrame();
                   f.getContentPane().add(c);
                   w = f;
              w.pack();
              w.setLocation(100, 100);
              if (exit) {
                   w.addWindowListener(new WindowClosingActions.Exit());
              w.setVisible(true);
              return w;

  • Constant Mouse

    Hello. My name is Chris. I took a basic java introduction class during the summer. My teacher created a graph program/sprite/turtle(logo)/keyboard/applet program. I know how to get all of that working. All I need to know is hoe I can have a constant mouse catcher. Here is my code (without all of the other stuff):
    while(true) {
    //loop forever
    mx=g.getMouseX();
    //mx is a double
    //g.getMouseX(); saves last mouse click x in mx
    my=g.getMouseY();
    //same as above, only for Y variable (of mouse)
    Tim.setPosition(mx,my);
    //Send invisible Tim, the Turtle to the place where the mouse was clicked
    Tim.forward(.01);
    //Tim makes a mark there.
    Now what I want is something that will allow me to make lines instead of just dots. So it will pick up when I have the mouse held down. How can I do this?
    Thanks,
    Chris

    Here is my PaintArea class. This should give you some idea about how mouse listeners work, and may be along the lines of what you're looking for.
    You are free to use and modify the code, but please do not change the package or take credit for it as your own.
    BTW, if you're trying to do this as a challenge, this may be kind of a spoiler, so if you want the thrill of figuring it all out, stop here.
    PaintArea.java
    ===========
    * Created on Jun 15, 2005 by @author Tom Jacobs
    package tjacobs.ui;
    import java.awt.image.BufferedImage;
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.ImageIcon;
    import javax.swing.JComboBox;
    import javax.swing.JComponent;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JToolBar;
    import javax.swing.SwingUtilities;
    import tjacobs.MathUtils;
    public class PaintArea extends JComponent {
         BufferedImage mImg; //= new BufferedImage();
         int mBrushSize = 1;
         private boolean mSizeChanged = false;
         private Color mColor1, mColor2;
         static class PaintIcon extends ImageIcon {
              int mSize;
              public PaintIcon(Image im, int size) {
                   super(im);
                   mSize = size;
         public PaintArea() {
              super();
              setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
              addComponentListener(new CListener());
              MListener ml = new MListener();
              addMouseListener(ml);
              addMouseMotionListener(ml);
              setBackground(Color.WHITE);
              setForeground(Color.BLACK);
         public void paintComponent(Graphics g) {
              if (mSizeChanged) {
                   handleResize();
              //g.drawImage(mImg, mImg.getWidth(), mImg.getHeight(), null);
              g.drawImage(mImg, 0, 0, null);
              //super.paintComponent(g);
              //System.out.println("Image = " + mImg);
              //System.out.println("Size: " + mImg.getWidth() + "," + mImg.getHeight());
         public void setBackground(Color c) {
              super.setBackground(c);
              if (mImg != null) {
                   Graphics g = mImg.getGraphics();
                   g.setColor(c);
                   g.fillRect(0, 0, mImg.getWidth(), mImg.getHeight());
                   g.dispose();
         public void setColor1(Color c) {
              mColor1 = c;
         public void setColor2(Color c) {
              mColor2 = c;
         public Color getColor1() {
              return mColor1;
         public Color getColor2() {
              return mColor2;
         class ToolBar extends JToolBar {
              ToolBar() {
                   final ColorButton fore = new ColorButton();
                   fore.setToolTipText("Foreground Color");
                   final ColorButton back = new ColorButton();
                   back.setToolTipText("Background Color");
                   JComboBox brushSize = new JComboBox();
                   //super.createImage(1, 1).;
                   FontMetrics fm = new FontMetrics(getFont()) {};
                   int ht = fm.getHeight();
                   int useheight = fm.getHeight() % 2 == 0 ? fm.getHeight() + 1 : fm.getHeight();
                   final BufferedImage im1 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   Graphics g = im1.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2, useheight / 2, 1, 1);
                   g.dispose();
                   //im1.setRGB(useheight / 2 + 1, useheight / 2 + 1, 0xFFFFFF);
                   final BufferedImage im2 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   g = im2.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2 - 1, useheight / 2 - 1, 3, 3);
                   g.dispose();
    //               im2.setRGB(useheight / 2 - 1, useheight / 2 - 1, 3, 3, new int[] {     0, 0xFFFFFF, 0,
    //                                                            0xFFFFFF, 0xFFFFFFF, 0xFFFFFF,
    //                                                            0, 0xFFFFFF, 0}, 0, 1);
                   final BufferedImage im3 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   g = im3.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2 - 2, useheight / 2 - 2, 5, 5);
                   g.dispose();
    //               im3.setRGB(useheight / 2 - 2, useheight / 2 - 2, 5, 5, new int[] {     0, 0, 0xFFFFFF, 0, 0, 
    //                                                            0, 0xFFFFFF, 0xFFFFFFF, 0xFFFFFF, 0,
    //                                                            0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF,
    //                                                            0, 0xFFFFFF, 0xFFFFFFF, 0xFFFFFF, 0,
    //                                                            0, 0, 0xFFFFFF, 0, 0}, 0, 1);
                   //JLabel l1 = new JLabel("1 pt", new ImageIcon(im1), JLabel.LEFT);
                   //JLabel l2 = new JLabel("3 pt", new ImageIcon(im2), JLabel.LEFT);
                   //JLabel l3 = new JLabel("5 pt", new ImageIcon(im3), JLabel.LEFT);
                   brushSize.addItem(new PaintIcon(im1, 1));
                   brushSize.addItem(new PaintIcon(im2, 3));
                   brushSize.addItem(new PaintIcon(im3, 5));
                   //brushSize.addItem("Other");
                   add(fore);
                   add(back);
                   add(brushSize);
                   PropertyChangeListener pl = new PropertyChangeListener() {
                        public void propertyChange(PropertyChangeEvent ev) {
                             Object src = ev.getSource();
                             if (src != fore && src != back) {
                                  return;
                             Color c = (Color) ev.getNewValue();
                             if (ev.getSource() == fore) {
                                  mColor1 = c;
                             else {
                                  mColor2 = c;
                   fore.addPropertyChangeListener("Color", pl);
                   back.addPropertyChangeListener("Color", pl);
                   fore.changeColor(Color.BLACK);
                   back.changeColor(Color.WHITE);
                   brushSize.addItemListener(new ItemListener() {
                        public void itemStateChanged(ItemEvent ev) {
                             System.out.println("ItemEvent");
                             if (ev.getID() == ItemEvent.DESELECTED) {
                                  return;
                             System.out.println("Selected");
                             Object o = ev.getItem();
                             mBrushSize = ((PaintIcon) o).mSize;
                   //Graphics g = im1.getGraphics();
                   //g.fillOval(0, 0, 1, 1);
                   //BufferedImage im1 = new BufferedImage();
                   //BufferedImage im1 = new BufferedImage();
         protected class MListener extends MouseAdapter implements MouseMotionListener {
              Point mLastPoint;
              public void mouseDragged(MouseEvent me) {
                   Graphics g = mImg.getGraphics();
                   if ((me.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
                        g.setColor(mColor1);
                   } else {
                        g.setColor(mColor2);
                   Point p = me.getPoint();
                   if (mLastPoint == null) {
                        g.fillOval(p.x - mBrushSize / 2, p.y - mBrushSize / 2, mBrushSize, mBrushSize);
                        //g.drawLine(p.x, p.y, p.x, p.y);
                   else {
                        g.drawLine(mLastPoint.x, mLastPoint.y, p.x, p.y);
                        //g.fillOval(p.x - mBrushSize / 2, p.y - mBrushSize / 2, mBrushSize, mBrushSize);
                        double angle = MathUtils.angle(mLastPoint, p);
                        if (angle < 0) {
                             angle += 2 * Math.PI;
                        double distance = MathUtils.distance(mLastPoint, p) * 1.5;
                        if (angle < Math.PI / 4 || angle > 7 * Math.PI / 4 || Math.abs(Math.PI - angle) < Math.PI / 4) {
                             for (int i = 0; i < mBrushSize / 2; i ++) {
                                  g.drawLine(mLastPoint.x, mLastPoint.y + i, p.x, p.y + i);
                                  g.drawLine(mLastPoint.x, mLastPoint.y - i, p.x, p.y - i);
    //                              System.out.println("y");
    //                              System.out.println("angle = " + angle / Math.PI * 180);
                        else {
                             for (int i = 0; i < mBrushSize / 2; i ++) {
                                  g.drawLine(mLastPoint.x + i, mLastPoint.y, p.x + i, p.y);
                                  g.drawLine(mLastPoint.x  - i, mLastPoint.y, p.x - i, p.y);
    //                              System.out.println("x");
    //                    System.out.println("new = " + PaintUtils.printPoint(p));
    //                    System.out.println("last = " + PaintUtils.printPoint(mLastPoint));
                        //System.out.println("distance = " + distance);
                        //Graphics2D g2 = (Graphics2D) g;
                        //g2.translate(mLastPoint.x + mBrushSize / 2, mLastPoint.y);
                        //g2.rotate(angle);
                        //g2.fillRect(0, 0, (int) Math.ceil(distance), mBrushSize);
                        //g2.rotate(-angle);
                        //g2.translate(-mLastPoint.x + mBrushSize / 2, -mLastPoint.y);
    //                    g.setColor(Color.RED);
    //                    g.drawRect(p.x, p.y, 1, 1);
                   mLastPoint = p;
                   g.dispose();
                   repaint();
              public void mouseMoved(MouseEvent me) {}
              public void mouseReleased(MouseEvent me) {
                   mLastPoint = null;
         private void handleResize() {
              Dimension size = getSize();
              mSizeChanged = false;
              if (mImg == null) {
                   mImg = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
                   Graphics g = mImg.getGraphics();
                   g.setColor(getBackground());
                   g.fillRect(0, 0, mImg.getWidth(), mImg.getHeight());
                   g.dispose();
              else {
                   int newWidth = Math.max(mImg.getWidth(),getWidth());
                   int newHeight = Math.max(mImg.getHeight(),getHeight());
                   if (newHeight == mImg.getHeight() && newWidth == mImg.getWidth()) {
                        return;
                   BufferedImage bi2 = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
                   Graphics g = bi2.getGraphics();
                   g.setColor(getBackground());
                   g.fillRect(0, 0, bi2.getWidth(), bi2.getHeight());
                   g.drawImage(mImg, mImg.getWidth(), mImg.getHeight(), null);
                   g.dispose();
                   mImg = bi2;
         public JToolBar getToolBar() {
              if (mToolBar == null) {
                   mToolBar = new ToolBar();
              return mToolBar;
         private ToolBar mToolBar;
         public static void main (String args[]) {
              PaintArea pa = new PaintArea();
              JPanel parent = new JPanel();
              parent.setLayout(new BorderLayout());
              parent.add(pa, BorderLayout.CENTER);
              pa.setPreferredSize(new Dimension(150, 150));
              parent.add(pa.getToolBar(), BorderLayout.NORTH);
              WindowUtilities.visualize(parent);
         protected class CListener extends ComponentAdapter {
              public void componentResized(ComponentEvent ce) {
                   mSizeChanged = true;
    }

  • Draw with single mouse click, help me!!!!

    I am using this code - as you understood from it- to paint with the mouse click.
    please help me either by completing it or by telling me what to do.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Hello extends JFrame{
         Graphics g;
         ImageIcon icon = new ImageIcon("hello.gif");
         public Hello(){
              super("Hello");
              setSize(200, 200);
              addMouseListener(
                   new MouseAdapter(){
                        public void mouseClicked(MouseEvent e){
                             icon.paintIcon(Hello.this, g, e.getX(), e.getY());
                             g.fillRect(10, 40, 10, 80);
                             JOptionPane.showMessageDialog(Hello.this, e.getX() + ", " + e.getY());
                             //repaint();
         // i have tried to place this listener in the paint method, but no way out.
              setVisible(true);
         public void paint(final Graphics g){
              this.g = g;
              icon.paintIcon(this, g, 100, 50);
         public static void main(String[] args){
              new Hello();
    **

    You can't save a graphics object like that and then paint on it.
    What you need is to use a BufferedImage, paint on that, and then paint that to the screen.
    See my paintarea class. You are welcome to use + modify this class as well as take any code snippets to fit into whatever you have but please add a comment where ever you've incorporated stuff from my class
    PaintArea.java
    ===========
    * Created on Jun 15, 2005 by @author Tom Jacobs
    package tjacobs.ui;
    import java.awt.image.BufferedImage;
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.ImageIcon;
    import javax.swing.JComboBox;
    import javax.swing.JComponent;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JToolBar;
    import javax.swing.SwingUtilities;
    import tjacobs.MathUtils;
    * PaintArea is a component that you can draw in similar to but
    * much simpler than the windows paint program.
    public class PaintArea extends JComponent {
         BufferedImage mImg; //= new BufferedImage();
         int mBrushSize = 1;
         private boolean mSizeChanged = false;
         private Color mColor1, mColor2;
         static class PaintIcon extends ImageIcon {
              int mSize;
              public PaintIcon(Image im, int size) {
                   super(im);
                   mSize = size;
         public PaintArea() {
              super();
              setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
              addComponentListener(new CListener());
              MListener ml = new MListener();
              addMouseListener(ml);
              addMouseMotionListener(ml);
              setBackground(Color.WHITE);
              setForeground(Color.BLACK);
         public void paintComponent(Graphics g) {
              if (mSizeChanged) {
                   handleResize();
              //g.drawImage(mImg, mImg.getWidth(), mImg.getHeight(), null);
              g.drawImage(mImg, 0, 0, null);
              //super.paintComponent(g);
              //System.out.println("Image = " + mImg);
              //System.out.println("Size: " + mImg.getWidth() + "," + mImg.getHeight());
         public void setBackground(Color c) {
              super.setBackground(c);
              if (mImg != null) {
                   Graphics g = mImg.getGraphics();
                   g.setColor(c);
                   g.fillRect(0, 0, mImg.getWidth(), mImg.getHeight());
                   g.dispose();
         public void setColor1(Color c) {
              mColor1 = c;
         public void setColor2(Color c) {
              mColor2 = c;
         public Color getColor1() {
              return mColor1;
         public Color getColor2() {
              return mColor2;
         class ToolBar extends JToolBar {
              ToolBar() {
                   final ColorButton fore = new ColorButton();
                   fore.setToolTipText("Foreground Color");
                   final ColorButton back = new ColorButton();
                   back.setToolTipText("Background Color");
                   JComboBox brushSize = new JComboBox();
                   //super.createImage(1, 1).;
                   FontMetrics fm = new FontMetrics(getFont()) {};
                   int ht = fm.getHeight();
                   int useheight = fm.getHeight() % 2 == 0 ? fm.getHeight() + 1 : fm.getHeight();
                   final BufferedImage im1 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   Graphics g = im1.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2, useheight / 2, 1, 1);
                   g.dispose();
                   //im1.setRGB(useheight / 2 + 1, useheight / 2 + 1, 0xFFFFFF);
                   final BufferedImage im2 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   g = im2.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2 - 1, useheight / 2 - 1, 3, 3);
                   g.dispose();
    //               im2.setRGB(useheight / 2 - 1, useheight / 2 - 1, 3, 3, new int[] {     0, 0xFFFFFF, 0,
    //                                                            0xFFFFFF, 0xFFFFFFF, 0xFFFFFF,
    //                                                            0, 0xFFFFFF, 0}, 0, 1);
                   final BufferedImage im3 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   g = im3.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2 - 2, useheight / 2 - 2, 5, 5);
                   g.dispose();
    //               im3.setRGB(useheight / 2 - 2, useheight / 2 - 2, 5, 5, new int[] {     0, 0, 0xFFFFFF, 0, 0, 
    //                                                            0, 0xFFFFFF, 0xFFFFFFF, 0xFFFFFF, 0,
    //                                                            0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF,
    //                                                            0, 0xFFFFFF, 0xFFFFFFF, 0xFFFFFF, 0,
    //                                                            0, 0, 0xFFFFFF, 0, 0}, 0, 1);
                   //JLabel l1 = new JLabel("1 pt", new ImageIcon(im1), JLabel.LEFT);
                   //JLabel l2 = new JLabel("3 pt", new ImageIcon(im2), JLabel.LEFT);
                   //JLabel l3 = new JLabel("5 pt", new ImageIcon(im3), JLabel.LEFT);
                   brushSize.addItem(new PaintIcon(im1, 1));
                   brushSize.addItem(new PaintIcon(im2, 3));
                   brushSize.addItem(new PaintIcon(im3, 5));
                   //brushSize.addItem("Other");
                   add(fore);
                   add(back);
                   add(brushSize);
                   PropertyChangeListener pl = new PropertyChangeListener() {
                        public void propertyChange(PropertyChangeEvent ev) {
                             Object src = ev.getSource();
                             if (src != fore && src != back) {
                                  return;
                             Color c = (Color) ev.getNewValue();
                             if (ev.getSource() == fore) {
                                  mColor1 = c;
                             else {
                                  mColor2 = c;
                   fore.addPropertyChangeListener("Color", pl);
                   back.addPropertyChangeListener("Color", pl);
                   fore.changeColor(Color.BLACK);
                   back.changeColor(Color.WHITE);
                   brushSize.addItemListener(new ItemListener() {
                        public void itemStateChanged(ItemEvent ev) {
                             System.out.println("ItemEvent");
                             if (ev.getID() == ItemEvent.DESELECTED) {
                                  return;
                             System.out.println("Selected");
                             Object o = ev.getItem();
                             mBrushSize = ((PaintIcon) o).mSize;
                   //Graphics g = im1.getGraphics();
                   //g.fillOval(0, 0, 1, 1);
                   //BufferedImage im1 = new BufferedImage();
                   //BufferedImage im1 = new BufferedImage();
         protected class MListener extends MouseAdapter implements MouseMotionListener {
              Point mLastPoint;
              public void mouseDragged(MouseEvent me) {
                   Graphics g = mImg.getGraphics();
                   if ((me.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
                        g.setColor(mColor1);
                   } else {
                        g.setColor(mColor2);
                   Point p = me.getPoint();
                   if (mLastPoint == null) {
                        g.fillOval(p.x - mBrushSize / 2, p.y - mBrushSize / 2, mBrushSize, mBrushSize);
                        //g.drawLine(p.x, p.y, p.x, p.y);
                   else {
                        g.drawLine(mLastPoint.x, mLastPoint.y, p.x, p.y);
                        //g.fillOval(p.x - mBrushSize / 2, p.y - mBrushSize / 2, mBrushSize, mBrushSize);
                        double angle = MathUtils.angle(mLastPoint, p);
                        if (angle < 0) {
                             angle += 2 * Math.PI;
                        double distance = MathUtils.distance(mLastPoint, p) * 1.5;
                        if (angle < Math.PI / 4 || angle > 7 * Math.PI / 4 || Math.abs(Math.PI - angle) < Math.PI / 4) {
                             for (int i = 0; i < mBrushSize / 2; i ++) {
                                  g.drawLine(mLastPoint.x, mLastPoint.y + i, p.x, p.y + i);
                                  g.drawLine(mLastPoint.x, mLastPoint.y - i, p.x, p.y - i);
    //                              System.out.println("y");
    //                              System.out.println("angle = " + angle / Math.PI * 180);
                        else {
                             for (int i = 0; i < mBrushSize / 2; i ++) {
                                  g.drawLine(mLastPoint.x + i, mLastPoint.y, p.x + i, p.y);
                                  g.drawLine(mLastPoint.x  - i, mLastPoint.y, p.x - i, p.y);
    //                              System.out.println("x");
    //                    System.out.println("new = " + PaintUtils.printPoint(p));
    //                    System.out.println("last = " + PaintUtils.printPoint(mLastPoint));
                        //System.out.println("distance = " + distance);
                        //Graphics2D g2 = (Graphics2D) g;
                        //g2.translate(mLastPoint.x + mBrushSize / 2, mLastPoint.y);
                        //g2.rotate(angle);
                        //g2.fillRect(0, 0, (int) Math.ceil(distance), mBrushSize);
                        //g2.rotate(-angle);
                        //g2.translate(-mLastPoint.x + mBrushSize / 2, -mLastPoint.y);
    //                    g.setColor(Color.RED);
    //                    g.drawRect(p.x, p.y, 1, 1);
                   mLastPoint = p;
                   g.dispose();
                   repaint();
              public void mouseMoved(MouseEvent me) {}
              public void mouseReleased(MouseEvent me) {
                   mLastPoint = null;
         private void handleResize() {
              Dimension size = getSize();
              mSizeChanged = false;
              if (mImg == null) {
                   mImg = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
                   Graphics g = mImg.getGraphics();
                   g.setColor(getBackground());
                   g.fillRect(0, 0, mImg.getWidth(), mImg.getHeight());
                   g.dispose();
              else {
                   int newWidth = Math.max(mImg.getWidth(),getWidth());
                   int newHeight = Math.max(mImg.getHeight(),getHeight());
                   if (newHeight == mImg.getHeight() && newWidth == mImg.getWidth()) {
                        return;
                   BufferedImage bi2 = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
                   Graphics g = bi2.getGraphics();
                   g.setColor(getBackground());
                   g.fillRect(0, 0, bi2.getWidth(), bi2.getHeight());
                   g.drawImage(mImg, mImg.getWidth(), mImg.getHeight(), null);
                   g.dispose();
                   mImg = bi2;
         public JToolBar getToolBar() {
              if (mToolBar == null) {
                   mToolBar = new ToolBar();
              return mToolBar;
         private ToolBar mToolBar;
         public static void main (String args[]) {
              PaintArea pa = new PaintArea();
              JPanel parent = new JPanel();
              parent.setLayout(new BorderLayout());
              parent.add(pa, BorderLayout.CENTER);
              pa.setPreferredSize(new Dimension(150, 150));
              parent.add(pa.getToolBar(), BorderLayout.NORTH);
              WindowUtilities.visualize(parent);
         protected class CListener extends ComponentAdapter {
              public void componentResized(ComponentEvent ce) {
                   mSizeChanged = true;
    }

  • Update Jcombobox 's label in render

    hi ,everybody, i have a problem about combobox, any body can help me!
    thank you!
    I want to have a combobox with checkbox as item, I rewrite a render writen by ice, because the combobox has three state, when I click diferent checkbox in this combobox , the label of combobox will update rightly, but if I click one checkbox to change the checkbox state ,the label will no update , it seem that when I click one checkbox many times .the menthod
    getListCellRendererComponent(JList list, Object value, int index,
                        boolean isSelected, boolean cellHasFocus)
    will no update label
    my code :
    mainclass:
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Iterator;
    import java.util.Vector;
    import javax.swing.DefaultListCellRenderer;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.plaf.basic.BasicComboBoxEditor;
    public class mainclass {
          public static void main(String[] args) {
                 final testbox myComboBox = new testbox();
                 myComboBox.addItem("SelectAll");
                 myComboBox.addItem("ClearAll");
                 myComboBox.addItem("GrayedAll");
                 for(int i = 0; i < 5; i++) {
                     myComboBox.addItem("Item " + i);
                 JFrame frame = new JFrame("My ComboBox");
                 frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                 frame.setSize(150, 60);
                 frame.setLocation(300, 300);
                 //frame.setJMenuBar( menubar );
                 JPanel panel=new JPanel();
                 panel.setLayout(new BorderLayout());
                 panel.add(myComboBox,BorderLayout.NORTH);        
                 frame.getContentPane().add(panel);
                 frame.setVisible(true);
                 final IconedCellRendererField renderer = IconedCellRendererField.getCheckBoxRendererInstance();
                 myComboBox.setRenderer(renderer);
                 myComboBox.addActionListener(new ActionListener()
                     public void actionPerformed(ActionEvent e)
                          if(myComboBox.getSelectedItem().toString().equals("SelectAll")){
                               renderer.selectAll(true);                         
                          if(myComboBox.getSelectedItem().toString().equals("ClearAll")){
                               renderer.clearAll(true);
                          if(myComboBox.getSelectedItem().toString().equals("GrayedAll")){
                               renderer.grayedAll(true);
    }renderer:
    import java.awt.*;
    import java.awt.event.*;
    //import java.io.*;
    //import java.net.*;
    import java.util.*;
    import javax.swing.*;
    //import javax.swing.event.*;
    import javax.swing.border.*;
    //import javax.swing.table.*;
    public class IconedCellRendererField extends DefaultListCellRenderer implements MouseListener {
         public Icon icon, selIcon;
         Icon[] icons = null;
         public boolean useIconBackground = true, useIndexSensitiveIcons = false,
                   useCheckBoxAsIcon = false, useLinkState = false;
         Dimension labelDim = null;
         public JLabel iconLabel;
         public JCheckBox box = null;
         public JPanel noback;
         public SelectionStateHandler selStateHandler = null;     
         private JList theList = null;
         public boolean[] selState = null, enableState = null;
         int offset = 5;
         Rectangle rect = null;
         int currentLinkRow = -1;
         boolean isOnRow = false, paintDivider = false;
         private Icon dividerImage = null;     
         private Color linkColor = Color.blue, hoverColor = Color.red, selectedLinkColor = Color.green;
         /* Initialises the renderer with one icon that is displayed without the
          * cell background.
         public IconedCellRendererField(Icon icon) {
              this(icon,false);
         /* Initialises the renderer with two icons that provide a switch capability
          * when a row is selected/deselected
         public IconedCellRendererField(Icon icon, Icon selIcon) {
              this.icon = icon;
              this.selIcon = selIcon;
              //addMouseListener(this);
         /* Initialises the renderer with two icons that provide a switch capability
          * when a row is selected/deselected. The boolean argument enables the icon
          * to either use the renderer background or appear transparent.
         public IconedCellRendererField(Icon icon, Icon selIcon, boolean useIconBackground) {
              this(icon, selIcon);
              setIconHasBackground(useIconBackground);
              createNoBackgroundPanel();
         /* Initialises the renderer with a single no siwthing icon. The boolean
          * argument enables the icon to either use the renderer background
          * or appear transparent.
         public IconedCellRendererField(Icon icon, boolean useIconBackground) {
              this(icon, icon, useIconBackground);
         /* Initialises the renderer to load two icons from the provided image locations.
          * This enables icon switching on selection.
         public IconedCellRendererField(String iconLoc, String selIconLoc) {
              icon = new ImageIcon(iconLoc);
              selIcon = new ImageIcon(selIconLoc);
              //addMouseListener(this);
         /* Initialises the renderer to load a single icon from the provided image location.
          * The icon can either have the renderer background or not based on the
          * boolean property.
         public IconedCellRendererField(String iconLoc, boolean iconBackground) {
              this(iconLoc, iconLoc, iconBackground);
         /* Initialises the renderer to load two icons from the provided image locations.
          * This enables icon switching on selection. The icon can either have the renderer
          * background or not based on the boolean property.
         public IconedCellRendererField(String iconLoc, String selIconLoc, boolean iconBackground) {
              this(iconLoc, selIconLoc);
              setIconHasBackground(iconBackground);
              createNoBackgroundPanel();
         /* Initialises the renderer to load a single icon from the provided image location.
         public IconedCellRendererField(String iconLoc) {
              this(iconLoc, true);
         /* Initialises the renderer with an array of image icons that are repeated for
          * each row in the list.
         public IconedCellRendererField(Icon[] icons, boolean useIconBackground) {
              this(icons[0], icons[0], useIconBackground);
         public void createNoBackgroundPanel() {
              iconLabel = new JLabel((Icon)null, JLabel.CENTER);
              if(labelDim != null) {      iconLabel.setPreferredSize(labelDim); }
              iconLabel.setBorder( new EmptyBorder(1,5,1,5) );
              noback = new JPanel( new BorderLayout() ) {
                  * Overridden for performance reasons.
                  * See the <a href="#override">Implementation Note</a>
                  * for more information.
                  //public void validate() {}
                 // public void invalidate() {}          
                  public void repaint() {}
                  //public void revalidate() {}
                  public void repaint(long tm, int x, int y, int width, int height) {}
                  public void repaint(Rectangle r) {}
                  protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
                        // Strings get interned...
                        if (propertyName == "text"
                                   || ((propertyName == "font" || propertyName == "foreground")
                                       && oldValue != newValue)) {
                            super.firePropertyChange(propertyName, oldValue, newValue);
                  public void firePropertyChange(String propertyName, byte oldValue, byte newValue) {}
                  public void firePropertyChange(String propertyName, char oldValue, char newValue) {}
                  public void firePropertyChange(String propertyName, short oldValue, short newValue) {}
                  public void firePropertyChange(String propertyName, int oldValue, int newValue) {}
                  public void firePropertyChange(String propertyName, long oldValue, long newValue) {}
                  public void firePropertyChange(String propertyName, float oldValue, float newValue) {}
                  public void firePropertyChange(String propertyName, double oldValue, double newValue) {}
                  public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {}
              if(useCheckBoxAsIcon()) {
                   box = new JCheckBox();
                   //box.addMouseListener(this);
                   box.setOpaque(false);
                   noback.add( box, BorderLayout.WEST );
                   //noback.addMouseListener(this);
                   rect = box.getBounds();
                   //list.addMouseListener(this);
              } else {
                   noback.add( iconLabel, BorderLayout.WEST );
              noback.add( this, BorderLayout.CENTER );
              noback.setBorder( new EmptyBorder(1,1,1,1) );
              noback.setOpaque(false);
         public Component getListCellRendererComponent(JList list, Object value, int index,
                        boolean isSelected, boolean cellHasFocus) {
              System.out.println(value+"+"+index+"+"+isSelected+"+"+cellHasFocus);
              if(theList == null || theList != list) {
                   theList = list;
                   if(useLinkState) {
                        attachLinkSimulationListener();
              setOpaque(true);
              setText( value == null ? "" : value.toString());
              if(useIndexSensitiveIcons) {
                   icon = getIcon(index);
              if(useIconBackground)
                   setIcon(icon);          
              setFont( list.getFont() );
              setToolTipText(value.toString() );
              if(list.isEnabled())
                   setEnabled( isEnabled(index) );
              else
                   setEnabled( list.isEnabled() );
              if(isSelected && isEnabled(index) ) {
                   setForeground( Color.black );
                   setBackground( new Color(223, 235, 245) );
                   if(useIndexSensitiveIcons) {
                        selIcon = getIcon(index);
                   if(useIconBackground)
                        setIcon(selIcon);
              } else {
                   setForeground(Color.black);
                   setBackground(Color.white);
                   setBorder(null);
              if(cellHasFocus) {
                   setBorder( new CompoundBorder( new LineBorder( new Color(150, 150, 220) ),
                                                      new EmptyBorder(2,2,2,2)  ) );
              } else {
                   setBorder( new EmptyBorder(2,2,2,2));
              if(useLinkState) {
                   if(currentLinkRow == index) {
                        setText("<html><u>" + value.toString()+"</u></html>" );     
                        setForeground( getHoverLinkColor() );               
                   } else {
                        setForeground( getLinkColor() );
                   if(isSelected) {
                        setForeground( getSelectedLinkColor() );
                   setBackground(Color.white);
                   setBorder( new EmptyBorder(1,1,1,1) );
              if( shdPaintDivider() ) {
                   Border border = null;
                   if(dividerImage != null) {
                        border = new MatteBorder(0,0,1,0, dividerImage);
                   } else {
                        border = new MatteBorder(0,0,1,0, getLinkColor() );
                   if(index < theList.getModel().getSize() - 1 ) {
                        setBorder( new CompoundBorder(getBorder(),border) );
                   } else {
                        setBorder( new EmptyBorder(1,1,1,1) );
              if(useIconBackground == false) {
                  if(isSelected)
                      iconLabel.setIcon(selIcon);
                  else
                      iconLabel.setIcon(icon);
                  if(useCheckBoxAsIcon()) {
                      if(selState == null) {
                          updateSelectionStateTrackers(list);
                      if(selStateHandler == null) {
                          list.addMouseListener( selStateHandler = new SelectionStateHandler(list) );
                      try {
                          box.setSelected( selState[index] );
                      } catch(Exception e) {}
                  if( shdPaintDivider() ) {              
                      //if(index < theList.getModel().getSize() - 1 ) {
                          noback.setBorder( getBorder() );
                          setBorder( new EmptyBorder(1,1,1,1) );
                      //} else {
                      //  noback.get
                  // this should cause a JComboBox to paint the Label instead of the
                  // check box + label combination
                  if(index == -1) {
                       Vector<Object> v=new Vector<Object>();
                       v=getSelectedObjects();
                        String val=generateString();
                       JLabel label=new JLabel(val);                    
                      if(iconLabel.getIcon() != null) {
                           label.setIcon( iconLabel.getIcon() );
                      System.out.println("label");
                      return label;
                  return noback;
              return this;
         public String generateString()
              String val = "";
              if(selState[0]==true&&selState[1]==false&&selState[2]==false){
                    for(int i = 3; i < theList.getModel().getSize(); i++) {
                           String curString=theList.getModel().getElementAt(i).toString();
                           if(val.length()==0){
                                  val=val+curString+"-1";
                           } else {                              
                                  val=val+"&"+curString+"-1";
               //clear all     
               if(selState[1]==true&&selState[0]==false&&selState[2]==false ){                                   
                      for(int i = 3; i < theList.getModel().getSize(); i++) {
                           String curString=theList.getModel().getElementAt(i).toString();
                           if(val.length()==0){
                                  val=val+curString+"-0";
                           } else {                              
                                  val=val+"&"+curString+"-0";
              //grayedall
               if(selState[2]==true&&selState[0]==false&&selState[1]==false ){                                   
                      val="";                      
               if(selState[0]==false&&selState[1]==false&&selState[2]==false ){
                    for(int i = 3; i < theList.getModel().getSize(); i++) {
                           String curString=theList.getModel().getElementAt(i).toString();
                           if(selState==true&&enableState[i]==false){
                             continue;
                        if(selState[i]==true&&enableState[i]==true){
                             if(val.length()==0){
                                       val=val+curString+"-1";
                             } else {                              
                                       val=val+"&"+curString+"-1";
                        if(selState[i]==false&&enableState[i]==true){
                             if(val.length()==0){
                                       val=val+curString+"-0";
                             } else {                              
                                       val=val+"&"+curString+"-0";
              return val;
         public void updateSelectionStateTrackers(JList list) {
              selState = new boolean[ list.getModel().getSize() ];
              enableState = new boolean[ list.getModel().getSize() ];
              for(int i = 0; i < selState.length; i++) {
                   selState[i] = false;
                   enableState[i] = true;
         public int[] getSelectedIndices() {
              if(!useCheckBoxAsIcon()) {
                   return new int[0];
              int length = 0;
              if(selState==null){
                   return null;
              for(int i = 0; i < selState.length; i++) {
                   if(selState[i]) {
                        length++;
              int[] indices = new int[length];
              for(int i = 0, n = 0; i < selState.length; i++) {
                   if(selState[i]) {
                        indices[n++] = i;
              //System.out.println("Selected Indices.length = " + indices.length);
              return indices;
         public Vector<Object> getSelectedObjects() {
              int[] indices = getSelectedIndices();
              Vector<Object> objects = new Vector<Object>();
              if(indices==null){
                   return null;
              for(int i = 0; i < indices.length; i++) {
                   objects.addElement( theList.getModel().getElementAt(indices[i]) );
              return objects;
         public void setIconHasBackground(boolean b) {
              useIconBackground = b;
         public Icon[] getIcons() {
              return icons;
         public Icon getIcon(int index) {
              if(icons != null && icons.length == 0) {
                   return icon;
              if(icons != null && index > icons.length) {
                   index = index - (icons.length - 1);
              return icons[index];
         public void setIcons(Icon[] icons) {
              if(icons != null) {
                   useIndexSensitiveIcons = true;
              this.icons = icons;
         public void setIcon(Icon icon, int index) {
              if(icons != null && icons.length > 0) {
                   icons[index] = icon;
         public void setIconLabelDimension(Dimension dim) {
              labelDim = dim;
         public static IconedCellRendererField getCheckBoxRendererInstance() {
              IconedCellRendererField cr = new IconedCellRendererField(new EmptyIcon());
                   cr.setUseCheckBoxAsIcon(true);
              return cr;
         public void setUseCheckBoxAsIcon(boolean use) {
              useCheckBoxAsIcon = use;
              createNoBackgroundPanel();
         public boolean useCheckBoxAsIcon() {
              return useCheckBoxAsIcon;
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
         public void setDisplayItemsAsLinks(boolean use) {
              useLinkState = use;
         public void setLinkColor(Color color) {
              linkColor = color;
              if(theList != null) {
                   theList.repaint();
         public Color getLinkColor() {
              return linkColor;
         public void setHoverLinkColor(Color color) {
              hoverColor = color;
              if(theList != null) {
                   theList.repaint();
         public Color getHoverLinkColor() {
              return hoverColor;
         public void setSelectedLinkColor(Color color) {
              selectedLinkColor = color;
              if(theList != null) {
                   theList.repaint();
         public Color getSelectedLinkColor() {
              return selectedLinkColor;
         public void attachLinkSimulationListener() {
              theList.setCursor( Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) );
              theList.addMouseListener( new MouseAdapter() {
                   public void mouseEntered(MouseEvent e) {
                        isOnRow = true;                    
                   public void mouseExited(MouseEvent e) {
                        isOnRow = false;
    currentLinkRow = -1;
    theList.repaint();
              theList.addMouseMotionListener( new MouseMotionAdapter() {
                   public void mouseMoved(MouseEvent e) {
    isOnRow = true;
    currentLinkRow = theList.locationToIndex( e.getPoint() );
    theList.repaint();
              /*table.addMouseListener(new MouseAdapter() {
    public void mouseEntered(MouseEvent e) {
    public void mouseExited(MouseEvent e) {
    isOnRow = false;
    currentHighlightRow = -1;
    table.repaint();
    table.addMouseMotionListener( new MouseMotionAdapter() {
    public void mouseMoved(MouseEvent e) {
    isOnRow = true;
    currentHighlightRow = table.rowAtPoint( e.getPoint() );
    table.repaint();
         public boolean shdPaintDivider() {
              return paintDivider;
         public void setPaintDivider(boolean paintDivider) {
              this.paintDivider = paintDivider;
         public void setDividerImage(Icon icon) {
              this.dividerImage = icon;
              setPaintDivider(true);
         private void dispatchEvent(MouseEvent me) {
    if(rect != null && box != null && rect.contains(me.getX(), me.getY())){
    Point pt = me.getPoint();
    pt.translate(0,0);
    box.setBounds(rect);
    box.dispatchEvent(new MouseEvent(box, me.getID()
    , me.getWhen(), me.getModifiers()
    , pt.x, pt.y, me.getClickCount()
    , me.isPopupTrigger(), me.getButton()));
    if(!box.isValid()) {
         repaint();
         System.out.println("Dispatch Event: Box.invalid called");
    System.out.println("Dispatch Event called");
    } else {
         System.out.println("Dispatch Event Called, rect null");
    public void mouseClicked(MouseEvent me){
    dispatchEvent(me);
    public void mouseEntered(MouseEvent me){
    dispatchEvent(me);
    public void mouseExited(MouseEvent me){
    dispatchEvent(me);
    public void mousePressed(MouseEvent me){
    dispatchEvent(me);
    public void mouseReleased(MouseEvent me){
    dispatchEvent(me);
    public class SelectionStateHandler extends MouseAdapter {
         JList list = null;
         public SelectionStateHandler(JList list) {
              this.list = list;
         public void mouseClicked(MouseEvent e)
              * Handles the checkbox selection process. Uses the bounds property of the
              * check box within the selected cell to determine whether the checkbox should
              * be selected or not
              public void mouseReleased(MouseEvent e) {
                   /*if(list == null || list.getSelectedIndex() == -1
         || !isEnabled( list.locationToIndex(e.getPoint()) ) ) {
         return;
              if(list == null || list.getSelectedIndex() == -1){
                   return;
         int[] indices = list.getSelectedIndices();
         // get the current relative position of the check box
         //rect = box.getBounds(rect);
         for(int i = 0; i < indices.length; i++) {
         // get the current relative position of the check box
         int loc = list.locationToIndex( e.getPoint() );
         rect = list.getCellBounds(loc,loc);
         // ensure the point clicked in within the checkBox
         if(e.getX() < (rect.getX() + 20) ) {
              Object obj=list.getModel().getElementAt(i);
              //if(!obj.equals("SelectAll")&&!obj.equals("ClearAll")&&!obj.equals("GrayedAll")){
                   if(indices[i]>2){
                        selState[0]=false;
                        selState[1]=false;
                        selState[2]=false;
                        //����
                        if(!this.isEnabled(indices[i])&&selState[indices[i]]==true){
                             this.setEnabled(indices[i],true);
                             selState[indices[i]]=false;
                        } else if(this.isEnabled(indices[i])&&selState[indices[i]]==true){
                             //����
                             selState[indices[i]]=true;
                             this.setEnabled(indices[i],false);                              
                        }else if(this.isEnabled(indices[i])&&selState[indices[i]]==false){
                             //����
                             selState[indices[i]]=true;
                             this.setEnabled(indices[i],true);
                   } else {
                        selState[indices[i]] = !selState[indices[i]];
         list.revalidate();
         list.repaint();
         public void selectAll(boolean b) {
              for(int i = 0; i < list.getModel().getSize(); i++) {
                   try {
                        this.enableAll(true);
                        Object obj=list.getModel().getElementAt(i);
                        if(!obj.equals("ClearAll")&&!obj.equals("GrayedAll")){
                             selState[i] = b;
                        } else{
                             selState[i]=!b;
                        selState[0]=false;
                   } catch(ArrayIndexOutOfBoundsException aie) {
                        updateSelectionStateTrackers(list);
                        selectAll(b);
                        return;
              if(list != null) {
                   list.revalidate();
                   list.repaint();
         public void clearAll(boolean b){
              for(int i = 0; i < list.getModel().getSize(); i++) {
                   try {
                        Object obj=list.getModel().getElementAt(i);
                        this.enableAll(true);
                        if(!obj.equals("ClearAll")){
                             selState[i] = !b;
                        } else{
                             selState[i]=b;
                        selState[1]=false;
                   } catch(ArrayIndexOutOfBoundsException aie) {
                        updateSelectionStateTrackers(list);
                        selectAll(b);
                        return;
              if(list != null) {
                   list.revalidate();
                   list.repaint();
         public void grayedAll(boolean b){
              for(int i = 0; i < list.getModel().getSize(); i++) {
                   try {
                        Object obj=list.getModel().getElementAt(i);
                        if(!obj.equals("SelectAll")&&!obj.equals("ClearAll")){
                             if(i==2){
                                  selState[i] = !b;
                             }else{                             
                                  selState[i] = b;
                             this.setEnabled(i,false);
                        } else{
                             selState[i]=!b;                          
                   } catch(ArrayIndexOutOfBoundsException aie) {
                        updateSelectionStateTrackers(list);
                        selectAll(b);
                        return;
              if(list != null) {
                   list.revalidate();
                   list.repaint();
         public void setSelectedIndex(int index) {
              for(int i = 0; i < list.getModel().getSize(); i++) {
                   selState[i] = false;
              selectIndex(index);
         public void selectIndex(int index) {
              try {
                   selState[index] = true;
              } catch(ArrayIndexOutOfBoundsException aie) {
                   updateSelectionStateTrackers(list);
                   selectIndex(index);
                   return;
              if(list != null) {
                   list.revalidate();
                   list.repaint();
         public void setEnabled(int index, boolean b) {
              try {
                   enableState[index] = b;
              } catch(ArrayIndexOutOfBoundsException aie) {
                   updateSelectionStateTrackers(list);
                   setEnabled(index, b);
         public boolean isEnabled(int index) {
              if(index == -1) {
                   return true;
              boolean isEnabled = true;
              try {
                   isEnabled = enableState[index];
              } catch(ArrayIndexOutOfBoundsException aie) {
                   updateSelectionStateTrackers(list);
                   return isEnabled(index);
              return isEnabled;
         public void enableAll(boolean b) {
              for(int i = 0; i < enableState.length; i++) {
                   enableState[i] = b;
    public void selectAll(boolean b) {
         if(selStateHandler == null) {
              return;
         selStateHandler.selectAll(b);
    public void clearAll(boolean b){
         if(selStateHandler == null) {
              return;
         selStateHandler.clearAll(b);
    public void grayedAll(boolean b){
         if(selStateHandler == null) {
              return;
         selStateHandler.grayedAll(b);
    public void setSelectedIndex(int index) {
         if(selStateHandler == null) {
              return;
         selStateHandler.setSelectedIndex(index);
    public void selectIndex(int index) {
         if(selStateHandler == null) {
              return;
         selStateHandler.selectIndex(index);
    public void enableAll(boolean b) {
         if(selStateHandler == null) {
              return;
         selStateHandler.enableAll(b);
    public void setEnabled(int index, boolean enable) {
         if(selStateHandler == null) {
              return;
         selStateHandler.setEnabled(index, enable);
    public boolean isEnabled(int index) {
         if(selStateHandler == null) {
              return true;
         return selStateHandler.isEnabled(index);
    public boolean isEnabledAll() {
         if(enableState == null) return true;
         for(int i = 0; i < enableState.length; i++) {
              if(!isEnabled(i)) {
                   return false;
         return true;
    // EmptyIcon implementation
    public static class EmptyIcon implements Icon {
         int width = 16, height = 16;
         public EmptyIcon() {
         setSize(16,16);
         public EmptyIcon(int width, int height) {
         setSize(width, height);
         public void setSize(int width, int height) {
         this.width = width;
         this.height = height;
         public int getIconWidth() {  return width; }
         public int getIconHeight() { return height; }
         public void paintIcon(Component c, Graphics g, int x, int y) {}
    public int getItemCount(){
         if(theList!=null){
              return theList.getModel().getSize();
         } else {
              return 0;
         public boolean[] getEnableState() {
              return enableState;
         public boolean[] getSelState() {
              return selState;
         public JList getTheList() {
              return theList;
    testbox :import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JComboBox;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    public class testbox extends JComboBox
    * @param args
    JComboBox myComboBox;
    public testbox()
    myComboBox = new JComboBox();
    public void setPopupVisible(boolean b)
         if(b)
              myComboBox.showPopup();
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             

    You are updating the label value when (index == -1), let change into (index<=0).
    like below
    // this should cause a JComboBox to paint the Label instead of the
                // check box + label combination
                if (index <= 0) {
                    Vector v = new Vector();
                    v = getSelectedObjects();
                    String val = generateString();
                    JLabel label = new JLabel(val);
                    if (iconLabel.getIcon() != null) {
                        label.setIcon(iconLabel.getIcon());
                    System.out.println("label");
                    return label;
                }

  • JComboBox event notification when select first entry in pop-up menu JDK 6

    I recently began testing a Java GUI, I originally developed with JDK 1.5.0_11, with JDK 1.6.0_3. I have used the JComboBox in several applications developed using JDK 1.3.x and 1.4.x over the years. In every one of these earlier JDKs the JComboBox widgets all behaved the same. When you select the JComboBox widget, the pop-up menu appears and you can select any of the items from the menu list. Having made the selection with either a mouse click or a key press, an event notification is sent. Typically, an ActionEvent as well as either a mouse click event or a keypressed event may be sent. When testing with 1.6.0_x versions of the JDK and JRE, I can't account for any event notification being sent when selecting the first item at the top of the pop-up menu as the initial selection. If I select some other item on the list and then the first item, it works as it is supposed to work, but only after selecting another item first.
    I've placed the JComboBox in a JDialog and a JPanel. There are NO AWT widgets in any containers of the application. The same behavior seems to exist regardless of what other containing Swing component I place the JComboBox in. I'm running these applications on Windows XP, service pack 2. The system is an AMD 64 bit dual processor with 4Gb of RAM. The essential code follows:
    private JComboBox getJcboAlias()
        /* Note here that I am using a defaultComboModel as I have always done */
       jcboAliases = new JComboBox(urls);
       *jcboAliases.setEditable(false);*                               // Note here that the JComboBox is NOT editable
       jcboAliases.addActionListener(new ActionListener()   // ActionListener only receives a notification if the second or
       {                                                                            // another item in the pop-menu list is selected...but never the
          public void actionPerformed(ActionEvent ae)           // first item in the list
             String s = (String) jcboAliases.getSelectedItem();
             for (int i = 0; i < connections.size(); i++)
                conAlias = (String[]) connections.get(i);
                if (s.equals(conAlias))
    isSelected = true;
    break;
    jlblName.setVisible(true);
    jlblAlias.setVisible(true);
    jlblUID.setVisible(true);
    jlblPWD.setVisible(true);
    jtxtName.setText(conAlias[0]);
    jtxtName.setVisible(true);
    jtxtAddress.setText(conAlias[1]);
    jtxtAddress.setVisible(true);
    jtxtUID.setText(conAlias[2]);
    jtxtUID.setVisible(true);
    jtxtPWD.setVisible(true);
    jtxtPWD.setText("");
    jtxtPWD.requestFocus();
    return jcboAliases;
    }    I'm using a non-editable JComboBox because there is a pop-up menu with this and not with the JList widget.  JComboBox behaves more like the JList MicroSoft counterpart.  Another code snippet follows in which the JComboBox is editable.  The same errant behavior occurs when selecting the first item from the pop-up menu: private JComboBox getJcboPCMember()
    jcboPCMember = new JComboBox(PCViewerCustom.getCurrentMembers());
    jcboPCMember.setBounds(250, 103, 180, 20);
    jcboPCMember.setToolTipText("PATHCHECK(ER) member name - Example: CKPPTHCK");
    jcboPCMember.setSelectedIndex(Integer.valueOf(PCViewerCustom.getCurrentHost(3)));
    jcboPCMember.setEditable(true); // Note here that this JComboBox IS editable
    jcboPCMember.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent ae)
    if (ae.getActionCommand().equals("comboBoxEdited"))
    boolean copy = false;
    for (int i = 0; i < jcboPCMember.getItemCount(); i++)
    if (jcboPCMember.getSelectedItem().equals(jcboPCMember.getItemAt(i)))
    copy = true;
    break;
    if (!copy)
    if (jcboPCMember.getItemCount() > 0)
    if (jcboPCMember.getItemAt(0).equals("No Entries"))
    jcboPCMember.removeItem("");
    jcboPCMember.removeItem("No Entries");
    jcboPCMember.insertItemAt((String) jcboPCMember.getSelectedItem(), 0);
    else
    jcboPCMember.removeItem("");
    jcboPCMember.addItem((String) jcboPCMember.getSelectedItem());
    enableJbtnOK();
    else
    if (jcboPCMember.getSelectedIndex() >= 0)
    PCViewerCustom.setCurrentHost(3, Integer.toString(jcboPCMember.getSelectedIndex()));
    enableJbtnOK();
    else
    JOptionPane.showMessageDialog(null, "Name not selected", "Error", JOptionPane.ERROR_MESSAGE);
    return jcboPCMember;
         I am able to add a new entry to the JComboBox, however, I am still unable to select the first item from the pop-up menu and fire any kind of notification event.  I have not seen this behavior before in any earlier versions of the JDK and it's playing havoc with my ability to deploy the application into a JDK or JRE V6 environment, without adding a bunch of additional code to pre-select the first item on the list, which pretty much defeats the purpose of the JComboBox.  I'll be the first to admit I've done something wrong, but i've built a number of test scenarios now on two systems runing Win XP SP2 and I get the same errant behavior.  I've also added in event listeners for a MouseListerner, a KeyListener and an ItemListener.  Still no event notification on this first item in the list.  Again, however, if I select one of the other items from the pop-up menu list and then select the first item, all is well.  Imagine selling that method of operation to a user....  It occurs to me that this must be a bug in the V6 JComboBox.  I wanted to post this here first, however, in order to determine if this is, in fact, a bug - in other words, am I the only one seeing this, or is this a more widespread issue?  Any assistance in making this determination is greatly appreciated.
    David Baker
    Edited by: Galstuk on Nov 27, 2007 12:21 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    here is the other file as well:
    Harold Timmis
    [email protected]
    Orlando,Fl
    *Kudos always welcome
    Attachments:
    VI2.vi ‏5 KB

  • JComboBox is not visible on JPanel

    I have a class that extends JPanel. Within this class I have added several different components; JLabels, JTextFields, JButtons and a JComboBox.
    All of the added components are visible and working except for the JComboBox. I can see the white background of the box and the popup and its list when I click on the area where the JComboBox is located, but I cannot see the selected text in the box. This seems strange since all the other components surrounding the JComboBox display correctly.
    The background is set to white and the foreground is set to black. It has three options in the popup which are displayed using the foreground color, as it should. When I select an option from the popup, it seems to be working because the next time I display the popup, that selection is highlighted. But the selected text never shows in the box.
    If I create a JComboBox in a JPanel, not an extended class, everything seems to work correctly. I can select from the popup and the selection appears in the box.
    Could you please give me some suggestions as to how to make the selected text in the JComboBox visible?
    Thanks
    Bob

    My layout manager is set to null. I don't think that there is anything obscuring it because the backgroud is visible. The only thing that I can't see it the selected text and the combo box down arrow. I am using VisualCafe to generate this code.
    The extended class is loaded from the following class:
    public class TheSchedule extends javax.swing.JFrame
    using the following code:
         void JButtonGenTimeUnits_actionPerformed(java.awt.event.ActionEvent event)
              JPanelMainPanel.add(new TimeUnitDefinition((Frame)this));
              JPanelMainPanel.repaint();
    The actual code of the TimeUnitDefinition is as follows:
    package com.klawuhn.schedule;
    import javax.swing.*;
    import java.beans.*;
    import java.awt.*;
    import com.symantec.itools.javax.swing.models.StringComboBoxModel;
    import symantec.itools.awt.util.Calendar;
    import com.symantec.itools.javax.swing.borders.LineBorder;
    public class TimeUnitDefinition extends javax.swing.JPanel {
    private Frame parentFrame = null;
         public TimeUnitDefinition(Frame parentFrame)
         this.parentFrame = parentFrame; // Needed when displaying the calendars
              //{{INIT_CONTROLS
              setAlignmentY(1.0F);
              setAlignmentX(1.0F);
              setOpaque(false);
              setLayout(null);
              setSize(457,283);
              JLabelStartDate.setText("Start Date:");
              add(JLabelStartDate);
              JLabelStartDate.setBounds(12,12,156,24);
              JTextFieldStartDate.setDisabledTextColor(java.awt.Color.white);
              JTextFieldStartDate.setToolTipText("This is the date to start generating time units.");
              JTextFieldStartDate.setEditable(false);
              add(JTextFieldStartDate);
              JTextFieldStartDate.setBackground(java.awt.Color.white);
              JTextFieldStartDate.setBounds(168,12,216,24);
              JButtonCalendar1.setText("-");
              JButtonCalendar1.setActionCommand("-");
              add(JButtonCalendar1);
              JButtonCalendar1.setBounds(384,12,24,24);
              JLabelEndDate.setText("End Date:");
              add(JLabelEndDate);
              JLabelEndDate.setBackground(java.awt.Color.cyan);
              JLabelEndDate.setBounds(12,48,156,24);
              JTextFieldEndDate.setDisabledTextColor(java.awt.Color.white);
              JTextFieldEndDate.setToolTipText("This is the date to start generating time units.");
              JTextFieldEndDate.setEditable(false);
              add(JTextFieldEndDate);
              JTextFieldEndDate.setBackground(java.awt.Color.white);
              JTextFieldEndDate.setBounds(168,48,216,24);
              JButtonCalendar2.setText("-");
              JButtonCalendar2.setActionCommand("-");
              add(JButtonCalendar2);
              JButtonCalendar2.setBounds(384,48,24,24);
              JLabelStartTime.setText("Start Time:");
              add(JLabelStartTime);
              JLabelStartTime.setBounds(12,84,156,24);
              JTextFieldStartTime.setToolTipText("This is the time of day to start generating time units.");
              add(JTextFieldStartTime);
              JTextFieldStartTime.setBounds(168,84,240,24);
              JLabelEndTime.setText("End Time:");
              add(JLabelEndTime);
              JLabelEndTime.setBounds(12,120,156,24);
              JTextFieldEndTime.setToolTipText("This is the time of day to end generating time units.");
              add(JTextFieldEndTime);
              JTextFieldEndTime.setBounds(168,120,240,24);
              JLabelUnitOfMeasure.setText("Unit of Measure:");
              add(JLabelUnitOfMeasure);
              JLabelUnitOfMeasure.setBounds(12,156,156,24);
              JComboBoxUnitOfMeasure.setModel(stringComboBoxModel1);
              JComboBoxUnitOfMeasure.setToolTipText("This is the unit of measure used when generating the time units.");
              add(JComboBoxUnitOfMeasure);
              JComboBoxUnitOfMeasure.setBackground(java.awt.Color.white);
              JComboBoxUnitOfMeasure.setForeground(java.awt.Color.black);
              JComboBoxUnitOfMeasure.setBounds(168,156,240,24);
              JLabelBlockSize.setText("Block Size:");
              add(JLabelBlockSize);
              JLabelBlockSize.setBounds(12,192,156,24);
              JTextFieldBlockSize.setText("45");
              JTextFieldBlockSize.setToolTipText("This is the size of the time unit in Unit of Measures.");
              add(JTextFieldBlockSize);
              JTextFieldBlockSize.setBounds(168,192,240,24);
              JButtonSubmit.setText("Submit");
              JButtonSubmit.setActionCommand("Submit");
              JButtonSubmit.setToolTipText("This button will generate the time units.");
              add(JButtonSubmit);
              JButtonSubmit.setBounds(36,228,108,40);
              JButtonCancel.setText("Cancel");
              JButtonCancel.setActionCommand("Cancel");
              JButtonCancel.setToolTipText("This button will discard any changes.");
              add(JButtonCancel);
              JButtonCancel.setBounds(288,228,108,40);
                   String[] tempString = new String[3];
                   tempString[0] = "Days";
                   tempString[1] = "Hours";
                   tempString[2] = "Minutes";
                   stringComboBoxModel1.setItems(tempString);
              //$$ stringComboBoxModel1.move(0,288);
              JComboBoxUnitOfMeasure.setSelectedIndex(2);
              //{{REGISTER_LISTENERS
              SymAction lSymAction = new SymAction();
              JButtonSubmit.addActionListener(lSymAction);
              JButtonCalendar1.addActionListener(lSymAction);
              JButtonCalendar2.addActionListener(lSymAction);
         //{{DECLARE_CONTROLS
         javax.swing.JLabel JLabelStartDate = new javax.swing.JLabel();
         javax.swing.JTextField JTextFieldStartDate = new javax.swing.JTextField();
         javax.swing.JButton JButtonCalendar1 = new javax.swing.JButton();
         javax.swing.JLabel JLabelEndDate = new javax.swing.JLabel();
         javax.swing.JTextField JTextFieldEndDate = new javax.swing.JTextField();
         javax.swing.JButton JButtonCalendar2 = new javax.swing.JButton();
         javax.swing.JLabel JLabelStartTime = new javax.swing.JLabel();
         javax.swing.JTextField JTextFieldStartTime = new javax.swing.JTextField();
         javax.swing.JLabel JLabelEndTime = new javax.swing.JLabel();
         javax.swing.JTextField JTextFieldEndTime = new javax.swing.JTextField();
         javax.swing.JLabel JLabelUnitOfMeasure = new javax.swing.JLabel();
         javax.swing.JComboBox JComboBoxUnitOfMeasure = new javax.swing.JComboBox();
         javax.swing.JLabel JLabelBlockSize = new javax.swing.JLabel();
         javax.swing.JTextField JTextFieldBlockSize = new javax.swing.JTextField();
         javax.swing.JButton JButtonSubmit = new javax.swing.JButton();
         javax.swing.JButton JButtonCancel = new javax.swing.JButton();
         com.symantec.itools.javax.swing.models.StringComboBoxModel stringComboBoxModel1 = new com.symantec.itools.javax.swing.models.StringComboBoxModel();
         class SymAction implements java.awt.event.ActionListener
              public void actionPerformed(java.awt.event.ActionEvent event)
                   Object object = event.getSource();
                   if (object == JButtonSubmit)
                        JButtonSubmit_actionPerformed(event);
                   else if (object == JButtonCalendar1)
                        JButtonCalendar1_actionPerformed(event);
                   else if (object == JButtonCalendar2)
                        JButtonCalendar2_actionPerformed(event);
         void JButtonSubmit_actionPerformed(java.awt.event.ActionEvent event)
              System.out.println("See Submit button");
              TimeUnitCreate timeUnitCreate = new TimeUnitCreate(
              JTextFieldStartDate.getText(),
              JTextFieldEndDate.getText(),
              JTextFieldStartTime.getText(),
              JTextFieldEndTime.getText(),
              (String)JComboBoxUnitOfMeasure.getSelectedItem(),
              JTextFieldBlockSize.getText()
              timeUnitCreate.createTimeUnits();
              this.setVisible(false);
    System.out.println("Done creating Time Units.");
    // (new TimeUnitDefinition()).setVisible(true);
         void JButtonCalendar1_actionPerformed(java.awt.event.ActionEvent event)
         CalendarDialog calendarDialog = new CalendarDialog(parentFrame,"Date",true);
         calendarDialog.show();
         JTextFieldStartDate.setText(calendarDialog.getSelectedDate());
         void JButtonCalendar2_actionPerformed(java.awt.event.ActionEvent event)
         CalendarDialog calendarDialog = new CalendarDialog(parentFrame,"Date",true);
         calendarDialog.show();
         JTextFieldEndDate.setText(calendarDialog.getSelectedDate());
    }

  • JTable with JComboBox/JSpinner problem

    The following code has a JTable with 2 columns.The lst column has JComboBoxes, the 2nd column has JSpinners.I want to set the spinner range of values based on the selection of JComboBox. The JComboBox selections are "small" and "large". For "small" the spinner should range from 0..49, for "large" from 50..99. When a selection is made, MyTable.itemStateChanged() is called, which in turn calls SpinnerEditor.setValueRange(). This sets an array with the desired values and then sets the model with this array. However, it sets the range not only for the row in which the combo box was clicked, but all rows.
    So in MyTable.setCellComponents(), there is this:
    spinnerEditor = new SpinnerEditor(this, defaultTableModel);
    modelColumn.setCellEditor(spinnerEditor);
    If the table has n rows, are n SpinnerEditors created, or just 1?
    If 1, do n need to be created and if so, how?
    public class MyTable extends JTable implements ItemListener {
         private DefaultTableModel defaultTableModel;
         private Vector<Object> columnNameVector;
         private JComboBox jComboBox;
         private SpinnerEditor spinnerEditor;
         private final int COMBO_BOX_COLUMN = 0;
         final static int SPINNER_COLUMN = 1;
         public static String SMALL = "Small";
         public String LARGE = "Large";
         private final String[] SMALL_LARGE = {
                   SMALL,
                   LARGE };
         public MyTable(String name, Object[][] variableNameArray, Object[] columnNameArray) {
              columnNameVector = new Vector<Object>();
              // need column names in order to make copy of table model
              for (Object object : columnNameArray) {
                   columnNameVector.add(object);
              defaultTableModel = new DefaultTableModel(variableNameArray, columnNameArray);
              this.setModel(defaultTableModel)     ;
              setCellComponents();
              setListeners();
         private void setCellComponents() {
              // combo box column -----------------------------------------------
              TableColumn modelColumn = this.getColumnModel().getColumn(COMBO_BOX_COLUMN);
              jComboBox = new JComboBox(SMALL_LARGE);
              // set default values
              for (int row = 0; row < defaultTableModel.getRowCount(); row++) {
                   defaultTableModel.setValueAt(SMALL_LARGE[0], row, COMBO_BOX_COLUMN);
              modelColumn.setCellEditor(new DefaultCellEditor(jComboBox));
              DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
              renderer.setToolTipText("Click for small/large"); // tooltip
              modelColumn.setCellRenderer(renderer);
              // index spinner column ------------------------------------------------------------
              modelColumn = this.getColumnModel().getColumn(SPINNER_COLUMN);
              spinnerEditor = new SpinnerEditor(this, defaultTableModel);
              modelColumn.setCellEditor(spinnerEditor);
              renderer = new DefaultTableCellRenderer();
              renderer.setToolTipText("Click for index value"); // tooltip
              modelColumn.setCellRenderer(renderer);
         private void setListeners() {
              jComboBox.addItemListener(this);
         @Override
         public void itemStateChanged(ItemEvent event) {
              // set spinner values depending on small or large
              String smallOrLarge = (String)event.getItem();
              if (this.getEditingRow() != -1 && this.getEditingColumn() != -1) {
                   spinnerEditor.setValueRange(smallOrLarge);
         public static void main(String[] args) {
              try{
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              catch (Exception e){
                   e.printStackTrace();
              String[] columnNameArray = {"JComboBox", "JSpinner"};
              Object[][]  dataArray = {
                        {"", "0"},
                        {"", "0"},
                        {"", "0"},
              final MyTable myTable = new MyTable("called from main", dataArray, columnNameArray);
              final JFrame frame = new JFrame();
              frame.getContentPane().add(new JScrollPane(myTable));
              frame.setTitle("My Table");
              frame.setPreferredSize(new Dimension(200, 125));
              frame.addWindowListener(new WindowAdapter(){
                   @Override
                   public void windowClosing(WindowEvent e) {
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.setLocation(800, 400);
              frame.pack();
              frame.setVisible(true);
    public class SpinnerEditor extends AbstractCellEditor implements TableCellEditor {
         private JComponent parent;
         private DefaultTableModel defaultTableModel;
         private final JSpinner spinner = new JSpinner();
         private String[] spinValues;
         private int row;
         private int column;
         public SpinnerEditor(JTable parent, DefaultTableModel defaultTableModel ) {
              super();
              this.parent = parent;
              this.defaultTableModel = defaultTableModel;
              setValueRange(MyTable.SMALL);
              // update every time spinner is incremented or decremented
              spinner.addChangeListener(new ChangeListener(){
                   public void stateChanged(ChangeEvent e) {
                        String value = (String) spinner.getValue();
                        System.out.println ("SpinnerEditor.stateChanged(): " + value);
                        setValue(value);
         private void setValue(String value) {
              // save to equation string
              System.out.println ("SpinnerEditor.setValue(): " + value + " at (" + row + ", " + MyTable.SPINNER_COLUMN + ")");
              ((JTable) parent).setValueAt(spinner.getValue(), this.row, this.column);
         @Override
         public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)      {
              System.out.println ("SpinnerEditor.getTableCellEditorComponent(): row: " + row + "\tcolumn: " + column);
              System.out.println ("SpinnerEditor.getTableCellEditorComponent(): value: " + value);
              this.row = row;
              this.column = column;
              return spinner;
         @Override
         public boolean isCellEditable(EventObject evt) {
              return true;
         // Returns the spinners current value.
         @Override
         public Object getCellEditorValue() {
              return spinner.getValue();
         @Override
         public boolean stopCellEditing() {
              System.out.println("SpinnerEditor.stopCellEditing(): spinner: " + spinner.getValue() + " at (" + this.row + ", " + this.column + ")");
              ((JTable) parent).setValueAt(spinner.getValue(), this.row, this.column);
              return true;
         public void setValueRange(String smallOrLarge) {
              System.out.println ("SpinnerEditor.setValueRange for " + smallOrLarge);
              final int ARRAY_SIZE = 50;
              if (MyTable.SMALL.equals(smallOrLarge)) {
                   final int MIN_SPIN_VALUE = 0;               
                   final int MAX_SPIN_VALUE = 49;
                   //System.out.println ("SpinnerEditor.setValueRange(): [" + MIN_SPIN_VALUE + ".." +  MAX_SPIN_VALUE + "]");
                   spinValues = new String[ARRAY_SIZE];
                   for (int i = MIN_SPIN_VALUE; i <= MAX_SPIN_VALUE; i++) {
                        spinValues[i] = new String(Integer.toString(i));
              else { // large
                   final int MIN_SPIN_VALUE = 50;               
                   final int MAX_SPIN_VALUE = 99;
                   //System.out.println ("SpinnerEditor.setValueRange(): [" + MIN_SPIN_VALUE + ".." +  MAX_SPIN_VALUE + "]");
                   spinValues = new String[ARRAY_SIZE];
                   for (int i = 0; i <ARRAY_SIZE; i++) {
                        spinValues[i] = new String(Integer.toString(MIN_SPIN_VALUE + i));
                   //for (int i = 0; i <ARRAY_SIZE; i++) {
                   //     System.out.println ("spinValues[" + i + "] = " + spinValues);
              System.out.println ("SpinnerEditor.setValueRange(): [" + spinValues[0] + ".." + spinValues[ARRAY_SIZE-1] + "]");
              // set model
              spinner.setModel(new SpinnerListModel(java.util.Arrays.asList(spinValues)));

    However, it sets the range not only for the row in which the combo box was clicked, but all rows. Yes, because a single editor is used by the column.
    One solution is to create two editors, then you override the getCellEditor(...) method to return the appropriated editor. Something like:
    If (column == ?)
        if (smallOrLarge)
          return the small or large spinner editor
        else
           return the large spinner editor
    else
        return super.getCellEditor(...);

  • JComboBox Cell Editor in JTable

    I've scouered the forums for an answer to my question, and while
    finding other valuable advice, I have yet to find an answer to my
    question. But first, a little description:
    I have a JTable consisting of 5 columns:
    col1= standard Object cell editor
    col2= JComboBox cell editor
    col3= JComboBox cell editor, values dependent on col2
    col4= JComboBox cell editor, values dependent on col3
    col5= JComboBox cell editor, values dependent on col4
    Data structure looks like this:
    col1= company object, containing vector of values for col2
    col2= lease object, containing vector of values for col3
    col3= well object, containing vector of values for col4
    col4= pump object, containing vector of values for col5
    col5= simply displayed.
    I have a JButton that adds a new row to the table via dialog, then menu
    options to add entries to the comboboxes/vectors. The kicker here is
    that everything is fine up until I've added a pump, and click the cell
    to view the entry. In my cellEditor class, I have a 'getSelected()'
    method that returns 'combobox.getSelectedIndex()'. When 'edittingStopped()'
    is thrown for any cell in this column, I get a null pointer in my
    getSelectedIndex() method of the lease combobox - only in this pump
    column. Even the part column works correctly. Code snips:
    public class MyApplication ... {
      private TableColumn leaseColumn;
      private TableColumn wellColumn;
      private TableColumn pumpColumn;
      private TableColumn partColumn;
      private LeaseDropDown leaseDropDown;
      private WellDropDown wellDropDown;
      private PumpDropDown pumpDropDown;
      private PartDropDown partDropDown;
      private int currentLease = 0;
      private int currentWell = 0;
      private int currentPump = 0;
      public MyApplication() {
        leaseColumn = pumpshopTable.getColumnModel().getColumn(1);
        leaseDropDown = new LeaseDropDown(companies);
        leaseColumn.setCellEditor(leaseDropDown);
        DefaultTableCellRenderer leaseRenderer =
          new DefaultTableCellRenderer();
        leaseRenderer.setToolTipText("Click for leases");
        leaseColumn.setCellRenderer(leaseRenderer);
        //... same for lease, well, pump, part ...
        leaseDropDown.addCellEditorListener(new CellEditorListener() {
          public void editingCanceled(ChangeEvent e) {
          } // end editingCanceled method
          public void editingStopped(ChangeEvent e) {
            updateCells();
          } // end editingStopped method
        }); // end addCellEditorListener inner class
        //.... same inner class for well, pump, part ...
      } // end MyApplication constructor
      public void updateCells() {
        currentLease = leaseDropDown.getSelectedLease();
        //... get current well, pump, part ...
        leaseDropDown = new LeaseDropDown(companies); // companies=Vector,col1
        leaseColumn.setCellEditor(leaseDropDown);
        //... same for lease, well, pump and part columns ...
      } // end updateCells method
    } // end MyApplication class
    public class LeaseDropDown extends AbstractCellEditor
        implements TableCellEditor {
      private Vector companiesVector;
      private JComboBox leaseList;
      public LeaseDropDown(Vector cVector) {
        companiesVector = cVector;     
      } // end LeaseDropDown constructor
      public Component getTableCellEditorComponent(JTable table,
          Object value, boolean isSelected, int rowIndex, int vColIndex) {
        Company thisCompany = (Company) companiesVector.get(rowIndex);
        Vector leasesVector = (Vector) thisCompany.getLeases();
        leaseList = new JComboBox(leasesVector);
        return leaseList;
      } // end getTableCellEditorComponent method
      public Object getCellEditorValue() {
        return leaseList.getSelectedItem();
      } // end getCellEditorValue method
      public int getSelectedLease() {
        JOptionPane.showInputDialog("Selected lease is: " +
          leaseList.getSelectedIndex());
        return leaseList.getSelectedIndex();          
      } // end getSelectedLease method
    } // end LeaseDropDown class... LeaseDropDown can be extrapolated to well, pump, and part,
    handing well the selected lease, handing pump the selected
    lease and well, handing part the selected lease, well and pump.
    I guess my question is how do I get the selected comboboxitem (I'd
    settle for the entire combobox if there's no other way) to fill in the
    next column? Why does the way I have it now work for the first 2 combobox
    columns and not the third?

    I'll try to provide more details.
    I use a JComboBox implementation as a cell in a JTable. The CombBox is editable . This is what I get when I try to type in something.
    java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
    at java.awt.Component.getLocationOnScreen_NoTreeLock(Component.java:1507)
    at java.awt.Component.getLocationOnScreen(Component.java:1481)
    at javax.swing.JPopupMenu.show(JPopupMenu.java:921)
    at javax.swing.plaf.basic.BasicComboPopup.show(BasicComboPopup.java:177)
    at javax.swing.plaf.basic.BasicComboBoxUI.setPopupVisible(BasicComboBoxUI.java:927)
    at javax.swing.JComboBox.setPopupVisible(JComboBox.java:790)
    at javax.swing.JComboBox.showPopup(JComboBox.java:775)
    I read some related bugs on the sun site but I am not sure if this is a bug and if it is then has it been fixed or work-around provided.
    any insights ??

  • Problem with setting tooltips for items of a JCombobox

    hi guys,
    I want to set tooltips for items of JComboBox & the code that i have written is given below , but the tooltip text is set for all the items of Nonitindustrycombo but the tooltips remain the same even for Nonitdesgcombo's items.
    Is that we need to refresh the ComboboxRenderer every time ?
    I am not able to trace out the exact reason for this,please if anyone can suggest me something regarding this would be of great use to me.
    class Searchpanel extends JPanel {
    String[] str = null;
    public SearchPanel(){
    Nonitindustrycombo.addItem("--Select--");
    ArrayList NonITindus = ERPModel.getAllNonitIndustry(); //gets all the items(strings) for Nonitindustrycombo
    for (Iterator iter = NonITindus.iterator(); iter.hasNext();) {
    String str = iter.next().toString();
    Nonitindustrycombo.addItem(str);
    SetTooltip(Nonitindustrycombo,NonITindus);
    Nonitdesgcombo.addItem("--Select---");
    ArrayList desg = ERPModel.getAllNonitDesg(); //gets all the items(strings) for Nonitdesgcombo
    for (Iterator iter = desg.iterator(); iter.hasNext();) {
    Nonitdesgcombo.addItem(iter.next());
    SetTooltip(Nonitdesgcombo,desg);
    class MyComboBoxRenderer extends BasicComboBoxRenderer
    public Component getListCellRendererComponent(JList list, Object value,
    int index, boolean isSelected,
    boolean cellHasFocus)
    if (isSelected)
    setBackground(list.getSelectionBackground());
    setForeground(list.getSelectionForeground());
    if (0 < (index))
    list.setToolTipText(str[index - 1]);
    else
    setBackground(list.getBackground());
    setForeground(list.getForeground());
    setFont(list.getFont());
    setText((value == null) ? "" : value.toString());
    return this;
    private void SetTooltip(JComboBox combo,ArrayList arr){
    str = (String []) arr.toArray (new String [arr.size ()]);
    combo.setRenderer(new MyComboBoxRenderer());
    public static void main(String[] args){
    new SearchPanel();
    Thanks ,
    vishal

    1) You where given a working example in your last posting on this topic. Compare your code with the working code to see whats different and fix it.
    2) The code you posted doesn't compile.
    3) You didn't use the "Code Formatting Tags" when you posted your code so it not readable.

  • Multiline tooltip for JComboBox items.

    Hi, As the title suggests I'd like to create a multiline tooltip for items in a combobox list.
    I have implemented a multiline tooltip renderer which works perfectly on any component except JComboBox items.
    I have also implemented a ListCellRenderer for a combobox that enables tooltips for the combobox items. Also works perfectly, except that they are single line tooltips.
    The tooltip text is read from an xml file, therefore I have no control on how long the line of text is. Most of the time the text also contains newlines.
    This is the method (overridden from JComponent) added to a subclass of a component so that that component uses the MultiLineToolTip:
        public JToolTip createToolTip() {
            MultiLineToolTip tip = new MultiLineToolTip(this);
            tip.setComponent(this);
            return tip;
        }And this is the ListCellRenderer used on the combobox, so that items have (single-line) tooltips enabled:
        private class ToolTipEnabledComboBoxRenderer extends JLabel implements ListCellRenderer{
             public ToolTipEnabledComboBoxRenderer(){
                  setOpaque(true);
             public Component getListCellRendererComponent(JList list,Object value,
                                                              int index,boolean isSelected,
                                                              boolean cellHasFocus) {
                  String entry = (String)value;
                  if (isSelected || cellHasFocus) {
                       this.setBackground(list.getSelectionBackground());
                       setForeground(list.getSelectionForeground());
                  } else {
                       this.setBackground(list.getBackground());
                       setForeground(list.getForeground());
                  this.setText(entry);
                  if(isSelected || cellHasFocus){
                       if(constraint!=null &&combobox!=null &&
                                   constraint.getType() == Constrained.CONTROLLED_VOCABULARY){
                            String tooltip = ((ControlledVocabulary)constraint).getEntryDescription(entry);
                            if(tooltip==null || tooltip.equals("")){
                                 tooltip="";
                            list.setToolTipText(tooltip);
                  return this;
        }It seems to me that what I have to do is subclass the list used by the combobox and override the createToolTip() method. But how can I set the list used by the combobox? As far as I know the only time I can access the list is in the getListCellRendererComponent() method of the ListCellRenderer, in which the list is a parameter.
    Any ideas?
    Don

    Hello,
    <p>Have you seen this one?</p>
    Francois

  • Problem in adding JComboBox in JTable

    Hi,
    I was trying to put some comboxes in a jtable. The problem is I am not able to add combo boxes in the 1st and 2nd column. But its adding from the 3rd column. What can be wrong in the following code?
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import javax.swing.*;
    * TableRenderDemo is just like TableDemo, except that it
    * explicitly initializes column sizes and it uses a combo box
    * as an editor for the Sport column.
    public class TableRenderDemo1 extends JPanel {
        private boolean DEBUG = true;
            DefaultTableCellRenderer renderer =  new DefaultTableCellRenderer();
        public TableRenderDemo1() {
            //super(new GridLayout(1,0));
            JTable table = new JTable(new MyTableModel());
            table.setPreferredScrollableViewportSize(new Dimension(500, 250));
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Set up column sizes.
            initColumnSizes(table);
            //Fiddle with the Sport column's cell editors/renderers.
            setUpNameColumn(table, table.getColumnModel().getColumn(3));
            //Fiddle with the Sport column's cell editors/renderers.
            setUpSportColumn(table, table.getColumnModel().getColumn(4));
            //Add the scroll pane to this panel.
            add(scrollPane);
            String strPlaf = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
            try {
                    UIManager.setLookAndFeel(strPlaf);
                    SwingUtilities.updateComponentTreeUI(scrollPane);
            } catch(Exception e) {
                    e.printStackTrace();
         * This method picks good column sizes.
         * If all column heads are wider than the column's cells'
         * contents, then you can just use column.sizeWidthToFit().
        private void initColumnSizes(JTable table) {
            MyTableModel model = (MyTableModel)table.getModel();
            TableColumn column = null;
            Component comp = null;
            int headerWidth = 0;
            int cellWidth = 0;
            Object[] longValues = model.longValues;
            TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
            for (int i = 0; i < 5; i++) {
                column = table.getColumnModel().getColumn(i);
                comp = headerRenderer.getTableCellRendererComponent(
                                     null, column.getHeaderValue(),
                                     false, false, 0, 0);
                headerWidth = comp.getPreferredSize().width;
                comp = table.getDefaultRenderer(model.getColumnClass(i)).
                                 getTableCellRendererComponent(
                                     table, longValues,
    false, false, 0, i);
    cellWidth = comp.getPreferredSize().width;
    if (DEBUG) {
    System.out.println("Initializing width of column "
    + i + ". "
    + "headerWidth = " + headerWidth
    + "; cellWidth = " + cellWidth);
    //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
    column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    public void setUpSportColumn(JTable table, TableColumn sportColumn) {
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("Snowboarding");
    comboBox.addItem("Rowing");
    comboBox.addItem("Knitting");
    comboBox.addItem("Speed reading");
    comboBox.addItem("Pool");
    comboBox.addItem("None of the above");
    comboBox.setVisible(true);
    sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    renderer.setToolTipText("Click for combo box");
    sportColumn.setCellRenderer(renderer);
    public void setUpNameColumn(JTable table, TableColumn nameColumn) {
    //Set up the editor for the sport cells.
    JComboBox comboBox = new JComboBox();
    comboBox.addItem("One");
    comboBox.addItem("Two");
    comboBox.addItem("Three");
    comboBox.addItem("Four");
    comboBox.addItem("Five");
    comboBox.setVisible(true);
    nameColumn.setCellEditor(new DefaultCellEditor(comboBox));
    //Set up tool tips for the sport cells.
    renderer.setToolTipText("Click for combo box");
    nameColumn.setCellRenderer(renderer);
    class MyTableModel extends AbstractTableModel {
    private String[] columnNames = {"First Name",
    "Last Name",
    "Sport",
    "# of Years",
    "Vegetarian"};
    private Object[][] data = {
    {"Mary", "Saikat", "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", "Srinath", "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", "Sheela", "Knitting", new Integer(2), new Boolean(false)},
    {"John", "Yashwant", "Something", new Integer(5), new Boolean(true)},
    {"Harry", "Jay", "Playing", new Integer(1), new Boolean(true)},
    public final Object[] longValues = {"Sharon", "Campione",
    "None of the above",
    new Integer(20), Boolean.TRUE};
    public int getColumnCount() {
    return columnNames.length;
    public int getRowCount() {
    return data.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int row, int col) {
    return data[row][col];
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    * Don't need to implement this method unless your table's
    * editable.
    public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col < 2) {
    return false;
    } else {
    return true;
    * Don't need to implement this method unless your table's
    * data can change.
    public void setValueAt(Object value, int row, int col) {
    if (DEBUG) {
    System.out.println("Setting value at " + row + "," + col
    + " to " + value
    + " (an instance of "
    + value.getClass() + ")");
    data[row][col] = value;
    fireTableCellUpdated(row, col);
    if (DEBUG) {
    System.out.println("New value of data:");
    printDebugData();
    private void printDebugData() {
    int numRows = getRowCount();
    int numCols = getColumnCount();
    for (int i=0; i < numRows; i++) {
    System.out.print(" row " + i + ":");
    for (int j=0; j < numCols; j++) {
    System.out.print(" " + data[i][j]);
    System.out.println();
    System.out.println("--------------------------");
    * Create the GUI and show it. For thread safety,
    * this method should be invoked from the
    * event-dispatching thread.
    private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("TableRenderDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    TableRenderDemo1 newContentPane = new TableRenderDemo1();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    Thanks in advance.

    First, I don't see where you are tying to set the combo box on the first two columns. I only see it for the 3 and 4.
    Also why are you putting combo boxes in columns that are not editable:
            public boolean isCellEditable(int row, int col) {
                //Note that the data/cell address is constant,
                //no matter where the cell appears onscreen.
                if (col < 2) {
                    return false;
                } else {
                    return true;
            }

  • Jcombobox,JButton problem

    Hi,
    i would like my button to show a new java class,
    My button actionlistener
    select2 select = new select2();
    select.createAndShowGUI();but, i want to choose which class i will go through JComboBox.....
    Let's say my string on the JComboBox is frame1,frame2,frame3....
    how should i put it in way that....
    if frame1 is selected....
    i click the button, it will show frame1 class...
    if frame2 is selcted....
    after clicked the button, it will show frame2 class...
    Edited by: vanharu on May 27, 2008 8:38 PM

    i understand the codes u put there...
    but how do i implement it to my button action
    * @(#)select2.java
    * @author
    * @version 1.00 2008/5/28
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.BorderFactory;
    import javax.swing.border.Border;
    import javax.swing.BoxLayout;
    public class select2 extends JFrame  implements ActionListener
         public JComboBox CharList;
         public JLabel Char,title;
         public JButton Play, Preview;
        public select2()
            setTitle("Select Your Character");
            setSize(340, 400);
            getContentPane().setLayout(
                    new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
             Border raisedbevel, loweredbevel, compound;
             raisedbevel = BorderFactory.createRaisedBevelBorder();
            loweredbevel = BorderFactory.createLoweredBevelBorder();
              // Puts in array of strings to the combo box
            // Can select the arrays that is inserted in the combo box
                String hero[] = {"Naruto", "Sasuke", "Ichigo", "Ulqiourra"};
                CharList = new JComboBox(hero);
             //Shows that the combo box will start at 0,
             //which is naruto  
                CharList.setSelectedIndex(0);
                CharList.addActionListener(this);
                 //Set up the animation part
                    Char = new JLabel();
                  Char.setHorizontalAlignment(JLabel.CENTER);
                  updateLabel(hero[CharList.getSelectedIndex()]);
                  compound = BorderFactory.createCompoundBorder(raisedbevel, loweredbevel);
                  Char.setBorder(compound);
                  Char.setPreferredSize(new Dimension(320, 266));
                  //Set up button part
                  Play = new JButton("Select This Character");
                 Play.setHorizontalAlignment(4);
                 Play.setPreferredSize(new Dimension(100,40));
                 Play.addActionListener(new confirm());
                      Preview = new JButton("Preview This Character");
                      Preview.setHorizontalAlignment(4);
                      Preview.setPreferredSize(new Dimension(80, 40));
                      Preview.addActionListener(new preview());     
                      getContentPane().add(CharList);
                 CharList.setAlignmentX(Component.CENTER_ALIGNMENT);
                 getContentPane().add(Char);
                 Char.setAlignmentX(Component.CENTER_ALIGNMENT);
                 getContentPane().add(Play);
                 Play.setAlignmentX(Component.CENTER_ALIGNMENT);
                 getContentPane().add(Preview);
                  Preview.setAlignmentX(Component.CENTER_ALIGNMENT);
        public void actionPerformed(ActionEvent e)
                 JComboBox nm = (JComboBox)e.getSource();
                 String CharName = (String)nm.getSelectedItem();
                 updateLabel(CharName);
        class confirm implements ActionListener {
            public void actionPerformed(ActionEvent event)
               System.exit(0);
        class preview implements ActionListener {
            public void actionPerformed(ActionEvent event)
            //lets say, if the combobox selection is naruto...
            //then when i click this button
            //it will show naruto class
             should i put like something like
             combobox = naruto
             show naruto.class
         protected void updateLabel(String name) {
            ImageIcon icon = new ImageIcon("Resources/"+name+"Pose" + ".gif");
            Char.setIcon(icon);
            Char.setToolTipText(name);
            if (icon != null) {
                Char.setText(null);
            } else {
                Char.setText("UNDER CONSTRUCTION");
       public static void createAndShowGUI() {
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("Choose Your Character");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     
              //Display the window.
            select2 sel = new select2();
            sel.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            sel.setVisible(true);
         public static void main(String[] args) {
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }Edited by: vanharu on May 27, 2008 10:27 PM

  • JComboBox MouseListener Problem

    Hi!
    I have problem in getting mouseEntered event from a JComboBox. I have registered a MouseListener with it but it doesn't fire any mouseEvent. Anyone has any idea how to get the mouseEntered Event fired from a JComboBox??
    Thanks!!

    Even I, have a similar problem. My obejective is to display the tooltip, When I move the mouse over every individual item in the combo box. The combo basically has a JList. So, I overrided the getListCellRenderer(...) method. It is not displaying the toolTip when the combo initially has no selectedItem. If there is a selected item, the first time itslef, it displays the toolTip. If theres no selectedItem, it displays the toolTip when I move the mouse out of the combo(when the combo is expanded). Tried all possible combinations... but doesnt work. Have set the toolTip with setToolTipText() method... and when I print the toolTip with getToolTipText() method. It prints correctly, but isnt getting displayed.. :-(

Maybe you are looking for

  • HP Laserjet Pro Scan not correct

    Since a few days the scans are not scanning properly using the flatbed anymore. If I have a selection box over something that I want to scan, the result is shifted a bit. A part of the right side is cut off and shown on the left in the scanned image.

  • Experience: Lack of Proactive interest to sell, Streamlined Escalation procedure and training

    Sequence of events Obtained coupon code for back to school special. Placed Order online for an iPad Mini Retina 128 GB Received email from Bestbuy.com that order was canceled. Phoned Best Buy Customer Service-Customer Services rep could not find out

  • How do I number columns in Pages '08?

    Hey all, I was hoping you guys can help me with a very simple question I have. I was wondering how would I go about numbering an entire column in Pages? For instance, let's say I have a document which contains 2 columns and 10 rows. In this document

  • My iPod nano 6th gen only plays through 1 speaker in my VW rabbit (2007). Help.

    I connected my ipod nano 6th gen using the VW aux cable in my 2007 rabbit. The connect came through, but only through the left front speaker. Please help!

  • To set up a local account in debug mode

    Hello, I am a beginner. I want to setup my local account in debug mode. My code is on the remote server. After setting up my local account in debug mode i want to use that code from a remote server . How should i do that? I am using eclipse. Running