Event handling of JComboBox outside a JTable

Hi to All,
I've a question about JTables and JComboBoxes... I'm working on a application which holds a JTable and several JButtons and JCombBoxes. When the user clicks on a cell in the JTable, this cell will get the focus and the text will be highlighted. An action will be performed when the user clicks on a JButton (this just works fine). When the user clicks on a JComboBox also an action must be performed... but this won't work. I guess it won't work because of the JComboBox will draw a popup, and this popup will be cover the cell with the focus...
I could not catch any event of the JComboBox...
How can I check for a click on a JComboBox when an other component (JTable cell) has the focus?
Thnx,

Hi Swetha,
Button controls in a table are available only in version 2.0 of the .NET PDK.
In order to use Button in a table and handle its events u will have to upgrade.
Further information about using input controls in a table is available in the How to section of the PDK documentation.
Thanks, Reshef

Similar Messages

  • Event handling between JComboBox & JCheckBox

    Hi.
    My problem is that when i click on the JCheckBox object, the code (i have) also executes the condition for JComboBox object. I assume there is a very simple solution, but i have yet to find it.
    This is the code i'm using:
         public void itemStateChanged(ItemEvent e){
              if(qcmCheckBox.isSelected()){
                   System.out.println("checkbox selected");
              if(e.getStateChange() == ItemEvent.SELECTED){
                   System.out.println("combo selected " + comboBoxOptions.getSelectedIndex());
         }My problem is, i think, that the e.getStateChange() is always returning true. I just haven't figured out a way to 'single out' when the JComboBox is selected.

    thanks for the tip, but that didn't exactly work.
    these are my steps:
    select second drop down option (out of 3)
    select checkbox
    deselect checkbox
    old output
    combo selected1
    qcm selected
    combo selected1new output (using instanceof)
    combo selected 1
    combo selected 1
    checkbox selected
    combo selected 1
    combo selected 1here's my code:
    // setting up vars
    private JCheckBox checkBox = new JCheckBox();
    private final String comboNames[] = {"Option 1", "Option 2", "Option 3"};
    private JComboBox comboBoxOptions = new JComboBox(comboNames);
    // combo box
    comboBoxOptions.addItemListener(this);
    // checkbox
    checkBox.addItemListener(this);
    // event handler
    public void itemStateChanged(ItemEvent e){
         if(checkBox.isSelected()){
              System.out.println("checkbox selected");
         //if(comboBoxOptions instanceof JComboBox){ // the suggested alternative
         if(e.getStateChange() == ItemEvent.SELECTED){
              System.out.println("combo selected " + comboBoxOptions.getSelectedIndex());
    }For some reason, the suggested answer gives me duplicate entries for the dropdown and it still gives me duplicate entries when i click on the checkbox.
    Again, what i'm trying to do is just get the checkbox not to execute the 2nd if statement "if(e.getStateChange() == ItemEvent.SELECTED){"
    I think the statement "e.getStateChange()" is returning everything true because its an event happening but i don't know a way to single the checkbox event.
    I would appreciate all the help I can get. Thanks.
    sijis

  • Problem in event handling of combo box in JTable cell

    Hi,
    I have a combo box as an editor for a column cells in JTable. I have a event listener for this combo box. When ever I click on the JTable cell whose editor is combo box,
    I get the following exception,
    Exception occurred during event dispatching:
    java.lang.NullPointerException
         at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.setDispatchComponent(Unknown Source)
         at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.mousePressed(Unknown Source)
         at java.awt.AWTEventMulticaster.mousePressed(Unknown Source)
         at java.awt.Component.processMouseEvent(Unknown Source)
         at java.awt.Component.processEvent(Unknown Source)
         at java.awt.Container.processEvent(Unknown Source)
         at java.awt.Component.dispatchEventImpl(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
         at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
         at java.awt.Container.dispatchEventImpl(Unknown Source)
         at java.awt.Component.dispatchEvent(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Can any one tell me how to over come this problem.
    Thanks,
    Raghu

    Here's an example of the model I used in my JTable. I've placed 2 comboBoxes with no problems.
    Hope this helps.
    public class FileModel5 extends AbstractTableModel
    public boolean isEditable = false;
    protected static int NUM_COLUMNS = 3;
    // initialize number of rows to start out with ...
    protected static int START_NUM_ROWS = 0;
    protected int nextEmptyRow = 0;
    protected int numRows = 0;
    static final public String file = "File";
    static final public String mailName = "Mail Id";
    static final public String postName = "Post Office Id";
    static final public String columnNames[] = {"File", "Mail Id", "Post Office Id"};
    // List of data
    protected Vector data = null;
    public FileModel5()
    data = new Vector();
    public boolean isCellEditable(int rowIndex, int columnIndex)
    // The 2nd & 3rd column or Value field is editable
    if(isEditable)
    if(columnIndex > 0)
    return true;
    return false;
    * JTable uses this method to determine the default renderer/
    * editor for each cell. If we didn't implement this method,
    * then the last column would contain text ("true"/"false"),
    * rather than a check box.
    public Class getColumnClass(int c)
    return getValueAt(0, c).getClass();
    * Retrieves number of columns
    public synchronized int getColumnCount()
    return NUM_COLUMNS;
    * Get a column name
    public String getColumnName(int col)
    return columnNames[col];
    * Retrieves number of records
    public synchronized int getRowCount()
    if (numRows < START_NUM_ROWS)
    return START_NUM_ROWS;
    else
    return numRows;
    * Returns cell information of a record at location row,column
    public synchronized Object getValueAt(int row, int column)
    try
    FileRecord5 p = (FileRecord5)data.elementAt(row);
    switch (column)
    case 0:
    return (String)p.file;
    case 1:
    return (String)p.mailName;
    case 2:
    return (String)p.postName;
    catch (Exception e)
    return "";
    public void setValueAt(Object aValue, int row, int column)
    FileRecord5 arow = (FileRecord5)data.elementAt(row);
    arow.setElementAt((String)aValue, column);
    fireTableCellUpdated(row, column);
    * Returns information of an entire record at location row
    public synchronized FileRecord5 getRecordAt(int row) throws Exception
    try
    return (FileRecord5)data.elementAt(row);
    catch (Exception e)
    throw new Exception("Record not found");
    * Used to add or update a record
    * @param tableRecord
    public synchronized void updateRecord(FileRecord5 tableRecord)
    String file = tableRecord.file;
    FileRecord5 p = null;
    int index = -1;
    boolean found = false;
    boolean addedRow = false;
    int i = 0;
    while (!found && (i < nextEmptyRow))
    p = (FileRecord5)data.elementAt(i);
    if (p.file.equals(file))
    found = true;
    index = i;
    } else
    i++;
    if (found)
    { //update
    data.setElementAt(tableRecord, index);
    else
    if (numRows <= nextEmptyRow)
    //add a row
    numRows++;
    addedRow = true;
    index = nextEmptyRow;
    data.addElement(tableRecord);
    //Notify listeners that the data changed.
    if (addedRow)
    nextEmptyRow++;
    fireTableRowsInserted(index, index);
    else
    fireTableRowsUpdated(index, index);
    * Used to delete a record
    public synchronized void deleteRecord(String file)
    FileRecord5 p = null;
    int index = -1;
    boolean found = false;
    int i = 0;
    while (!found && (i < nextEmptyRow))
    p = (FileRecord5)data.elementAt(i);
    if (p.file.equals(file))
    found = true;
    index = i;
    } else
    i++;
    if (found)
    data.removeElementAt(i);
    nextEmptyRow--;
    numRows--;
    fireTableRowsDeleted(START_NUM_ROWS, numRows);
    * Clears all records
    public synchronized void clear()
    int oldNumRows = numRows;
    numRows = START_NUM_ROWS;
    data.removeAllElements();
    nextEmptyRow = 0;
    if (oldNumRows > START_NUM_ROWS)
    fireTableRowsDeleted(START_NUM_ROWS, oldNumRows - 1);
    fireTableRowsUpdated(0, START_NUM_ROWS - 1);
    * Loads the values into the combo box within the table for mail id
    public void setUpMailColumn(JTable mapTable, ArrayList mailList)
    TableColumn col = mapTable.getColumnModel().getColumn(1);
    javax.swing.JComboBox comboMail = new javax.swing.JComboBox();
    int s = mailList.size();
    for(int i=0; i<s; i++)
    comboMail.addItem(mailList.get(i));
    col.setCellEditor(new DefaultCellEditor(comboMail));
    //Set up tool tips.
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for mail Id list");
    col.setCellRenderer(renderer);
    //Set up tool tip for the mailName column header.
    TableCellRenderer headerRenderer = col.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer)
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the Mail Id to see a list of choices");
    * Loads the values into the combo box within the table for post office id
    public void setUpPostColumn(JTable mapTable, ArrayList postList)
    TableColumn col = mapTable.getColumnModel().getColumn(2);
    javax.swing.JComboBox combo = new javax.swing.JComboBox();
    int s = postList.size();
    for(int i=0; i<s; i++)
    combo.addItem(postList.get(i));
    col.setCellEditor(new DefaultCellEditor(combo));
    //Set up tool tips.
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setToolTipText("Click for post office Id list");
    col.setCellRenderer(renderer);
    //Set up tool tip for the mailName column header.
    TableCellRenderer headerRenderer = col.getHeaderRenderer();
    if (headerRenderer instanceof DefaultTableCellRenderer)
    ((DefaultTableCellRenderer)headerRenderer).setToolTipText(
    "Click the Post Office Id to see a list of choices");
    }

  • Please help me.... event handling on JComboBox...

    hi all,
    I have a combobox and i want a event to be fired for a single click on the down-arrow of the JComboBox. What i mean is its not the itemListener i am looking for. Only by a click on arrow i want a even to be fired. I tried using mouselistener. But the combobox ia not listening to this event. Please tell me how to achieve this?
    thx,
    -Soni.

    thx a lot.....
    it worked :)
    Now i have one more doubt.
    I am using a scroll pane and my event on this scroll pane is like this.
    I have a text field inside the pane and when i press the up arrow of scroll pane the value(intger value) inside the text field increases and the other way for down arrow button.
    i have just replaced ur code like this,
    class ScrollUI extends BasicScrollPaneUI {
    public JButton createDecreaseButton(int i) {
    try {
         ImageIcon dayDownIcon = new ImageIcon("down.gif");
         JButton b = new JButton(dayDownIcon);
         b.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent ae) {
                   System.out.println("222");
         return b;
    } catch (Exception e) {
    e.printStackTrace();
    return null;
    and setting the UI like this:
    JScrollPane pane= new JScrollPane(pp);
    pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    pane.getVerticalScrollBar().setUI(new ScrollUI());
    but it throws error like this
    setUI(javax.swing.plaf.ComponentUI) has protected access in javax.swing.JComponent
    pane.getVerticalScrollBar().setUI(new ScrollUI());
    what is the reason?
    how to solve it...
    plss....help..
    -Soni

  • Swing: when trying to get the values from a JTable inside an event handler

    Hi,
    I am trying to write a graphical interface to compute the Gauss Elimination procedure for solving linear systems. The class for computing the output of a linear system already works fine on console mode, but I am fighting a little bit to make it work with Swing.
    I put two buttons (plus labels) and a JTextField . The buttons have the following role:
    One of them gets the value from the JTextField and it will be used to the system dimension. The other should compute the solution. I also added a JTable so that the user can type the values in the screen.
    So whenever the user hits the button Dimensiona the program should retrieve the values from the table cells and pass them to a 2D Array. However, the program throws a NullPointerException when I try to
    do it. I have put the code for copying this Matrix inside a method and I call it from the inner class event handler.
    I would thank you very much for the help.
    Daniel V. Gomes
    here goes the code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import AdvanceMath.*;
    public class MathF2 extends JFrame {
    private JTextField ArrayOfFields[];
    private JTextField DimOfSis;
    private JButton Calcular;
    private JButton Ativar;
    private JLabel label1;
    private JLabel label2;
    private Container container;
    private int value;
    private JTable DataTable;
    private double[][] A;
    private double[] B;
    private boolean dimensionado = false;
    private boolean podecalc = false;
    public MathF2 (){
    super("Math Calcs");
    Container container = getContentPane();
    container.setLayout( new FlowLayout(FlowLayout.CENTER) );
    Calcular = new JButton("Resolver");
    Calcular.setEnabled(false);
    Ativar = new JButton("Dimensionar");
    label1 = new JLabel("Clique no bot�o para resolver o sistema.");
    label2 = new JLabel("Qual a ordem do sistema?");
    DimOfSis = new JTextField(4);
    DimOfSis.setText("0");
    JTable DataTable = new JTable(10,10);
    container.add(label2);
    container.add(DimOfSis);
    container.add(Ativar);
    container.add(label1);
    container.add(Calcular);
    container.add(DataTable);
    for ( int i = 0; i < 10 ; i ++ ){
    for ( int j = 0 ; j < 10 ; j++) {
    DataTable.setValueAt("0",i,j);
    myHandler handler = new myHandler();
    Calcular.addActionListener(handler);
    Ativar.addActionListener(handler);
    setSize( 500 , 500 );
    setVisible( true );
    public static void main ( String args[] ){
    MathF2 application = new MathF2();
    application.addWindowListener(
    new WindowAdapter(){
    public void windowClosing (WindowEvent event)
    System.exit( 0 );
    private class myHandler implements ActionListener {
    public void actionPerformed ( ActionEvent event ){
    if ( event.getSource()== Calcular ) {
    if ( event.getSource()== Ativar ) {
    //dimensiona a Matriz A
    if (dimensionado == false) {
    if (DimOfSis.getText()=="0") {
    value = 2;
    } else {
    value = Integer.parseInt(DimOfSis.getText());
    dimensionado = true;
    Ativar.setEnabled(false);
    System.out.println(value);
    } else {
    Ativar.setEnabled(false);
    Calcular.setEnabled(true);
    podecalc = true;
    try {
    InitValores( DataTable, value );
    } catch (Exception e) {
    System.out.println("Erro ao criar matriz" + e );
    private class myHandler2 implements ItemListener {
    public void itemStateChanged( ItemEvent event ){
    private void InitValores( JTable table, int n ) {
    A = new double[n][n];
    B = new double[n];
    javax.swing.table.TableModel model = table.getModel();
    for ( int i = 0 ; i < n ; i++ ){
    for (int j = 0 ; j < n ; j++ ){
    Object temp1 = model.getValueAt(i,j);
    String temp2 = String.valueOf(temp1);
    A[i][j] = Double.parseDouble(temp2);

    What I did is set up a :
    // This code will setup a listener for the table to handle a selection
    players.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    ListSelectionModel rowSM = players.getSelectionModel();
    rowSM.addListSelectionListener(new Delete_Player_row_Selection(this));
    //Class will take the event and call a method inside the Delete_Player object.
    class Delete_Player_row_Selection
    implements javax.swing.event.ListSelectionListener
    Delete_Player adaptee;
    Delete_Player_row_Selection (Delete_Player temp)
    adaptee = temp;
    public void valueChanged (ListSelectionEvent listSelectionEvent)
    adaptee.row_Selection(listSelectionEvent);
    in the row_Selection function
    if(ex.getValueIsAdjusting()) //To remove double selection
    return;
    ListSelectionModel lsm = (ListSelectionModel) ex.getSource();
    if(lsm.isSelectionEmpty())
    System.out.println("EMtpy");
    else
    int selected_row = lsm.getMinSelectionIndex();
    ResultSetTableModel model = (ResultSetTableModel) players.getModel();
    String name = (String) model.getValueAt(selected_row, 1);
    Integer id = (Integer) model.getValueAt(selected_row, 3);
    This is how I got info out of a table when the user selected it

  • General Event Handling (Outside AWT)

    Hi all, I am looking for info on allowing my classes to send and recieve events between classes (the set of events is to be defined by me). What is Java's event handling approach? Is there something outside the AWT?
    I realise there may be design patterns for this scenario but though there may be some Java specific way as well (like in the AWT).
    Thanks,
    David

    listeners.
    like this...
    FooEvent <- your event class
    FooEventListener <- listener interface
    FooMaker <- class that generates foo events
    An interface for the listener.
    public interface FooEventListener{
      public void processEvent(FooEvent evt);
    }the class making the events
    public FooMaker{
      // among other things might have methods like...
      public void addFooEventListener(FooEventListener fel){
        // add the listener to some collection
      // called when events happen
      private void notifyListeners(){
         // notify each listener
    }and your listeners will implement the interface.
    does that help?

  • JTable Event Handling for Boolean Columns

    I have a JTable (tableOne) with two columns. ColumnA contains simple text and ColumnB contains a boolean value which is rendered (via getColumnClass in the table model) as a check box.
    When the user selects/deselects a check box, an action must take place in another jtable (tableTwo) in the same frame (a column in tableTwo must be hidden/displayed).
    What is the correct way to do this type of event handling? Do I register the tableTwo as a listener with the table model for tableOne and then simply execute fireTableCellUpdated()? Is it appropriate for tableTwo to have access to tableOne's table model?
    Thanks for any help.
    NT

    Better create a table model listener that gets tableTwo in the constructor and keep it as a private member.
    Then regsiter this listener to tableOne model.

  • Multiple JComboBox Event Handling Problem

    Hi, guys
    I am a newbie in Java. I need to create three JComboBox, say date, month and year and a JButton "submit". After I select the entries from the three JComboBox, I click the "search" button to display something in terms of the information I selected, but I have no idea how to write the actionPerformed( ActionEvent evt) to deal with the problem. Can anyone give me some hint?
    Any help would be appreciated.

    If you are asking how to write a basic event handler for when your button is pressed, RTM.
    http://java.sun.com/docs/books/tutorial/uiswing/events/index.html

  • Event Handling of 2 JComboBoxes in 1 Frame

    Hello,
    thank you very much for your help in the following problem:
    problem: Differntiating events of 2 JComboBoxes in 1 JFrame.
    solution trial: differentiating via information of an Event-object ("list0","list1"). This solution works as stand-alone Frame, but integrating it in menu of another Frame the List-Information turns dependent on the frequency of clicking the JComboBoxes to "list2", "list3",...
    Object o = Event.getSource();
    String ComboInf = String.valueOf(o);
    ComboInf=ComboInf.substring(14,19);//here the 2 ComboBoxes are differentiated
    if(ComboInf.equals("list0")//only works for stand-alone Jframe
    -->ComboBox1
    if(ComboInf.equals("list1")//only works for stand-alone Jframe
    -->ComboBox2Thank you very much again for your answer
    BJoa

    Cast the event source object to what you added the listener to, here JComboBox
        JComboBox comboBox1 = new JComboBox();
        public void actionPerformed(ActionEvent e)
            JComboBox combo = (JComboBox)e.getSource();
            if(combo == comboBox1)
                doSomethingWith comboBox1();
            if(combo == comboBox2)
        }

  • How to add event handler to JTable?

    I need an event listener that tells me whenever a cell has been edited. Does anyone have any ideas on how to implement this. There doesn't seem to be much documentation on the subject.
    Thanks in advance..
    dosteov

    Hello,
    It looks like you are interested in the
    BeforeAttachmentAdd event of Outlook items. It is fired before an attachment is added to an instance of the parent object. So, you can analyze the attachment object passed as a parameter and set then Cancel argument - set
    it to true to cancel the operation; otherwise, set to false to allow the Attachment to
    be added.
    Also the Outlook object model provides the
    AttachmentAdd event for Outlook items. It is fired when an attachment has been added to an instance of the parent object. You can also analyze the attachment object passed as a parameter to the event handler. You will not be able to
    cancel the action in that case.

  • Button Event Handler in a JList, Please help.

    Hi everyone,
    I have created a small Java application which has a JList. The JList uses a custom cell renderer I named SmartCellRenderer. The SmartCellRenderer extends JPanel and implements the ListCellRenderer. I have added two buttons on the right side inside the JPanel of the SmartCellRenderer, since I want to buttons for each list item, and I have added mouse/action listeners for both buttons. However, they don't respond. It seems that the JList property overcomes the buttons underneath it. So the buttons never really get clicked because before that happens the JList item is being selected beforehand. I've tried everything. I've put listeners in the Main class, called Editor, which has the JList and also have listeners in the SmartCellRenderer itself and none of them get invoked.
    I also tried a manual solution. Every time the event handler for the JList was invoked (this is the handler for the JList itself and not the buttons), I sent the mouse event object to the SmartCellRenderer to manually check if the point the click happened was on one of the buttons in order to handle it.
    I used:
    // Inside SmartCellRenderer.java
    // e is the mouse event object being passed from the Editor whenever
    // a JList item is selected or clicked on
    Component comp = this.getComponent (e.getX(), e.getY())
    if(!(comp instanceof JButton)) {
              System.out.println("Recoqnized Event, but not a button click...");
              //return;
    } else {
              System.out.println("Recognized Event, IT IS A MOUSE CLICK, PROCESSING...");
              System.out.println("VALUE: "+comp.toString());
    What I realized is that not only this still doesn't work (it never realizes the component as a JButton) it also throws an exception for the last line saying comp is null. Meaning with the passed x,y position the getComponent() returns a null which happens when the coordinates passed to it are outside the range of the Panel. Which is a whole other problem?
    I have yet to find an example on the web, using Google, that demonstrated using buttons inside a JList.
    Can anyone help me with this. Thanks.

    A renderer is not a component, so you can't click on it. A renderer is just used to paint a representation of a component at a certain position in your JList.
    I have yet to find an example on the web, using Google, that demonstrated using buttons inside a JList.Thats probably because this is not a common design. The following two designs are more common:
    a) Create a separate panel for your JButtons. Then when you click on the button it would act on each selected row in the JList
    b) Or maybe like windows explorer. Select the items in the list and then use a JPopupMenu to perform the desired functionality.
    I've never tried to add a clickable button to a panel, but this [url http://forum.java.sun.com/thread.jspa?threadID=573721]posting shows one way to add a clickable JButton as a column in a JTable. You might be able to use some of the concepts to add 2 button to the JPanel or maybe you could use a JTable with 3 columns, one for your data and the last two for your buttons.

  • Bug: RichTextEditor "Initialize" not classed as event handler

    I'm trying to load the RichTextEditor control in a popup window. Here's my code:
    var rte:RichTextEditor = new RichTextEditor();
    rte.width   =  600;
    rte.height  =  500;
    rte.title   =  'Edit Text';
    I need to add the initialize event handler so I can add a button to the toolbar (as per the example on the Adobe website).
    However, when I type:
    rte.initialize  =  "addSaveButton()";
    Flash Builder says this is invalid as "initialize" is actually a function and doesn't accept any parameters.
    Compare this with:
    <mx:RichTextEditor initialize="addSaveButton()"/>
    Flash Builder recongises "initialize" as an event handler and therefore accepts the addSaveButton() function.
    Can anyone else confirm whether this is a bug with the SDK or not? I can simply add the button outside of the RTE for now, but then I'd have to wrap the RTE in a separate panel to accomodate the button, which isn't ideal.
    Thanks in advance.

    Hi,
    this is how to add the event listener
    rte.addEventListener(FlexEvent.INITIALIZE,addSaveButton);
    David.

  • Event Handling Help needed please.

    Hi,
    I am writing a program to simulate a supermarket checkout. I have done the GUI and now i am trying to do the event handling. I have come up against a problem.
    I have a JCombobox called prodList and i have added an string array to it called prods . I have also created 2 more arrays with numbers in them.
    I want to write the code for if an item is selected from the combo box that the name from the array is shown in a textfield tf1, and also the price and stock no which correspond to the seclected item (both initialised in the other arrays) are also added to the textfield tf1.
    I have started writng the code but i am really stuck. Could someone please help me with this please. The code i have done so far is as follows(just the event handling code shown)
              public void ItemStateChange(ItemEvent ie){
              if(ie.getItemSelected()== prodList)
                   changeOutput();
              public void changeOutput()
                   if(ItemSelected ==0)
                        tf1.setText("You have selected" +a +b +c);
         }

    Do you say this because i missed the d of ItemStateChanged ?
    I have amended that but still i am getting the same errors class or enum expected. 4 of them relating to the itemStateChanged method.
    i will post my whole code if it helps
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Observer;  //new
    import java.util.Observable;//new
    import javax.swing.BorderFactory;
    import javax.swing.border.Border;
    import javax.swing.border.TitledBorder;
    public class MySuperMktPro
         public MySuperMktPro()
              CheckoutView Check1 = new CheckoutView(1,0,0);
              CheckoutView Check2 = new CheckoutView(2,300,0);
              CheckoutView Check3 = new CheckoutView(3,600,0);
              CheckoutView Check4 = new CheckoutView(4,0,350);
              CheckoutView Check5 = new CheckoutView(5,600,350);
              OfficeView off111 = new OfficeView();
        public static void main(String[] args) {
             // TODO, add your application code
             System.out.println("Starting My Supermarket Project...");
             MySuperMktPro startup = new MySuperMktPro();
        class CheckoutView implements ItemListener , ActionListener
        private OfficeView off1;
         private JFrame chk1;
         private Container cont1;
         private Dimension screensize,tempDim;
         private JPanel pan1,pan2,pan3,pan4,pan5;
         private JButton buyBut,prodCode;
         private JButton purchase,cashBack,manual,remove,disCo;
         private JButton but1,but2,finaLi1,but4,but5,but6;
         private JTextArea tArea1,tArea2;
         private JTextField tf1,tf2,tf3,list2;
         private JComboBox prodList;
         private JLabel lab1,lab2,lab3,lab4,lab5,lab6,lab7;
         private int checkoutID; //New private int for all methods of this class
         private int passedX,passedY;
         private String prods[];
         private JButton rb1,rb2,rb3,rb4;
         private double price[];
         private int code[];
         public CheckoutView(int passedInteger,int passedX,int passedY)
              checkoutID = passedInteger; //Store the int passed into the method
            this.passedX = passedX;
            this.passedY = passedY;
              drawCheckoutGui();
         public void drawCheckoutGui()
              prods= new String[20];
              prods[0] = "Beans";
              prods[1] = "Eggs";
              prods[2] = "bread";
              prods[3] = "Jam";
              prods[4] = "Butter";
              prods[5] = "Cream";
              prods[6] = "Sugar";
              prods[7] = "Peas";
              prods[8] = "Milk";
              prods[9] = "Bacon";
              prods[10] = "Spaghetti";
              prods[11] = "Corn Flakes";
              prods[12] = "Carrots";
              prods[13] = "Oranges";
              prods[14] = "Bananas";
              prods[15] = "Snickers";
              prods[16] = "Wine";
              prods[17] = "Beer";
              prods[18] = "Lager";
              prods[19] = "Cheese";
              for(i=0; i<prods.length;i++);
              code = new int [20];
              code[0] = 1;
              code[1] = 2;
              code[2] = 3;
              code[3] = 4;
              code[4] = 5;
              code[5] = 6;
              code[6] = 7;
              code[7] = 8;
              code[8] = 9;
              code[9] = 10;
              code[10] = 11;
              code[11] = 12;
              code[12] = 13;
              code[13] = 14;
              code[14] = 15;
              code[15] = 16;
              code[16] = 17;
              code[17] = 18;
              code[18] = 19;
              code[19] = 20;
              for(b=0; b<code.length; b++);
              price = new double [20];
              price[0] = 0.65;
              price[1] = 0.84;
              price[2] = 0.98;
              price[3] = 0.75;
              price[4] = 0.45;
              price[5] = 0.65;
              price[6] = 1.78;
              price[7] = 1.14;
              price[8] = 0.98;
              price[9] = 0.99;
              price[10] = 0.98;
              price[11] = 0.65;
              price[12] = 1.69;
              price[13] = 2.99;
              price[14] = 0.99;
              price[15] = 2.68;
              price[16] = 0.89;
              price[17] = 5.99;
              price[18] = 1.54;
              price[19] = 2.99;
              for(c=0; c<code.length; c++);
              screensize = Toolkit.getDefaultToolkit().getScreenSize();
              chk1 = new JFrame();
              chk1.setTitle("Checkout #" + checkoutID); //Use the new stored int
              chk1.setSize(300,350);
              chk1.setLocation(passedX,passedY);
              chk1.setLayout(new GridLayout(5,1));
              //chk1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              cont1 = chk1.getContentPane();
              //chk1.setLayout(new BorderLayout());
                 pan1 = new JPanel();
                 pan2 = new JPanel();
              pan3 = new JPanel();
              pan4 = new JPanel();
              pan5 = new JPanel();
              //panel 1
              pan1.setLayout(new FlowLayout());
              pan1.setBackground(Color.black);          
              prodList = new JComboBox(prods);
              prodList.setMaximumRowCount(2);
              prodList.addItemListener(this);
              but1 = new JButton("Buy");
              but1.addActionListener(this);
              lab1 = new JLabel("Products");
              lab1.setForeground(Color.white);
              lab1.setBorder(BorderFactory.createLineBorder(Color.white));
              pan1.add(lab1);
              pan1.add(prodList);          
              pan1.add(but1);
              //panel 2
              pan2 = new JPanel();
              pan2.setLayout(new BorderLayout());
              pan2.setBackground(Color.black);
              lab3 = new JLabel("                                Enter Product Code");
              lab3.setForeground(Color.white);
              tArea2 = new JTextArea(8,10);
              tArea2.setBorder(BorderFactory.createLineBorder(Color.white));
              lab5 = new JLabel("  Tesco's   ");
              lab5.setForeground(Color.white);
              lab5.setBorder(BorderFactory.createLineBorder(Color.white));
              lab6 = new JLabel("Checkout");
              lab6.setForeground(Color.white);
              lab6.setBorder(BorderFactory.createLineBorder(Color.white));
              lab7 = new JLabel("You  selected                      ");
              lab7.setForeground(Color.cyan);
              //lab7.setBorder(BorderFactory.createLineBorder(Color.white));
              pan2.add(lab7,"North");
              pan2.add(lab6,"East");
              pan2.add(tArea2,"Center");
              pan2.add(lab5,"West");
              pan2.add(lab3,"South");
              //panel 3
              pan3 = new JPanel();
              pan3.setLayout(new FlowLayout());
              pan3.setBackground(Color.black);
              manual = new JButton("Manual");
              manual.addActionListener(this);
              manual.setBorder(BorderFactory.createLineBorder(Color.white));
              remove = new JButton("Remove");
              remove.addActionListener(this);
              remove.setBorder(BorderFactory.createLineBorder(Color.white));
              tf1 = new JTextField(5);
              pan3.add(manual);
              pan3.add(tf1);
              pan3.add(remove);
              //panel 4
              pan4 = new JPanel();
              pan4.setLayout(new FlowLayout());
              pan4.setBackground(Color.black);
              finaLi1 = new JButton("Finalise");
         //     finaLi1.addActionListener(this);
              cashBack = new JButton("Cashback");
              JTextField list2 = new JTextField(5);
              but4 = new JButton(" Sum Total");
              but4.addActionListener(this);
              but4.setBorder(BorderFactory.createLineBorder(Color.white));
              cashBack.setBorder(BorderFactory.createLineBorder(Color.white));
              pan4.add(cashBack);
              pan4.add(list2);
              pan4.add(but4);
              //panel 5
              pan5 = new JPanel();
              pan5.setLayout(new GridLayout(2,3));
              pan5.setBackground(Color.black);
              disCo = new JButton("Discount");
              disCo.addActionListener(this);
              disCo.setBorder(BorderFactory.createLineBorder(Color.black));
              but6 = new JButton("Finalise");
              but6.addActionListener(this);
              but6.setBorder(BorderFactory.createLineBorder(Color.black));
              rb1 = new JButton("Cash");
              rb1.addActionListener(this);
              rb1.setBorder(BorderFactory.createLineBorder(Color.black));
              rb2 = new JButton("Card");
              rb2.addActionListener(this);
              rb2.setBorder(BorderFactory.createLineBorder(Color.black));
              rb3 = new JButton("Cheque");
              rb3.addActionListener(this);
              rb3.setBorder(BorderFactory.createLineBorder(Color.black));
              rb4 = new JButton("Voucher");
              rb4.addActionListener(this);
              rb4.setBorder(BorderFactory.createLineBorder(Color.black));
              pan5.add(disCo);
              pan5.add(but6);
              pan5.add(rb1);
              pan5.add(rb2);
              pan5.add(rb3);
              pan5.add(rb4);
              //add the panels to the container        
              cont1.add(pan1);
              cont1.add(pan4);     
              cont1.add(pan2);
              cont1.add(pan3);          
              cont1.add(pan5);          
              chk1.setContentPane(cont1);
              chk1.setVisible(true);     
    class OfficeView
         private OfficeView off111;
         private JFrame offMod1;
         private JPanel pane1;
         private JButton refill;
         private Container cont11;
         private Dimension screensize;
         private JTextField tf11,tf12;
         public OfficeView()
              drawOfficeGUI();
         public void drawOfficeGUI()
              screensize = Toolkit.getDefaultToolkit().getScreenSize();
              offMod1 = new JFrame("Office Control");
              int frameWidth = 300;
              int frameHeight = 250;
              offMod1.setSize(frameWidth,frameHeight);
              offMod1.setLocation(300,350);
              offMod1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              cont11 = offMod1.getContentPane();
              pane1 = new JPanel();
              pane1.setBackground(Color.cyan);
              refill = new JButton("Refill");
              tf11 = new JTextField(25);
              tf12 = new JTextField(25);
              pane1.add(tf11);
              pane1.add(refill);
              pane1.add(tf12);
              cont11.add(pane1);
              offMod1.setContentPane(cont11);
              offMod1.setVisible(true);
              public void ItemStateChanged(ItemEvent ie)
                        if(ie.getItemSelected()== prodList)
                                  changeOutput();
              public void changeOutput()
                        if(ItemSelected ==0)
                                  tf1.setText("You have selected", +a +b +c);
                   }Message was edited by:
    fowlergod09

  • GUI event handling problems appear in 1.4.1 vs. 1.3.1?

    Hi,
    Has anyone else experienced strange event handling problems when migrating from 1.3.1 to 1.4.1? My GUI applications that make use of Swing's AbstractTableModel suddenly don't track mouse and selection events quickly anymore. Formerly zippy tables are now very unresponsive to user interactions.
    I've run the code through JProbe under both 1.3 and 1.4 and see no differences in the profiles, yet the 1.4.1 version is virtually unusable. I had hoped that JProbe would show me that some low-level event-handling related or drawing method was getting wailed on in 1.4, but that was not the case.
    My only guess is that the existing installation of 1.3.1 is interfering with the 1.4.1 installation is some way. Any thoughts on that before I trash the 1.3.1 installation (which I'm slightly reluctant to do)?
    My platform is Windows XP Pro on a 2GHz P4 with 1GB RAM.
    Here's my test case:
    import javax.swing.table.AbstractTableModel;
    import javax.swing.*;
    import java.awt.*;
    public class VerySimpleTableModel extends AbstractTableModel
    private int d_rows = 0;
    private int d_cols = 0;
    private String[][] d_data = null;
    public VerySimpleTableModel(int rows,int cols)
    System.err.println("Creating table of size [" + rows + "," + cols +
    d_rows = rows;
    d_cols = cols;
    d_data = new String[d_rows][d_cols];
    int r = 0;
    while (r < d_rows){
    int c = 0;
    while (c < d_cols){
    d_data[r][c] = new String("[" + r + "," + c + "]");
    c++;
    r++;
    System.err.println("Done.");
    public int getRowCount()
    return d_rows;
    public int getColumnCount()
    return d_cols;
    public Object getValueAt(int rowIndex, int columnIndex)
    return d_data[rowIndex][columnIndex];
    public static void main(String[] args)
    System.err.println( "1.4..." );
    JFrame window = new JFrame();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    Dimension size = new Dimension(500,500);
    panel.setMinimumSize(size);
    panel.setMaximumSize(size);
    JTable table = new JTable(new VerySimpleTableModel(40,5));
    panel.add(table);
    window.getContentPane().add(panel);
    window.setSize(new Dimension(600,800));
    window.validate();
    window.setVisible(true);
    Thanks in advance!!
    - Dean

    Hi,
    I've fixed the problem by upgrading to 1.4.1_02. I was on 1.4.1_01.
    I did further narrow down the symptoms more. It seemed the further the distance from the previous mouse click, the longer it would take for the table row to highlight. So, clicking on row 1, then 2, was much faster than clicking on row 1, then row 40.
    If no one else has seen this problem -- good! I wouldn't wish the tremendous waste of time I've had on anyone!
    - Dean

  • Editable JComboBox in a JTable

    I posted my problem into the "Java Essentials/Java programming" forum but it would be much better if I'd posted it here into the swing theme :).
    Here it is what I posted:
    Funky_1321
    Posts:8
    Registered: 2/22/06
    editable JComboBox in a JTable
    Oct 21, 2006 1:32 PM
    Click to email this message
    Hello!
    Yesterday I posted a problem, solved it and there's another one, referring the same theme.
    So it's about a editable JComboBox with autocomplete function. The combo is a JTables cellEditors component. So it's in a table. So when the user presses the enter key to select an item from the JComboBox drop down menu, I can't get which item is it, not even which index has the item in the list. If for exemple the JComboBox isn't in a table but is added on a JPanel, it works fine. So I want to get the selectedItem in the actionPerformed method implemented in the combo box. I always get null instead of the item.
    Oh... if user picks up some item in the JComboBox-s list with the mouse, it's working fine but I want that it could be picked up with the enter key.
    Any solutions appreciated!
    Thanks, Tilen
    YAT_Archivist
    Posts:1,321
    Registered: 13/08/05
    Re: editable JComboBox in a JTable
    Oct 21, 2006 1:55 PM (reply 1 of 2)
    Click to email this message
    I suggest that you distill your current code into a simple class which has the following attributes:
    1. It can be copied and pasted and will compile straight out.
    2. It has a main method which brings up a simple example frame.
    3. It's no more than 50 lines long.
    4. It demonstrates accurately what you've currently got working.
    Without that it's hard to know exactly what you're currently doing, and requires a significant investment of time for someone who hasn't already solved this problem before to attempt to help. I'm not saying that you won't get help if you don't post a simple demo class, but it will significantly improve your chances.
    Funky_1321
    Posts:8
    Registered: 2/22/06
    Re: editable JComboBox in a JTable
    Oct 21, 2006 2:11 PM (reply 2 of 2)
    Click to email this message
    Okay ... I'll write the code in short format:
    class acJComboBox extends JComboBox {
      public acJComboBox() {
        this.setEditable(true);
        this.setSelectedItem("");
        this.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) {
         // ... code code code
         // that's tricky ... the method getSelectedItem() always returns null - remember; the acJComboBox is in a JTable!
         if (e.getKeyCode() == 10 && new String((String)getEditor().getItem()).length() != 0) { getEditor().setItem(getSelectedItem()); }
    }And something more ... adding the acJComboBox into the JTable:
    TableColumn column = someTable.getColumn(0);
    column.setCellEditor(new DefaultCellEditor(new acJComboBox());
    So if the user presses the enter key to pick up an item in the combo box drop down menu, it should set the editors item to the selected item from the drop down menu (
    getEditor().setItem(getSelectedItem());
    When the acJComboBox is on a usual JPanel, it does fine, but if it's in the JTable, it doesn't (getSelectedItem() always returns null).
    Hope I described the problem well now ;).

    Okay look ... I couldn't write a shorter code just for an example. I thought that my problem could be understoodable just in mind. However ... type in the first combo box the letter "i" and then select some item from the list with pressing the enter key. Do the same in the 2nd combo box who's in the JTable ... the user just can't select that way if the same combo is in the JTable. Why? Thanks alot for future help!
    the code:
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.Vector;
    import javax.swing.DefaultCellEditor;
    import javax.swing.DefaultComboBoxModel;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumn;
    class Example extends JFrame {
        private String[] columns = { "1", "2", "3" };
        private String[][] rows = {};
        private DefaultTableModel model = new DefaultTableModel(rows, columns);
        private JTable table = new JTable(model);
        private JScrollPane jsp = new JScrollPane(table);
        private acJComboBox jcb1 = new acJComboBox();
        private acJComboBox jcb2 = new acJComboBox();
        public Example() {
            // initialize JFrame
            this.setLayout(null);
            this.setLocation(150, 30);
            this.setSize(300, 300);
            this.setDefaultCloseOperation(EXIT_ON_CLOSE);
            // initialize JFrame
            // initialize components
            Vector<String> v1 = new Vector<String>();
            v1.add("item1");
            v1.add("item2");
            v1.add("item3");
            jcb1.setData(v1);
            jcb2.setData(v1);
            jcb1.setBounds(30, 30, 120, 20);
            jsp.setBounds(30, 70, 250, 100);
            add(jcb1);
            add(jsp);
            TableColumn column = table.getColumnModel().getColumn(0);
            column.setCellEditor(new DefaultCellEditor(jcb2));
            Object[] data = { "", "", "" };
            model.addRow(data);
            // initialize components
            this.setVisible(true);
        public static void main(String[] args) {
            Example comboIssue = new Example();
    class acJComboBox extends JComboBox {
        private Vector<String> data = new Vector<String>();
        private void init() {
            this.setEditable(true);
            this.setSelectedItem("");
            this.setData(this.data);
            this.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent e) {
                        if (e.getKeyCode() != 38 && e.getKeyCode() != 40) {
                            String a = getEditor().getItem().toString();
                            setModel(new DefaultComboBoxModel());
                            int st = 0;
                            for (int i = 0; i < getData().size(); i++) {
                                String str1 = a.toUpperCase();
                                String tmp = (String)getData().get(i).toUpperCase();
                                if (str1.length() <= tmp.length()) {
                                    String str2 = tmp.substring(0, str1.length());
                                    if (str1.equals(str2)) {
                                        DefaultComboBoxModel model = (DefaultComboBoxModel)getModel();
                                        model.insertElementAt(getData().get(i), getItemCount());
                                        st++;
                            getEditor().setItem(new String(a));
                            JTextField jtf = (JTextField)e.getSource();
                            jtf.setCaretPosition(jtf.getDocument().getLength());
                            hidePopup();
                            if (st != 0 && e.getKeyCode() != 10 && new String((String)getEditor().getItem()).length() != 0) { showPopup(); }
                            if (e.getKeyCode() == 10 && new String((String)getEditor().getItem()).length() != 0) { getSelectedItem(); }
                            if (new String((String)getEditor().getItem()).length() == 0) { whenEmpty(); }
            this.addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent e) {
                hidePopup();
        // - constructors -
        public acJComboBox() {
            init();
        public acJComboBox(Vector<String> data) {
            this.data = data;
            init();
        // - constructors -
        // - interface -
        public void whenEmpty() { } // implement if needed
        public void setData(Vector<String> data) {
            this.data = data;
            for (int i = 0; i < data.size(); i++) {
                this.addItem(data.get(i));
        public Vector<String> getData() {
            return this.data;
        // - interface -
    }

Maybe you are looking for

  • Connect macbook pro 13" (2.7 GHz) to a plasma panasonic 42" TV with a rocketfish adapter

    (macpro13" 2.7GHz) I have a rocketfish HDMI adapter connected to a 42 inch plasma panasonic and it is not displaying any video or audio (does display blue screen as if properly connecting). attempted to play music and got occasional pops. Why is it n

  • Please Guide

    Hi, In J2SE, while using SSL, we create key-stores and trust-stores using keytool. Now, if I want to use HTTPS to transfer a msg to a Server that is implemented in C, how do I go about... Here I have my client implemented in Java? Will trust-store ex

  • Client attribute returning null value in adf

    hi i am using jdev version = 11.1.1.5.0 I have 2inputs and 2buttons in my adf form.One of my input boxes calls a javascript function using client listener,I need ids of remaining 1input and 2buttons and I am using client attribute. All the controls h

  • [Solved] Broke my install (a little bit) - /usr issue?

    Hi folks, I am new to Arch Linux and until now I have had great success with configuring my system and have learnt a lot ... until I tried a little experiment to compressing my /usr folder as per these instructions http://forums.gentoo.org/viewtopic-

  • Thumbnails in iMovie are displaying incorrect photos

    I have an iMovie project open and added photos to the project timeline. I had everything set but somehow iMovie is now showing the correct thumbnail but when I mouse over the preview shows the incorrect photo... i exported anyway just to see if it wa