Help with JComboBox-JTable

Hi there!
I'll try to explain my problem the best I can, I hope you can understand me so you may get to help me, I'd really appreciate it. I'm trying to make a JTable to render a cell as a JComboBox, that's ok and it's working fine. The problem comes when I try to change the combo value. The itemStateChanged method is supposed to get some values from a database, if the first is bigger than the second it shows an alert, else it makes an update to the database. Now, the problem is that, if the combobox default value is blank (""), it works fine, but if it's filled with something as a name ("anything") it automatically shows the alert, even if I'm not changing the combo value. The second problem is that it shows the alert twice, I'll try to explain with code:
class Cambia_Cita extends javax.swing.AbstractCellEditor implements javax.swing.table.TableCellEditor ,java.awt.event.ItemListener{
    protected EventListenerList listenerList = new EventListenerList();
    protected ChangeEvent changeEvent = new ChangeEvent(this);   
    protected javax.swing.JComboBox combo = new javax.swing.JComboBox();
    int i;
    String valor = "";
    int j;
    javax.swing.JTable tabla = new javax.swing.JTable();
    public Cambia_Cita() {
        super();
        combo.addItemListener(this);
        Base base = new Base();
        Statement sta = base.conectar();
        try {
            ResultSet rs = sta.executeQuery("SELECT DISTINCT Nombre_Completo FROM Pacientes WHERE Alta = 'n'");
            combo.addItem("");
            while(rs.next())
                combo.addItem(rs.getString("Nombre_Completo"));
        }catch(SQLException e) {
            System.out.println (e.getMessage());
        } finally {
            base.cerrar(sta);
        combo.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                System.out.println("algo");
                tabla.setValueAt(valor,i,j);
    public Object getCellEditorValue() {
        return(combo.getSelectedItem());
    public java.awt.Component getTableCellEditorComponent(javax.swing.JTable table, Object value, boolean isSelected, int row, int column) {
        i = row;
        j = column;
        tabla = table;
        valor = value.toString();
        combo.setSelectedItem(tabla.getValueAt(i,j));
        System.out.println (i + "," + j);
        java.awt.Component c = table.getDefaultRenderer(String.class).getTableCellRendererComponent(table, value, isSelected, false, row, column);
        if (c != null) {
            combo.setBackground(c.getBackground());
        return combo;
    public void itemStateChanged(java.awt.event.ItemEvent e) {
        Base base = new Base();
        Statement sta = base.conectar();
        try {
            String asist;
            if (tabla.getValueAt(i,3).equals(new Boolean(true))) {
                asist = "s";
            } else {
                asist = "n";
            ResultSet rs = sta.executeQuery("SELECT COUNT(ID_Cita) FROM Cita JOIN Pacientes ON Cita.RFC_Paciente " +
                    "= Pacientes.RFC_Paciente WHERE Nombre_Completo = '" + combo.getSelectedItem() + "'");
            rs.next();
            int result = rs.getInt("COUNT(ID_Cita)");
            rs = sta.executeQuery("SELECT Consultas FROM Ciclo JOIN Pacientes ON Ciclo.RFC_Paciente = Pacientes." +
                    "RFC_Paciente WHERE Nombre_Completo = '"+ combo.getSelectedItem() +"' AND Ciclo.Numero_Ciclo = " +
                    "Pacientes.Ciclo");
            rs.next();
            int maximo = rs.getInt("Consultas");
            /* if maximo is bigger than result plus 1, then it shows the alert, but it is shown even if I don't change the combo value!!!, this part only works if the default value of the combo is blank */
            if (maximo >= result +1 ) {
                sta.executeUpdate("UPDATE Cita,Pacientes SET Cita.RFC_Paciente = Pacientes.RFC_Paciente WHERE " +
                        "Nombre_Completo = '" + combo.getSelectedItem() + "' AND ID_Cita = " + tabla.getValueAt(i,0));
            }else
                javax.swing.JOptionPane.showMessageDialog(null,"No se puede agregar otra cita...");
        }catch (ArrayIndexOutOfBoundsException ex) {
            System.out.println (ex.getMessage());
        } catch (SQLException ex) {
            System.out.println (ex.getMessage());
        } finally {
            base.cerrar(sta);
}So, I'd like to know why the alert appears twice when it works and why it appears even if the combo value ain't changed. I really hope anyone can help me. Thank you!

if the first is bigger than the second it shows an alertIf you want to know when data is changed in the table then you use a TableModelListener, not an ItemListener. Here is a simple example:
http://forum.java.sun.com/thread.jspa?forumID=57&threadID=566133
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 (SSCCE) 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.

Similar Messages

  • Help with dispatching JTable event to underlying components in a cell.

    Hello..
    I have a JTable in which i show a panel with clickable labels.. I found that jTable by default doesnt dispatch or allow mouseevents to be caught by underlying elements..
    i need help with dispatching an event from jTable to a label on a panel in a jTable cell.. below is the code i have come up with after finding help with some websites. but i couldnt not get it right.. my dispatched event seems to go back to the jtable itself ..
    any help or suggestion is appreciated..
    Thanks
    'Harish.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.table.*;
    * @author  harish
    public class tableDemo extends javax.swing.JFrame {
        JTable jTable1;
        testpane dummyPane;
        /** Creates new form tableDemo */
        public tableDemo() {
            initComponents();
            //table settings
            String[] columnNames = {"Task", "Action"," "};
            Object[][] data = { };
            DefaultTableModel model = new DefaultTableModel(data, columnNames) {
              // This method returns the Class object of the first
              // cell in specified column in the table model.
            public Class getColumnClass(int mColIndex) {
                int rowIndex = 0;
                Object o = getValueAt(rowIndex, mColIndex);
                if (o == null)
                    return Object.class;
                } else
                    return o.getClass();
            jTable1 = new javax.swing.JTable(model);
            jTable1.addMouseListener(new MouseAdapter(){
              public void mouseClicked(MouseEvent e){
                  System.out.println("Clicked");
                  handleTableMouseEvents(e);
                 //invokeExternalApp("http://www.pixagogo.com");
              public void mouseEntered(MouseEvent e){
                  System.out.println("Entered");
                  //handleTableMouseEvents(e);
              public void mouseExited(MouseEvent e){
                  System.out.println("Exited");
                  //handleTableMouseEvents(e);
            jTable1.setRowHeight(100);
            jTable1.getTableHeader().setReorderingAllowed(false);
            jTable1.setBackground(new java.awt.Color(255, 255, 255));
            jTable1.setGridColor(new Color(250,250,250));
            jTable1.setShowGrid(true);
            jTable1.setShowVerticalLines(true);
            jTable1.setShowHorizontalLines(false);
            jTable1.setFont(new Font("Arial",0,11));
            jTable1.setMaximumSize(new java.awt.Dimension(32767, 32767));
            jTable1.setMinimumSize(new java.awt.Dimension(630, 255));
            jTable1.setPreferredSize(null);
            jTable1.setBackground(new Color(255,255,255));
            int vColIndex=0;
            TableColumn col = jTable1.getColumnModel().getColumn(vColIndex);
            int width = 100;
            col.setPreferredWidth(width);
            //add item to 2nd cell       
            Vector vec = new Vector();
            vec.addElement(null);
            dummyPane = new testpane();
            vec.addElement(dummyPane);
            ((DefaultTableModel)jTable1.getModel()).addRow(vec);
            jTable1.repaint();
            this.getContentPane().add(jTable1);
            jTable1.getColumn("Action").setCellRenderer(
              new MultiRenderer());
        protected void handleTableMouseEvents(MouseEvent e){
            TableColumnModel columnModel = jTable1.getColumnModel();
            int column = columnModel.getColumnIndexAtX(e.getX());
            int row    = e.getY() / jTable1.getRowHeight();
            testpane contentPane = (testpane)(jTable1.getModel().getValueAt(row, column));
            // get the mouse click point relative to the content pane
            Point containerPoint = SwingUtilities.convertPoint(jTable1, e.getPoint(),contentPane);
            if (column==1 && row==0)
            // so the user clicked on the cell that we are bothered about.         
            MouseEvent ev1 = (MouseEvent)SwingUtilities.convertMouseEvent(jTable1, e, contentPane);
            //once clicked on the cell.. we dispatch event to the object in that cell
         jTable1.dispatchEvent(ev1);
        private void initComponents() {
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-528)/2, (screenSize.height-423)/2, 528, 423);
        /** Exit the Application */
        private void exitForm(java.awt.event.WindowEvent evt) {
            System.exit(0);
         * @param args the command line arguments
        public static void main(String args[]) {
            new tableDemo().show();
        // Variables declaration - do not modify
        // End of variables declaration
        class testpane extends JPanel{
            public testpane(){
            GridBagConstraints gridBagConstraints;
            JPanel testpane = new JPanel(new GridBagLayout());
            testpane.setBackground(Color.CYAN);
            JLabel lblTest = new JLabel("test");
            lblTest.addMouseListener(new MouseAdapter(){
              public void mouseClicked(MouseEvent e){
                  System.out.println("panelClicked");
              public void mouseEntered(MouseEvent e){
                  System.out.println("panelEntered");
              public void mouseExited(MouseEvent e){
                  System.out.println("panelExited");
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.gridx = 0;
            gridBagConstraints.gridy = 0;
            gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
            testpane.add(lblTest,gridBagConstraints);
            this.add(testpane);
    class MultiRenderer extends DefaultTableCellRenderer {
      JCheckBox checkBox = new JCheckBox();
      public Component getTableCellRendererComponent(
                         JTable table, Object value,
                         boolean isSelected, boolean hasFocus,
                         int row, int column) {
        if (value instanceof Boolean) {                    // Boolean
          checkBox.setSelected(((Boolean)value).booleanValue());
          checkBox.setHorizontalAlignment(JLabel.CENTER);
          return checkBox;
        String str = (value == null) ? "" : value.toString();
        return super.getTableCellRendererComponent(
             table,str,isSelected,hasFocus,row,column);
        return (testpane)value;
    class MultiEditor implements TableCellEditor {
      public MultiEditor() {
      public boolean isCellEditable(EventObject anEvent) {return false;}
      public boolean stopCellEditing() {return true;}
      public Object getCellEditorValue() {return null;} 
      public void cancelCellEditing() {}
      public boolean shouldSelectCell(EventObject anEvent) {return false;}
      public Component getTableCellEditorComponent(JTable table, Object value,
                  boolean isSelected, int row, int column) {
        if (value instanceof testpane) {                       // ComboString
          System.out.println("yes instance");
        return null;
      public void addCellEditorListener(javax.swing.event.CellEditorListener l) {
      public void removeCellEditorListener(javax.swing.event.CellEditorListener l) {
    }

    any help on this.. anybody. ?

  • Help with JcomboBoxes

    Hi,
    Im having trouble with a combobox
    I have created a bean class for an ftp site, that contains;
    - ftp site name
    - address
    - username
    - password
    I then create an array of these sites and add them to the jComboBox.
    I only want to display the ftp site name in the box, however, when i select a certain site, i then want to pass the rest of the info. (ie. address, username, and password) to a connect method i have in another class.
    I'm quite sure this is a reasonably simply task but i just cant get my head around it.
    can anybody please help me?
    Much Thanks!

    Check out this posting for a solution:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=613731

  • Help with uneditable JTable - frustrated

    can someone please give me WORKING code (not, oh it is easy do this and that) to make the whole JTable uneditable? if you give me the abstract model with cell renderer, i will put in the JTable using the:
    JTable (yourAbstractModel)
    my JTable is 100 percent purely DYNAMIC. i will have no idea how many columns there may be until after the user chooses the columns to see (which i have working).
    when a user selects a row, i will set the column to a
    light gray .
    after a day, i was able to get the columns to stop shrinking and let the scoll bars work on the scroll pane (after going to some 20 web sites looking at code). i am very frustrated.
    i do need to get the value of a cell to determine which record they are going to edit.
    THANKS FOR ANY HELP!!!!!

    SORRY
    this >
    when a user selects a row, i will set the column to a
    light gray .
    should READ >
    when a user selects a row, i will set the ROW to a
    light gray .

  • Web Guy Using Swing - Need Help With jComboBox

    I'm new to doing desktop Java development (come from a web application background) and am trying to accomplish migrating some of a web application's functionality to a desktop app for distribution. I'm already a bit stuck when it comes to using the jComboBox. What is intuitive to me in the web world would be to have one combo box/select box that after making a selection, it returns it's value so I could use that to run another query that would populate the next drop down menu. Populating the display of the combo box isn't the problem, that seems easy enough, but what I so far can't find is how I can attach a value to the combo box; that is for instance, having the drop down show a list of country names, and needing to have that list of country names correspond to a country code. For the web, you'd just have the option value tied to the code and the contents of the option be the name.
    Is this do-able? Am I completely thinking about this in the wrong way when working in desktop GUI things? I am using NetBeans 6.0 for my GUI layout and such, don't know if that helps or hurts matters. Also currently using Java 1.5.
    Any information or points in the right direction are greatly appreciated.
    Cheers.

    If I understand you correctly, you need to have a class that holds country name and country code, with a toString override method that returns just the country name (this is what the combobox shows). You then put an array of these objects in your jcombobox, obtain the selected object, get it's country code, and you're off and running.
    Edited by: Encephalopathic on Mar 31, 2008 3:26 PM

  • Hi, i need help with a jtable

    hi, iam new here, i try to read an excel file, and put the rows and columns in a jtable, i dont have the code exactly but maybe someone can help me.

    You can use this
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    //String myDB ="myExcel";
    String myDB =  "jdbc:odbc:Driver={Microsoft Excel Driver (*.xls)};DBQ=c:/book.xls;"
        + "DriverID=22;READONLY=false";
    //con=DriverManager.getConnection("jdbc:odbc:myExcel");
    con=DriverManager.getConnection(myDB,"","");
    dbmd=con.getMetaData();
    stat=con.createStatement();
    rs=stat.executeQuery("Select * from `Sheet1$`");//[Sheet1$]
    ResultSetMetaData rsmd = rs.getMetaData();
    int numberOfColumns = rsmd.getColumnCount();
    while (rs.next()) {
    for (int i = 1; i <= numberOfColumns; i++) {
    if (i > 1) System.out.print(", ");
    String columnValue = rs.getString(i);
    System.out.print(columnValue);
    System.out.println("");
    for (int j = 1; j <= numberOfColumns; j++)
      System.out.println(rsmd.getColumnName(j));
    rsTable=dbmd.getTables(null,null,"%",null);
    while (rsTable.next())
    //String tableCatalog = rsTable.getString(1);
    //String tableSchema = rsTable.getString(2);
    System.out.println("Table Name "+rsTable.getString(3)+" Table catalog "+rsTable.getString(1)+" Table Schema "+rsTable.getString(2));
    rsTable.close();You can store Column Names,data in the String Array.
    To generate a JTable with this check this
    http://www.codetoad.com/java_JTable.asp.
    There at method createBlankElement()
    put values from the data array or if you want, from the database.
    For the Columns, pass columnNames array to addColumns method.

  • Need help with advanced JTable

    The application I am converting to Java has a string grid (table) with special behavior that I need to be able to bring to the Java version. It let's users filter the column data (that I know how to do) using a locked first row (just below the column header) that always stays in place and that shows what filter is applied to each column (by showing a combo box).
    I usually write server apps and have only been trying to grasp Swing for about a week, and I find myself stuck :(
    Is this at all possible in Java? If not, can I make the header respond to mouse events and show a popup menu for each column? If so how?
    Please help!

    I have made an attempt as follows (to show where I am stuck).
    I have two TableModels that contain rows and data;
    a) the grid data that's coming from our EJB session facade
    b) the filter settings (a String[] with initially empty strings) which show what filter is used for each column.
    The two table models are shown in two tables that share a common TableColumnModel so that whenever i move or resize a column both tables are updated.
    The filter table shows it's header and the row of empty cells. The Table Model I've used for it is ripped from the Sorted Table example from Sun, so that I can capture mouse events, set the sort order for each column and notify the grid table that it needs to update accordingly.
    I attempted to use the filter table as a header view in a JScrollPane, which would keep it in place all the time while the user would be able to scroll and resize the grid table.
    This is where I fail - I can't even get it to show up in the header. And if I only put the two tables on a JPanel it seems impossible to get them to stick together when the pane is resized (aside from the fact that I no longer can capture the mouse events).
    I'd be happy to send someone the code fragments if you think you have a solution to this - that will allow users to resize, edit and move columns in a table where you initially have no clue as to how many columns it will contain.
    Please please continue to help me :)

  • Help with JComboBox and Model creation

    hi,
    I'm trying to figure out the best way to set up the data behind the JComboBox and copy part of that data to be shown by the JComboBox. Here is what I would like it to do.
    My data:
    itemID, dbaseID, name
    1, 2, test1
    2, 2, test2
    3, 2, test3
    The JCombo will only display the name in this case "test1", "test2", or "test3". However when the user selects the name, I want to easily retrieve the hidden itemID or dbaseID. I've got the combobox working with just the "test1" but it doesn't tell me which dbase it is from. I have to search all of them and worry about identical names.
    What is the best way to set this up? I was thinking about an multiDimensional model but not sure how that would look. It is just not clicking how set up the data and then add parts of to the combo box.
    Any guidance or examples would be appreciated.

    From what I can tell both getSelectedItem() and getSelectedValue() return the string value of the GUI component. Read the API, that is not what they return. They return the "selected" Object.
    The renderer, by default, displays the toString() value of the Object.
    I'm casting the string into Item No you aren't, because that is not possible.
    My understanding was casting was just converting one thing to another.Casting does not "convert" anything. Time to get out your Java textbook and read up on casting.
    However this looks like it is actually grabbing the memory point to an item.Exactly. The getSelected... methods simply return a reference to the Object that was selected. Thats all any get... method does.

  • Help with JComboBox

    From the code below it looks like the only last competitor number entered get displayed in the JComboBox five times but if five of them is entered they all have to be different.
    public Integer[] listCompNumbers()
      // This should return an array of Integers that are the competitor numbers
      // of all the competitors in your competition.
      // it is called once to create the drop down list to select whom to enter result for
        Integer nums[] =  new Integer[5];
        // replace next line with code that gets the competitor numbers
        nums[0] = new Integer(gui.getAddCompetitorNumber());
        nums[1] = new Integer(gui.getAddCompetitorNumber());
        nums[2] = new Integer(gui.getAddCompetitorNumber());
        nums[3] = new Integer(gui.getAddCompetitorNumber());
        nums[4] = new Integer(gui.getAddCompetitorNumber());
        return nums;
      }

    What does the method gui.getAddCompetitorNumber() do?

  • Get help with JComboBox, itemStateChange

    hi, i get quite complex a problem.
    i have a list containing 2 types of list. one list is the car model and the other is the car type.
    so in one combo box, there will be a list of car model. when one car is selected in this, the other combo box will automatically update all the available car type (e.g. car model is BMW and car type is 318).
    i dont know how to keep the second combo box updated immediately after item of the first combo box changes state.
    some one help me pls

    hi,
    thanks for replying but my problem seems too hard for me.
    i just got another problem.
    i still have the file with a number of JFrames inside and the first, or considered to be the "main" JFrame. Now, when i click a button, a second JFrame after that will pop up but I dont know how to setVisible(false) for the main window using Netbeans. could you please help me do that?
    thanks alot

  • Help with TableRowSorter , JTable and JList

    Hello,
    I�m developing an application in which I�m using a Jtable and Jlist to display data from a database. Jtable and Jlist share the same model.
    public class DBSharedModel extends DefaultListModel implements TableModelFor the Jtable I set a sorter and an filter
    DBSharedModel dataModel = new DBSharedModel();
    Jtable jTable = new JTable(dataModel) ;
    jTable.createDefaultColumnsFromModel();
    jTable.setRowSelectionAllowed(true);
    TableRowSorter<DBSharedModel> sorter = new TableRowSorter <DBSharedModel> (dataModel);
    jTable.setRowSorter(sorter);From what I read until now JavaSE 6 has NOT a sorter for JList (like one for JTable).
    So, I am using one from a this article http://java.sun.com/developer/technicalArticles/J2SE/Desktop/sorted_jlist/index.html
    When I sort the data from the table, I need to sort the data from the list, too.
    My ideea is to make the Jlist an Observer for the Jtable.
    My questions are:
    1.     How can I find if the sorter makes an ASCENDING or DESCENDING ordering?
    2.     How can I find what the column that is ordered?
    Or if you have any idea on how can I do the ordering on Jlist to be simultaneous to Jtable .
    Please help!
    Thank you

    Oh what the hell:
    Sun's basic Java tutorial
    Sun's New To Java Center. Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    http://javaalmanac.com. A couple dozen code examples that supplement The Java Developers Almanac.
    jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    Bruce Eckel's Thinking in Java (Available online.)
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java. This one has been getting a lot of very positive comments lately.

  • Help with connecting JTable to northWind database

    hi
    actually i want to connect to products table then display it on JTable automatically.
    Now i've got the connecting code , but i'm not sure how and where code for displaying that data from the northwind table onto a Jtable with
    all the calumnNames and rows should be
    Thanks in advance

    this a re-arrangment of the code, i've tried this from one of the posts
    but still, it doesn't show nothing
    <code>
    tableData = new Vector();
    Vector titles = new Vector();
    int currentRow = 0;
    try
    Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); // load the driver
    conn = DriverManager.getConnection ("jdbc:microsoft:sqlserver://213.107.6.45;user=foo;password=foobar");
    // connect to SQL server
    conn.setCatalog("Northwind");
    // choose the database
    Statement stmt = conn.createStatement();
    // create an SQL statement
    String query = "SELECT * FROM Products;";
    table = stmt.executeQuery(query);
    ResultSetMetaData md = table.getMetaData();
    // get the meta data
    final int numberOfColumns = md.getColumnCount();
    // Vector columnNames = new Vector();
    // for(int i = 0; i < numberOfColumns; i++)
    // columnNames.add(md.getColumnName(i+1)); //indexed from 1, not 0
    // Iterator it = columnNames.iterator();
    // int i = 30;
    if(table.next())
    //rowData(table.getObject(1).toString());
    //jTextFieldField2.setText(table.getObject(2).toString());
    Vector rowVector = new Vector();
    for (int currentCol = 1; currentCol < numCols; currentCol++)
    Object obj = table.getObject(currentCol);
    rowVector.addElement(obj);
    //rowVector.add(table.getString (currentCol + 1));
    tableData.addAll(rowVector);
    //tableData.addElement(rowVector);
    //currentRow++;
    for (int currentCol=1; currentCol<= numCols ; currentCol++)
    titles.addElement(md.getColumnLabel(currentCol));
    // Close connection to database
    stmt.close();
    conn.close();
    }//end try
    catch (Exception ex)
    JOptionPane.showMessageDialog(null, ex.getMessage());
    }// end catch
    JTable table = new JTable(tableData,titles);
    JScrollPane scrollpane = new JScrollPane(table);
    this.getContentPane().add(scrollpane);

  • Help with GUI project.

    I need help with JcomboBox when I select the Exit in the File box it will open
    //inner class
    class exitListener implements ActionListener {
    I have the part of the parts of statement but I don't know how to assign the Keystoke. here is that part of the code
    filemenu.setMnemonic(KeyEvent.VK_X);Here is my code...
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class MyFrame extends JFrame {
         String[] file = { "New", "Open", "Exit" };//items for file
        String[] edit = { "Cut", "Copy", "Paste" };//items for edit
        JComboBox filemenu = new JComboBox();
        JComboBox editmenu = new JComboBox();
         public MyFrame(String title) {
              super(title);
              this.setSize(250, 250); //sets the size for the frame
              this.setLocation(200, 200);//location where frame is at
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // setup contents
              makeComponents();
              initComponents();
              buildGUI();
              // display
              this.setVisible(true);
         private void makeComponents() {
              JPanel pane = new JPanel();
    //          file menu section
              filemenu = new JComboBox();
            JLabel fileLabel = new JLabel();
            pane.add(fileLabel);
            for (int i = 0; i < file.length; i++)
                 filemenu.addItem(file);
    pane.add(filemenu);
    add(pane);
    setVisible(true);
    //edit menu section
    editmenu = new JComboBox();
    JLabel editLabel = new JLabel();
    pane.add(editLabel);
    for (int i = 0; i < edit.length; i++)
         editmenu.addItem(edit[i]);
    pane.add(editmenu);
    add(pane);
    setVisible(true);
         private void initComponents() {
              filemenu.addActionListener(new exitListener());
         //inner class
    class exitListener implements ActionListener {
    public void actionPerformed(ActionEvent arg0) {
    int x = JOptionPane.showOptionDialog(MyFrame.this, "Exit Program?",
    "Exit Request", JOptionPane.YES_NO_OPTION,
    JOptionPane.QUESTION_MESSAGE, null, null,
    JOptionPane.NO_OPTION);
    if (x == JOptionPane.YES_OPTION) {
    MyFrame.this.dispose();
         private void buildGUI() {
              Container cont = this.getContentPane();// set gui components into the frame
              this.setLayout(new FlowLayout(FlowLayout.LEFT));// Comp are added to the frame
              cont.add(filemenu);
              cont.add(editmenu);
         // / inner classes
    public class ButtonFrame {
         public static void main(String[] args) {
              MyFrame f1 = new MyFrame("This is my Project for GUI");
    Thanks
    SandyR.

    One way is to
    1) pass a reference of the Window object to the USDListener class, and set a local Window variable say call it window, to this reference.
    2) Give the Window class a public method that returns a String and allows you to get the text from USDField. Same to allow you to set text on the euroField.
    3) Give the Listener class a Converter object.

  • Help with editing a cell in a JTable. DESPERATE

    Hi! Is there someone out there that could help with some source code for editing a cell in my JTable when I run it as an applet??
    It works fine when I run it as an application.
    I manage to select the row and write a number in it, but I can't get out of the cell (it seems that the program stops??). I want to enter an integer in a cell and when I click enter or with the mouse in an other cell the value that I enter should update some other cell( multiply the entered value with some fixed number and update a cell in a second coloumn)
    I am really desperate now..... I have thought about using a MouseListener....
    I am using a tablemodel that is from AbstractTableModel.

    Are you using some cell editors?
    While converting inside them, you might be getting some exceptions (like parseexception)which is stopping you from proceeding further.
    Are you using your own tablemodel with custom datatypes?
    Hope this helps,
    Ramkumar

  • Help with Filtering a JTable by multiple columns

    Hi everyone, I need some help with filtering a JTable.
    Basically I have five columns in my table and five text fields for Username, First Name, Last Name, Address and Phone Number.
    What I need to do is have each text field filter the column it is assigned to. So if the table was
    So if I put 'foo' into the username field and two users have a username containing 'foo' they stay on the table, but if i also enter text in first name, say 'john' and only one of those entries has a first name of 'john', the other disappears.
    I'm probably not explaining that very well so let me know if you need clarification.
    I found this code (which I assume works correctly) but I don't know how to interface it with my other class that displays the JTable
    import javax.swing.RowFilter;
    public class UsersFilter extends RowFilter {
         private String[] filters;
         public UsersFilter(String uName, String fName, String lName, String address, String phone) {
              filters = new String[]{uName, fName, lName, address, phone};
        public void setFilter(int column, String filter) {
            if(column < filters.length)
                filters[column] = filter;
        public boolean include(Entry entry) {
            boolean result = true;
            for (int i = 0; i < filters.length; i++) {
                if (result && !(filters.equals("")) ) {
    String v = entry.getValue(i).toString();
    result = v.startsWith(filters[i]);
    return result;

    dbuvid wrote:
    Hi everyone, I need some help with filtering a JTable.For 1.6+, set a RowSorter (which can also do filtering). Details in the 1.6 JavaDocs for JTable.

Maybe you are looking for

  • Account Modification in omr0

    Dear Forum, In omr0, go to simulation and click on account assignment. 1 May I know what does -e- at AM(account modification) mean? Also when it is empty also what does it mean? 2 May I know what does -Missing- at GL account field? Some are empty som

  • Confusion in Order of row and statement level trigger

    Hi can anyone tell me, if i create some trigger on table emp as in below order.. BEFORE INSERT .. ROW LEVEL BEFORE INSERT .. STMNT LEVEL AFTER INSERT .. ROW LEVEL AFTER INSERT .. STMNT LEVEL than what will will be order of execution of trigers? How o

  • Database not starting,REDO log file error?

    My DB was working fine uptill last evening, when i restarted it for some DB task it showed me an error .. ORA-00333: redo log read error block 57346 count 8192 I studied the alert log file & related trace file .... but could not conclude what to do ?

  • What are the Basic Features of Enterprise Portal

    What are the default, given or otherwise features of SAP netweaver/enterprise portal. I do not want to redo a function or feature/template of the feature/basic iview (portlet) already exists. And where I can find/get these features. Thanks.

  • I posted question but still haven't got problem solved, please help

    I have a table which has two columes time- timestamp value- integer I have problem writing query to get rolling up cumulative of value for time buckets Wanted results like following: like cumulative value for rolling 5 minutes time bucket for past 1