JComboBox MouseListener Problem

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

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

Similar Messages

  • JComboBox MouseListener

    Hi guys,
    I am facing a weird problem while using an JComboBox.
    I've got an JPanel to which I am adding a JComboBox, and when I try to set its border on the MouseListener event class:
    public void mouseEntered(MouseEvent e)
            ((JComponent)e.getSource()).setBorder(Color.Blue, 1);
    }The comboBox changes its location, I mean the Jpanel where it was added moves its location to the top/east location in th JFrame.
    But If I do this:
    myObjCbo.getComponent(0).addMouseListener(myMouseListerner);
    myObjCbo.getComponent(1).addMouseListener(myMouseListerner);
    myObjCbo.getComponent(2).addMouseListener(myMouseListerner);
    BorderlessTextField
    CellRenderedPane
    BasicArrowPaneIt sort of works... and its position is not changed anymore.
    Is this behaviour normal??
    Thanks,
    MeTitus

    I just found what the problem is.
    Back in the work I am using Xp and I enable L&F, now I am trying the program at home in my linux box and I'm getting this stack trace:
    (<unknown>:9292): Gtk-WARNING **: Attempting to add a widget with type GtkButton to a GtkComboBoxEntry (need an instance of GtkEntry or of a subclass)
    (<unknown>:9292): Gtk-CRITICAL **: gtk_widget_realize: assertion `GTK_WIDGET_ANCHORED (widget) || GTK_IS_INVISIBLE (widget)' failed
    (<unknown>:9292): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failed
    (<unknown>:9292): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failed
    (<unknown>:9292): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failed
    (<unknown>:9292): Gtk-CRITICAL **: gtk_paint_box: assertion `style->depth == gdk_drawable_get_depth (window)' failedAnd simple things like changing the background of a component fail to work. I disabled L&F and the problem I was getting with the component changing its location when using setBorder now works properly.
    So enabling L&F both in windows and linux have problems. Do you guys experience any problems when using L&F at all??
    Thanks,
    MeTitus

  • JCombobox selection problem

    Hello,
    I have some problem implementing events associated with JComboBox. My requirement is "the event should get fired only when an item is selected in the combobox". It may occur thet using arrow keys I can traverse all elements in the combobox and on item change the event should not get fired. I tried with itemstatechanged, actionperformed but no result.
    Any help will be appreciated.
    regards,
    Ranjan

    A simple working example:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class ComboBoxAction extends JFrame implements ActionListener
         private JComboBox comboBox;
         public ComboBoxAction()
              comboBox = new JComboBox();
              comboBox.addActionListener( this );
              comboBox.addItem( "Item 1" );
              comboBox.addItem( "Item 2" );
              comboBox.addItem( "Item 3" );
              comboBox.addItem( "Item 4" );
              //  This prevents action events from being fired when the
              //  up/down arrow keys are used on the dropdown menu
              comboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
              getContentPane().add( comboBox );
         public void actionPerformed(ActionEvent e)
              System.out.println( comboBox.getSelectedItem() );
              //  make sure popup is closed when 'isTableCellEditor' is used
              comboBox.hidePopup();
         public static void main(String[] args)
              JFrame frame = new ComboBoxAction();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible( true );
    }

  • JcomboBox + FOR - problem

    Hi,
    I try changing this code:
    ArrayList<String> tmp = new ArrayList<String>();
    tmp.add(numbertext.getText());
    for(String temp1 : tmp)
    System.out.println("a="+temp1.toString());
    <b>
    Legend:
    </b>
    numbertext is a JtextField.for JComboBox using FOR but i have error and problems.
    String[] items = {"item1", "item2", "item3"};
    jComboBox1.setModel(new DefaultComboBoxModel(items));
    int num = jComboBox1.getItemCount();
    String my = Integer.toString(num);
    for (String s : my ) {
            Object item = jComboBox1.getItemAt(num);
            System.out.println("a="+s.toString());I don;t know how to translate for JComoboBox.
    Please help

    Hmmmm,
    I try creating code which I choose in JComoboBox1 value for example Items2 and I click the button. My first value Items2 will be include in string, next I choose value items 4 in JcomboBox and the second value will be in string. Now In string I have a 2 value: items 2 and items 4 And I will have doing choose new value to infinity.
    I don't now how to create.

  • JComboBox listener problem

    Hi all,
    I have following problem, i use combobox and i need to write listener for selecting item.
    But both ActionListener and ItemListener are unusable for me, because i dont know how to differ between selecting item when combobox is poped up.
    I dont want to react on going thru items in popup, but only to FINAL select of button.
    Please Help.
    Mathew, HSIGP

         This works on non editable combo boxes
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class ComboBoxAction extends JFrame implements ActionListener
         JComboBox comboBox;
         public ComboBoxAction()
              comboBox = new JComboBox();
              comboBox.addActionListener( this );
              comboBox.addItem( "Item 1" );
              comboBox.addItem( "Item 2" );
              comboBox.addItem( "Item 3" );
              comboBox.addItem( "Item 4" );
              //  This prevents action events from being fired when the
              //  up/down arrow keys are used on the dropdown menu
              comboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
              getContentPane().add( comboBox );
         public void actionPerformed(ActionEvent e)
              System.out.println( comboBox.getSelectedItem() );
              //  make sure popup is closed when 'isTableCellEditor' is used
              comboBox.hidePopup();
         public static void main(String[] args)
              final ComboBoxAction frame = new ComboBoxAction();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible( true );
    }

  • JComboBox Render Problem........

    Hi I have a problem in JCombox renderer in my application Problem is i have Three comboBox columns in my table wing same Renderer and Editor. second and third combo column's aree working fine But in first combo-column if i add a new row clicking add button and if change a value in top- most comboBox i will reflect in all ComboBox's below, this is not happening in othe two Combo-column. i'am not at all gettin why this happens where i am using same renderer for all combo-columns how to stop this, When a new row is add ComboBox first item as Selected,
    Can any one please tell me how to solve this,
    since i cannot past entair application i am pasting example with similar suituation using same renderer.
    Thank's in Advance
    CODE:-
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.TableColumn;
    * @author 501376972
    public class MainTable extends JFrame{
    DefaultTableModel model = null;
    JTable table = null;
    JScrollPane scrollpane = null;
    JButton btCancel = null;
    JButton btADD = null;
    JPanel panelButton = null;
    public Object[][] data = null;
    String column[] = {" ","A","B","C","D","E","F"};
    String oprator[] = {" ","=","/","*","-","+"};
    String number[] = {" ","1","2","3","4","5","6"};
    /** Creates a new instance of MainTable */
    public MainTable() {
    model = new DefaultTableModel();
    model.addColumn("Column");
    model.addColumn("Operator");
    model.addColumn("Value");
    model.addColumn("Number");
    table = new JTable();
    table.setModel(model);
    data = new Object[][]{
    {column, oprator, null, number}
    model.addRow(data);
    TableColumn colCol = table.getColumnModel().getColumn(0);
    colCol.setCellRenderer(new ComboBoxCellRenderer(column));
    colCol.setCellEditor(new ComboBoxCellEditor(column));
    TableColumn colOpr = table.getColumnModel().getColumn(1);
    colOpr.setCellRenderer(new ComboBoxCellRenderer(oprator));
    colOpr.setCellEditor(new ComboBoxCellEditor(oprator));
    TableColumn colLog = table.getColumnModel().getColumn(3);
    colLog.setCellRenderer(new ComboBoxCellRenderer(number));
    colLog.setCellEditor(new ComboBoxCellEditor(number));
    scrollpane = new JScrollPane(table);
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(scrollpane,BorderLayout.CENTER);
    panelButton = new JPanel();
    btADD = new JButton("ADD");
    btCancel = new JButton("Cancel");
    panelButton.add(btADD);
    panelButton.add(btCancel);
    getContentPane().add(panelButton,BorderLayout.SOUTH);
    btCancel.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e) {
    dispose();
    btADD.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e) {
    model.addRow(data);
    getContentPane().add(scrollpane);
    setSize(500,500);
    class ComboBoxCellRenderer extends JComboBox implements TableCellRenderer {
    public ComboBoxCellRenderer(String[] items) {
    super(items);
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected) {
    //DO NOTHIING
    } else {
    //DO NOTHIING
    // Select the current value
    if(value == null)
    setSelectedIndex(0);
    else
    setSelectedItem(value);
    return this;
    public class ComboBoxCellEditor extends DefaultCellEditor {
    public ComboBoxCellEditor(String[] items) {
    super(new JComboBox(items));
    * @param args the command line arguments
    public static void main(String[] args) {
    MainTable mt = new MainTable();
    mt.setVisible(true);
    }

    Don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the posted code retains its original formatting.
    Don't know why the code works the way it does, but the code is wrong. The correct way to add a row is like this:
    //model.addRow(data);
    String[] rowData = { " ", " ", " ", " "};
    model.addRow(rowData);

  • JComboBox addActionListener problem?

    HI,
    i am using JComboBox to add each item action perform of use StyleEditorKit.FontSizeAction("String", int), but i only can add one item action perform only. See my code any problem...
    for(int i>12;i<=50 ; i++){
                  comboBox.addItem(" "+i);
               // i want to loop each item can function
                comboBox.addActionListener(new StyleEditorKit.FontSizeAcion("i ", i)Thanks

    FontSizeAction is able to set the size to a value delivered in String format as the command String of its ActionEvent. Unfortunately, the JComboBox doesn't deliver the String value of the selected item as command string but an arbitrary value to be set once. So you have to wrap your FontSizeAction in a custom ActionListener of your own where you retrieve the selected item, cast it to a String and pass this value to FontSizeAction as the command String of a new ActionEvent object.
    You should also get rid of that whitespace when creating the size value, String.valueOf(int) is a better way to create a String for an int.

  • JComboBox Dropping Problem

    Hi, I have a JComboBox in a table cell with all the Item I need. But the problem is when I click on JComboBox, dropdown menu pops up and immediately hides automatically. And cannot allow me to choose anything.
    Any suggestions plz.
    Thanks

    You've got a coding problem, so read this section from the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html]How to Use Combo Boxes for example on how to do this correctly.

  • JComboBox Editing problem

    hi all ,
    I have problem with JComboBox
    like this :
    JComboBox comTech = new JComboBox();
    comTech.addItem(" ");
    comTech.addItem("one");
    comTech.addItem("two");
    the problem is I want first( comTech.addItem(" ");) item is Editable remaing are uneditable
    I am not getting any solution if anyone knows please send the solution
    thanks

    You missunderstand the use of JComboBox. A JComboBox is used to allow the user to selection from a list of items.
    An uneditable combox allows the user to select an item from the list.
    An editable combo box allows the user to select an item from the list or to enter there own value. It does not allow you to change the value of the entries in the list.
    See this section from the Swing tutorial on "How to Use Combo Boxes":
    http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html

  • 2 JComboBox  sync problem

    Hi, im getting crazy with this error. I have two different JComboBox with two differents DefaultComboBoxModel.
    The first shows a list of files.
    The second shows a data list from the selected file in the first.
    When i select a different file in the first combo, i want to change the data list in the second combo. So i call the removeAllElements method in the DefaultComboBoxModel, but i dont know why, then the second combo code is executed too (it shouldnt) and i get an error.
    The code is something like this:
    cmb1 is a jcombobox linked to dcbm1, which is a defaultcomboboxmodel
    cmb2 is a jcombobox linked to dcbm2, which is a defaultcomboboxmodel
    MyObject is a customized class which has two fields: a Vector and a String. There is a Vector of MyObject, where is load the file data.
      void cmb1_actionPerformed(ActionEvent e){
        dcbm2.removeAllElements();
        // Load the file
        // Get data load on vector (class Vector)
        // Then, send data from vector to 2nd combomodel:
        for (int i=0; i<vector.size(); i++){
          mo = (MyObject)vector.get(i);
          dcbm2.addElement(mo.getString());
      void cmb2_actionPerformed(ActionEvent e){
        dlm.clear();                                                    // ListModel which i use to show data
        int x = cmb2.getSelectedIndex();
        m = (MyObject)vector.get(x);                       // This line throws the error (ArrayOutOfBounds). x=-1
        vector2 = m.getVector();
        for (int i=0; i<vector2.size(); i++){
          dlm.addElement((vector2.getString()
      }So thats my problem. When i select an item in the 1st combo, the 2nd combo code is executed too, throwing an ArrayIndexOutOfBounds because there is no item selected

    as I see, in this listing, you did not try using what I told you before, try using this:
    public void actionPerformed(ActionEvent e) {
         Object obj = e.getSource();
         if (obj == cmbFiles) {
              parser = new MyXMLParser((String) dcbmFiles.getSelectedItem());
              try {
                   carrera = parser.read();
              } catch (Exception z) {
                   z.printStackTrace();
              cursos = carrera.getCursos();
              for (int i = 0; i < cursos.size(); i++) {
                   cur = (Curso) cursos.get(i);
                   dcbmCursos.addElement(cur.getCurso());
         } else if (obj == cmbCursos) {
              dlmAsignaturas.clear();
              int x = cmbCursos.getSelectedIndex();
              cur = (Curso) cursos.get(x);
              asignaturas = cur.getAsignaturas();
              for (int i = 0; i < asignaturas.size(); i++) {
                   dlmAsignaturas.addElement(
                        ((Asignatura) asignaturas.get(i)).getId()
                             + ((Asignatura) asignaturas.get(i)).getGrupo().toLowerCase());
    }

  • JMenu and MouseListener problems

    I have a JMenu that is used as a JMenuItem in another JMenu in the menu bar. The same JMenu is added as a popup menu to a button.
    I added a MouseListener to the JMenu because I want to execute some code upon mouseEntered() and mouseExited().
    Problem: the listener is only fired when I enter or exit the menu from the menu bar, never when the popup menu of the button is entered or exited.
    What can I do to trigger the mouse listener?

    I have a JMenu that is used as a JMenuItem in another JMenu in the menu bar.Components can only have a single parent. I don't know how what you are describing is possible.
    If you want to share the ActionEvent then you should be using an Action when creating the menu. Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/misc/action.html]How to use Actions.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • MouseListener Problems - need code solution

    I've been banging my head against the wall the past month or so on this assignment of mine - i've come to the stage where i really some help from a person that really know the java - i have a due date coming up and i really need to output this program.
    I've been thru event handling, but the majority of the code i didnt even have to look at it - im very new to java -doing it for about 6 months or less - did C so that helped a bit. But i can;t make head or tails about mousepressed,mouse pressed,mouse realsed,mouse entered and mouse exited - my code my out put is also blank...
    Can somebody, anybody help me with this coding - im sorry i dont have any dukes, but i promise as soon as i get i will remember the person and give as much as he or she wants.
    im gona paste my entire code assignment here...sorry for this...
    This is my main class : javac ShowRubik.java and java ShowRubik
    please let me know.
    Regards
    RAfiek
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ShowRubik extends JApplet implements MouseListener {
       Rubik cube;
       private int width = 300, height = 300;
       int count = 0;
       public void init()
         cube = new Rubik(width, height);
         cube.addMouseListener(this); 
         // get content pane and set its layout
         Container container = getContentPane();
         container.setLayout( new BorderLayout() );
         container.add(cube, BorderLayout.CENTER);
       // execute application
       public static void main( String args[] )
          int width=300, height=300;
          if (args.length !=2) {
         width = 300;
         height = 300;
          JFrame applicationWindow = new JFrame("Rubik's Cube Demo");
          applicationWindow.setDefaultCloseOperation(
             JFrame.EXIT_ON_CLOSE );
          ShowRubik appletObject = new ShowRubik();
          appletObject.setWidth(width);
          appletObject.setHeight(height);
          appletObject.init();
          appletObject.start();
          applicationWindow.getContentPane().add(appletObject);
          applicationWindow.setSize(width,height);
          applicationWindow.setVisible(true);
          applicationWindow.show();
       // enables application to specify width of drawing area
       public void setWidth( int newWidth )
          width = newWidth;
       // enables application to specify height of drawing area
       public void setHeight( int newHeight )
          height = newHeight;
    // MouseListener event handlers
       // handle event when mouse released immediately after press
       public void mouseClicked( MouseEvent event )
         if (count == 0){
         cube.Turn(Rubik.LEFT);
         if (count == 1){
         cube.Turn(Rubik.RIGHT);
         if (count == 2){
         cube.Turn(Rubik.UP);
         if (count == 3){
         cube.Turn(Rubik.DOWN);
         if (count == 4){
         cube.Twist(Rubik.LEFT,0);
         if (count == 5){
         cube.Twist(Rubik.RIGHT,1);
         if (count == 6){
         cube.Twist(Rubik.UP,2);
         if (count == 7){
         cube.Twist(Rubik.DOWN,0);
         if (count == 8){
         cube.Twist(Rubik.LEFT,2);
         if (count == 9){
         cube.Twist(Rubik.RIGHT,2);
         if (count == 10){
         cube.Twist(Rubik.UP,0);
         if (count == 11){
         cube.Twist(Rubik.DOWN,1);
         if (count == 12){
         cube.Twist(Rubik.LEFT,2);
         if (count == 13){
         cube.Twist(Rubik.RIGHT,0);
         if (count == 14){
         cube.Twist(Rubik.UP,1);
         if (count == 15){
         cube.Twist(Rubik.DOWN,2);
         if (count == 16){
         cube.Reset();   
         if (count == 17){
         cube.Scramble();
         if (count == 18){
         cube.Reset();   
         count++;
       // handle event when mouse pressed
       public void mousePressed( MouseEvent event )
         repaint();
         show();
       // handle event when mouse released after dragging
       public void mouseReleased( MouseEvent event )
         cube.repaint();
       // handle event when mouse enters area
       public void mouseEntered( MouseEvent event )
         cube.repaint();
       // handle event when mouse exits area
       public void mouseExited( MouseEvent event )
         cube.repaint();
    }My Rubik class
    * Rubik.java
    * Created on 10 May 2004, 01:50
    * @author  Rafiek Buffkins
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.JApplet;
    import java.io.*;
    import java.lang.*;
    import java.util.*;
    public class Rubik extends JPanel
    public static int UP =0;
    public static int DOWN = 1;
    public static int TOP = 0;
    public static int BOTTOM = 1;
    public static int LEFT = 2;
    public static int RIGHT = 3;
    public static int BACK = 4;
    public static int FRONT = 5;
    private Face[] faces = new Face[6];
    private Color[] colorList = new Color[] { Color.YELLOW, Color.BLUE, Color.GREEN, Color.WHITE, Color.ORANGE, Color.RED};
    private int current = 0;
    private int top = 4;
    private int height, width;
    //[6][6][4]
    private int[][][] neighbors = {
                   {     {-1,-1,-1,-1}, {2,0,4,5}, {-1,-1,-1,-1}, {2,0,5,4}, {2,0,1,3}, {2,0,3,1}     },
                   {     {3,0,4,5}, {-1,-1,-1,-1}, {3,0,5,4}, {-1,-1,-1,-1}, {3,0,1,2}, {3,0,2,1}     },
                   {     {-1,-1,-1,-1}, {0,2,5,4}, {-1,-1,-1,-1}, {0,2,4,5}, {0,3,2,1}, {0,3,1,2}     },
                   {     {1,3,4,5}, {-1,-1,-1,-1}, {1,3,5,4}, {-1,-1,-1,-1}, {1,3,2,0}, {1,3,0,2}     },
                   {     {5,4,1,3}, {5,4,2,0}, {5,4,3,1}, {5,4,0,2}, {-1,-1,-1,-1}, {-1,-1,-1,-1}     },
                   {     {4,5,3,1}, {4,5,0,2}, {4,5,1,3}, {4,5,2,0}, {-1,-1,-1,-1}, {-1,-1,-1,-1}     },
    Rubik(int w, int h)
      width = w;
        height = h;
    public void Reset()
        for (int i=0; i<6; i++)
         faces[i] = new Face(i);
        current = 0;
        top = 4;
        repaint();
    public void Turn(int direction)
        for (int i=0; i<3; i++)
         Twist(direction,i);
          repaint();
    public void Twist(int direction, int rowOrCol)
         int front_face = current;
         int top_face = top;
         int left_face = neighbors[top][current][RIGHT];
         int right_face = neighbors[top][current][LEFT];
         int bottom_face = neighbors[top][current][UP];
                 int back_face = neighbors[current][bottom_face][UP];     //trying to create and store faces into arrays and then
                                       //and then change them accordingly
         int face1, face2, face3, face4;
         if((direction==LEFT)||(direction==RIGHT))               //row twisting
              int[] rowCopy = new int[3];
              face1 = current;
              face2 = neighbors[top][face1][direction];          //trying to determine which faces are involved...
              face3 = neighbors[top][face2][direction];          //not sure....
              face4 = neighbors[top][face3][direction];
              rowCopy[0] = faces[face1].getBlocks(rowOrCol,0);     //copy face1
              rowCopy[1] = faces[face1].getBlocks(rowOrCol,1);
              rowCopy[2] = faces[face1].getBlocks(rowOrCol,2);
              for(int j = 0; j<3 ;j++)                    //twisting
                faces[face1].setBlocks(rowOrCol, j, faces[face2].getBlocks(rowOrCol,j));
              for(int j = 0; j<3; j++)
                faces[face2].setBlocks(rowOrCol, j, faces[face3].getBlocks(rowOrCol,j));
              for(int j = 0; j<3; j++)
                faces[face3].setBlocks(rowOrCol, j, faces[face4].getBlocks(rowOrCol,j));
              for(int j = 0; j<3; j++)
                faces[face4].setBlocks(rowOrCol, j, rowCopy[j]);
                                          //if twisting up :
                                       // back become reverse(top)
                                       // bottom become reverse(back)
                                       // front become bottom
                                       // top become front
         else if((direction==UP)||(direction==DOWN))          //trying column twist
           int[] colCopy = new int[3];
           int x, y, i;
         if(direction==UP)                         //twist up
           colCopy[0] = faces[front_face].getBlocks(0,rowOrCol);
           colCopy[1] = faces[front_face].getBlocks(1,rowOrCol);
           colCopy[2] = faces[front_face].getBlocks(2,rowOrCol);
         //front become bottom or bottom changes to front?
         for( i = 0; i<3; i++)
           faces[front_face].setBlocks(i, rowOrCol, faces[bottom_face].getBlocks(i, rowOrCol));
         //bottom become reverse(back)
         y = Math.abs(2 - rowOrCol);
         for( i = 0; i<3; i++)
         x = Math.abs(2-i);
           faces[bottom_face].setBlocks(i, rowOrCol, faces[back_face].getBlocks(x, y));
         //back become reverse(top)
         y = Math.abs(2 - rowOrCol);
         for( i = 0; i<3; i++)
         x = Math.abs(2-i);
           faces[back_face].setBlocks(x, y, faces[top_face].getBlocks(i, rowOrCol));
         // top become front or front become top
         for(i = 0; i<3; i++)
           faces[top_face].setBlocks(i, rowOrCol, colCopy);
                                       //when twisting down
                                       //top become reverse(back)
                                       //back become reverse(bottom)
                                       //bottom become front
                                       //front become top
         if(direction==DOWN)     
         //copy front
         for(i=0; i<3; i++)
         colCopy[i] = faces[front_face].getBlocks(i, rowOrCol);
         //front become top
         for(i = 0; i<3; i++)
         faces[front_face].setBlocks(i, rowOrCol, faces[top_face].getBlocks(i, rowOrCol));
         //top become reverse(back)
         y = Math.abs(2 - rowOrCol);
         for(i = 0; i<3; i++)
         x = Math.abs(2 - i);
         faces[top_face].setBlocks(i, rowOrCol, faces[top_face].getBlocks(x, y));
         //back become reverse(bottom)
         y = Math.abs(2 - rowOrCol);
         for(i = 0; i<3; i++)
         x = Math.abs(2 - i);
         faces[back_face].setBlocks(x, y, faces[bottom_face].getBlocks(i, rowOrCol));
         //bottom become front
         for(i = 0; i<3; i++)
         faces[bottom_face].setBlocks(i, rowOrCol, colCopy[i]);
         //if not middle row or colomn, twist the attached faces of the cube
         if(rowOrCol != 1)
         //row twisting
         //top row
         if((rowOrCol==0)&&(direction==RIGHT))
         faces[top].Rotate(Face.COUNTER);
         if((rowOrCol==0)&&(direction==LEFT))
         faces[top].Rotate(Face.CLOCK);
         //bottom row
         if((rowOrCol==2)&&(direction==RIGHT))
         faces[bottom_face].Rotate(Face.CLOCK);
         if((rowOrCol==2)&&(direction==LEFT))
         faces[bottom_face].Rotate(Face.COUNTER);
         //column twisting
         //left column
         if((rowOrCol==0)&&(direction==UP))
         faces[left_face].Rotate(Face.COUNTER);
         if((rowOrCol==0)&&(direction==DOWN))
         faces[left_face].Rotate(Face.CLOCK);
         //right column
         if((rowOrCol==2)&&(direction==UP))
         faces[right_face].Rotate(Face.CLOCK);
         if((rowOrCol==2)&&(direction==DOWN))
         faces[right_face].Rotate(Face.COUNTER);
         repaint();
    }//close public void twist...
    public void Scramble()
    int dir, slice;
    for (int i=0; i< 1000; i++)
    dir = (int) (Math.random() * 4);
    slice = (int) (Math.random() * 3);
    Twist(dir,slice);
    repaint();
         protected void paintComponent(Graphics g)
         super.paintComponent(g);
         for (int i=0; i<3; i++)
         for (int j=0; j<3; j++)
              g.setColor(getColor(faces[current].getBlocks(i,j)));
              g.fillRect(j*55,i*55,50,50);
         protected Color getColor(int index)
         return colorList[index];
         protected Face getFace(int which)
         int front_face = current;
         int top_face = top;
         int left_face = neighbors[top][current][RIGHT];
         int right_face = neighbors[top][current][LEFT];
         int bottom_face = neighbors[top][current][UP];
         int back_face = neighbors[current][bottom_face][UP];
         if (which == FRONT)
         return faces[front_face];
         else if (which == TOP)
         return faces[top_face];
         else if (which == LEFT)
         return faces[left_face];
         else if (which == RIGHT)
         return faces[right_face];
         else if (which == BOTTOM)
         return faces[bottom_face];
         else /* (which == BACK) */
         return faces[back_face];
    }//close of rubik class
    My face class
    public class Face
      private int side;
      private int[][] blocks = new int[3][3];
      public static int CLOCK = 0;
      public static int COUNTER = 1; 
         public Face(int sideOfCube)
           side = sideOfCube;
           for(int i=0; i<3; i++)
             for(int j=0; j<3; j++)
               blocks[i][j] = sideOfCube;     //Not sure about this....
    public int getBlocks(int i, int j)
       return blocks[i][j];
    public int setBlocks(int i, int j, int colorNum)
         return blocks[i][j] = colorNum;
       public void Rotate(int direction)
         int[][] blocks_old = new int[3][3];
         int x, y;
         for(int i = 0; i<3; i++)
            for(int j = 0;j<3; j++)
              blocks_old[i][j] = blocks[i][j];               //blocks = old_blocks???
            }                              //or blocks_new = blocks??
         if(direction==0)
           for(int i=0; i<3; i++)
               for(int j=0; j<3; j++)
              y = i;
              x = Math.abs(2-j);
              blocks[i][j] = blocks_old[x][y];
         if(direction==1)
            for(int i = 0; i<3; i++)
               for(int j = 0; j<3; j++)
              x = j;
              y = Math.abs(2-i);
              blocks[i][j] = blocks_old[x][y];

    What is your problem here?
    What are the different methods doing:
    mouseEntered(MouseEvent e) is being fired, when the mousepointer entered the current component.
    mouseExited(MouseEvent e) is being fired, when the mousepointer left the current component.
    mousePressed(MouseEvent e) is being fired, when the user presses any of the mousebuttons over the current component
    mouseReleased(MouseEvent e) is being fired, when the user releases the pressed button and
    mouseClicked(MouseEvent e) is being fired, when the user presses and releases any of the mousebuttons.
    the current component in this case is the component, where the mouseListener is registered to.
    Your code throws a NullPointerException, since the array faces is not initialized. "Reset" is missing in the constructor of Rubik.
    when you click the mouse (press and release), the colors changes 18 times, because what is missing in mouseClicked(...) is:
           if (count == 19){
                   count = 0;
           }for your example the Methods mousePressed to mouseExited are not nessessary and could be implemented empty:
         // handle event when mouse pressed
         public void mousePressed( MouseEvent event ) {}So: why are you bangig your head? What do you expect?
    Michael

  • Custom JComboBox -- MouseListener

    Hi. I'm in the process of making a custom JComboBox (called TitledComboBox).
    It's going to use a ComboBox as the component that is always visible, but when you click it instead of the standard dropdown, I'm creating a JPopupMenu to replace that. That way I want to avoid the first element (or the selected one) being repeated inside the list.
    So I've created my class extending JComboBox, and implemented MouseListener, but I'm unable to make the listener work for the JComboBox layout manager. It works perfectly for the spots on the JComboBox where the LayoutManager doesnt paint (or whatever it does), so the "arrow" doesn't effect the MouseListener....
    How can I extend the default JComboBox LayoutManager to have the same MouseListener??

    package gui;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.*;
    @SuppressWarnings("serial")
    public class TitledComboBox extends JComboBox implements MouseListener
        @SuppressWarnings("serial")
        private class PopItem extends JMenuItem
             public PopItem(String text)
                setLayout(null);
                setText(text);
                setOpaque(false);
                setBackground(Color.BLACK);
            public void paint(Graphics g)
                super.paint(g);
        @SuppressWarnings("serial")
        private class PopMenu extends JPopupMenu
              public PopMenu()
                   this.setLayout(null);
                   this.setPopupSize(120, 23*this.getComponentCount());
                   this.setOpaque(false);
              public PopMenu(String[] items)
                   this();
                   for(int i = 0; i < items.length; i++)
                        this.add(new PopItem(items));
                   updateSize();
              private void updateSize()
                   this.setPopupSize(120, 23*this.getComponentCount());
              public void show(Component arg0, int arg1, int arg2)
                   super.show(arg0, arg1, arg2);
                   this.setVisible(true);
              public void paint(Graphics g)
                   super.paint(g);
         public PopMenu dropdown;
         private TitledComboBox()
              super();
              this.addMouseListener(this);
              this.setVisible(true);
    this.setEnabled(false);
         public TitledComboBox(String title)
              this();
              this.addItem(title);
              dropdown = new PopMenu();
         public TitledComboBox(String title, String[] items)
              this();
              this.addItem(title);
              dropdown = new PopMenu(items);
         public void addPopItem(String item)
              dropdown.add(new PopItem(item));
              dropdown.updateSize();
         public void removePopItem(int itemIndex)
              dropdown.remove(itemIndex);
              dropdown.updateSize();
         public void paint(Graphics g)
              this.setEnabled(true);
              super.paint(g);
              this.setEnabled(false);
         public void mouseClicked(MouseEvent m)
    dropdown.show(this, 0, 20);
         public void mouseEntered(MouseEvent arg0)
         public void mouseExited(MouseEvent arg0)
         public void mousePressed(MouseEvent arg0)
         public void mouseReleased(MouseEvent arg0)
    Using this now gives something very similar to a JComboBox, just without the top element showing. However, I STILL don't know how to get the LayoutManager to be a part of the MouseListener... Please help!
    Edited by: Ondkloss on Nov 21, 2007 7:12 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • JTable with JComboBox/JSpinner problem

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

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

  • JComboBox color problem

    Problem:
    Setting the button background color via UIManager.put(....) actually changes part of the background of my comboboxes. I also set the combobox background with UIManager, but it only applys this color where the data is within the combobox. The area where the down arrow is (on the combobox) is the color that I set the buttons to.
    Question:
    Is there a way to prevent this line:
    UIManager.put("Button.background", ButtonColor);
    from affecting my combobox background?
    I want to achieve custom user colors for the various components within the application, but I want to set these colors in one location, through UIManager.put(...).

    Try storing a custom Object in the model, not a text string. The object would contain the text, foreground and background color. Then the renderer simply gets the value to be rendered, casts it to your Object type and retrieves the 3 pieces of information which it uses to set the text, background and foreground. No need for if / else statements. Here is a simple example:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=613731

Maybe you are looking for

  • Portal runtime error when trying to create new Iviews in EP

    Hi Require an Urgent help getting portal runtime error when trying to create a new iView in portal. I am unable to create a single iView  in portal. It was working before please see this error message   Portal Runtime Error An exception occurred whil

  • Gif is animated in Sent folder but not received by others as animated

    I've always used Entourage but would like to use Mail if only because it will send animated gifs. I sent one to myself at another (not .mac) address and received it in Entourage but it's quite different from what I sent. gif isn't animated and format

  • How to create Web service proxy in Eclipse?

    Hi, I want to create web service proxy in Eclipse. Can someone tell me what all plug ins are needed for it and what is the detail procedure for the same? Thanks in advance.

  • Waveform graph:move cursor automatically to know coordinate

    Good Day Can i know how to move cursor automatically in the waveform graph example: i have known Y =2 what is the value of  x is... which properties in property node should i use? attached also my vi (Coordinate of XY data using cursor) Best Regards

  • Nokia had deleted some map from ovi map loader!

    Why did nokia had deleted some countries map same Armenia, Georgia, South Korea, Japan and ...? Are they under updating routine and deleted now for substitute by newer version or they deleted for all times and they will not possible to download never