Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

updating a combobox contents

Status
Not open for further replies.

cram81

Technical User
Dec 27, 2003
29
GB
hi
im really stuck with my combobox. I have a button on my gui which says add sound which adds a filename to my database and then consequently should update the combobox.

The problem is sometimes the combox is updated when othertimes it goes completely blank but when i click in it the filenames then appear.. thus i know the database update is fine and its even loading them into the combobox but they are not appearing on their own....

my loadAccounts() method for updating the combox basically involves:
getting the query results as a vector... formatting each element of the vector so that its compatible with the database then adding the new string to a new vector called vtry. (as seen below)
Code:
 soundVector = mydb.loadAccounts("sounds", "sound_path", "sound_id");
        vtry.removeAllElements();
        for(int i=0; i < soundVector.size(); i++)
          {              
            String s = (String)soundVector.get(i);
            stringCorrect test = new stringCorrect();
            vtry.add(test.soundPath(s));
        }

I need some sort of combobox update method....or something
I originally initialise the combobox with the vector vtry and so i thought if vtry was an instance variable for the class it would automatically update the contents of the combobox....

If any one could help it would be very much ap
preicated...

thanks

mark

my full code is listed below...
Code:
package db;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.sql.*;
import java.util.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.*;
import java.applet.AudioClip;
import java.net.URL;
import java.net.MalformedURLException;
import java.lang.*;
import javax.swing.table.TableColumn;

