?
Solved

removing and adding components from JPanel

Posted on 2005-03-10
13
Medium Priority
?
266 Views
Last Modified: 2013-11-23
Hi,
This question is a kind of hard put up:
This GUI: http://people.clarkson.edu/~havenssm/gui2.doc
is contructed with this class:

public class StudentSupportServices extends JFrame
{
    private StudentPanel student;
    private JPanel coursePanel;
    private ProfessorPanel professor;
    private ExamPanel exam;
    private ControlPanel controls;
    private String url;
    private JTextArea output;
    private    Connection accessCon;// = null;
    private Container c;
   
    /** Creates a new instance of StudentInformations */
    public StudentSupportServices()
    {
     
        super("Student Support Services");
        if (!startApplication() ) System.exit(0);

        c = getContentPane();
        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        fileMenu.add(new RenewDatabase());
       
        menuBar.add( fileMenu );
        setJMenuBar(menuBar);
       
        output = new JTextArea();
        output.setEditable(false);
       
        //setup window size
      //  Dimension wndSize = this.getToolkit().getScreenSize();
      //set the position to screen center and size to half screen size.
     //   setBounds(1, 1, wndSize.width -  wndSize.width/8 , wndSize.height/2);
        //setLocationRelativeTo(null);
         
         setDefaultCloseOperation( EXIT_ON_CLOSE );

      //  course = new CoursePanel();
        student = new StudentPanel( );
        professor = new ProfessorPanel();
        exam = new ExamPanel();
       
        JPanel StudentProfessor = new JPanel();
        StudentProfessor.setLayout(new GridLayout(1,2));
        StudentProfessor.add( student );
        StudentProfessor.add( professor );
       
        JPanel StudentCourseProfessorExamPanel = new JPanel();
        StudentCourseProfessorExamPanel.setLayout( new GridLayout(3,1) );
        StudentCourseProfessorExamPanel.add( StudentProfessor );  
        setCoursePanel( );
        StudentCourseProfessorExamPanel.add( coursePanel );
        StudentCourseProfessorExamPanel.add( exam );

        try
        {
         //Connect to ess database.  
            url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" +
            "C:/accessDb/Students.mdb";
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            accessCon = DriverManager.getConnection( url );
            output.append("Connection successful\n");
         
        }
     
        catch( SQLException sqlex )
        {
            //process SQLException
            sqlex.printStackTrace();
            output.append("Connection Uncessful\n" + sqlex.toString() );
        }
          catch( Exception ex )
        {
            //process remaining Exception here
            ex.printStackTrace();
            output.append( ex.toString() );
        }
 
        c.setLayout( new BorderLayout() );
        c.add( StudentCourseProfessorExamPanel ) ;
        controls = new ControlPanel(accessCon, student,professor,this);
        c.add( controls, BorderLayout.NORTH );
        c.add( output, BorderLayout.SOUTH );

       
       pack();
       show();
    }///////////////////// END OF CONSTRUCTOR
   
...
....
   public void updateCombo(JComboBox combo1, JComboBox combo2)  <<<<<======= using this function
   {
       System.out.println("count:" + student.getComponentCount());                    
       student.remove( 0 );
       student.add( combo1, 0);
       student.remove( 1 );
      // student.add( combo1, 0);
       student.add( combo2, 1);
        student.validate();

   }
     ....
}
============
by press refresh button, i would like to remove the two existing comboBox (on studentPanel)
and replace them with new ones after quering the database  using the function flaged above.
How i am quering the db and calling updateCombo(JComboBox combo1, JComboBox combo2)
is how here:
public class RefreshCombo //extends StudentSupportServices
implements ActionListener

{
    private StudentSupportServices sss ;// = new StudentSupportServices();
    private StudentPanel student;
    private Connection connection ;
    private Vector lastNames ;
    private Vector firstNames ;
    private JComboBox lastCombo;
    private JComboBox firstCombo;

    /** Creates a new instance of Refresh */
    public RefreshCombo(Connection con, StudentPanel student, StudentSupportServices sss )
    {
        connection = con;
        this.student = student;
        this.sss = sss;
    }
   
    public void actionPerformed(ActionEvent e)
    {
        Statement s = null;
       // ResultSet lastRs = null;
        ResultSet rs  = null;
         
        try
       {
                s = connection.createStatement();
                rs = s.executeQuery("SELECT [Last Name], [First Name] FROM Student");

               Vector firstNames = new Vector();
               Vector lastNames = new Vector();
       
                while( rs.next() )
                {
                    lastNames.addElement( rs.getString("Last Name") );
                    firstNames.addElement( rs.getString("First Name"));
                 }
               
        lastCombo = new JComboBox( lastNames );
        firstCombo = new JComboBox( firstNames );
        sss.updateCombo(lastCombo, firstCombo );

               s.close();
 
               //student.printaList(students);
       }
       catch (SQLException sqlex)
       {
           sqlex.printStackTrace();
       }

}

}
=====
Everything is working fine, but after i press refresh button, the studentPanel freezes.
I try to print student.getComponentCount( ) i get 2 which wired since StudentPanel has more that 2 component.
Here is StudentPanel class:
public class StudentPanel extends JPanel
{
 private final JTextField idField, phoneField, boxField, accomField;
 private final JComboBox lastCombo, firstCombo;
 
  private Connection con;
 
