GlassPane - JComboBox

Hi,
I have a glass pane, which redispatches all mouse, mouse motion, and mouse wheel events. I have a JComboBox under the glass pane. When I mouse over the combo and click on it, the popup menu appears. But when I move my mouse on the popup menu, the item that my mouse moves over does not become selected/highlighted as normal. I can select the item, but it doesnt look like I am selecting it.
Any ideas?
I already set, JComboBox.setLightWeightPopupEnabled(false);

My 2 cents about searching for deep components...
I usually start searches for components at the window level.
You suggest doing it at the layered pane instead of the content pane (since the content pane is below the layered pane, searching the content pane misses components in the layered pane). Good idea, but why stop there?
Take it a step further... the JRootPane is next up, which is just a JComponent containing the glasspane, layered pane, content pane, etc, and the Window is above that. Just start searching at the window, which you know is at the top of the component hierarchy.
Technically it's possible to put components directly in the Window, so you can't really say you've found the deepest component unless you search starting at the window.
Also, SwingUtilities only returns the deepest VISIBLE component (i.e., the component must be realized in the component hierarchy) If you are searching for something that renders itself and is not in the component hierarchy, then you will not find it.

Similar Messages

  • Redispatching MouseEvents Through GlassPane

    Hey all,
    I'm trying to do some drawing on a GlassPane overtop of a JFrame consisting of several Components. I followed the tutorial on GlassPanes I found [here |http://java.sun.com/docs/books/tutorial/uiswing/components/rootpane.html#glasspane] to redispatch MouseEvents through the GlassPane to the proper Components underneath.
    For the most part, this works perfectly. But there are several Components for which this doesn't seem to redispatch correctly (I used a JComboBox in the SSCCE, but I'm experiencing a similar problem with JTabbedPane as well). The problem arises when a Component contains "extra parts" that overlap another Component (like when the JComboBox's list extends on top of the JPanel.. Or, I'm assuming, when a JTabbedPane's tabs do the same).
    Anyway, any insight into this would be much appreciated.
    SSCCE:
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    public class GlassPaneTest{
         JFrame frame = new JFrame("Testing GlassPane");
         public GlassPaneTest(){     
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              BoxLayout layout = new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS);
              frame.getContentPane().setLayout(layout);
              JPanel buttonPanel = new JPanel();
              buttonPanel.add(new JButton("button"));
              buttonPanel.add(new JComboBox(new String[]{"one", "two", "three"}));
              frame.add(buttonPanel);
              createGlassPane();
              frame.setMinimumSize(new Dimension(200,200));
              frame.setMaximumSize(new Dimension(200,200));
              frame.setPreferredSize(new Dimension(200,200));
              frame.setVisible(true);
         public void createGlassPane(){
              final Point mousePoint = new Point(0,0);
              final JPanel glassPanel = new JPanel(){
                   public void paintComponent(Graphics g){
                        super.paintComponent(g);
                        g.setColor(Color.GREEN);
                        g.fillOval((int)mousePoint.getX(), (int)mousePoint.getY(), 20, 20);
              MouseAdapter mouseAdapter = new MouseAdapter(){
                   public void mouseClicked(MouseEvent me){
                        redispatchMouseEvent(me);
                   public void mouseEntered(MouseEvent me){
                        redispatchMouseEvent(me);
                   public void mouseExited(MouseEvent me){
                        redispatchMouseEvent(me);
                   public void mousePressed(MouseEvent me){
                        redispatchMouseEvent(me);
                   public void mouseReleased(MouseEvent me){
                        redispatchMouseEvent(me);
                   public void mouseDragged(MouseEvent me){
                        redispatchMouseEvent(me);
                   public void mouseMoved(MouseEvent me){
                        mousePoint.setLocation(me.getX(), me.getY());
                        glassPanel.repaint();
                        redispatchMouseEvent(me);
                   public void mouseWheelMoved(MouseWheelEvent me){
                        redispatchMouseEvent(me);
                   public void redispatchMouseEvent(MouseEvent me){
                        Point glassPanelPoint = me.getPoint();
                        Container container = frame.getContentPane();
                        Point containerPoint = SwingUtilities.convertPoint(glassPanel,
                                                      glassPanelPoint, container);
                        if(containerPoint.getY() >= 0){
                             Component component =
                                  SwingUtilities.getDeepestComponentAt(container, (int)containerPoint.getX(), (int)containerPoint.getY());
                             if(component != null){
                                  Point componentPoint = SwingUtilities.convertPoint(glassPanel, glassPanelPoint, component);
                                  System.out.println("mouse " + component.getClass().toString());
                                  component.dispatchEvent(new MouseEvent(component,
                                            me.getID(),
                                            me.getWhen(), me.getModifiers(),
                                            (int)componentPoint.getX(),
                                            (int)componentPoint.getY(),
                                            me.getClickCount(),
                                            me.isPopupTrigger()));
                             else{
                                  System.out.println("null component");
              glassPanel.addMouseListener(mouseAdapter);
              glassPanel.addMouseMotionListener(mouseAdapter);
              glassPanel.setOpaque(false);
              frame.setGlassPane(glassPanel);
              glassPanel.setVisible(true);
         public static void main(String [] argS){
              new GlassPaneTest();
    }

    jboeing wrote:
    It appears that the Motif LnF doesn't actually contain the mouse-over highlight at all, even without a glass pane.:o right you are! I had to laugh at myself when I read this. I guess I was looking for things that went wrong since adding the GlassPane and started picking up on things that didn't actually change. Wow. Who knows how long I would have pounded away at that "problem" if you hadn't pointed that out?
    Otherwise, I did successfully get the lightweight solution to work:Thanks so much for taking the time to come up with and offer a solution. I also came across [this page|http://weblogs.java.net/blog/alexfromsun/archive/2006/09/a_wellbehaved_g.html] offering another solution (even to some problems that I didn't know about at first, interesting read).
    Following that page, I came up with this approach:
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    public class GlassPaneTest{
         JFrame frame = new JFrame("Testing GlassPane");
         JComboBox comboBox = new JComboBox(new String[]{"one", "two", "three"});
         public GlassPaneTest(){
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              BoxLayout layout = new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS);
              frame.getContentPane().setLayout(layout);
              JPanel buttonPanel = new JPanel();
              buttonPanel.add(new JButton("button"));
              buttonPanel.add(comboBox);
              frame.add(buttonPanel);
              createGlassPane();
              frame.setMinimumSize(new Dimension(200,200));
              frame.setMaximumSize(new Dimension(200,200));
              frame.setPreferredSize(new Dimension(200,200));
              frame.setVisible(true);
         public void createGlassPane(){
              final Point mousePoint = new Point(0,0);
              final JPanel glassPanel = new JPanel(){
                   public void paintComponent(Graphics g){
                        super.paintComponent(g);
                        g.setColor(Color.GREEN);
                        g.fillOval((int)mousePoint.getX(), (int)mousePoint.getY(), 20, 20);
                   public boolean contains(int x, int y){
                        return false;
              AWTEventListener awtListener = new AWTEventListener(){
                   public void eventDispatched(AWTEvent e){
                        if(e instanceof MouseEvent){
                             MouseEvent me = (MouseEvent)e;
                             MouseEvent converted = SwingUtilities.convertMouseEvent(me.getComponent(), me, glassPanel);
                             mousePoint.setLocation(converted.getX(), converted.getY());
                             glassPanel.repaint();
              Toolkit.getDefaultToolkit().addAWTEventListener(awtListener, AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK);
              glassPanel.setOpaque(false);
              frame.setGlassPane(glassPanel);
              glassPanel.setVisible(true);
         public static void main(String [] argS){
                        try {
                             UIManager
                             .setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
                        } catch (Exception e) {
                             e.printStackTrace();
              new GlassPaneTest();
    }Does anybody see anything glaringly wrong with this? It seems to work perfectly, so I'm calling it a week :)
    Thanks again!

  • Popupmenu & JComboBox shows up behind JInternalFrame on glasspane

    Till Java 6 update 12 we used setLightWeightPopupEnabled on the popupmenus and JComboBoxes to make them appear on the toplevel when showing the glasspane. The situation is as followed:
    - A Swing application
    - Over the Swing application is a glasspane (extends JPanel)
    - Added on the glasspane is a JInternalFrame (with on it components like a JPanel)
    - When clicking with right mouse button, a popupmenu shows up. When using setLightWeightPopupEnabled it works perfectly
    But when Java 6 update 12 was released, the popupmenu and JComboBox popup are shown behind the JInternalFrame (but above the glasspane).
    SUN made some adjustments in the system. Does anyone knows how I can solve the problem as described above?

    I made a simple code example which simulates the problem. The combobox popup falls behind the JInternalFrame. Another strange effect is when you try to resize the JInternalFrame, the JInternalFrame is closed.
    import java.awt.BorderLayout;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JInternalFrame;
    import javax.swing.JPanel;
    public class PopupBehindInternalFrame
         public static void main (String args[]){
              JFrame frame = new JFrame();
              JPanel panel = new JPanel();
              frame.getContentPane().add(panel);
              frame.setSize(800, 600);
              frame.setVisible(true);
              JInternalFrame jif = new JInternalFrame();
              jif.setSize(400, 300);
              jif.setResizable(true);
              JPanel panelJif = new JPanel();
              jif.add(panelJif, BorderLayout.SOUTH);
              JComboBox cb = new JComboBox();
              cb.setSize(100, 10);
              cb.addItem("Test 1");
              cb.addItem("Test 2");
              cb.addItem("Test 3");
              cb.addItem("Test 4");
              cb.setLightWeightPopupEnabled(false);
              panelJif.add(cb);
              panel.getRootPane().setGlassPane(GlassPane.getInstance());
              GlassPane.getInstance().setVisible(true);
              GlassPane.getInstance().add(jif);
              jif.setVisible(true);
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.event.MouseAdapter;
    import javax.swing.InputVerifier;
    import javax.swing.JComponent;
    import javax.swing.JPanel;
    public class GlassPane extends JPanel
         private static final long serialVersionUID = 1L;
         private static GlassPane glassPane = null;
         private Color color = new Color(0, 128, 128, 128);
         public GlassPane()
              setOpaque(false);
              setLayout(null);
              addMouseListener(new MouseAdapter()
              setInputVerifier(new InputVerifier()
                   public boolean verify(JComponent input)
                        return !isVisible();
         protected void paintComponent(Graphics g)
              if (getComponents().length > 0)
                   Graphics2D g2 = (Graphics2D) g.create();
                   g2.setColor(color);
                   g2.fillRect(0, 0, getWidth(), getHeight());
                   g2.dispose();
              else
                   super.paintComponent(g);
         public static GlassPane getInstance()
              if (glassPane == null)
                   glassPane = new GlassPane();
              return glassPane;
    }

  • ComboBox scroll and selected/highlight on glasspane

    I'm using JInternalFrame as a modal frame( we couldn't use JDialog).
    For that I used an example that i found on net, which in this way the JInternalFrame is added to GlassPane of JFrame .
    On JInternalFrame there is a JComboBox.
    When I drag its scrollpad and move it up and down (to see items in Combo box), content moves ok, but scrollpad stays fixed on one place (instead of going up and down too).
    Also, when mouse points an item, it's not highlighted.
    After browsing the web and this forum i found 2 threads about this but no answer.
    Does anyone have a solution for that?
    Sample code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.beans.*;
    public class ModalInternalFrame extends JInternalFrame {
      private static final JDesktopPane glass = new JDesktopPane();
      public ModalInternalFrame(String title, JRootPane
          rootPane, Component desktop) {
        super(title);
        // create opaque glass pane   
        glass.setOpaque(false);
        glass.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
        // Attach mouse listeners
        MouseInputAdapter adapter = new MouseInputAdapter(){};
        glass.addMouseListener(adapter);
        glass.addMouseMotionListener(adapter);
        desktop.validate();
        try {
          setSelected(true);
        } catch (PropertyVetoException ignored) {
        // Add modal internal frame to glass pane
        glass.add(this);
        // Change glass pane to our panel
        rootPane.setGlassPane(glass);
        @Override
      public void setVisible(boolean value) {
        super.setVisible(value);
        // Show glass pane, then modal dialog
        if(glass != null)
            glass.setVisible(value);   
        if (value) {
          startModal();
        } else {
          stopModal();
      private synchronized void startModal() {
        try {
          if (SwingUtilities.isEventDispatchThread()) {
            EventQueue theQueue =
              getToolkit().getSystemEventQueue();
            while (isVisible()) {
              AWTEvent event = theQueue.getNextEvent();
              Object source = event.getSource();
              if (event instanceof ActiveEvent) {             
                ((ActiveEvent)event).dispatch();
              } else if (source instanceof Component) {
                  ((Component)source).dispatchEvent(event);                           
              } else if (source instanceof MenuComponent) {             
                ((MenuComponent)source).dispatchEvent(
                  event);
              } else {
                System.out.println(
                  "Unable to dispatch: " + event);
          } else {
            while (isVisible()) {
              wait();
        } catch (InterruptedException ignored) {
      private synchronized void stopModal() {
        notifyAll();
      public static void main(String args[]) {
          final JFrame frame = new JFrame(
          "Modal Internal Frame");
        frame.setDefaultCloseOperation(
          JFrame.EXIT_ON_CLOSE);
        final JDesktopPane desktop = new JDesktopPane();
        ActionListener showModal =
            new ActionListener() {
          Integer ZERO = new Integer(0);
          Integer ONE = new Integer(1);
          public void actionPerformed(ActionEvent e) {
            // Construct a message internal frame popup
            final JInternalFrame modal =
              new ModalInternalFrame("Really Modal",
              frame.getRootPane(), desktop);
            JTextField text = new JTextField("hello");
            JButton btn = new JButton("close");
            JComboBox cbo = new JComboBox(new String[]{"-01-", "-02-", "-03-", "-04-", "-05-", "-06-", "-07-", "-08-", "-09-", "-10-", "-11-", "-12-"});
            btn.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                            modal.setVisible(false);
            cbo.setLightWeightPopupEnabled(false);
            Container iContent = modal.getContentPane();
            iContent.add(text, BorderLayout.NORTH);
            iContent.add(cbo, BorderLayout.CENTER);       
            iContent.add(btn, BorderLayout.SOUTH);
            //modal.setBounds(25, 25, 200, 100);
            modal.pack();
            modal.setVisible(true);    
        JInternalFrame jif = new JInternalFrame();
        jif.setSize(200, 200);
        desktop.add(jif);
        jif.setVisible(true);
        JButton button = new JButton("Open");
        button.addActionListener(showModal);
        Container iContent = jif.getContentPane();
        iContent.add(button, BorderLayout.CENTER);
        jif.setBounds(25, 25, 200, 100);
        jif.setVisible(true);
        Container content = frame.getContentPane();
        content.add(desktop, BorderLayout.CENTER);
        frame.setSize(500, 300);
        frame.setVisible(true);
    }

    This is a bug, and there are several open bugs on the same subject.
    The only pop up that works in this situation is a heavy weight pop up.
    There are 3 types of pop up windows: light weight, medium weight and heavy weight.
    When you call setLightWeightPopupEnabled(false) the combo box uses the medium weight when the pop up window is inside the application frame, and heavy weight when the window exceeds the frame bounds.
    There is no easy way to force the pop up to heavy weight, since most of the functions and fields in the relevant classes are private.
    But you can use reflection to access them.
    Here is one solution (tested and working with JDK 5) - adding the client property forceHeavyWeightPopupKey from PopupFactory to your combo box.
    cbo.setLightWeightPopupEnabled(false);
    try {                         
         Class cls = Class.forName("javax.swing.PopupFactory");
         Field field = cls.getDeclaredField("forceHeavyWeightPopupKey");
         field.setAccessible(true);
         cbo.putClientProperty(field.get(null), Boolean.TRUE);
    } catch (Exception e1) {e1.printStackTrace();}
    ...

  • Problem in Swing Component (JComboBox)

    Hello i've got one amazing problem in my Swing Component (JComboBox) while testing for Glasspane..
    Please check this photo http://www.flickr.com/photos/39683118@N07/4483608081/
    Well i used Netbeans Drag n Drop Swing so the code might be messing..any way my code looks like this:
    My code looks like this:
    public class NewJPanel extends javax.swing.JPanel {
        /** Creates new form NewJPanel */
        public NewJPanel() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            jTextField1 = new javax.swing.JTextField();
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            jLabel3 = new javax.swing.JLabel();
            jButton1 = new javax.swing.JButton();
            jComboBox1 = new javax.swing.JComboBox();
            jCheckBox1 = new javax.swing.JCheckBox();
            setOpaque(false);
            jTextField1.setText("jTextField1");
            jLabel1.setText("jLabel1");
            jLabel2.setText("jLabel2");
            jLabel3.setText("jLabel3");
            jButton1.setText("jButton1");
            jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
            jComboBox1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
            jComboBox1.setNextFocusableComponent(jCheckBox1);
            jComboBox1.setOpaque(false);
            jComboBox1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jComboBox1ActionPerformed(evt);
            jCheckBox1.setText("jCheckBox1");
            jCheckBox1.setOpaque(false);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
            this.setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(119, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel1)
                        .addComponent(jLabel2)
                        .addComponent(jLabel3))
                    .addGap(51, 51, 51)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jButton1)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jCheckBox1)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(115, 115, 115))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(70, 70, 70)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel1))
                    .addGap(15, 15, 15)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(jCheckBox1))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(18, 18, 18)
                    .addComponent(jButton1)
                    .addContainerGap(93, Short.MAX_VALUE))
            jComboBox1.getAccessibleContext().setAccessibleParent(null);
        }// </editor-fold>
        private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JCheckBox jCheckBox1;
        private javax.swing.JComboBox jComboBox1;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JTextField jTextField1;
        // End of variables declaration
    }

    For more help create a [SSCCE (Short, Self Contained, Compilable and Executable, Example Program)|http://sscce.org], that demonstrates the incorrect behaviour.

  • JComboBox customization

    Hi folks,
    I try to use GlassPane to dispatch event to a JComboBox in a JTable. The problem occurs when I try to dispatch events to the popup menu. First, when the mouse moves into the region of popup, SwingUtilities.getDeepestComponenet() always return BasicComboPopup$2 instead of the BasicComboPopup object I returned in my own createPopup method (I override the BasicComboPopup class). Second, if there gets too many items in popup to fit in 1 page, vectical scroll bar appears. At this time, I scroll to the 2nd page of popup, click the mouse on any item and when I try to dispatch this click event to BasicComboPopup$2, strange that always the item in first page is selected. Any hints ?
    Also, is there any detailed explanation of JComboBox implementation avilable on the net ? e.g. how BasicComboPopup, ArrorButton related to JCombobox, how scrolling is handled, etc. I think this helps me to locate what is going wrong in my program.

    To customise a full JComboBox might take some UI work.
    I'd suggest going with a custom JTextField and popupmenu if you want that look.
    Tip: use custom painting to get the arrow painted on the textfield
    ICE

  • JComboBox in JTable not refresh automatically

    Hi folks,
    I put a JComboBox in a JTable cell as editor and with a GlassPane over the whole frame. Initially, I got lots of problems in dispatching events to JComboBox. Eventually, comboBox.setLightWeightPopupEnabled(false) seems solve many of them. However, after I called the said API to prevent light-weighted popup in JTable, when I move mouse on popup list or navigate with scroll bar, the UI does not refresh at all. I am pretty sure that all the models except UI has been updated because when I switch to another application and back, the UI repaints with expected appearance.
    Any idea ? Thanks a lot.!

    I think you might be doing this to yourself. This block here:
        private void tblContactFocusLost(java.awt.event.FocusEvent evt)
            if (tbl.isVisible())
                TableCellEditor tce = tbl.getCellEditor();
                if (tce != null) tce.stopCellEditing();
        }What purpose does it serve? It seems to muck up your table cell editing, including the combobox editing. If you comment out the tce.stopCellEditing() like so:
        private void tblContactFocusLost(java.awt.event.FocusEvent evt)
            if (tbl.isVisible())
                TableCellEditor tce = tbl.getCellEditor();
                if (tce != null) ; //tce.stopCellEditing();
        }Things work better.

  • GlassPane problem

    Hi all,
    I've tried to put a glasspane over some JButtons/JTable/JComboBox in order to better control the focus & field validation. Here is the Sun official tutorial I am looking at:
    http://java.sun.com/docs/books/tutorial/uiswing/components/rootpane.html
    Here they emphasis to redispatch mouseDrag event:
    "... If a mouse event occurs over the check box or menu bar, then the glass pane redispatches the event so that the check box or menu component receives it. So that the check box and menu behave properly, they also receive all drag events that started with a press in the button or menu bar ..."
    Surprise me much, they know the problem but their sample code does not work. When the glasspane is on (visiable), I try to click on the check box, keep mouse pressed and drag off the check box, the check box still stays grayed. Similar thing happens on Jbutton, scroll bar.
    Anyone has any idea on this ? Your help will be greatly appreicated.
    KC

    If you would explain what you are trying to do, then maybe we could actually help you. Post your question in the form of a requirement.
    You may be using the wrong approach to solve the problem, but if we don't know what the problem is then we can't offer alternatives.
    As a wild guess maybe crwoods DimOverlay example in this posting will help:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=791415

  • 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

  • JComboBox causing GTK-WARNING and GTK-CRITICAL on Ubuntu 8.04

    I was wondering why whenever I use the GTK Look and Feel, my JComboBox's cause GTK issues. They also don't display right...
    Here is the code I am using....
    import javax.swing.*;
    public class ComboBoxDisplayTest extends JFrame
      public ComboBoxDisplayTest()
        try
          UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
          SwingUtilities.updateComponentTreeUI(this);
        catch(Exception ex)
          ex.printStackTrace();
        JComboBox cb = new JComboBox();
        this.add(cb);
        cb.addItem("Item 1");
        cb.addItem("Item 2");
      public static void main(String[] args)
        ComboBoxDisplayTest c = new ComboBoxDisplayTest();
        c.pack();
        c.setVisible(true);
    }This is what get's printed onto the terminal when I run the program:
    java ComboBoxDisplayTest
    (<unknown>:7078): Gtk-WARNING **: Attempting to add a widget with type GtkButton to a GtkComboBoxEntry (need an instance of GtkEntry or of a subclass)
    (<unknown>:7078): Gtk-CRITICAL **: gtk_widget_realize: assertion `GTK_WIDGET_ANCHORED (widget) || GTK_IS_INVISIBLE (widget)' failed
    (<unknown>:7078): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failed
    (<unknown>:7078): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failed
    (<unknown>:7078): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failed
    (<unknown>:7078): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failed
    (<unknown>:7078): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failed
    (<unknown>:7078): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failedWhat exactly is going on?
    Is there something wrong with my code?
    Is there any way to fix this?
    Any answers are much appreciated...
    Thanks

    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6624717
    as far as i know (i am using Ubuntu 7.10 & OpenJDK 1.6.0_0-b11 & Sun JDK) not fixed yet ....
    Ronald

  • Associate Action with jcombobox item

    Is it possible to associate a particular Action with a jcombobox item (for example using setAction()). When the user selects a particular item of jcombobox, the Action must be triggered.
    regards,
    Nirvan.

    Hi,
    You can associate a particular action with a JComboBox. As per my understanding u can add one action perfrom action to combobox or itemStateChanged action
    if u add action perform action, u need to add the following method to ur logic.
    JComboBox combobox=new JComboBox();
        combobox.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
             JComboBox combo = (JComboBox)evt.getSource();
                if(combo.getSelectedItem().equals("LOCATION")) {
                A a = new A();
                a.show();
            } else if(combo.getSelectedItem().equals("HOUSE")) {
                B b= new B();
                b.show();
            });if action is ItemStateChanged then add the following method.
    combobox.addItemListener(new java.awt.event.ItemListener() {
                public void itemStateChanged(java.awt.event.ItemEvent evt) {
                    and write your logic here which one needs to be triggered when this action performed.
            });Hope this will help to you....
    Thanks & Regards,
    Maadhav..

  • Retrieving values from a JComboBox - Design question.

    I would like some design guidance on a problem that I am hoping has been solved before. Here is my situation:
    I have a JComboBox that I populate with String values from a database table. The exact set of values to be loaded into the JComboBox varies according values specified elsewhere on the GUI.
    When I select an item from the JComboBox, I need to read the database to retrieve more information. The text is not sufficient for me to identify the data I need, so I need to get the table key from somewhere.
    Is there anyway I can associate my table key with the text value inside the JComboBox and retrieve it when the user selects a drop down value from the JComboBox?
    Many thanks in advance.

    when you load the data from the db, try to get ALL the information needed: item label+item value+description. put this data into a map (a hashmap) for example using a unique identifier. For example, use a numeric index. In this case, the item value should be the index that uniquely identifies your items.
    create a simple bean that encapsulates the item contents: index+value+label, description.
    Doing this will avoid the huge db access occurences.
    hth

  • How to change font/ font color etc in a graphic object using JCombobox?

    Hello
    My program im writing recently is a small tiny application which can change fonts, font sizes, font colors and background color of the graphics object containing some strings. Im planning to use Jcomboboxes for all those 4 ideas in implementing those functions. Somehow it doesnt work! Any help would be grateful.
    So currently what ive done so far is that: Im using two classes to implement the whole program. One class is the main class which contains the GUI with its components (Jcomboboxes etc..) and the other class is a class extending JPanel which does all the drawing. Therefore it contains a graphics object in that class which draws the string. However what i want it to do is using jcombobox which should contain alit of all fonts available/ font sizes/ colors etc. When i scroll through the lists and click the one item i want - the graphics object properties (font sizes/ color etc) should change as a result.
    What ive gt so far is implemented the jcomboboxes in place. Problem is i cant get the font to change once selecting an item form it.
    Another problem is that to set the color of font - i need to use it with a graphics object in the paintcomponent method. In this case i dnt want to create several diff paint.. method with different property settings (font/ size/ color)
    Below is my code; perhaps you'll understand more looking at code.
    public class main...
    Color[] Colors = {Color.BLUE, Color.RED, Color.GREEN};
            ColorList = new JComboBox(Colors);
    ColorList.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ev) {
                     JComboBox cb = (JComboBox)ev.getSource();
                    Color colorType = (Color)cb.getSelectedItem();
                    drawingBoard.setBackground(colorType);
              });;1) providing the GUI is correctly implemented with components
    2) Combobox stores the colors in an array
    3) ActionListener should do following job: (but cant get it right - that is where my problem is)
    - once selected the item (color/ font size etc... as i would have similar methods for each) i want, it should pass the item into the drawingboard class (JPanel) and then this class should do the job.
    public class DrawingBoard extends JPanel {
           private String message;
           public DrawingBoard() {
                  setBackground(Color.white);
                  Font font = new Font("Serif", Font.PLAIN, fontSize);
                  setFont(font);
                  message = "";
           public void setMessage(String m) {
                message = m;
                repaint();
           public void paintComponent(Graphics g) {
                  super.paintComponent(g);
                  //setBackground(Color.RED);
                  Graphics2D g2 = (Graphics2D) g;
                  g2.setRenderingHint             
                  g2.drawString(message, 50, 50);
           public void settingFont(String font) {
                //not sure how to implement this?                          //Jcombobox should pass an item to this
                                   //it should match against all known fonts in system then set that font to the graphics
          private void settingFontSize(Graphics g, int f) {
                         //same probelm with above..              
          public void setBackgroundColor(Color c) {
               setBackground(c);
               repaint(); // still not sure if this done corretly.
          public void setFontColor(Color c) {
                    //not sure how to do this part aswell.
                   //i know a method " g.setColor(c)" exist but i need to use a graphics object - and to do that i need to pass it in (then it will cause some confusion in the main class (previous code)
           My problems have been highlighted in the comments of code above.
    Any help will be much appreciated thanks!!!

    It is the completely correct code
    I hope that's what you need
    Just put DrawingBoard into JFrame and run
    Good luck!
    public class DrawingBoard extends JPanel implements ActionListener{
         private String message = "message";
         private Font font = new Font("Serif", Font.PLAIN, 10);
         private Color color = Color.RED;
         private Color bg = Color.WHITE;
         private int size = 10;
         public DrawingBoard(){
              JComboBox cbFont = new JComboBox(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames());
              cbFont.setActionCommand("font");
              JComboBox cbSize = new JComboBox(new Integer[]{new Integer(14), new Integer(13)});
              cbSize.setActionCommand("size");
              JComboBox cbColor = new JComboBox(new Color[]{Color.BLUE, Color.RED, Color.GREEN});
              cbColor.setActionCommand("color");
              JComboBox cbBG = new JComboBox(new Color[]{Color.BLUE, Color.RED, Color.GREEN});
              cbBG.setActionCommand("bg");
              add(cbFont);
              cbFont.addActionListener(this);
              add(cbSize);
              cbSize.addActionListener(this);
              add(cbColor);
              cbColor.addActionListener(this);
              add(cbBG);
              cbBG.addActionListener(this);
         public void setMessage(String m){
              message = m;
              repaint();
         protected void paintComponent(Graphics g){
              super.paintComponent(g);
              Graphics2D g2 = (Graphics2D)g;
              g2.setColor(bg);//set background color
              g2.fillRect(0,0, getWidth(), getHeight());          
              g2.setColor(color);//set text color
              FontRenderContext frc = g2.getFontRenderContext();
              TextLayout tl = new TextLayout(message,font,frc);//set font and message
              AffineTransform at = new AffineTransform();
              at.setToTranslation(getWidth()/2-tl.getBounds().getWidth()/2,
                        getWidth()/2 + tl.getBounds().getHeight()/2);//set text at center of panel
              g2.fill(tl.getOutline(at));
         public void actionPerformed(ActionEvent e){
              JComboBox cb = (JComboBox)e.getSource();
              if (e.getActionCommand().equals("font")){
                   font = new Font(cb.getSelectedItem().toString(), Font.PLAIN, size);
              }else if (e.getActionCommand().equals("size")){
                   size = ((Integer)cb.getSelectedItem()).intValue();
              }else if (e.getActionCommand().equals("color")){
                   color = (Color)cb.getSelectedItem();
              }else if (e.getActionCommand().equals("bg")){
                   bg = (Color)cb.getSelectedItem();
              repaint();
    }

  • Problem with JComboBox in a JPanel

    I have a JComboBox in a JPanel (with a gridbaglayout), and I add items to the combobox:
    String[] stateList={"AL",.....};
    JCombobox stateCB=new JComboBox(stateList);
    and when I run the application, the states appear in the box, but when I click on the box, there is no drop-down list!
    any ideas?

    Is the combobox Enabled if it is then after adding it to anything set it to true cause i poersonally tried out as u have given it it works and else if it does not show a list then use the setmodel function and set the model to DefaultComboBoxModel and then add the items using a for loop

  • Problem with JComboBox in a fixed JToolBar

    Hi,
    I've created a JComboBox in a JToolBar that contains all available fonts. When I click on the drop down arrow I only see the first font and a small part of the second. The JComboBox is dropped down in fact just as far as the border of the JToolbar. All the rest isn't visible to me; it seems that they are behind the other components of my JApplet. However, if I move the JToolBar from it's position (as it's a floatable component), there's no problem at all. So I'm wondering why I can't see everything when the JToolBar is docked.... Can anyone help me?
    Thanks in advance!!
    E_J

    it seems that they are behind the other components of my JApplet.Sounds like you are mixing AWT components with your Swing application. Make sure you are using JPanel, JButton ... and not Panel, Button....

Maybe you are looking for

  • Can 2 websites share the same cookie?

    Hi, Can two different websites share the same cookie? For example, Blah-Forums.com and Blah-Store.com are interlinked and share the same audience. When a person signs on at Blah-Forums.com, I want to make it so that he/she can move to Blah-Store.com

  • Resource object not showing while provisioning a User

    Simple task but I am not able to fix this. I have a dummy resource whcih I created for some testing.However I am not able to see this resource when I try to provision a user to this resource. Any Ideas? FYI:.I have checked Allow SelfService,Allow All

  • Switching off and moving HH4 and OR boxes

    Apologies if this question's been asked before, or is a bit simple - but I'm thinking of moving my HH4 and OR boxes, and neatening up the cabling around my desk. The boxes have never been switched off since the day of installatin (in June this year).

  • Printing from Classic App to new HP printer

    My new HP 6988dt will not print from a Classic App. Is there a Classic printer driver that will produce a file that could then be printed? (Something like the "Save as PDF" option in OS X print dialog.) Pete

  • Setting transaction isolation upon enlistment for XA driver not supported !!?!!?

    Hi ! I've been developping a simple webapplication with a few Entity CMP EJB, Struts and some JSP. I registred a Pointbase XA JDBC driver in Weblogic 8.1. When I want to create a new post in the database via one of my EJB, I get "Due to vendor limita