public class ComboProblem extends JFrame implements ActionListener,
                                         ItemListener {      
    private JButton loadFile,
                    loadSoundFile,                   
                    loadSoundButton,
                    deleteSoundButton
                  ;
                    
    private JList sList;
    private JTextField userIDText,
                       usernameText,
                       sirNameText,
                       passwordText,
                       pictureIDText,
                       q_numText,
                       sound_id,
                       sound_text,
                       soundIDText,
                       soundTextText,
                       fileName,
                       soundFileName,
                       soundName,
                       currentPicText,
                       emailAddressText,
                       disabledText,
                       regQText,
                       noOpenQText,
                       noClsdQText,
                       noCondQText,
                       qNameText,
                       qIDText;
    private JLabel idLabel, nameLabel,sirNameLabel, passwordLabel,pictureIDLabel, qNumLabel,soundIDLabel,soundTextLabel,soundLabel,
    emailAddressLabel, disabledLabel, regQLabel, noOpenQLabel, noClsdQLabel, noCondQLabel, qNameLabel, qIDLabel;
    private JTabbedPane tabpane;
    private Connection connection, conx2;  
    private Statement statement, s2,s3;
    private ResultSet rs2, rs3;
    private JTextArea errorText;
    private ArrayList userInfoList, questionList, answerList, templateList;
    private String currentUserId;
    private JButton nextPic, prevPic;
    private JFileChooser chooser;

    public DbWork mydb;
    public String imgPath;
    private int tot;
    public String currentID;
    
    // sounds
    SoundList soundList;
    
    String chosenFile;
    Vector soundVector;
    Vector vtry; 
    
    AudioClip onceClip, loopClip;
    URL codeBase;

    JComboBox formats;
    JButton playButton, loopButton, stopButton;
    JLabel status;
    boolean looping = false;
                          
    Container c;
    
    public ComboProblem(){
        initGui();
        mydb = new DbWork();
    }
    public void actionPerformed(ActionEvent event) {
        //PLAY BUTTON
        Object source = event.getSource();
        if (source == playButton) {
            //Try to get the AudioClip.
            onceClip = soundList.getClip(chosenFile);
            stopButton.setEnabled(true);
            onceClip.play();     //Play it once.
            status.setText("Playing sound " + chosenFile + ".");
            if (onceClip == null) {
                status.setText("Sound " + chosenFile + " not loaded yet.");
            }
            return;
        }     
        //STOP LOOP BUTTON
        if (source == stopButton) {
                if (onceClip != null) {
                onceClip.stop();
            }
            stopButton.setEnabled(false);
            status.setText("Stopped playing " + chosenFile + ".");
            return;
        }
    }
      public void stop() {
        onceClip.stop();        //Cut short the one-time sound.
    } 
    public void itemStateChanged(ItemEvent e){
        chosenFile = (String)formats.getSelectedItem();
        soundList.startLoading(chosenFile);
    }
     void startLoadingSounds(Vector v) {
        try {
            codeBase = new URL("file:C:/");
        } catch (MalformedURLException e) {
            System.err.println(e.getMessage());
        }

        System.out.println("file:" + System.getProperty("user.dir") + "/");        
        soundList = new SoundList(codeBase);

         for(int i=0; i < v.size(); i++)
          {              
         String s = (String)v.get(i);
         System.out.println("PLEASE : " + s);
         soundList.startLoading(s);
         }        
    }
     
    public void initGui(){
   
        
        nextPic = new JButton(">");
        prevPic = new JButton("<");
        loadFile = new JButton("Browse");
        loadSoundFile = new JButton("Browse");
        chooser = new JFileChooser();      
        currentPicText = new JTextField(5);
        sList = new JList();
        vtry = new Vector();
        //formats = new JComboBox();
        
        idLabel = new JLabel("User ID");
        nameLabel = new JLabel("Name");
        sirNameLabel = new JLabel("Surname");
        passwordLabel = new JLabel("Password");

        pictureIDLabel = new JLabel("Pic ID");
        qNumLabel = new JLabel("Num of Q");
        soundIDLabel = new JLabel("Sound Clip Id");
        soundTextLabel = new JLabel("Users Sound Text");
        emailAddressLabel = new JLabel("Email");
        disabledLabel = new JLabel("Disabled");
        regQLabel = new JLabel("No. Registered Q");
        noOpenQLabel = new JLabel("No. of open questions");
        noClsdQLabel = new JLabel("No. of closed questions");
        noCondQLabel = new JLabel("No. of condtional questions");
        qNameLabel = new JLabel("Name: ");
        qIDLabel = new JLabel("ID: ");
               
        errorText = new JTextArea(3,30);
        errorText.setEditable(false);
                                    
        //**********  Sounds Setup  **************//
        soundLabel = new JLabel("Filename");
        loadSoundButton = new JButton("Add Sound");
        deleteSoundButton = new JButton("Delete Sound");
        
    }
    
    // This method passes parameters to do db query. I know it is query is working ok.
    private void loadAccountInfo(){         
              
        soundVector = mydb.loadAccounts("sounds", "sound_path", "sound_id");
        vtry.removeAllElements();
        for(int i=0; i < soundVector.size(); i++)
          {              
            String s = (String)soundVector.get(i);
            stringCorrect test = new stringCorrect();
            vtry.add(test.soundPath(s));
        }
        
        upDateError();
        mydb.resetError();
    }
    
    private void insertSoundButton(){
     loadSoundButton.addActionListener (
      new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            
            stringCorrect s = new stringCorrect();
            System.out.println("Filename: " + soundFileName.getText());
            System.out.println("CORRECTION: " + s.correctString(soundFileName.getText()));
             if(soundFileName.getText().equals(""))
                        {
                        JOptionPane.showMessageDialog(ComboProblem.this,"Please enter a valid file name","Warning!",JOptionPane.INFORMATION_MESSAGE);   
                        }else{
                            mydb.insertSoundQuery(soundFileName.getText());
                            loadAccountInfo();
                            //formats.setSelectedIndex(0);
                        }
        }
      }
    );   
    }
    
    private void removeSoundButton()
    {
     deleteSoundButton.addActionListener( 
            new ActionListener() {
                public void actionPerformed (ActionEvent e) {
                    System.out.print("DELETE: " + chosenFile);
                    stringCorrect temp = new stringCorrect();
                    String restore = temp.restorePath(chosenFile);
                    System.out.print("SENT: " + restore);
                    mydb.removeSoundQuery(restore);
                    
                    soundVector.removeAllElements();
                    //formats.removeAllItems();
                    loadAccountInfo();
                    formats.setSelectedIndex(0);
                }
            }
            );   
    }
             
    private void buildGUI() {
        c = getContentPane();
        c.setLayout(null);     
        loadAccountInfo();
        
        sList.setVisibleRowCount(2);                
        
        JScrollPane sListScrollPane = new JScrollPane(sList);
        sListScrollPane.getViewport().setView(sList);
        sList.ensureIndexIsVisible(sList.getSelectedIndex());
        
        //**********Picture + Sounds Tab  ************//         
        JPanel psPanel = new JPanel();
        psPanel.setLayout(null);                                
        JPanel soundPanel = new JPanel();
        soundPanel.setBounds(370,10,363,340);
        soundPanel.setLayout(null);
        soundPanel.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0)));
        
        soundPanel.add(soundLabel);
        soundLabel.setBounds(13,25,55,20);
        
        soundFileName = new JTextField(15);
        soundPanel.add(soundFileName);
        soundFileName.setBounds(72, 25,185, 20); 
        
        soundPanel.add(loadSoundFile);
        loadSoundFile.setBounds(265,25, 90, 20);
        loadSoundFile.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            int returnval = chooser.showOpenDialog(loadFile);
            if (returnval == JFileChooser.APPROVE_OPTION) {
                soundFileName.setText(chooser.getSelectedFile().getPath());
            }else {
                soundFileName.setText("Please choose a new file");
                  }
            }
          }
        );
        
        soundPanel.add(loadSoundButton);
        loadSoundButton.setBounds(105,50, 150,20);
        
        JPanel controlPanel = new JPanel();
        controlPanel.setBounds(13,100,330,50);
        controlPanel.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0)));
        soundPanel.add(controlPanel);
       
        formats = new JComboBox(vtry);

        chosenFile = (String)formats.getSelectedItem();
        formats.addItemListener(this);

        playButton = new JButton("Play");
        playButton.addActionListener(this);

        stopButton = new JButton("Stop");
        stopButton.addActionListener(this);
        stopButton.setEnabled(false);
        
        status = new JLabel(
                    "Click Play  to play the selected sound file.");
        
        controlPanel.add(formats);
        controlPanel.add(playButton);
        controlPanel.add(stopButton); 
        
        JPanel statusPanel = new JPanel();
        statusPanel.add(status);
        statusPanel.setBounds(50,160,250,30);
        statusPanel.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0)));

        soundPanel.add(statusPanel);
        
        soundPanel.add(deleteSoundButton);
        deleteSoundButton.setBounds(50,200,250, 30);
        
        startLoadingSounds(vtry);
        insertSoundButton();
        removeSoundButton();
        
        JLabel soundLabel = new JLabel("Sound Setup");
        soundLabel.setBounds(525,15, 100, 20);
        psPanel.add(soundLabel);
       
        psPanel.add(soundPanel);

        //***************End of sound ****************//
                                        
        tabpane = new JTabbedPane(); 
        tabpane.add(psPanel,"Pictures and Sounds");
        tabpane.setBounds(140, 30, 750, 390);              
        c.add(tabpane);       
        setSize(910,521);
        show();
    }
      private void displaySQLErrors(SQLException e) {
        errorText.append("SQLException: " + e.getMessage() + "\n" );
        errorText.append("SQLState:     " + e.getSQLState()+ "\n");
        errorText.append("VendorError:  " + e.getErrorCode()+ "\n");
    }
     public void upDateError()
     {
     errorText.append(mydb.getError()); 
     errorText.append("");
     }
     
      
    private void init() {        
        mydb.connectTODB();
    }
    
    public static void main(String[] args) {
     
       ComboProblem users = new ComboProblem();
       users.addWindowListener(
        new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
       }
       );
       users.init();
       users.buildGUI();
    }              
}



 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Vector;

