Java 6 JComboBox Regression?

Today I decided to try out my application with the Java 6 JRE. I was quite impressed until I found that the JComboBox is no longer firing action events when the user selects the same item from the list. Action events are fired in JRE 1.4 and 1.5, but it breaks in 1.6.
Here is a simple test case:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class ActionTest extends JFrame {
public ActionTest() {
String[] items = { "item1", "item2", "item3"};
JComboBox jComboBox = new JComboBox(items);
jComboBox.addActionListener(new ActionHandler());
getContentPane().add(jComboBox);
pack();
setVisible(true);
public static void main(String[] args) {
ActionTest actionTest = new ActionTest();
class ActionHandler implements ActionListener {
public final void actionPerformed(final ActionEvent e) {
System.out.println("Action Event Fired");
When the above code is run under java 1.4 or 1.5, an action event is fired even when the user selects the same item from the list. According to the docs this is the correct behaviour. However, when the above code is run under 1.6, no action events are fired when the user selects the same item from the list. This seems like a rather serious regression. Has anyone else experienced this?
Robert

After a long research and many many tries, if finallay found a workaround.
Below is a working demo.
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Serializable;
import java.util.Vector;
import javax.swing.ComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.event.ListDataEvent;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
public class AlwaysSelectableComboBoxDemo extends JFrame {
     public static void main(String[] args) {
          AlwaysSelectableComboBoxDemo frame = new AlwaysSelectableComboBoxDemo();
          frame.setMinimumSize(new Dimension(150,50));
          frame.setVisible(true);
          frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
     public AlwaysSelectableComboBoxDemo() {
          final AlwaysSelectableComboBox combi = new AlwaysSelectableComboBox(
                                                                 new Object[]{"Item 1","Item 2", "Item 3"});
          combi.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent ae) {
                    System.out.println("Yeah");
          combi.addPopupMenuListener(new PopupMenuListener(){
               private boolean isCanceled = false;
               private Object oldSelection = null;
               public void popupMenuCanceled(PopupMenuEvent e) {
                    isCanceled = true;
               public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
                    JComboBox comboBox = ((JComboBox)e.getSource());
                    if(!isCanceled && comboBox.getSelectedItem() == oldSelection) {
                         comboBox.contentsChanged(new ListDataEvent(e.getSource(),ListDataEvent.CONTENTS_CHANGED,0,0));
                    isCanceled = false;
               public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                    oldSelection = ((JComboBox)e.getSource()).getSelectedItem();
          this.add(combi);
     public class AlwaysSelectableComboBox extends JComboBox implements     Serializable
          public AlwaysSelectableComboBox(ComboBoxModel aModel){
               super(aModel);
          public AlwaysSelectableComboBox(final Object items[]) {
               super(items);
          public AlwaysSelectableComboBox(Vector items) {
               super(items);
         public AlwaysSelectableComboBox() {
              super();
         public void contentsChanged(ListDataEvent e) {
             selectedItemReminder = null;
             super.contentsChanged(e);
}

Similar Messages

  • A possible *bug* in java jcombobox

    Hi all,
    I think i found a possible bug in java jcombobox .. i am sure some of you must have already experienced it..
    supposedly you put a jcombobox in a jpanel
    returned the panel from a method to a calling method..
    and that method adds it to another panel that it had created to a frame..
    and if this happens dynamicaly at runtime, as only after u click a button..
    meaning : without adding the combobox or the immediate parent panelto the contentpane .. directly..
    Then,
    your combox's keylistener may not catch events fired.
    .. this has happened to me many times.. and always i could only find a way out
    .. by adding the combobox to panel that is loaded during startup itself and is
    .. not returned through a method call.
    Your opinions please ?
    'Harish.

    All components in a UI are created at run-time.
    When you create your JFrame you call pack() to align and resize the UI. This validates all the components, and sets the default focus on what ever component should have the focus at start up.
    When you create components and add them as children of another component you have to validate the child and parent. This can be done by calling JComponent.validate()
    As for keylisteners not getting called, this might be fixed if you call grabFocus on the new combobox. I can't see a reason why any listener would stop working.
    For me to really understand what your talking about. I'd need to see source code reproducing this problem.

  • Impact of Installing BI Java on an ABAP only BI 7.0 system

    Afternoon Everyone,
    I'm looking to answer a couple of questions around installation of BI Java on an ABAP only BI 7.0 system.
    Firstly, I am looking for some guidelines around common problems we would expect to see if a BI java stack is implemented on a BI 7.0 system that is currently ABAP only.  I would like to be able to gauge the impact of any such exercise, so we can translate that into extra project effort (both technically and functionally).
    Secondly, I am looking for suggestions around the areas where the post Java install regression testing should be focused so we can ensure the existing functionality of the system is unaffected by the install & activation of the BI Java stack.
    I’d be really grateful for any input you would be able to provide around these questions!
    Thanks
    Tim.

    Hi,
    Pls Look at note 917950, esp. Problem_Analysis.zip in Attachments for the Installing BI Java on an ABAP only BI 7.0 .
    For  Some more thoughts ,pls chk below link
    https://www.sdn.sap.com/irj/sdn/threadmessageid=3034054#3034054
    What are the pros and cons of installing java+abap stack for portal?
    WAS 6.4 with Java or ABAP + Java
    http://help.sap.com/saphelp_nw70/helpdata/en/29/ff9036e1e4b603e10000009b38f889/frameset.htm
    *pls assign points,if info is useful*
    Regards
    CSM reddy

  • How to create a default value for a JComboBox through his model

    Hi,
    I have created a "myComboBox" component.
    This component extend the standard Java JComboBox and simply add some helper features.
    The values that "myComboBox" display are coming from his bound model. (In fact, "myComboBox" has been designed to allow JComboBox to be implemented accordingly to the MVC design pattern: The model contains the data, the view the GUI and the controller handle the GUI events).
    My question is how can I add a default "none" item to the content displayed by an instance of "myComboBox" without doing any refactoring of the existing code implementing "myComboBox" ?
    Thank you very much for your help.

    It sounds like what you really want is to display "None" when the selected index = -1. Simple, write a custom list cell renderer that display's something instead of nothing when the index is -1.

  • JComboBox with Horizontal ScrollBar

    Hi all,
    I created this custom ComboBox:
    import com.sun.java.swing.*;
    import com.sun.java.swing.plaf.basic.*;
    public class myCombo extends JComboBox{
        public myCombo(){
            super();
            setUI(new myComboUI());
        public class myComboUI extends BasicComboBoxUI{
            protected ComboPopup createPopup(){
                BasicComboPopup popup = new BasicComboPopup(comboBox){
                    protected JScrollPane createScroller() {
                            return new JScrollPane( list, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                                    ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED );
                return popup;
      {code}
    When i add this ComboBox to a Frame, it has a look and feel diffrent from the others component !
    How to resolve that ?
    Regards
    Jack                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    [removed]
    Just another cross poster.
    [http://www.coderanch.com/t/432788/Swing-AWT-SWT-JFace/java/JComboBox-with-horizontall-scroll-bar]
    Edited by: Darryl.Burke

  • Java.lang.NullPointerException when scrolling in JComboBox

    Hi everybody,
    I use a JComboBox in my application. If I scroll it a NullPointerException is thrown:
    java.lang.NullPointerException
         at javax.swing.BufferStrategyPaintManager.flushAccumulatedRegion(BufferStrategyPaintManager.java:406)
         at javax.swing.BufferStrategyPaintManager.copyArea(BufferStrategyPaintManager.java:334)
         at javax.swing.RepaintManager.copyArea(RepaintManager.java:1143)
         at javax.swing.JViewport.blitDoubleBuffered(JViewport.java:1604)
         at javax.swing.JViewport.windowBlitPaint(JViewport.java:1573)
         at javax.swing.JViewport.setViewPosition(JViewport.java:1118)
         at javax.swing.plaf.basic.BasicScrollPaneUI$Handler.vsbStateChanged(BasicScrollPaneUI.java:1027)
         at javax.swing.plaf.basic.BasicScrollPaneUI$Handler.stateChanged(BasicScrollPaneUI.java:1016)
         at javax.swing.DefaultBoundedRangeModel.fireStateChanged(DefaultBoundedRangeModel.java:348)
         at javax.swing.DefaultBoundedRangeModel.setRangeProperties(DefaultBoundedRangeModel.java:285)
         at javax.swing.DefaultBoundedRangeModel.setValue(DefaultBoundedRangeModel.java:151)
         at javax.swing.JScrollBar.setValue(JScrollBar.java:446)
         at javax.swing.plaf.basic.BasicScrollPaneUI$Handler.mouseWheelMoved(BasicScrollPaneUI.java:962)
         at java.awt.Component.processMouseWheelEvent(Component.java:6126)
         at java.awt.Component.processEvent(Component.java:5810)
         at java.awt.Container.processEvent(Container.java:2058)
         at java.awt.Component.dispatchEventImpl(Component.java:4410)
         at java.awt.Container.dispatchEventImpl(Container.java:2116)
         at java.awt.Component.dispatchMouseWheelToAncestor(Component.java:4555)
         at java.awt.Component.dispatchEventImpl(Component.java:4296)
         at java.awt.Container.dispatchEventImpl(Container.java:2116)
         at java.awt.Component.dispatchEvent(Component.java:4240)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4015)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
         at java.awt.Container.dispatchEventImpl(Container.java:2102)
         at java.awt.Window.dispatchEventImpl(Window.java:2429)
         at java.awt.Component.dispatchEvent(Component.java:4240)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
         at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)This is the code I execute:
       public static void test()
          Object[] items = new Object[10];
          items[0] = 0;
          items[1] = 1;
          items[2] = 2;
          items[3] = 3;
          items[4] = 4;
          items[5] = 5;
          items[6] = 6;
          items[7] = 7;
          items[8] = 8;
          items[9] = 9;
          JFrame frame = new JFrame("Test frame");
          JPanel panel = new JPanel();
          panel.add(new JLabel("Combobox:"));
          panel.add(new JComboBox(items));
          frame.add(panel);
          frame.pack();
          frame.setVisible(true);
       }The weird thing is that if I execute this piece of code outside my program, in a test class, everything goes fine. I am not sure how this is possible.
    Best regards,
    Jethro Borsje

    You not assign any ActionListener to your ComboBox ?Well, in my real-life implementation I plan to do so, however in the test() method I do not. And the problem is still there in the test method, so to answer your question: no I do not add an ActionListener to the JComoBox in my test case.
    A little bit more info: when I scroll in the JComboBox the scrollwheel of my mouse, the scrollbar on the right side does not move, however the contents of the JComboBox does move.

  • XML parsing regressing from Java 1.4 to 1.5

    Hi,
    I have a piece of code using Jakarta digester. This piece of code is prety simple and was working fine until I switched from java 1.4 to java 1.5. However, i didn't changed the Digester jar.
    After investigation, I noticed that the problem disappear if i remove the DOCTYPE entry from the XML file I'm parsing.
    Is there any known regression ?
    Thanks =P
    Stack Trace
    java.net.UnknownHostException: D
         at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:177)
         at java.net.Socket.connect(Socket.java:507)
         at java.net.Socket.connect(Socket.java:457)
         at sun.net.NetworkClient.doConnect(NetworkClient.java:157)
         at sun.net.NetworkClient.openServer(NetworkClient.java:118)
         at sun.net.ftp.FtpClient.openServer(FtpClient.java:488)
         at sun.net.ftp.FtpClient.openServer(FtpClient.java:475)
         at sun.net.www.protocol.ftp.FtpURLConnection.connect(FtpURLConnection.java:270)
         at sun.net.www.protocol.ftp.FtpURLConnection.getInputStream(FtpURLConnection.java:352)
         at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:973)
         at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startEntity(XMLEntityManager.java:905)
         at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startDTDEntity(XMLEntityManager.java:872)
         at com.sun.org.apache.xerces.internal.impl.XMLDTDScannerImpl.setInputSource(XMLDTDScannerImpl.java:282)
         at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDispatcher.dispatch(XMLDocumentScannerImpl.java:1021)
         at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:368)
         at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:834)Error while getting input files description. Process aborted.
         at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
         at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:148)
         at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1242)
         at org.apache.commons.digester.Digester.parse(Digester.java:1556)
         at com.wwdm.datahandle.TransformDescriptorFactory.getTransformer(TransformDescriptorFactory.java:99)
         at mainTest.main(mainTest.java:29)
    XML
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <!DOCTYPE descriptor SYSTEM "file://D:/dtds/WWDM_Input.dtd">
    <descriptor>
    </description>
    ------

    I made an error in my XML while posting... so just to avoid replies telling it cames from there :
    XML
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <!DOCTYPE descriptor SYSTEM "file://D:/dtds/WWDM_Input.dtd">
    <descriptor>
    </descriptor>

  • JComboBox shows "Java Applet Window" as last element

    Hey all,
    I am having a problem with using JComboBox. When I use JComboBox and show it in a JDialog (popup window), the last element of the drop down (JComboBox) is "Java Applet Window". This element is, however, not selectable. I want to get rid fo the "Java Applet Window" in my dropdown.
    This problem only happens when my applet opens up a JDialog that has the JComboBox, but does not happen when I add the JComboBox directly to the applet.
    I've read around in other forums that this has to do with security. I understand the need to show that a popup window (JDialog) is an applet window so the user doesn't mistake it as one of the native windows. But, the JComboBox is not a whole 'nother window, so why does it feel the needs to add that last line to designate it as a "Java Applet Window?"
    Thanks.
    Nina.

    My apologies, I did not clarify myself in my question. Sorry that I created misunderstandings of the problem - as evident in the response in the previous post from himanshug.
    I am using JDK 1.3.1
    I must use an applet, but all my components are standalone. They can be ran as a standalone application. But for deployment, we are using applets. It's easier to do applets so clients can access via browser than deploy a whole application installation on 50 machines halfway across the world.
    And no, there is no element in my list that says "Java Applet Window". When running my application standalone, the "Java Applet Window" does not appear as the last element in my drop down.
    The "Java Applet Window" also does NOT appear when I add the drop down directly to the applet. It only appears when the drop down is in a JDialog that gets launched by an applet.
    My problem: How to get rid of the "Java Applet Window" as it seems something is adding this to my dropdown. And it's not my code that is adding it.
    Thanks. I am also up'ing the duke dollars for a solution to this to 15.

  • JTable tab key navigation with JComboBox Cell Editors in Java 1.3 & 1.4

    Hello - this is one for the experts!
    I have a JTable which has an editable JComboBox as one of the cell editors for a particular column. Users must be able to navigate through the table using the tab key. After editing a cell a single tab should advance the cell selection to the next column and then the user should just be able to start typing to populate the cell.
    However, i've come across some really frustrating differences between the Swing implementation of JDK1.3.1_09 and JDK 1.4.2_04 which means this behaviour is very different between versions!....
    1. Editing Cells and then advancing to the next column using tab.
    Using standard cell editors (based around JTextFields) in 1.3.1 the user has to press tab twice to traverse to the next column after editing. However, in 1.4.2 a single tab key is enough to move to the next column after editing.
    2. Editable JComboBox editors and and advancing to the next column using tab.
    Using JDK 1.3.1, having entered some text in the editable combo it takes 2 tabs to transfer the selected cell to the next column. With 1.4.2 a single tab while editing the editable combo ends editing and transfers the selection out of the table completely?!?
    With these 2 issues I don't know how to make a single tab key reliably transfer to the next cell, between java versions. Can anyone please help me?!??!
    (i've attached test code below which can be run in both 1.3 and 1.4 and demonstrates the above behaviour.)
    package com.test;
    import java.awt.*;
    import javax.swing.table.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class TableTest4 extends JFrame {
         private JTable table;
         private DefaultTableModel tableModel;
         public TableTest4() {
              initFrame();
          * Initialises the test frame.
         public void initFrame() {
              // initialise table
              table = new JTable(10, 5);
              tableModel = (DefaultTableModel) table.getModel();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              table.setRowHeight(22);
              JScrollPane scrollPane = new JScrollPane(table);
              getContentPane().add(scrollPane);
              JButton dummyBtn1 = new JButton("Dummy Button 1");
              JButton dummyBtn2 = new JButton("Dummy Button 2");
              // initialise frame
              JPanel btnPanel = new JPanel(new GridLayout(2, 1));
              btnPanel.add(dummyBtn1);
              btnPanel.add(dummyBtn2);
              getContentPane().add(btnPanel, BorderLayout.SOUTH);
              // set renderer of first table column to be an editable combobox
              JComboBox editableCombo = new JComboBox();
              editableCombo.setEditable(true);
              TableColumn firstColumn = table.getColumnModel().getColumn(0);
              firstColumn.setCellEditor(new DefaultCellEditor(editableCombo));
         public static void main(String[] args) {
              TableTest4 frame = new TableTest4();
              frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
              frame.pack();
              frame.setVisible(true);

    Run the above code in 1.3 and 1.4 and you can see that after editing a cell, the tab key behaviour works differently between versions.
    I don't believe by adding a key listener to the cell editors will have the desired effect.
    I've read other posts and from what i've read it looks like the processKeyBinding method of the JTable can be overridden to manually handle key events.
    Has anyone done this to handle tab key presses so that the same java app running under 1.3 and 1.4 works in the same way ??? I would really appreciate some advice on this as its very frustrating !

  • Regressing Java RunTime to previous version

    I have a problem uninstalling Java 1.5.0_12 and regressing back to an existing version , example 1.4.2_10.
    If I uninstall using the Control Panel (Add Remove Programs) everything is fine.
    If I try and uninstall remotely using a deployment tool registry settings in the users profile are still trying to use the version just removed.
    Anyone had any experience or advice on this?

    I figured out the problem with the sqljdbc4.jar but...
    now i am getting this error
    java.lang.ClassNotFoundException: No ClassLoaders found for: com.microsoft.sqlserver.jdbc.SQLServerDriver
         at org.jboss.mx.loading.LoadMgr3.beginLoadTask(LoadMgr3.java:212)
         at org.jboss.mx.loading.RepositoryClassLoader.loadClassImpl(RepositoryClassLoader.java:521)
         at org.jboss.mx.loading.RepositoryClassLoader.loadClass(RepositoryClassLoader.java:415)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
         at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:316)
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Class.java:169)

  • Anti-aliased JComboBox (Java 1.4) + text alignment

    In a JComboBox with a drop-down list is there an easy way to get the text to be antialised (with Java 1.4)? (I can't move to 1.5 yet)
    Also - is there an easy way to get the text displayed in the JComboBox "button" (not the list) right justified?
    Thanks

    . Also - is there an easy way to get the text displayed in the JComboBox "button" (not the list) right justified?
    Use a custom renderer
    class MyRenderer extends BasicComboBoxRenderer
         public Component getListCellRendererComponent(
              JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
              super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
              setHorizontalAlignment(index == -1 ? JLabel.TRAILING : JLabel.LEADING);
              return this;
    is there an easy way to get the text to be antialised (with Java 1.4)?Again use a custom renderer. This time you would need to override the paintComponent(...) method of your renderer and use the drawString(...) method. Heres an example that may (or may not) help:
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class Rotate     extends JComponent
        public void paintComponent(Graphics g)
            Graphics2D g2 = (Graphics2D)g;
            JLabel label = new JLabel("Some text on a label");
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
            g2.setFont( new Font( "Helvetica", Font.BOLD, 12 ) );
            for( double angle = 0; angle< 360; angle+=30 )
                String text = "Test_rotate_0123456789_Test_rotate_end";
                AffineTransform af = new AffineTransform();
                af.translate( 300, 300 );
                af.rotate( Math.toRadians( angle ) );
                g2.setTransform( af );
                g2.setColor( Color.black );
                g2.drawString( text, 0, 0 );
                        g2.setColor( Color.red );
                        g2.drawLine(0, 0, 300, 0 );
                         label.paint(g2);
        public static void main(String s[])
            JFrame f = new JFrame();
            f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            f.getContentPane().add(new Rotate());
            f.setSize( 600, 600 );
            f.show();
    }

  • Java Swing: JComboBox  setEditable(true)

    How to limit the length of the text in Jcombobox with seteditable true to 255 characters.So that user can't enter text more then 255 characters.

    You can get editor from the JComboBox. In the editor get a text filed used for edit. You can cast it to JTextField in the simplest case. Then add a DocumentFilter to the JTextFiled's document. Override the methods to check existing Document's length and ignore edits when limit is achieved.
        public void insertString(FilterBypass fb, int offset, String string,
                                 AttributeSet attr) throws BadLocationException {
            fb.insertString(offset, string, attr);
        public void replace(FilterBypass fb, int offset, int length, String text,
                            AttributeSet attrs) throws BadLocationException {
            fb.replace(offset, length, text, attrs);
        }

  • Java.awt.IllegalComponentStateException in JTable

    Hi folks,
    I am trying to write a JTable cell validation. Input data in a cell, if failure, prompt message and set focus & editing back to the cell. I've tried InputVerifier() but it doesn't work since I can easily use the mouse click to shift to other cells in the same table.
    What I am trying to do now is to define my DefaultCellEditor. I record the row & index position when getting focus. In the lost focus event, do the validation and set the focus & editing back if failure. Seems it works fine. However, when I randomly click different cells in the table quickly. It prompts:
    "java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location"
    Here is my stack dump:
         at java.awt.Component.getLocationOnScreen_NoTreeLock(Component.java:1487)
         at java.awt.Component.getLocationOnScreen(Component.java:1461)
         at javax.swing.Autoscroller.mouseDragged(Autoscroller.java:79)
         at javax.swing.JComponent.processMouseMotionEvent(JComponent.java:2759)
         at java.awt.Component.processEvent(Component.java:4822)
         at java.awt.Container.processEvent(Container.java:1525)
         at java.awt.Component.dispatchEventImpl(Component.java:3526)
         at java.awt.Container.dispatchEventImpl(Container.java:1582)
         at java.awt.Component.dispatchEvent(Component.java:3367)
         at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.repostEvent(BasicTableUI.java:475)
         at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.mouseDragged(BasicTableUI.java:554)
         at java.awt.AWTEventMulticaster.mouseDragged(AWTEventMulticaster.java:258)
         at java.awt.AWTEventMulticaster.mouseDragged(AWTEventMulticaster.java:257)
         at java.awt.AWTEventMulticaster.mouseDragged(AWTEventMulticaster.java:257)
         at java.awt.Component.processMouseMotionEvent(Component.java:5069)
         at javax.swing.JComponent.processMouseMotionEvent(JComponent.java:2763)
         at java.awt.Component.processEvent(Component.java:4822)
         at java.awt.Container.processEvent(Container.java:1525)
         at java.awt.Component.dispatchEventImpl(Component.java:3526)
         at java.awt.Container.dispatchEventImpl(Container.java:1582)
         at java.awt.Component.dispatchEvent(Component.java:3367)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3359)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3091)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3004)
         at java.awt.Container.dispatchEventImpl(Container.java:1568)
         at java.awt.Window.dispatchEventImpl(Window.java:1581)
         at java.awt.Component.dispatchEvent(Component.java:3367)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:445)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:191)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:144)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:130)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:98)
    Also, enclosed is my modified DefaultCellEditor class. Your input will be greatly appreicated. Thanks.
    class NewDefaultCellEditor extends DefaultCellEditor {
    public NewDefaultCellEditor(JTextField jTextField) {
    super(jTextField);
    this.setClickCountToStart(1);
    jTextField.addFocusListener(new FocusAdapter() {
    JTable tbl;
    int row;
    int column;
    public void focusGained(FocusEvent e) {
    tbl = (JTable)((JTextField)e.getSource()).getParent();
    row = tbl.getEditingRow();
    column = tbl.getEditingColumn();
    public void focusLost(FocusEvent e) {
    /*** Put validation here, execute the following if failed ***/
    tbl.editCellAt(row, column);
    ((JTextField)e.getSource()).requestFocus();

    Your use in a JTable isn't too clear to me, but I feel you're overthinking the basic requirement:
    I have an extended JComboBox which is meant to display its information only. Thus it
    - does not allow any selection
    - shows the first item of the list in the TextField only and not once more in the listI don't see the need for duplicating the model and using a popup menu listener.
    import java.awt.Component;
    import javax.swing.*;
    public class DisplayOnlyComboBoxDemo {
      public static void main(String[] args) throws Exception {
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            new DisplayOnlyComboBoxDemo().makeUI();
      public void makeUI() {
        JFrame frame = new JFrame();
        frame.add(new DisplayOnlyComboBox("One", new String[]{"Two", "Three", "Four", "Five"}));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    class DisplayOnlyComboBox extends JComboBox {
      private String firstItem;
      public DisplayOnlyComboBox(String firstItem, String[] items) {
        super(items);
        this.firstItem = firstItem;
        setRenderer(new DefaultListCellRenderer() {
          @Override
          public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            if (index == -1) {
              setText(DisplayOnlyComboBox.this.firstItem);
            return this;
    }db

  • Urgent  help needed(java frames)

    Hi,
    I need urgent help for correcting a piece of code.
    I have written a piece of code for building a gui with some buttons, drawing some geometric shapes.The code consists of two files called Graph and Frame.
    The problem I suppose in the last part of the Graph file, which Rectangle and Circle are called together, the only shape that the program draws is rectangle.Here is the code:
    //Graph
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.io.*;
    import java.util.*;
    public class Graph extends JPanel {
    LinkedList color;
    LinkedList figures;
    public Graph() {
    setBackground(Color.white);
    figures = new LinkedList();
    color = new LinkedList();
    int z;
    class Point {
    int x;
    int y;
    public Point(int x, int y) {
    this.x = x;
    this.y = y;
    public Point(Point p) {
    x = p.x;
    y = p.y;
    public String toString() {
    return "(" + x + ", " + y + ")";
    public void move(Point dist) {
    x += dist.x;
    y += dist.y;
    abstract class GeomFigur {
    public abstract void move(Point p);
    class Line extends GeomFigur {
    Point p1, p2;
    public Line(Point p1, Point p2) {
    this.p1 = new Point(p1);
    this.p2 = new Point(p2);
    public String toString() { return "Line from " + p1 + " to " + p2;  }
    public void move(Point dist) {
    p1.move(dist);
    p2.move(dist);
    class Rectangle extends Line {
    public Rectangle(Point p1, Point p2) {
    super(p1, p2);
    public String toString() { return "Rectangle from " + p1 + " to " + p2; }
    class Circle extends GeomFigur{
    Point centre;
    int radius;
    public Circle(Point centre, int radius) {
    this.centre = new Point(centre);
    this.radius = radius;
    public String toString() {
    return "Circle, centre " + centre + ", radius " + radius;
    public void move(Point dist) { centre.move(dist); }
    public void addRectangle(int x, int y, Color col) {
    Rectangle r =new Rectangle(new Point(x,y),new Point(x+20,y+20));
    figures.addLast(r);
    color.addLast(col);
    repaint();
    public void addCircle(int x, int y, Color col) {
    Circle c =new Circle(new Point(x,y), 1 );
    figures.addLast(c);
    color.addLast(col);
    repaint();
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    for (int i=0;i < figures.size();i++) {
    Rectangle rect = (Rectangle)figures.get(i);
    //Circle circ = (Circle)figures.get(i);
    g.setColor(Color.black);
    g.drawRect(rect.p1.x,rect.p1.y,20,20);
    g.setColor((Color)color.get(i));
    g.fillRect(rect.p1.x,rect.p1.y,20,20);
    //g.setColor(Color.black);
    // g.drawOval(circ.centre.x,circ.centre.y,20,20);
    // g.setColor((Color)color.get(i));
    // g.fillOval(circ.centre.x, circ.centre.y, 20, 20);
    //Frame
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    public class Frame extends JFrame implements ActionListener {
    JButton button1, button2, button3, button4, button5 ;
    Graph gr;
    JComboBox cbx;
    JComboBox cby;
    JComboBox col;
    JMenu filemenu;
    JMenuItem quit;
    JMenuBar menubar;
    int x=10;
    int y=10;
    Color color=Color.red;
    public Frame() {
    menubar = new JMenuBar();
    filemenu = new JMenu("File");
    filemenu.setMnemonic('F');
    quit = new JMenuItem("Quit");
    quit.addActionListener(this);
    quit.setMnemonic('Q');
    quit.setAccelerator(KeyStroke.getKeyStroke('Q',Event.CTRL_MASK,false));
    filemenu.add(quit);
    menubar.add(filemenu);
    setJMenuBar(menubar);
    button1 = new JButton("Rectangle");
    button1.addActionListener(this);
    button2 = new JButton("Circle");
    button2.addActionListener(this);
    button4 = new JButton("Ellipse");
    button4.addActionListener(this);
    button5 = new JButton("Triangle");
    button5.addActionListener(this);
    button3 = new JButton("Reset");
    button3.addActionListener(this);
    String[] elements_x= {"10","20","30","40","50","60","70"};
    cbx = new JComboBox(elements_x);
    cbx.addActionListener(this);
    cbx.setActionCommand("cbx");
    String[] elements_y= {"10","20","30","40","50","60","70"};
    cby = new JComboBox(elements_y);
    cby.addActionListener(this);
    cby.setActionCommand("cby");
    String[] elements_color = {"Red","Blue","Green","Orange","Yellow" };
    col = new JComboBox(elements_color);
    col.addActionListener(this);
    col.setActionCommand("col");
    gr = new Graph();
    JPanel top = new JPanel(new BorderLayout());
    JPanel inputs = new JPanel(new GridLayout(6,1));
    inputs.add(button1);
    inputs.add(button2);
    inputs.add(button3);
    inputs.add(button4);
    inputs.add(button5);
    inputs.add(cbx);
    inputs.add(cby);
    inputs.add(col);
    top.add(gr,BorderLayout.CENTER);
    top.add(inputs,BorderLayout.WEST);
    getContentPane().add(BorderLayout.CENTER, top);
    setSize(500,300);//set window size
    //take care of actions
    public void actionPerformed(ActionEvent e) {
    String command = e.getActionCommand();
    if (command.equals("Quit")){
    System.exit(0);//terminate program
    else if (command.equals("Rectangle")){
    //add Rectangle to graph at
    //position x,y and with certain color
    gr.addRectangle(x,y,color);
    else if (command.equals("Circle")){
    gr.addCircle(x,y,color);
    else if (command.equals("Reset")){
    else if (command.equals("Triangle")){
    else if (command.equals("Ellipse")){
    else if (command.equals("cbx")){
    x=Integer.valueOf((String)((JComboBox)e.getSource()).getSelectedItem()).intValue();
    else if (command.equals("cby")){
    y=Integer.valueOf((String)((JComboBox)e.getSource()).getSelectedItem()).intValue();
    else if (command.equals("col")){
    String temp=(String)((JComboBox)e.getSource()).getSelectedItem();
    if (temp=="Red") color=Color.red;
    else if (temp=="Blue") color=Color.blue;
    else if (temp=="Green") color=Color.green;
    else if (temp=="pink") color=Color.pink;
    else if (temp=="lightGray") color=Color.lightGray;
    //main program
    public static void main(String [] args) {
    Frame appl = new Frame();
    appl.setVisible(true);
    Thanks in advance
    Marina

    Hi,
    You are very lucky that I'm currently boored. You should never tag a question as urgent. It might be urgent to you, but not to us who answer. And you should also use code formatting when you post code (see the formatting tips, or use the code-button).
    I made some changes to your Graph class. The most important thing is the abstract draw method that I added to the GeomFigur class.
    import java.awt.*;
    import javax.swing.*;
    import java.util.*;
    public class Graph extends JPanel {
        LinkedList figures;
        public Graph() {
            setBackground(Color.white);
            figures = new LinkedList();
        int z;
        abstract class GeomFigur {
            protected Color color;
            public GeomFigur(Color color) {
                this.color = color;
            public abstract void move(Point p);
            public abstract void draw(Graphics g);
        abstract class Line extends GeomFigur {
            Point p1, p2;
            public Line(Color c, Point p1, Point p2) {
                super(c);
                this.p1 = new Point(p1);
                this.p2 = new Point(p2);
            public String toString() {
                return "Line from " + p1 + " to " + p2;
            public void move(Point dist) {
                p1.move(dist.x, dist.y);
                p2.move(dist.x, dist.y);
        class Rectangle extends Line {
            public Rectangle(Color c, Point p1, Point p2) {
                super(c, p1, p2);
            public String toString() {
                return "Rectangle from " + p1 + " to " + p2;
            public void draw(Graphics g) {
                System.out.println("Draw rectangle at " + p1 + " with color " + color);
                g.setColor(Color.black);
                g.drawRect(p1.x, p1.y, 20, 20);
                g.setColor(color);
                g.fillRect(p1.x, p1.y, 20, 20);
        class Circle extends GeomFigur {
            Point centre;
            int radius;
            public Circle(Color c, Point centre, int radius) {
                super(c);
                this.centre = new Point(centre);
                this.radius = radius;
            public String toString() {
                return "Circle, centre " + centre + ", radius " + radius;
            public void move(Point dist) {
                centre.move(dist.x, dist.y);
            public void draw(Graphics g) {
                System.out.println("Draw circle at " + centre + " with color " + color);
                g.setColor(Color.black);
                g.drawOval(centre.x, centre.y, 20, 20);
                g.setColor(color);
                g.fillOval(centre.x, centre.y, 20, 20);
        public void addRectangle(int x, int y, Color col) {
            System.out.println("x,y,col " + x + ":" + y + ":" + col);
            Rectangle r = new Rectangle(col, new Point(x, y), new Point(x + 20, y + 20));
            figures.addLast(r);
            repaint();
        public void addCircle(int x, int y, Color col) {
            System.out.println("x,y,col" + x + ":" + y + ":" + col);
            Circle c = new Circle(col, new Point(x, y), 1);
            figures.addLast(c);
            repaint();
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            for (int i = 0; i < figures.size(); i++) {
                GeomFigur drawable = (GeomFigur)figures.get(i);
                drawable.draw(g);
    }/Kaj

  • Not Updating the Values in the JComboBox and JTable

    Hi Friends
    In my program i hava Two JComboBox and One JTable. I Update the ComboBox with different field on A Table. and then Display a list of record in the JTable.
    It is Displaying the Values in the Begining But when i try to Select the Next Item in the ComboBox it is not Updating the Records Eeither to JComboBox or JTable.
    MY CODE is this
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.DefaultComboBoxModel.*;
    import javax.swing.table.*;
    import java.sql.*;
    import java.util.*;
    public class SearchBook extends JDialog implements ActionListener
         private JComboBox comboCategory,comboAuthor;
         private JSplitPane splitpane;
         private JTable table;
         private JToolBar toolBar;
         private JButton btnclose, btncancel;
         private JPanel panel1,panel2,panel3,panel4;
         private JLabel lblCategory,lblAuthor;
         private Container c;
         //DefaultTableModel model;
         Statement st;
         ResultSet rs;
         Vector v = new Vector();
         public SearchBook (Connection con)
              // Property for JDialog
              setTitle("Search Books");
              setLocation(40,110);
              setModal(true);
              setSize(750,450);
              // Creating ToolBar Button
              btnclose = new JButton(new ImageIcon("Images/export.gif"));
              btnclose.addActionListener(this);
              // Creating Tool Bar
              toolBar = new JToolBar();
              toolBar.add(btnclose);
              try
                   st=con.createStatement();
                   rs =st.executeQuery("SELECT BCat from Books Group By Books.BCat");
                   while(rs.next())
                        v.add(rs.getString(1));
              catch(SQLException ex)
                   System.out.println("Error");
              panel1= new JPanel();
              panel1.setLayout(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.fill = GridBagConstraints.HORIZONTAL;
              lblCategory = new JLabel("Category:");
              lblCategory.setHorizontalAlignment (JTextField.CENTER);
              c.gridx=2;
              c.gridy=2;
              panel1.add(lblCategory,c);
              comboCategory = new JComboBox(v);
              comboCategory.addActionListener(this);
              c.ipadx=20;
              c.gridx=3;
              c.gridwidth=1;
              c.gridy=2;
              panel1.add(comboCategory,c);
              lblAuthor = new JLabel("Author/Publisher:");
              c.gridwidth=2;
              c.gridx=1;
              c.gridy=4;
              panel1.add(lblAuthor,c);
              lblAuthor.setHorizontalAlignment (JTextField.LEFT);
              comboAuthor = new JComboBox();
              comboAuthor.addActionListener(this);
              c.insets= new Insets(20,0,0,0);
              c.ipadx=20;
              c.gridx=3;
              c.gridy=4;
              panel1.add(comboAuthor,c);
              comboAuthor.setBounds (125, 165, 175, 25);
              table = new JTable();
              JScrollPane scrollpane = new JScrollPane(table);
              //panel2 = new JPanel();
              //panel2.add(scrollpane);
              splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,panel1,scrollpane);
              splitpane.setDividerSize(15);
              splitpane.setDividerLocation(190);
              getContentPane().add(toolBar,BorderLayout.NORTH);
              getContentPane().add(splitpane);
         public void actionPerformed(ActionEvent ae)
              Object obj= ae.getSource();
              if(obj==comboCategory)
                   String selecteditem = (String)comboCategory.getSelectedItem();
                   displayAuthor(selecteditem);
                   System.out.println("Selected Item"+selecteditem);
              else if(obj==btnclose)
                   setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
              else if(obj==comboAuthor)
                   String selecteditem1 = (String)comboAuthor.getSelectedItem();
                   displayavailablity(selecteditem1);
                   //System.out.println("Selected Item"+selecteditem1);
                   System.out.println("Selected Author"+selecteditem1);
         private void displayAuthor(String selecteditem)
              try
              {     Vector data = new Vector();
                   rs= st.executeQuery("SELECT BAuthorandPublisher FROM Books where BCat='" + selecteditem + "' Group By Books.BAuthorandPublisher");
                   System.out.println("Executing");
                   while(rs.next())
                        data.add(rs.getString(1));
                   //((DefaultComboBoxModel)comboAuthor.getModel()).setVectorData(data);
                   comboAuthor.setModel(new DefaultComboBoxModel(data));
              catch(SQLException ex)
                   System.out.println("ERROR");
         private void displayavailablity(String selecteditem1)
                   try
                        Vector columnNames = new Vector();
                        Vector data1 = new Vector();
                        rs= st.executeQuery("SELECT * FROM Books where BAuthorandPublisher='" + selecteditem1 +"'");     
                        ResultSetMetaData md= rs.getMetaData();
                        int columns =md.getColumnCount();
                        String booktblheading[]={"Book ID","Book NAME","BOOK AUTHOR/PUBLISHER","REFRENCE","CATEGORY"};
                        for(int i=1; i<= booktblheading.length;i++)
                             columnNames.addElement(booktblheading[i-1]);
                        while(rs.next())
                             Vector row = new Vector(columns);
                             for(int i=1;i<=columns;i++)
                                  row.addElement(rs.getObject(i));
                             data1.addElement(row);
                             //System.out.println("data is:"+data);
                        ((DefaultTableModel)table.getModel()).setDataVector(data1,columnNames);
                        //DefaultTableModel model = new DefaultTableModel(data1,columnNames);
                        //table.setModel(model);
                        rs.close();
                        st.close();
                   catch(SQLException ex)
    }Please check my code and give me some Better Solution
    Thank you

    You already have a posting on this topic:
    http://forum.java.sun.com/thread.jspa?threadID=5143235

Maybe you are looking for

  • Deploying Application Without codebase and an extension (installer.jnlp)

    Hi, It seems that the deployment file can be relative to launch.html but the extension file requires the codebase attribute. This launch fails http://www.dksy.net/auctionzoom/downloads/download/jpawebstart-no-codebase/launch.html this launch succeeds

  • Apple customer service representative says: "FaceTime is not good. Don't use it."

    The other day my friend and I were trying to chat using FaceTime.  She keep getting connection error.  We were both on WiFi network.  Both of us have our Apple IDs set up on the phone.  In the past I successfully used FaceTime to chat with other frie

  • Dump in production

    hi floks, We have created one new DSO and moved to Production system. When we did data load and try activating the request we are getting a short dump. The screen shots are attached here with. We did not face any problems in D and Q systems. Please l

  • My itouch has many songs that will not download to my new laptop

    I purcased these songs an had them downloaded to old computer but that hard drive died. tried to upload these songs to mew computer-only about 150/350 downloaded. Th itunes library doesnt show these songs either-What to do?

  • Sgd + ldap auth + ssh and numeric usernames

    Hi there, sorry if there is a well known answer to my problem, bu tI have not found it. anyway, We have a problem where our customer wants to use purelly numeric usernames to logg in to secure global desktop From the point of secure global desktop we