JComboBox content

Hi All:
I have two JComboBox A and B on same JPanel. If the content in B is changed when I select diffent items in A. How can I implement it.Thank you very much in Advance!

It is pretty simple really. Add a listener to the first combo box so you know when it changes. Then when it changes update the data in the other combo box.
Looking up in the API documentation should yield the specifics. Let us know if you run into troubles and be sure to post code snipits so we can provide specific help.

Similar Messages

  • JComboBox contents from a SQL query

    Hi
    What I'm trying to do is to retrieve 2 fields from a table in my database into a String[] which is then put into a vector. This vector is then passed to a JComboBox. The problem is that when I do this the contents of the JComboBox is gobbly-goop. I think its displaying the address of the string data in memory rather than the data itself. If I only retrieve one coloumn (i.e column 1) from the table into the vector it displays fine.
    Any ideas, suggestions will be appreciated.
    Thanks

    Heres a code snippet of what Im triing to do. Hopefully it will give people a better idea of what Im trying to achieve.
              try
                   Statement stufind = con.createStatement();
                   String lookup = "SELECT * FROM Student WHERE Techset = '" grpid "'";
                   ResultSet rs = stufind.executeQuery(lookup);
                   while(rs.next())
                        String[] record = new String[2];
                        record[0] = rs.getString(2);
                        record[1] = rs.getString(3);
                        students.addElement(record);
                        //students.addElement(rs.getString("StudentID"));
                   stufind.close();
              catch(SQLException sqlex)
              student = new JComboBox(students);

  • JComboBox contents dont get updated(repainted) dynamically

    Hi,
    I have 2 Combo Boxes as 2 columns of a Table and the contents of the second combo box depend on the selection in the first one.
    So I added an ActionListener to the first Combo Box and depending on selection, I update the contents of the other. The contents do get updated. But I see the change only when I click on the second Combo Box. I am trying to get the user to see the change w/o him touching the other combo box. The code snippet is as below:
    public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equals(FIRSTCOMBO)) {
    combo1Index = ((JComboBox)(e.getSource())).getSelectedIndex();
    DefaultComboBoxModel model = (DefaultComboBoxModel)comboBox2.getModel();
    model.removeAllElements();
    model.addElements(as obtained);
    comboBox2.setSelectedItem(0);
    comboBox2.revalidate();
    comboBox2.repaint();
    Doesn't seem to work. Any ideas?
    Thanks a ton!

    I don't understand the design of your table. A combo box is used in a table to give the user a choice of values to choose from. Assume the combo box contains the values "a", "b", "c", "d", "e". As a user I choose "c". The "c" now gets stored in the data model and displayed in the table cell.
    Now assume you change the contents of the combo box to "1", "2", "3", "4", "5". The value in the data model has not changed , it is still "c", so there is nothing to repaint.
    When the user clicks on the cell then the new values in the combo box are displayed, allowing the user to choose a new value.
    If you want the table cell to repaint a new value when the second combo box is changed then you must change the data model value. Use the table.setValueAt(row, column) method.

  • Unable to refresh JComboBox Content

    Hi all,
    I have 2 JComboBoxx boxes on a jTable. They need to be dynamically updated. It works, but sometimes the combobox appears as a empty list even though it it has content. At that moment, the combobox will return to normal with a more mouse click on the list.
    I feel that there is sth. wrong with the refresh. I do the refresh with the following codes. Do you have any idea on this??
    jComboBox1.repaint();j>>ComboBox2.repaint();
    j>>Table.revalidate();
    j>>Table.repaint();
    Thanks,
    Eva

    Have you tried the fire methodes in Abstract/DefaultTableModel ?
    --> fireTableDataChanged()
    perhaps this could be a solution ?
    have fun
    grtz Kristof

  • JComboBox problem again..

    I have a problem not entirely dissimilar to Jofin's.
    My combo box is populated on 10 seconds pulses by a remote server.
    Once a value has been selected from the combobox, it auto populates two jTextFields below based on the selection made from the box.
    My problem is as soon as the 10 second pulse comes around, the JComboBox contents is refreshed/repopulated, the selected index jumps back to 0 and the text boxes below are updated based on the element at 0.
    I can't seem to get the combination of event handling right, I've tried mousePressed, but that seems to be on the jComboBox its self rather than the selected item, I've tried mouseReleased with some success but the user MUST click and hold then release on the correct item or it doesn't work.
    Any help on the matter would be very much appreciated.
    Thanks.
    Andy

    I need to select live items from an auction which are displayed in a drop down list to bid on in an auction program.
    users select an item: http://www.andywebb.me.uk/jcombobox.jpg
    item populates bid section: http://www.andywebb.me.uk/jcombobox2.jpg
    the items last a specific amount of time (this is an assignment, not a real program) and CAN disappear from the list of available items to bid on. I need a way of holding the values of the item being bidded on and a way of controlling how to display the items that are available to bid on.
    The items index in the list is irrelevant, i'm simply using the combo box item which is being clicked to populate the fields below.

  • Code to display  hindi fonts in JComboBox in a JFrame

    Hi friends,
    My mail id is [email protected] and please give response as soon as possible.
    My problem:In java,my Jcombobox contents is displaying only english fonts like arial or verdena or timesnewroman
    My requirement:
    I want source code or logic to display the contents in a JComboBox with hindi fonts or any other international language.
    That means,by choosing the language font my Jcombobox contents should be changed to that corresponding language dynamically.
    Note: I have used java internationalization with locale classes,but it is not working. please help me

    You might try giving the file a ".txt" extension. Then drag it on top of your Safari icon in the dock, which should open it with Safari. Then, under "View", select a Japanese "Text Encoding". My guess is that this is Shift-JIS.
    I am assuming you have not removed Japanese fonts from your system.

  • Populating dynamic components in a remotely connected desktop application

    Hii Javaties
    I develping a desktop appliaction, which will remotely connect to internet.
    My requiremnets for the project are
    1)- Combo boxes, lists are dynamic(they need 2 be populated from databse).Since user will not be always connected to internet , so i need to devise some other way 2 do this .
    the solution tht i m thinking upon is tht , the comboboxes ,lists will be populated fom XML file tht will be stored in user P.C(rather tht this file will be in jar file of the desktop application).
    So now whenever user has access to net, then he can click on a menu
    button (UPDATE FILES), so tht he can get the latest copy from the central server .
    In the central server , the data will be stored in an RDBMS , and this data will be sent 2 the application on client computer as an XML file.
    and this will rewrite the (XML)files , tht the appliaction needs for poplulating Combo boxes and lists.
    2)User needs to transmit data back to central server remotely.
    I plan to use XML for this.
    Now My questions are -------
    1) Is this approach Correct ?
    2) if the data is large , is it wise to store it as an XML file
    3) How 2 go abt it.
    If anythng is not clear , plz tell me ?
    U can also click on the link below to see the original question posted by me
    http://forum.java.sun.com/thread.jspa?threadID=734442

    I don't understand why you need xml for jcombobox content? A flat file for each combobox will serve its purpose quite well.the contents of combo boxes will be fetched , from a repository (XML) file, which will contain data from database.
    This repository can be aslo updated by connecting to server,and updating it with new data from database.
    If u still have dobt do tell me .?

  • Filtering contents of JComboBox using a Renderer

    Hi all,
    I'm writing a Swing panel that needs to display two combo boxes (themes and sub-themes), where the contents of the sub-theme combo is dependent on the theme selected in the first combo box.
    The subtheme combobox model is initialized with ALL the subthemes that can be displayed and my idea was to filter the subthemes for the selected theme within the getListCellRendererComponent() of my subtheme combo renderer.
    The problem I'm having is that the renderer getListCellRendererComponent() method is called for all elements in the subtheme combobox only once, the first time the combo box is displayed. When I update the selected Theme and try to select a SubTheme, the getListCellRendererComponent() method appears to be only called for the set of SubThemes that are being displayed within the scroll area of the combo.
    Is there a way to indicate that the getListCellRendererComponent() should be called for ALL elements in the combo, instead of just those that displayed within the viewable scroll area?
    Or should I not be attemping to perform this filtering in the renderer class?
    Thanks in advance!
    public class SubThemeListCellRenderer extends BasicComboBoxRenderer
                          implements  ItemListener
         private Theme selectedTheme = null;
         private JLabel voidLabel = new JLabel();
         public SubTemaListCellRenderer(Theme theme)
              this.theme = theme;
         public Component getListCellRendererComponent(JList list, Object value,
                   int index, boolean isSelected, boolean cellHasFocus)
              SubTheme subTheme = (SubTheme) value;
                    // Only display subthemes associated with the selected Theme
                    if ( subTheme  != null && selectedTheme != null && subTheme.getCodigoTema() == selectedTheme.getCodigo() )
                       return super.getListCellRendererComponent(list, subTheme.getDescription(), index, isSelected,cellHasFocus);
                    else
                       return voidLabel;
          * (non-Javadoc)
          * @see java.awt.event.ItemListener#itemStateChanged(java.awt.event.ItemEvent)
         public void itemStateChanged(ItemEvent e)
              Object source = e.getSource();
              if (source instanceof JComboBox)
                   Object selectedTheme = ((JComboBox) source).getSelectedItem();
                   if (selectedTheme instanceof Theme)
                        this.theme = (Theme) selectedTheme;
         }

    Thanks for your response. Actually, before I had the idea of using the renderer, I updated the combo box by doing exactly what you suggested. It worked fine, however I was recommended to move this functionality to the renderer!
    After two days of struggling with this, I've reached the conclusion that this operation should not be performed in the renderer and instead by updating the underlying ComboBoxModel (removing and inserting the items as necessary).

  • How is it possible to show contents of JComboBox that aren't in list

    I have an application that I have developed over time that requires that I be able to select any item in a JComboBox list and send an actionEvent. In order to do this I set the value of the JComboBox selectedIndex to -1 indicating no selection. This enables me to select the first item in the list and send an actionEvent. The only problem is that the window where the items for the box appears is initially blank. (I don't know if window is the correct term). I would like the ability to place a message in this window such as "Please Select FooBar". Anyone know how to do this?

    Maybe something like this:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.plaf.basic.*;
    public class ComboBoxPrompt extends JFrame implements ActionListener
         JComboBox comboBox;
         public ComboBoxPrompt()
              String[] items = { "Bryan", "Nick", "Tom" };
              comboBox = new JComboBox( items );
              comboBox.setSelectedIndex(-1);
              comboBox.setRenderer( new PromptRenderer("Select Person") );
              getContentPane().add( comboBox, BorderLayout.NORTH );
              JButton button = new JButton("Clear Selection");
              getContentPane().add( button, BorderLayout.SOUTH );
              button.addActionListener(this);
         public void actionPerformed(ActionEvent e)
              comboBox.setSelectedIndex(-1);
         public static void main(String[] args)
              JFrame frame = new ComboBoxPrompt();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible( true );
         class PromptRenderer extends BasicComboBoxRenderer
              private String prompt;
              public PromptRenderer(String prompt)
                   this.prompt = prompt;
              public Component getListCellRendererComponent(
                   JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
                   super.getListCellRendererComponent(list,
                        value, index, isSelected, cellHasFocus);
                   if (value == null)
                        setText( prompt );
                   return this;
    }

  • JComboBox autoselecting contents

    I populate a JComboBox with a few strings:
    String[] items = {"apple","orange","kiwi","oreilly"};
    JComboBox cb = new JComboBox(items);
    cb.setEditable(true);I want a user to be able to start typeing "or" in the combo box and have the combo box automatically display "orange" as the first match. Also, the letters "or" that the user typed are not selected, but the "ange" that the combo box automatically inserted will be selected. If the user continues to type "ore" then "oreilly" is selected.
    It doesn't look like the stock JComboBox supports this. Is there one that someone may have written with this functionality? It looks like using a ComboBoxEditor or JComboBox.KeySelectionManager is the route to presue.
    Thanks

    Have a look at the folowing link.
    http://www.spindoczine.com/sbe/files/uts2/Chapter9html/Chapter9.htm
    If you browse to the bottom of the chapter you will find an example of how to implement a ComboBoxEditor that looks up the item your typing set it as the current item in the combobox and then set the caret position.
    Hope it helps

  • Retrieving values from a JComboBox - Design question.

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

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

  • Imageicon in a JComboBox

    hi, i do a program to create "business case table", but i've a problem in the 2nd part of the table, because in my 2nd table i have a JComboBox with image, when i click the combobox the images are show, but when select some figure the cell don�t keep the image, only keep the text.
    Anyone can help me???
    Here is my principal class that create the principal screen and tables:
    /*                      Poseidon                                 */
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    * Summary description for Poseidon
    *2052102
    public class Poseidon extends JFrame
         // Variables declaration
         private JTabbedPane jTabbedPane1;
         private JPanel contentPane, paineltabela, painelgrafo, painelvariavel, paineltarefa;
         private JTable tabelavariavel,tabelatarefa, tabelateste;
         private JScrollPane scrollvariavel, scrolltarefa;
         private int totallinhas, alt, al, linhastarefa,cont, linhas, tamanholinhas,
                        controlalinhas, index, contastring;
         private String variavel;
         private JComboBox combobox;
         JMenuItem sair, abrir, guardar, miadtarefa, miadvariavel;
         JTable [] tabelasvar = new JTable[30];
         JFrame w;
         // End of variables declaration
         public Poseidon()
              super("Poseidon");
              initializeComponent();
              this.setVisible(true);
          * This method is called from within the constructor to initialize the form.
          * WARNING: Do NOT modify this code. The content of this method is always regenerated
          * by the Windows Form Designer. Otherwise, retrieving design might not work properly.
          * Tip: If you must revise this method, please backup this GUI file for JFrameBuilder
          * to retrieve your design properly in future, before revising this method.
         private void initializeComponent()
              JMenuBar barra = new JMenuBar();
              setJMenuBar(barra);
              TratBarra trat = new TratBarra();
              tabelavariavel = new JTable();
              tabelatarefa = new JTable();
              tabelavariavel.getTableHeader().setReorderingAllowed(false);
              tabelavariavel.setModel(new DefaultTableModel());
              tabelavariavel.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
              tabelavariavel.setBackground(Color.cyan);
              tabelatarefa.getTableHeader().setReorderingAllowed(false);
              tabelatarefa.setModel(new DefaultTableModel());
              tabelatarefa.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              tabelatarefa.setBackground(Color.white);
              CaixaCombinacao combobox = new CaixaCombinacao();
              DefaultCellEditor editor = new DefaultCellEditor(combobox);
              tabelatarefa.setDefaultEditor(Object.class, editor);
              painelvariavel = new JPanel();
              painelvariavel.setLayout(new GridLayout(1, 0));
              painelvariavel.setBorder(new TitledBorder("Variaveis"));
              painelvariavel.setBounds(15, 35, 490, 650);
              painelvariavel.setVisible(false);
              this.add(painelvariavel);
              scrollvariavel = new JScrollPane();
              scrollvariavel.setViewportView(tabelavariavel);
              painelvariavel.add(scrollvariavel);
              paineltarefa = new JPanel();
              paineltarefa.setLayout(new GridLayout(1,0));
              paineltarefa.setBorder(new TitledBorder("Tarefas"));
              paineltarefa.setBounds(506, 35, 490,650);
              paineltarefa.setVisible(false);
              this.add(paineltarefa);
              scrolltarefa = new JScrollPane();
              scrolltarefa.setViewportView(tabelatarefa);
              paineltarefa.add(scrolltarefa);
              tamanholinhas = 1;
              linhas=1;
              cont=0;
              JMenu arquivo = new JMenu("Arquivo");
              JMenu mtabela = new JMenu("Tabela");
              arquivo.setMnemonic(KeyEvent.VK_A);
              mtabela.setMnemonic(KeyEvent.VK_T);
              miadvariavel = new JMenuItem("Adicionar Variavel");
              miadtarefa = new JMenuItem("Adicionar Tarefa");
              abrir = new JMenuItem("Abrir");
              guardar = new JMenuItem("Guardar");
              sair = new JMenuItem("Sair");
              sair.addActionListener(trat);
              miadvariavel.addActionListener(trat);
              miadtarefa.addActionListener(trat);
              mtabela.add(miadvariavel);
              miadvariavel.setMnemonic(KeyEvent.VK_V);
              mtabela.add(miadtarefa);
              miadtarefa.setMnemonic(KeyEvent.VK_F);
              arquivo.add(abrir);
              abrir.setMnemonic(KeyEvent.VK_B);
              arquivo.add(guardar);
              guardar.setMnemonic(KeyEvent.VK_G);
              arquivo.addSeparator();
              arquivo.add(sair);
              sair.setMnemonic(KeyEvent.VK_S);
              barra.add(arquivo);
              barra.add(mtabela);
              jTabbedPane1 = new JTabbedPane();
              contentPane = (JPanel)this.getContentPane();
              paineltabela = new JPanel();
              painelgrafo = new JPanel();
              // jTabbedPane1
              jTabbedPane1.addTab("Tabela", paineltabela);
              jTabbedPane1.addTab("Grafo", painelgrafo);
              jTabbedPane1.addChangeListener(new ChangeListener() {
                   public void stateChanged(ChangeEvent e)
                        painelvariavel.setVisible(false);
              // contentPane
              contentPane.setLayout(null);
              addComponent(contentPane, jTabbedPane1, 11,10,990,690);
              // paineltabela
              paineltabela.setLayout(null);
              // painelgrafo
              painelgrafo.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
              // Poseidon
              this.setTitle("UMa Poseidon");
              this.setLocation(new Point(2, 1));
              this.setSize(new Dimension(558, 441));
              this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              this.setExtendedState(MAXIMIZED_BOTH);
         /** Add Component Without a Layout Manager (Absolute Positioning) */
         private void addComponent(Container container,Component c,int x,int y,int width,int height)
              c.setBounds(x,y,width,height);
              container.add(c);
         // TODO: Add any appropriate code in the following Event Handling Methods
         private void jTabbedPane1_stateChanged(ChangeEvent e)
              System.out.println("\njTabbedPane1_stateChanged(ChangeEvent e) called.");
              // TODO: Add any handling code here
         // TODO: Add any method code to meet your needs in the following area
         private class TratBarra implements ActionListener{
              public void actionPerformed(ActionEvent e){
                   if(e.getSource() == sair){
                        int op = JOptionPane.showConfirmDialog(null, "Deseja mesmo fechar o aplicativo?","Sair", JOptionPane.YES_NO_OPTION);
                        if(op == JOptionPane.YES_OPTION){
                             System.exit(0);
                   if(e.getSource() == miadvariavel){
                        final JFrame w = new JFrame();
                        new AdVariavel(w);
                   if(e.getSource() == miadtarefa){
                        final JFrame w = new JFrame();
                        new AdTarefa(w);
    //============================= Testing ================================//
    //=                                                                    =//
    //= The following main method is just for testing this class you built.=//
    //= After testing,you may simply delete it.                            =//
    //======================================================================//
         public static void main(String[] args)
              Spash sp = new Spash(3000);
              sp.mostraTela();
              JFrame.setDefaultLookAndFeelDecorated(true);
              JDialog.setDefaultLookAndFeelDecorated(true);
              try
                   UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
              catch (Exception ex)
                   System.out.println("Failed loading L&F: ");
                   System.out.println(ex);
              new Poseidon();
    //= End of Testing =
    private class AdVariavel extends JDialog
         // Variables declaration
         private JLabel jLabel1;
         private JTextField jTextField1;
         private JButton varOK;
         private JButton varCancel;
         private JPanel contentPane;
         private JTextField jTextField2;
         private JList listadominio;
         private JScrollPane jScrollPane1;
         private JButton varAdiciona;
         private JButton varRemove;
         private JPanel jPanel1;
         private DefaultListModel modelo1;
         // End of variables declaration
         public AdVariavel(Frame w)
              super(w);
              initializeComponent();
              // TODO: Add any constructor code after initializeComponent call
              this.setVisible(true);
          * This method is called from within the constructor to initialize the form.
          * WARNING: Do NOT modify this code. The content of this method is always regenerated
          * by the Windows Form Designer. Otherwise, retrieving design might not work properly.
          * Tip: If you must revise this method, please backup this GUI file for JFrameBuilder
          * to retrieve your design properly in future, before revising this method.
         private void initializeComponent()
              modelo1 = new DefaultListModel();
              jLabel1 = new JLabel();
              jTextField1 = new JTextField();
              varOK = new JButton();
              varCancel = new JButton();
              contentPane = (JPanel)this.getContentPane();
              jTextField2 = new JTextField();
              listadominio = new JList(modelo1);
              jScrollPane1 = new JScrollPane();
              varAdiciona = new JButton();
              varRemove = new JButton();
              jPanel1 = new JPanel();
              // jLabel1
              jLabel1.setText("Nome da vari�vel:");
              // jTextField1
              jTextField1.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jTextField1_actionPerformed(e);
              // varOK
              varOK.setText("OK");
              varOK.setMnemonic(KeyEvent.VK_O);
              varOK.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        varOK_actionPerformed(e);
              // varCancel
              varCancel.setText("Cancelar");
              varCancel.setMnemonic(KeyEvent.VK_C);
              varCancel.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        varCancel_actionPerformed(e);
              // contentPane
              contentPane.setLayout(null);
              addComponent(contentPane, jLabel1, 12,12,105,18);
              addComponent(contentPane, jTextField1, 118,10,137,22);
              addComponent(contentPane, varOK, 170,227,83,28);
              addComponent(contentPane, varCancel, 257,227,85,28);
              addComponent(contentPane, jPanel1, 12,42,332,180);
              // jTextField2
              jTextField2.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jTextField2_actionPerformed(e);
              // listadominio
              listadominio.addListSelectionListener(new ListSelectionListener() {
                   public void valueChanged(ListSelectionEvent e)
                        listadominio_valueChanged(e);
              // jScrollPane1
              jScrollPane1.setViewportView(listadominio);
              // varAdiciona
              varAdiciona.setText("Adicionar");
              varAdiciona.setMnemonic(KeyEvent.VK_A);
              varAdiciona.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        varAdiciona_actionPerformed(e);
              // varRemove
              varRemove.setText("Remover");
              varRemove.setMnemonic(KeyEvent.VK_R);
              varRemove.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        varRemove_actionPerformed(e);
              // jPanel1
              jPanel1.setLayout(null);
              jPanel1.setBorder(new TitledBorder("Dominio:"));
              addComponent(jPanel1, jTextField2, 17,22,130,22);
              addComponent(jPanel1, jScrollPane1, 165,21,154,144);
              addComponent(jPanel1, varAdiciona, 56,50,89,28);
              addComponent(jPanel1, varRemove, 57,84,88,28);
              // AdTarefas
              this.setTitle("Adicionar Variavel");
              this.setLocation(new Point(1, 0));
              this.setSize(new Dimension(367, 296));
              this.setLocationRelativeTo(null);
              this.setResizable(false);
         /** Add Component Without a Layout Manager (Absolute Positioning) */
         private void addComponent(Container container,Component c,int x,int y,int width,int height)
              c.setBounds(x,y,width,height);
              container.add(c);
         // TODO: Add any appropriate code in the following Event Handling Methods
         private void jTextField1_actionPerformed(ActionEvent e)
              System.out.println("\njTextField1_actionPerformed(ActionEvent e) called.");
              // TODO: Add any handling code here
         private void varOK_actionPerformed(ActionEvent e)
              System.out.println("\nvarOK_actionPerformed(ActionEvent e) called.");
              if (jTextField1 == null){
                   return;
              if (jTextField1.getText().length()<1){
                   JOptionPane.showMessageDialog(null,"N�o introduziu nenhuma variavel","AVISO", 1 );
                   jTextField1.requestFocus();
                   return;
              else {
                   if (modelo1.getSize() == 0){
                        JOptionPane.showMessageDialog(null,"N�o introduziu nenhum dominio","AVISO", 1 );
                        return;
                   else{
                        painelvariavel.add(scrollvariavel);
                        index = 0;
                        variavel = jTextField1.getText();
                        contastring = variavel.length();
                        System.out.println(contastring);
                        DefaultTableModel dtm = (DefaultTableModel)tabelavariavel.getModel();
                        tabelavariavel.getTableHeader().setBackground(Color.yellow);
                        dtm.addColumn(variavel, new Object[]{});
                        al = modelo1.getSize();
                        totallinhas = al;
                        for(int i = 0;i < modelo1.getSize();i++){
                             listadominio.setSelectedIndex(index) ;
                             Object dominio = listadominio.getSelectedValue();
                             dtm.addRow(new Object[]{dominio});
                             index ++;
                        tabelasvar[cont] = tabelavariavel;
                        cont++;
                        System.out.println(cont);
                        for(int i=0;i<cont;i++){
                             tabelateste = tabelasvar;
                             linhas = tabelateste.getRowCount();
                             if (linhas >= tamanholinhas){
                                  tamanholinhas = linhas;
                        for (int i=0;i<cont;i++){
                             tabelateste = tabelasvar[i];
                             System.out.println(linhas);
                             linhas = tabelateste.getRowCount();
                             tabelateste.setRowHeight((tamanholinhas/linhas)*20);
                             tabelasvar[i] = tabelateste;
                             System.out.println(tabelateste);
                   tabelavariavel = new JTable();
              scrollvariavel = new JScrollPane();
              painelvariavel.add(tabelavariavel);
              tabelavariavel.setBackground(Color.cyan);
         tabelavariavel.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
                   scrollvariavel.setViewportView(tabelavariavel);
                   painelvariavel.setVisible(true);
         tabelavariavel.getTableHeader().setReorderingAllowed(false);
         this.setVisible(false);
         miadtarefa.setEnabled(true);
         miadvariavel.setEnabled(true);
         DefaultTableModel dtm = (DefaultTableModel)tabelatarefa.getModel();
                   tabelatarefa.getTableHeader().setBackground(Color.yellow);
                   controlalinhas = tamanholinhas - linhastarefa;
                   for(int i = 0;i < controlalinhas;i++){
                             dtm.addRow(new Object[]{});
                             linhastarefa++;
                   tabelatarefa.setRowHeight((tamanholinhas/linhas)*20);
              // TODO: Add any handling code here
         private void varCancel_actionPerformed(ActionEvent e)
              System.out.println("\nvarCancel_actionPerformed(ActionEvent e) called.");
              this.setVisible(false);
         private void jTextField2_actionPerformed(ActionEvent e)
              System.out.println("\njTextField2_actionPerformed(ActionEvent e) called.");
              // TODO: Add any handling code here
         private void listadominio_valueChanged(ListSelectionEvent e)
              System.out.println("\nlistadominio_valueChanged(ListSelectionEvent e) called.");
              if(!e.getValueIsAdjusting())
                   Object o = listadominio.getSelectedValue();
                   System.out.println(">>" + ((o==null)? "null" : o.toString()) + " is selected.");
                   // TODO: Add any handling code here for the particular object being selected
         private void varAdiciona_actionPerformed(ActionEvent e)
              System.out.println("\nvarAdiciona_actionPerformed(ActionEvent e) called.");
              if(jTextField2.getText().length()>=1){
                   modelo1.addElement(jTextField2.getText());
                   jTextField2.setText("");
                   jTextField2.requestFocus();
         private void varRemove_actionPerformed(ActionEvent e)
              System.out.println("\nvarRemove_actionPerformed(ActionEvent e) called.");
              int index = listadominio.getSelectedIndex();
              modelo1.remove(index);
         // TODO: Add any method code to meet your needs in the following area
    private class AdTarefa extends JDialog
         // Variables declaration
         private JLabel jLabel1;
         private JTextField jTextField1;
         private JButton tarOK;
         private JButton tarCancel;
         private JPanel contentPane;
         private JPanel jPanel1;
         // End of variables declaration
         public AdTarefa(Frame w)
              super(w);
              initializeComponent();
              // TODO: Add any constructor code after initializeComponent call
              this.setVisible(true);
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always regenerated
         * by the Windows Form Designer. Otherwise, retrieving design might not work properly.
         * Tip: If you must revise this method, please backup this GUI file for JFrameBuilder
         * to retrieve your design properly in future, before revising this method.
         private void initializeComponent()
              jLabel1 = new JLabel();
              jTextField1 = new JTextField();
              tarOK = new JButton();
              tarCancel = new JButton();
              contentPane = (JPanel)this.getContentPane();
              // jLabel1
              jLabel1.setText("Nome da tarefa:");
              // jTextField1
              jTextField1.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jTextField1_actionPerformed(e);
              // tarOK
              tarOK.setText("OK");
              tarOK.setMnemonic(KeyEvent.VK_O);
              tarOK.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        tarOK_actionPerformed(e);
              // tarCancel
              tarCancel.setText("Cancelar");
              tarCancel.setMnemonic(KeyEvent.VK_C);
              tarCancel.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        tarCancel_actionPerformed(e);
              // contentPane
              contentPane.setLayout(null);
              addComponent(contentPane, jLabel1, 12,12,105,18);
              addComponent(contentPane, jTextField1, 118,10,120,22);
              addComponent(contentPane, tarOK, 10,50,83,28);
              addComponent(contentPane, tarCancel, 153,50,85,28);
              // AdTarefas
              this.setTitle("Adicionar Tarefa");
              this.setLocation(new Point(1, 0));
              this.setSize(new Dimension(250, 120));
              this.setLocationRelativeTo(null);
              this.setResizable(false);
         /** Add Component Without a Layout Manager (Absolute Positioning) */
         private void addComponent(Container container,Component c,int x,int y,int width,int height)
              c.setBounds(x,y,width,height);
              container.add(c);
         // TODO: Add any appropriate code in the following Event Handling Methods
         private void jTextField1_actionPerformed(ActionEvent e)
              System.out.println("\njTextField1_actionPerformed(ActionEvent e) called.");
              // TODO: Add any handling code here
         private void tarOK_actionPerformed(ActionEvent e)
              System.out.println("\ntarOK_actionPerformed(ActionEvent e) called.");
              if (jTextField1 == null){
                   return;
              if (jTextField1.getText().length()<1){
                   JOptionPane.showMessageDialog(null,"N�o introduziu nenhuma tarefa","AVISO", 1 );
                   jTextField1.requestFocus();
                   return;
              else{
                   String variavel = jTextField1.getText();
                   DefaultTableModel dtm = (DefaultTableModel)tabelatarefa.getModel();
                   dtm.addColumn(variavel,new Object[]{});
                   controlalinhas = tamanholinhas - linhastarefa;
                   for(int i = 0;i < controlalinhas;i++){
                             dtm.addRow(new Object[]{});
                             linhastarefa++;
                   for(int i=0; i < tabelatarefa.getColumnCount(); i++){
                        tabelatarefa.getColumnModel().getColumn(i).setPreferredWidth(100);
                   tabelatarefa.getColumnModel().getColumn(i).setResizable(false);
                   tabelatarefa.getTableHeader().setBackground(Color.yellow);
                   tabelatarefa.setRowHeight((tamanholinhas/linhas)*20);
                   paineltarefa.setVisible(true);
         tabelatarefa.getTableHeader().setReorderingAllowed(true);
         this.setVisible(false);
         miadtarefa.setEnabled(true);
         miadvariavel.setEnabled(true);
         // TODO: Add any handling code here
         private void tarCancel_actionPerformed(ActionEvent e)
              System.out.println("\ntarCancel_actionPerformed(ActionEvent e) called.");
              this.setVisible(false);
    now the code to create the JComboBox is here:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class CaixaCombinacao extends JComboBox{
         ImageIcon[] imagens;
        String[] op = {"x", "check"};
    public CaixaCombinacao(){
         imagens = new ImageIcon[op.length];
        Integer[] intArray = new Integer[op.length];
        for (int i = 0; i < op.length; i++) {
             intArray[i] = new Integer(i);
            imagens[i] = createImageIcon("imagens/" + op[i] + ".gif");
            this.addItem(imagens);
    if (imagens[i] != null) {
    imagens[i].setDescription(op[i]);
         JComboBox lista = new JComboBox(intArray);
         ComboBoxRenderer renderer= new ComboBoxRenderer();
         lista.setRenderer(renderer);
    protected static ImageIcon createImageIcon(String path) {
    java.net.URL imgURL = CaixaCombinacao.class.getResource(path);
    if (imgURL != null) {
         return new ImageIcon(imgURL);
    return null;
    class ComboBoxRenderer extends JLabel
    implements ListCellRenderer {
    public ComboBoxRenderer() {
    setOpaque(true);
    setHorizontalAlignment(CENTER);
    setVerticalAlignment(CENTER);
    public Component getListCellRendererComponent(
    JList list,
    Object value,
    int index,
    boolean isSelected,
    boolean cellHasFocus) {
                   int selectedIndex = ((Integer)value).intValue();
                   if (isSelected) {
    setBackground(list.getSelectionBackground());
    setForeground(list.getSelectionForeground());
    } else {
    setBackground(list.getBackground());
    setForeground(list.getForeground());
                   ImageIcon icon = imagens[selectedIndex];
                   String opc = op[selectedIndex];
    setIcon(icon);
    return this;

    I'm sure 90% of the code posted here has nothing to do with displaying images in a JTable.
    Here is an example that shows how to display an icon in a table:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableIcon extends JFrame
         public TableIcon()
              String[] columnNames = {"Picture", "Description"};
              Object[][] data =
                   {new ImageIcon("copy16.gif"), "Copy"},
                   {new ImageIcon("add16.gif"), "Add"},
              DefaultTableModel model = new DefaultTableModel(data, columnNames);
              JTable table = new JTable( model )
                   //  Returning the Class of each column will allow different
                   //  renderers to be used based on Class
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              TableIcon frame = new TableIcon();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }If this doesn't help then post a similiar demo program that shows the problems you are having, not your entire application.

  • Changing the size of a JComboBox

    Greetings,
    I am trying to build a mechanism to perform zooming on a JPanel with an arbitrary collection of components (including nested JPanels). I've tried a number of things with little success. The following is my most promising contraption. It can zoom labels, textfields, checkboxes, and buttons. However, for some reason, the combo box refuses to accept a changes to its size. I'm not sure why this is the case. Its font changes size appropriately.
    Anyway, I'm running in JDK 1.4, and the following program lays out a palette of components. To change the size of the components, hit F1 to zoom in, and F2 to zoom out.
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.KeyEventPostProcessor;
    import java.awt.KeyboardFocusManager;
    import java.awt.event.KeyEvent;
    import java.awt.geom.AffineTransform;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class Demo extends JPanel
        public class Zoomer
            private double m_zoom = 1;
            private JPanel m_panel;
            public Zoomer(JPanel panel)
                m_panel = panel;
            private AffineTransform getTransform()
                return AffineTransform.getScaleInstance(m_zoom, m_zoom);
            private Font transform(Font font)
                return font.deriveFont(getTransform());
            private Dimension transform(Dimension dimension)
                Dimension retval = new Dimension();
                retval.setSize(dimension.getWidth() * m_zoom, dimension.getHeight() * m_zoom);
                return retval;
            private void performZoom(Container container)
                Component[] components = container.getComponents();
                for(int i = 0; i < components.length; i++)
                    Component component = (Component)components;
    component.setFont(transform(component.getFont()));
    component.setSize(transform(component.getSize()));
    for(int i = 0; i < components.length; i++)
    Component component = components[i];
    if(component instanceof Container)
    performZoom((Container)component);
    public double getZoom()
    return m_zoom;
    public void setZoom(double zoom)
    if(zoom > 8.0 || zoom < 0.125) return;
    m_zoom = zoom;
    performZoom(m_panel);
    public void zoom(double factor)
    setZoom(getZoom() * factor);
    public Demo()
    JPanel panel = new JPanel();
    panel.add(buildPanel());
    panel.add(buildPanel());
    final Zoomer zoomer = new Zoomer(panel);
    add(panel);
    KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventPostProcessor(new KeyEventPostProcessor()
    public boolean postProcessKeyEvent(KeyEvent e)
    if(e.getID() != KeyEvent.KEY_PRESSED) return false;
    if(e.getKeyCode() == KeyEvent.VK_F1)
    zoomer.zoom(1.2);
    if(e.getKeyCode() == KeyEvent.VK_F2)
    zoomer.zoom(1/1.2);
    return false;
    private JPanel buildPanel()
    JPanel panel = new JPanel();
    panel.add(new JLabel("label: "));
    panel.add(new JTextField("Hello World"));
    panel.add(new JCheckBox("checkbox"));
    panel.add(new JComboBox(new String[] { "Bread", "Milk", "Butter" }));
    panel.add(new JButton("Hit Me!"));
    return panel;
    * Create the GUI and show it. For thread safety, this method should be
    * invoked from the event-dispatching thread.
    private static void createAndShowGUI()
    // Create and set up the window.
    JFrame frame = new JFrame("Demo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Create and set up the content pane.
    Demo newContentPane = new Demo();
    newContentPane.setOpaque(true); // content panes must be opaque
    frame.setContentPane(newContentPane);
    // Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args)
    // Schedule a job for the event-dispatching thread:
    // creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable()
    public void run()
    createAndShowGUI();

    component.setSize(transform(component.getSize()));First of all the above line is not needed. The LayoutManager will determine the bounds (size and location) of each component in the container based on the rules of the LayoutManager. The Flow Layout is the default layout manager for a panel and it simply uses the preferred size of the component as the size of the component.
    So what happens is that when you change the font of the component you are changing the preferred size of the component.
    So why doesn't the combo box work? Well I took a look at the preferred size calculation of the combo box (from the BasicComboBoxUI) and it actually caches the preferred size. The combo box uses a renderer, so the value is cached for performance one would assume. The method does recalculate the size when certain properties change. Note the isDisplaySizeDirty flag used in the code below:
             else if (propertyName.equals("prototypeDisplayValue")) {
                    isMinimumSizeDirty = true;
                    isDisplaySizeDirty = true;
                    comboBox.revalidate();
             else if (propertyName.equals("renderer")) {
                    isMinimumSizeDirty = true;
                    isDisplaySizeDirty = true;
                    comboBox.revalidate();
                }It also handles a Font property change as well:
                else if ( propertyName.equals( "font" ) ) {
                    listBox.setFont( comboBox.getFont() );
                    if ( editor != null ) {
                        editor.setFont( comboBox.getFont() );
                    isMinimumSizeDirty = true;
                    comboBox.validate();
                }but notice that the isDisplaySizeDirty flag is missing. This would seem to be a bug (but I don't know why two flags are required).
    Anyway, the following change to your code seems to work:
    // component.setSize(transform(component.getSize()));
    if (component instanceof JComponent)
         ((JComponent)component).updateUI();
    }

  • How to create a default value for a JComboBox through his model

    Hi,
    I have created a "myComboBox" component.
    This component extend the standard Java JComboBox and simply add some helper features.
    The values that "myComboBox" display are coming from his bound model. (In fact, "myComboBox" has been designed to allow JComboBox to be implemented accordingly to the MVC design pattern: The model contains the data, the view the GUI and the controller handle the GUI events).
    My question is how can I add a default "none" item to the content displayed by an instance of "myComboBox" without doing any refactoring of the existing code implementing "myComboBox" ?
    Thank you very much for your help.

    It sounds like what you really want is to display "None" when the selected index = -1. Simple, write a custom list cell renderer that display's something instead of nothing when the index is -1.

  • JComboBox - Bottom border is not visible for the first time

    JComboBox - Bottom border is not visible for the first time i click on the arrow to drop the list down.
    This happens because the list when dropped down goes out of the frame.
    If have the increased the size of the Frame then i am able to see it,but i dont want to do this.
    I am using jdk1.3.1_02.
    Any Help would be great.
    Please find the code below.
    Thanks,
    Sridhar.
    //file: Lister.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Lister {
        public static void main(String[] args) {
            JFrame frame = new JFrame("Lister v1.0");
            // create a combo box
            String [] items = { "uno", "due", "tre", "quattro", "cinque",
            "sei", "sette", "otto", "nove", "deici",
            "undici", "dodici" };
            JComboBox comboBox = new JComboBox(items);
            comboBox.setEditable(true);
            // put the controls the content pane
            Container c = frame.getContentPane( );
            JPanel comboPanel = new JPanel( );
            comboPanel.add(comboBox);
            c.add(comboPanel, BorderLayout.NORTH);
            c.setBackground(Color.white);
            comboBox.setBackground(Color.white);
            comboPanel.setBackground(Color.white);
            frame.setBackground(Color.white);
            frame.setResizable(false);
            frame.setSize(200, 200);
            frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            frame.setVisible(true);
    }

    Hello,
    try this:JPanel comboPanel = new JPanel(new BorderLayout());Regards,
    Tim

Maybe you are looking for

  • "disk could not be read"? WHAT?

    Anyone heard of this...during the process of updating my ipod on itunes (loading more music on my ipod) the update stops and this message comes up..."Attempting to copy to the disk "XXXX's IPOD" failed. The disk could not be read from or written to."

  • Process Types in Process Chains - Loading - Repeatable/repairable

    Hi, I know SAP recommends that we do not change the properties of the Process Types for Process Chains. I want to know if any one has ever changed the property of "LOADING" process type to "repeatable" or "repairable". We are keen to change this attr

  • Website images not displaying on Windows 7?

    I just put this site up recently: www.bltcoffee.com  I used Dreamweaver 8 to create it. I've checked the pages on both PCs and Macs and it seems to work fine, but a friend of mine has a newer PC running Windows 7. He says that when he clicks on the E

  • " Returns from customers" process

    I want to create inspection plan for " Returns from customers". In this case what should be the task list usage code? Regards, Vemula

  • Sent mail reappears

    Whenever I send an email from my BlackBerry's email program (which is attached to my gmail account), the sent message reappears after I've sent it. I have gone to options and picked Hide Sent Messages, yet this still happens. Please advise. Thanks. S