class MyCombo2 extends JFrame
{
Vector v = new Vector();
int counter;
JComboBox jc;
public MyCombo2()
{
super("Frame1");
counter = 0;
getContentPane().setLayout(new GridLayout(2,1));
jc = new JComboBox();
JButton jb = new JButton("add");
jb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
jc.removeAllItems();
v.add( String.valueOf(counter) );
for (int i=0; i<(counter+1); i++)
jc.addItem( v.get(i) );
counter++;
}
});
getContentPane().add(jb);
getContentPane().add(jc);
}
public static void main(String args[])
{
MyCombo2 MyComboObj = new MyCombo2();
MyComboObj.setSize(400,400);
MyComboObj.setVisible(true);
}
}
 
hi
thanks for your reply but what u typed is what ive done so far. Now say you have another method which updates the contents of your jc ojbject how would u go about updating the display?

thanks

mark
 
suppose your JComboBox data come from a vector object
After you use JComboBox.removeAllItems()
then you use JComboBox.addItem( v.get(i) ) to add all elements(you update the vecotr v to by your data)
The JcomboBox should show all the elements you want, you don't need to update the display
try this method
jc.validate();
jc.updateUI();
 
thanks mate! updateUI() did the trick - i have no idea why it was acting up but thats the last of my bugs!

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top