Help on JComboBox

Hi,
I want to create a custom combobox. if i open the popup menu in the combo box, it should display a jtable in that rendering area of the combo box popup menu. i want to add any types of component in that jtable(Jbutton, label, combobox).
Finally i want to add a new JButton in that jCombo popup area. the content of the button is "Connect". If the user click the connect button, then only the popup should be invisible.
Any Idea?
Can i use the ComboBoxRenderer to this?

hi,
i didn't had any sample program.. i did this just for your help.. this is just an idea that how it can go..
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.Popup;
import javax.swing.PopupFactory;
* @author          : aniruddha<br>
* @date          : Apr 11, 2007,  3:49:15 PM<br>
* @source          : ADCCombo.java<br>
* @project          : HelpForum<br>
public class ADCCombo extends JPanel
     private JButton     m_btnBrowse     = null;
     private JLabel     m_lblMain     = null;
     private Popup     m_objPopup     = null;
     private boolean m_bisVisible = false;
     public ADCCombo()
          final PopupFactory factory = PopupFactory.getSharedInstance();
          setLayout(new BorderLayout());
          add(m_lblMain = new JLabel("OK"), BorderLayout.CENTER);
          add(m_btnBrowse = new JButton("..."), BorderLayout.EAST);
          m_btnBrowse.setMargin(new Insets(0, 0, 0, 0));
          final JTextArea txt = new JTextArea(3, 10);
          final Component l_cmp = new JScrollPane(txt);
          m_btnBrowse.setFocusable(false);
          m_btnBrowse.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent a_objEvent)
                    if(m_objPopup != null)
                         if(m_bisVisible)
                              m_objPopup.hide();
                              m_bisVisible = false;
                              return;
                    m_objPopup = factory.getPopup(ADCCombo.this, l_cmp, l_objJFrame.getX() + 3, l_objJFrame.getY() + ADCCombo.this.getHeight() + ADCCombo.this.getY() + 25);
                    m_objPopup.show();
                    txt.requestFocus();
                    txt.setText(ADCCombo.this.toString());
                    m_bisVisible = true;
     static JFrame l_objJFrame = new JFrame("Custom Combo");
     public static void main(String[] args)
          l_objJFrame.add(new ADCCombo(), BorderLayout.NORTH);
          Dimension dimSize = Toolkit.getDefaultToolkit().getScreenSize();
          l_objJFrame.setSize((int) (dimSize.getWidth() / 10) * 4, (int) (dimSize.getHeight() / 10) * 4);
          l_objJFrame.setLocationRelativeTo(null);
          l_objJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          l_objJFrame.setVisible(true);
}this is another way...
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.Popup;
import javax.swing.PopupFactory;
* @author          : aniruddha<br>
* @date          : Apr 11, 2007,  3:49:15 PM<br>
* @source          : ADCCombo.java<br>
* @project          : HelpForum<br>
public class ADCCombo extends JPanel
     private JButton     m_btnBrowse     = null;
     private JLabel     m_lblMain     = null;
     private JPopupMenu     m_objPopup     = null;
     public ADCCombo()
          setLayout(new BorderLayout());
          add(m_lblMain = new JLabel("OK"), BorderLayout.CENTER);
          add(m_btnBrowse = new JButton("..."), BorderLayout.EAST);
          m_btnBrowse.setMargin(new Insets(0, 0, 0, 0));
          final JTextArea txt = new JTextArea(3, 10);
          final Component l_cmp = new JScrollPane(txt);
          m_objPopup = new JPopupMenu();
          m_objPopup.add(l_cmp);
          m_btnBrowse.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent a_objEvent)
                    m_objPopup.show(ADCCombo.this, getX(), getY() + getHeight());
     static JFrame l_objJFrame = new JFrame("Custom Combo");
     public static void main(String[] args)
          l_objJFrame.add(new ADCCombo(), BorderLayout.NORTH);
          Dimension dimSize = Toolkit.getDefaultToolkit().getScreenSize();
          l_objJFrame.setSize((int) (dimSize.getWidth() / 10) * 4, (int) (dimSize.getHeight() / 10) * 4);
          l_objJFrame.setLocationRelativeTo(null);
          l_objJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          l_objJFrame.setVisible(true);
}regards
Aniruddha