    /** Creates a new instance of StudentPanel */
    public StudentPanel( )
    {
       
         setLayout(new BorderLayout());
         JPanel labels = new JPanel();
         labels.setLayout( new GridLayout(6,1,0,3) );
           
         JLabel lastLabel = new JLabel("Last Name: ", SwingConstants.RIGHT);
         JLabel firstLabel = new JLabel("First Name: ", SwingConstants.RIGHT);
         JLabel idLabel = new JLabel("Student Num: ", SwingConstants.RIGHT);
         JLabel phoneLabel = new JLabel("Phone #: ", SwingConstants.RIGHT);
         JLabel boxLabel = new JLabel("Box #: ", SwingConstants.RIGHT);          
         JLabel accomLabel = new JLabel("Accomodation: ", SwingConstants.RIGHT);          
         
         labels.add(lastLabel );
         labels.add( firstLabel);
         labels.add(idLabel );
         labels.add(phoneLabel );
         labels.add( boxLabel );
         labels.add( accomLabel);
         
         JPanel fields = new JPanel();
         fields.setLayout( new GridLayout(6,1,0,3) );
       
         lastCombo = new JComboBox( ) ;
         lastCombo.setEditable(true);
         firstCombo = new JComboBox( ) ;
         firstCombo.setEditable(true);

         idField  = new JTextField();
         phoneField = new JTextField(5);
         boxField = new JTextField(5);
         accomField = new JTextField();
         
         fields.add( lastCombo );
         fields.add(firstCombo);
         fields.add(idField );
         fields.add(phoneField );
         fields.add( boxField );
         fields.add( accomField);
         
         add( labels, BorderLayout.WEST);
         add(fields, BorderLayout.CENTER);

         setBorder(new TitledBorder(new EtchedBorder(),"Student: "));

}
    //return last name
    public String getLast()
    {
        return ((String)lastCombo.getSelectedItem()).trim();
    }
   
    //return first name
    public String getFirst()
    {
        return ( (String)firstCombo.getSelectedItem()).trim();
    }
   
    //return student num
    public String getStudentNum()
    {
        return ( (String)idField.getText() ).trim();
    }

    //return phone #
    public String getPhoneNum()
    {
        return ( (String)phoneField.getText() ).trim();
    }
   
    //return Box num
    public String getBoxNum()
    {
        return ( (String)boxField.getText() ).trim();
    }
   
    public String getAccom()
    {
        return ( (String)accomField.getText() ).trim();
    }
   
    public void setLastName( String text )
    {
        lastCombo.setSelectedItem( text );
    }
   
    public void setFirstName ( String text )
    {
        firstCombo.setSelectedItem( text );
    }
   
    public void setStudentNum ( String text )
    {
        idField.setText( text );
    }
   
    public void setPhoneNum ( String text )
    {
       phoneField.setText( text );
    }
   
    public void setBoxNum ( String text )
    {
        boxField.setText( text );
    }
   
    public void setAccom ( String text )
    {
        accomField.setText( text );
    }

...So my question is how can i replace the existing comboBox with new new ones by pressing refresh button?

0
Comment
Question by:komlaaa
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
  • 3
  • +1
13 Comments
 
LVL 92

Expert Comment

by:objects
ID: 13513811
your student panel only appears to contain two components (labels and fields) neither of which are combos.
Also can't see why you need to replace the combos, a better approach would be to assign them a new model (see the setModel() method)
0
 

Author Comment

by:komlaaa
ID: 13514066
>>....neither of which are combos.
i do have two combo as u can see below and on the GUI posted
  lastCombo = new JComboBox( ) ;
         lastCombo.setEditable(true);
         firstCombo = new JComboBox( ) ;
         firstCombo.setEditable(true);

0
 

Author Comment

by:komlaaa
ID: 13514180
I am not sure how to use this function to change my combo( ) to  combo( Vector );
public void setModel(ComboBoxModel aModel)
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 13514193
astCombo = new JComboBox(YourVectorObject ) ;
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 13514200
there is a constructor available for you that takes vector as an argument
http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JComboBox.html#JComboBox(java.util.Vector)
0
 

Author Comment

by:komlaaa
ID: 13514204
myCombo.setModel( ..... i am not sure  what to pass here ) , of course a ComboBoxModel, but how to use it since it is an interface.

Please help out.
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 13514210
I think I am bit confused. Sorry for last postings
0
 

Author Comment

by:komlaaa
ID: 13514264
how to use setModel on a comboBox? i would to change the model of an existing comboBox so that in take a vector argument.
0
 
LVL 5

Assisted Solution

by:Triguna
Triguna earned 400 total points
ID: 13514322
DefaultComboBoxModel cmbModel = new DefaultComboBoxModel(<your - vector - object>);
cmb.setModel(cmbModel);

I think this is the solution you want.
0
 

Author Comment

by:komlaaa
ID: 13514357
>>cmb.setModel(cmbModel);
can cmb be any kind on ComboBox( ...) constructor?
0
 
LVL 92

Accepted Solution

by:
objects earned 1200 total points
ID: 13514381
> i  do have two combo as u can see below and on the GUI posted

they are added to the fields panel, not the student panel.

> how to use setModel on a comboBox?

add the following method to your StudentPanel class

public void setComboModels(Vector first, Vector last)
{
    firstCombo.setModel(new DefaultComboBoxModel(first));
    lastCombo.setModel(new DefaultComboBoxModel(last));
}

and call it from your refresh action listener

 sss.setComboModels(firstNames, lastNames);
0
 
LVL 5

Expert Comment

by:Triguna
ID: 13514384
Ya. cmb can have any kind of parameter. It can have Object[] or Vector or Collection
0
 
LVL 5

Expert Comment

by:Triguna
ID: 13541648
:)
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
How to install Selenium IDE and loops for quick automated testing. Get Selenium IDE from http://seleniumhq.org Go to that link and select download selenium in the right hand column That will then direct you to their download page. From that p…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses
Course of the Month8 days, 18 hours left to enroll

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question