Similar Messages

  • 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

  • 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

  • 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.

  • HELP ABOUT JComboBox ?

    Hello All,
    Can any body tell me in MSN chat window when we want to
    send some images with our message then we press Emoticone button
    and we get multiple rows and columns with diffrent images i think
    this is JcomboBox.
    i want to do same thing , but i dont know how can i creat multiple rows and columns JcomboBox with images if any body give me any example or
    any Help.
    i m thanksfull.
    Arif.

    I would recommend using a simple JPanel with GridLayout and adding JLabels in each cell. Use the JLabel.setIcon() method to make the labels have images.
    A JComboBox is more of a single-selection drop down menu. JTable would work also, though I think a JPanel with several JLabels is easier to manage.

  • 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?

  • Need help about Jcombobox

    Dear all:
    i have a Jcombobox and a Jtable on my display, the user will be about to change the content of the table by selecting different things from the JCombox......
    how do i do it? i tried so hard, but the content of the table won't change
    thanks in advance

    table.setModel(...);

  • 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! JcomboBox button listener problem

    Hi all,
    I wanna capture the action while the user is clicking the right button of the jcombo box (which is a down side arrow).
    I used mouseListener, it could only capture the action that the user drop the box , but not for the button.
    Anyone has idea for it?
    Thanks very much

    [url http://forum.java.sun.com/thread.jsp?forum=57&thread=532636]Crosspost.

  • Transfer of the variable through JComboBox

    Hello people,
    I have the following question. In the main JFrame class i put on the JPanel JComboBox. Depending on the values i choose with the help of JCombobox, my following program shoud change the behavior, then in one of classes which is called from another class i use the chosen value.
    so, should i again call main class in one of subclasses with the aim to transfer of the given value.? When i call the main the program was hanging,
    Thank you in advance
    GJavagirl

    My
    AnimatorFrame.class calls 2 classes
    Animator11 and Animator33
    Animator33 calls ReadFile.class, but the value (the name of the file is defined in the AnimatorFrame ,
    i see only one way to call Animator33(filename), which calles the ReadFile(filename)
    Finally my main program doesn't work, what wrong with it?
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class AnimatorFrame extends JFrame implements ActionListener
         Animator11 an1;
         Animator33 an3;
           JButton okbutton,endbutton;
            JPanel buttonPanel;
         public AnimatorFrame() {
              super("Animator");
              addWindowListener(new WindowDestroyer());
              createComponents();
              pack();
              setVisible(true);
         private void createComponents() {
              Container c=getContentPane();
                    buttonPanel=new JPanel();
                    okbutton=new JButton("Start");
                    endbutton=new JButton("Stop");
              buttonPanel.add(okbutton,BorderLayout.CENTER);
                    buttonPanel.add(endbutton,BorderLayout.CENTER);
                    an1=new Animator11();
              an3=new Animator33();
              an1.setLayout(new BorderLayout());
              an1.add(an3, BorderLayout.NORTH);
                    an1.add(buttonPanel,BorderLayout.CENTER); 
              c.add(an1, BorderLayout.SOUTH);
         public void startAnimation() {
              an1.start();
              an3.start();
             public void actionPerforme(ActionEvent e)
       if(e.getActionCommand().equals("Start"))
          this.startAnimation();
       if(e.getActionCommand().equals("Stop"))
        System.exit(0);
         public static void main(String[] args) {
              AnimatorFrame f=new AnimatorFrame();
                    f.createComponents();
                    f.setVisible(true);
    //          f.startAnimation();
    }It gives animator class must be declared abstract!
    i didn't present here ComboBox problem......

  • 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.

  • Adding items in JComboBox - Help

    Hy, I have a JComboBox() and a JTextField().
    when I input a name in the JTextField and clicks on the "Ok" button
    the name is added in the JComboBox().
    What I want is when I click on the "Ok" button, a check is made to see
    whether the name input in the JTextField already exist in the JComboBox().
    If is exist a message is displayed else it is added.
    How to perform the check.
    PLease send me code for doing this.
    thanks

    Hi.
    The JComboBox uses a model to get its hands on the elements to be displayed. Thus you must search the model to see if the string is already contained.
    Use something like this:
        public boolean contains(JComboBox comboBox, String s) {
            int elementCount = comboBox.getModel().getSize();
            for (int i = 0; i < elementCount; i ++) {
                String t = (String)comboBox.getModel().getElementAt(i);
                if (t.equals(s))
                    return true;
            return false;
        }Hope this helps,
    Michael

  • The problem in using JComboBox. Need Help!

    HI,
    I am programming to make an address bar as IE? Now, I am using JComboBox as the address bar. I also read the article of "how to use JComboBox" in sun tutorial.
    The problem is I cann't make the icon and text together in the address bar. As in the tutorial article, I can make it there since the JComboBox is uneditable.
    My case is I still want the icon in the JTextField of JComboBox, but I am still able to input address into this JTextField as well.
    Is it able to add a JLabel into JTextField first, and then be able to input text exactly after this icon, then my problem is solved.
    Thanks!
    Feng

    Hi Feng,
    My suggestion is that you try out the JComboBox methods setEditor() and setRenderer(). They allow you to specify custom components that will be used to show the combo box items. You'll need to do a bit of work, but you'll probably be able to provide a custom component that will display your icon.
    Hope that helps!
    Shannon Hickey (Swing Team)

  • Help on Look-and-Feel of JComboBox

    Can anyone guide me on how to change the look-and-feel and style of a JComboBox? Is it possible? If yes, how?

    I was wondering about that myself... I want to change the look of a combobox, or any other component. I think I should do it with the following code
    public static void setLookAndFeel(String�className)
    but I don't know what className to use. If I am not mistaken it should be the name of the class that implements the Look and Feel, please help!

Maybe you are looking for

  • Iphone does not sync OUTLOOK CONTACT NOR CALENDAR EVENTS (XP)

    I was able to sync photos- music but no contacts-Calendar events from OUTLOOK 2003. The fact that my outlook PST file is not located in the default Outlook directory could be the problem but I am not sure. Anyone out there having the same issue??? Pl

  • PowerMac G4 used as backup hard drive?

    I have an older PowerMac G4 with dual 500mhz processors. Can I install Leopard on this machine and use it as my backup drive. Also is it necessary to install Leopard to do so? Thirdly can I connect them wirelessly or do they need to be hard wired? Th

  • Dimension only query to show manager and employees in one row

    Hi Gurus, I am creating a dimension only report. This report will show managers and their direct reportees. Since one manager can have several employees working under him, I am getting one row in the report for each employee. But our end users want e

  • Prince of Persia the NON HD version

    Well I have both HD and nonHD versions, and considering the HD version wasnt intended for the 5800, it lags like hell, so I downloaded the 2D version from Ovi Store, and what do you know, the thing cannot load the 9th stage. Anyone know where to get

  • My application "stickies" is missing entirely from my Mac... Where'd it go? And how can I get it back?

    I have recently been told about "stickies" as an application on all Macs. When I went to find it in my search engine, it doesn't come up at all. I don't know where it is or how to get it back? Help!