Dynamic JCheckBoxes

Hi All,
I hope someone may be able to help me with program.
I have a class (called PlotterFrame.java). It is a JFrame extension and codes for the GUI part of a program.
My wish is to have a number of JCheckBoxes next to a list of files which the program has pulled from the current
user directory. These are stored in an Array called sequenceList. I have set up a filter to only select files
ending in .seq . The contents of sequenceList is therefore something like
0 sequence1.seq
1 sequence2.seq
2 sequence3.seq
3 sequence4.seq
4 sequence5.seq
I am using the following code to set up the JCheckBoxes:
for(int i=0; i<sequenceList.length; i++)
JCheckBox checkBox = new JCheckBox(sequenceList<i>);
fileList.add(checkBox);
(fileList is the name of the JPanel onto which I am adding the check boxes.)
Now, this works fine, producing the boxes with the associated filenames on the panel.
I also have an array called whichAreTicked<> which is the same length as sequenceList. My aim is
to have the program change the contents of whichAreTicked depending on which checkboxes have been selected.
Normally I would use a private innder class to see which boxes have been selected/deselected:
private class CheckBoxHandler implements ItemListener
public void itemStateChanged(ItemEvent e)
for(int i=0; i<sequenceList.length; i++)
if ( e.getSource() == nameOfAComponent)
if (e.getStateChange() == ItemEvent.SELECTED)
whichAreTicked<i>=1;
else
whichAreTicked<i>=0;
where nameOfAComponent is a CheckBox that has been explicity declared.
However, as the JCheckBoxes have been dynamically generated, I'm not sure how to get e.GetSource() to know
what its looking at. I have tried every book Ive got, but can find nothing about referencing dynamically genarated
components in this manner.
Can anyone help?
Thanks

hi,I think getSource return a random name.You must ask for the Name that your Checkbox Constructor has sequenceList<i> to identify a box

Similar Messages

  • How to handle ItemListener in Dynamic JCheckBoxs

    In my code i create dynamic JCheckBoxes and add ItemListener to every JCheckBox. I want to triger different actions by selecting JCheckBoxes.
    here is my code....
    String names[] ={"AAAA","BBBB","CCCC","DDDD"};
    JCheckBox cb[]=new JCheckBox[names.length];
    for( int j=0;j<names.length;j++) {
    cb[j] = new JCheckBox(names[j]);
    cb[j].addItemListener(this);
    this.add(cb[j]);
    in my item stateChanged method,...
    public void itemStateChanged(ItemEvent e) {
    Object x=e.getItemSelectable();
    if (x == cb1) {
    System.out.println("AAA is selected");
    if (x == cb2) {
    System.out.println("BBB is selected");
    ....like wise.
    but here (x==cb1) gives an error
    Is there any way to specify the exact JCheckBox which was selected?
    pls help

    you only said you get an error, but how can we help if you did not show the error you are getting? Please make sure you post your error or your code even; so that we can figure out what the problem is.

  • Boolean Fields as JCheckbox in a Dynamic JTable

    Hi,
    I am building an application like an sql query browser. I want to show boolean fields as JCheckbox in JTable. But the problem is that the table is dynamic, i don't know which column is boolean. How can i handle this? Should i configure getValueAt() overrided method in my TableModel class? If yes, how? Or any other suggestion . . .
    Regards.

    As default, boolean fields are shown as jcheckbox in jtable if getValueAt() method in my TableModel returns Object (not by getting string value). I am not careful nowadays :)

  • Dynamic generate JCheckBoxes...

    Hello,
    can anybody give me an impulse?
    It concerns the following:
    - my script is reading out a folder (reading out the names of the files in this folder)
    - I get a String[] array with the names in it
    - on the basis of the names in the String[] array I will dynamic generate some JCheckBoxes
    - my problem is that I don't know how I can dynamic generate the names of the JCheckBoxes, because the data types are different
    Regards,
    kostro03

    JCheckBox[] folderReadOutAsCheckBoxes (File file) {
        String[] fileNames = file.list ();
        JCheckBox[] checkBoxes = new JCheckBox[files.length];
        for (int i = 0; i < checkBoxes.length; i ++) {
            checkBoxes[i] = new JCheckBox (fileNames);
    // add listeners and such
    return checkBoxes;
    }Remember that [[i]i] is being replaced with <i> by the parser.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Dynamic adding & setText JCheckBox in table

    I try to populate my data in table with Jcheckbox. when I add the data i also want to set the checkbox text.
    anyone can help?

    Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/table.html]How to Use Tables for a working example of using checkboxes.
    To change the state of a checkbox you simply update the TableModel:
    table.setValueAt(new Boolean(true), row, column);

  • How do I add a JCheckBox to a JTable - URGENT HELP NEEDED

    Hello All,
    This is kicking my butt. I need to create a JTable that I can dynamically add and delete rows of data to and this table must contain a JCheckBox which I can read the value of. I've been able to find examples out there that provides the ability to have a JCheckBox in the JTable, but do not also provide the function to add / delete rows from the JTable. I need to have both funtions in my table. Can somebody out there please help me with this?
    Here's a simple example that I'm working with as a test to figure this out. This example has the functionality to add rows of data.
    Thanks in advance.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.JFrame;
    import javax.swing.JTable;
    import javax.swing.table.*;
    public class TableTest extends JFrame implements ActionListener
         JButton btnAdd;
         BorderLayout layout;
         DefaultTableModel model;
         public static void main(String[] args)
              TableTest app = new TableTest();
              app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public TableTest()
              super("Table Example");
              layout = new BorderLayout();
              Container container = getContentPane();
              container.setLayout(layout);
              btnAdd = new JButton("Add");
              btnAdd.addActionListener(this);
              model = new DefaultTableModel();
              JTable table = new JTable(model);
              // Create a couple of columns
              model.addColumn("Col1");
              model.addColumn("Col2");
              // Append a row
              model.addRow(new Object[] { "v1", "v2" });
              model.addRow(new Object[] { "v3", "v4" });
              JScrollPane scrollPane = new JScrollPane(table);
              container.add(btnAdd, BorderLayout.NORTH);
              container.add(scrollPane,BorderLayout.CENTER);
              setSize(300, 200);
              setVisible(true);
         public void actionPerformed(ActionEvent e)
              if (e.getSource() == btnAdd)
                   model.addRow(new Object[]{"Test", new Boolean(true)});
    }

    I got it, I added the public Class getColumnClass to new DefaultTableModel(). Here it is for your viewing pleasure.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.JFrame;
    import javax.swing.JTable;
    import javax.swing.table.*;
    public class TableTest extends JFrame implements ActionListener
         JButton btnAdd;
         BorderLayout layout;
         DefaultTableModel model;
         JTable table;
         public static void main(String[] args)
              TableTest app = new TableTest();
              app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public TableTest()
              super("Table Example");
              layout = new BorderLayout();
              Container container = getContentPane();
              container.setLayout(layout);
              btnAdd = new JButton("Add");
              btnAdd.addActionListener(this);
              model = new DefaultTableModel()
                   public Class getColumnClass(int col)
                        switch (col)
                             case 1 :
                                  return Boolean.class;
                             default :
                                  return Object.class;
              table = new JTable(model);
              // Create a couple of columns
              model.addColumn("Col1");
              model.addColumn("Col2");
              // Append a row
              model.addRow(new Object[] { "v1", new Boolean(false)});
              model.addRow(new Object[] { "v3", new Boolean(false)});
              JScrollPane scrollPane = new JScrollPane(table);
              container.add(btnAdd, BorderLayout.NORTH);
              container.add(scrollPane, BorderLayout.CENTER);
              setSize(300, 200);
              setVisible(true);
         public void actionPerformed(ActionEvent e)
              if (e.getSource() == btnAdd)
                   model.addRow(new Object[] { "Karl", new Boolean(true)});

  • Dynamic jmenu bar

    i have a dynamic JMenu on a jframe. The menu is populated by looking up database entries and ptting them into the right place. This is done by a method 'menus()'.
    I also have an addingredients class which adds new ingredient entries into the database, problem is when it does this, the JMenu has to be repopulated. The following code shows the main frame
    // Recipe Creation GUI
    // Written by Michael Emett
    // Monday 15th Decemeber 2003
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.JFrame.*;
    import java.sql.*;
    import java.util.*;
    public class TextAreaDemo extends JFrame     {
    private static JTextArea part1;
    private JButton Browse, Enter, Preview, Remove;
    public static JList printList, newList;
    private JCheckBox pic;
    private JLabel namePrompt, title1, title2, title3;
    private static JTextField nameInput;
    private JPanel jp, jp1, jp2, jp3, jp4, jp5;
    private Connection con;
    private Statement stmt;
    public static JMenu fileMenu;
    private static JMenuBar bar;
    // additions /////////////////////////////////////////////////////////////////////////
    //set up GUI
    public TextAreaDemo()     {
    super( "Recipe Entry Sheet" );
    // set up File menu and its menu items
    // Menu and button Initialization ////////////////////////////////////////////////////
    //myMouse = new MyMouseAdapter();
    //final JMenu
    fileMenu = new JMenu( "Ingredients");
             fileMenu.setMnemonic( 'I' );
    fileMenu.add(menus());
    bar = new JMenuBar();
    setJMenuBar( bar );
    JMenu file = new JMenu( "File");
    file.setMnemonic( 'F' );
        bar.add(file);
              JMenuItem Adder = new JMenuItem( "New Ingredient");
             Adder.setMnemonic( 'N' );
    JMenuItem Subber = new JMenuItem( "New subMenu");
             Subber.setMnemonic( 'S' );
             // set up About... menu item
             JMenuItem aboutItem = new JMenuItem( "About..." );
             aboutItem.setMnemonic( 'A' );
    namePrompt = new JLabel( "Recipe Name " );
    nameInput = new JTextField( 20 );
    title1 = new JLabel( "Selected ingredients" );
    title3 = new JLabel( "Please enter the Recipe Instructions" );
    title2 = new JLabel( "Enter The SubMenu Name " );
    pic = new JCheckBox("Add Picture", false);
    file.add( Adder );
         Adder.addActionListener(
              new ActionListener()     {
                    public void actionPerformed( ActionEvent event )
                        getList f = new getList();
    // Add Ingredient menu item //////////////////////////////////////////////////////////
    file.add( Subber );
         Subber.addActionListener(
              new ActionListener()     {
                    public void actionPerformed( ActionEvent event )
                        AddSubMenu f = new AddSubMenu();
    // About menu item ///////////////////////////////////////////////////////////////////
    file.add( aboutItem );
          aboutItem.addActionListener(
             new ActionListener() {  // anonymous inner class
                // display message dialog when user selects About...
                public void actionPerformed( ActionEvent event )
                   JOptionPane.showMessageDialog( TextAreaDemo.this,
                      "Developed by Michael Emett, 2004",
                      "About", JOptionPane.PLAIN_MESSAGE );
              }     // end anonymous inner class
         );  // end call to addActionListener
    // Exit menu item ////////////////////////////////////////////////////////////////////
         JMenuItem exitItem = new JMenuItem( "Exit" );
         exitItem.setMnemonic( 'x' );
         file.add( exitItem );
          exitItem.addActionListener(
             new ActionListener() {  // anonymous inner class
                // terminate application when user clicks exitItem
                public void actionPerformed( ActionEvent event )
                   System.exit( 0 );
             }  // end anonymous inner class
          ); // end call to addActionListener
    //create Button Enter
    Enter = new JButton("Enter");
    Enter.addActionListener(
              new ActionListener()     {
                              public void actionPerformed( ActionEvent event )
                        StringBuffer a = new StringBuffer();
                        StringBuffer b = new StringBuffer();
                        StringBuffer c = new StringBuffer();
                        for(int i= 0; i< victor.size(); i++){
                        b.append(victor.elementAt(i));
                        b.append("; ");
                        a.append(nameInput.getText());
                        c.append(part1.getText());
                        //System.out.println(a);
                        //System.out.println(b);
                        //System.out.println(c);
                        InsertRecipe f = new InsertRecipe(a,b,c);
                        //invalidate();
                //fileMenu.updateUI();
               // fileMenu.revalidate();
    //create Button Remove
    Remove = new JButton("Remove");
    //add Actionlistener
    Remove.addActionListener(
              new ActionListener()     {
                    public void actionPerformed( ActionEvent event )
    int[] arr;
    arr = printList.getSelectedIndices();
    int counter = 0;
         for (int i= 0; i< arr.length; i++){
              int n=arr;
              victor.remove(n-counter);
              counter++;
    printList.setListData(victor);
    //create Button Remove
    Browse = new JButton("Browse");
    //create Button Preview
    Preview = new JButton("Clear");
    Preview.addActionListener(
    new ActionListener() {  // anonymous inner class
    // display message dialog when user selects Preview...
    public void actionPerformed( ActionEvent event )
    int result = JOptionPane.showConfirmDialog
                             (null,      "Are you sure to want to clear this form", "Clear?",      JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);
                             if(result == JOptionPane.YES_OPTION)
                             {TextAreaDemo.clear();
                                  //System.out.println("Recipe Entered");
              }//end of joptionpane
    printList = new JList();
    printList.setVisibleRowCount(9);
    printList.setFixedCellWidth(150);
    printList.setFixedCellHeight(15);
    printList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
    newList = new JList();
    newList.setVisibleRowCount(9);
    newList.setFixedCellWidth(150);
    newList.setFixedCellHeight(15);
    newList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION );
    // Initialise Text Areas //
    part1 = new JTextArea( 25, 50);
    part1.setFont(new Font("Courier", Font.BOLD, 12));
    part1.setLineWrap(true);
    part1.setWrapStyleWord(true);
    // JPanels for Layout //
    jp = new JPanel();
    jp1 = new JPanel();
    jp2 = new JPanel();
    jp3 = new JPanel();
    jp4 = new JPanel();
    jp5 = new JPanel();
    final Container c = getContentPane();
    GridBagLayout gbl = new GridBagLayout();
    GridBagConstraints gbc = new GridBagConstraints();
         c.setLayout(gbl);
         gbc.weightx = 0.1;
         gbc.weighty = 0.5;
    gbc.fill = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.NORTHWEST;
    add(jp1, gbc, 0, 0, 1, 1);
    gbc.fill = GridBagConstraints.NONE;
    add(jp2, gbc, 0, 1, 1, 1);
    add(jp3, gbc, 1, 0, 2, 2);
    jp1.add(jp4, BorderLayout.CENTER);
    jp2.add(jp, BorderLayout.CENTER);
    bar.add( namePrompt );
    bar.add( nameInput);
    bar.add( fileMenu );
    jp4.setLayout(new BorderLayout());
    jp4.add(title1, BorderLayout.NORTH);
    jp4.add(new JScrollPane( printList), BorderLayout.CENTER);
    jp4.add(Remove, BorderLayout.SOUTH);
    jp.setLayout(new BorderLayout());
    jp.add(pic, BorderLayout.NORTH);
    jp.add(new JScrollPane (newList), BorderLayout.CENTER);
    jp.add(Browse, BorderLayout.SOUTH);
    jp3.setLayout(new BorderLayout());
    jp3.add (title3, BorderLayout.NORTH);
    jp3.add (new JScrollPane(part1), BorderLayout.CENTER);
    //c.addMouseListener(myMouse);
    gbc.anchor = GridBagConstraints.LAST_LINE_END;
    add(jp5, gbc, 2, 3, 1, 1);
    jp5.setLayout(new FlowLayout());
    jp5.add(Preview);
    jp5.add(Enter);
    setSize(770, 620);
         pack();
         setVisible(true);
         setResizable(false);
    private static Vector victor = new Vector();
    public static void printListset(String t) {
         victor.add(t);
    for(int i = 0; i<victor.size(); i++)
    printList.setListData(victor);
    public void add(Component ce, GridBagConstraints constraints, int x, int y, int w, int h) {
                   constraints.gridx = x;
                   constraints.gridy = y;
                   constraints.gridwidth = w;
                   constraints.gridheight = h;
                   getContentPane().add(ce, constraints);
    public static JMenu menus()     {
         // Map Created to Handle JMenuItem Addition //
              Map labelToMenu = new HashMap();
              Map labelToMenu2 = new HashMap();
              Map labelToMenu3 = new HashMap();
              String url = "jdbc:odbc:database";
              Connection con;
              Statement stmt;
                        try     {
                             Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                        catch(ClassNotFoundException e)     {
                        System.err.print("Class Not found");
                        String query = "select baseIngred.IngredientType, baseIngred.PrimaryKey FROM baseIngred";
                        String query2 = "select baseIngred.IngredientType, baseIngred.PrimaryKey,"
                        + "subMenu.menuNumber, subMenu.subMenu FROM baseIngred, "
                        + "subMenu WHERE baseIngred.PrimaryKey = subMenu.menuNumber ORDER BY submenu";
                                  String query3 = "select subMenu.subMenu, subMenu.PrimaryNumber,"
                                       + "Ingredient.Ingredient, Ingredient.MenuNumber FROM subMenu, Ingredient"
                        + " WHERE Ingredient.MenuNumber = subMenu.PrimaryNumber ORDER BY PrimaryNumber";
         String query4 = "select Ingredient.Ingredient, Ingredient.MenuNumber FROM Ingredient";
                             try     {
                                       con = DriverManager.getConnection(url, "myLogin", "myPassword");
                                       stmt = con.createStatement();
         // Initial Jmenu added ///////////////////////////////////////////////////////////////
                   ResultSet rs = stmt.executeQuery(query);
                   String[] arr = new String[100];
                   int[] num = new int[200];
                   int[] num2 = new int[200];
                   int counter = 0;
                   int counter2 = 0;
                   while     (rs.next())     {
                                  //String t is set to the value contained in ingredient type
                                  String t = rs.getString("IngredientType");
                                  //map labelToMenu has String t and a new JMenu with the menu
                                  //name contained in t stored in it
                                  labelToMenu.put(t, fileMenu.add(new JMenu(t)));
                                  //an array containing values of the priamry key is produced
                                  num[counter] = rs.getInt("PrimaryKey");
                                  //a counter is incremeted so that upon further
                                  //interations it is stored in a new array field
                                  counter++;
         // Second Jmenu added ////////////////////////////////////////////////////////////////
                   ResultSet rs2 = stmt.executeQuery(query2);
                   while     (rs2.next()) {
                                  //String first is set to the value contained in ingredient type
                                  String first = rs2.getString("IngredientType");
                                  //String second is set to the value contained in subMenu
                                  String second = rs2.getString("subMenu");
                                  //firstlevel looks up item t in the map, and creates a jmenu name as it.
                                  JMenu firstLevel = (JMenu)labelToMenu.get(first);
                                  //handles menu placement by comparing PrimaryKeys with MenuNumbers
                                  // f = rs2.getInt("menuNumber");
                                  num2[counter2] = rs2.getInt("menuNumber");
         for (int nm = 0; nm<num.length; nm++){
                   if (num[nm] == num2[counter2]
                                            //adds the second value to the jmenu with th name stored in t.
                                            labelToMenu2.put(second, (firstLevel.add(new JMenu (second))));
                                       }counter2++;
         // Third JMenu added /////////////////////////////////////////////////////////////////
         ResultSet rs3 = stmt.executeQuery(query3);
              while     (rs3.next()) {
                                  //String next is set to the value contained in subMenu
                                  String next = rs3.getString("subMenu");
                                  //String third is set to the value contained in ingredient
                                  String third = rs3.getString("Ingredient");
                                  JMenu secondLevel = (JMenu)labelToMenu2.get(next);
                                  int f2 = rs3.getInt("MenuNumber");
                                  //System.out.println(f2);
                                  int f3 = rs3.getInt("PrimaryNumber");
                   if (f3 == f2){
                             labelToMenu3.put(third, secondLevel.add(new JMenuItem(third)));
         // Add AtionListeners ////////////////////////////////////////////////////////////////
         ResultSet rs4 = stmt.executeQuery(query4);
              while     (rs4.next()) {
                   String third2 = rs4.getString("Ingredient");
         JMenuItem thirdLevel = (JMenuItem)labelToMenu3.get(third2);
         thirdLevel.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                   JMenuItem source = (JMenuItem)(e.getSource());
                   String actionText = source.getText();
                   PopUp pop = new PopUp(actionText);
                        stmt.close();
                        con.close();
                             }catch(SQLException ex)     {
                        System.err.println(ex);
    return (fileMenu);
         //                                        End Of Connection                                             //
         // Add subMenu menu item /////////////////////////////////////////////////////////////
    public static void clear()     {
    nameInput.setText("");
    victor.removeAllElements();
    printList.setListData(victor);
    part1.setText("");
    public static void rebuild()     {
    fileMenu.removeAll();
    fileMenu.add(menus());
    bar.add( fileMenu );
    public static void main(String args[])     {
         TextAreaDemo t = new TextAreaDemo();
         t.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
    the code inside the method 'rebuild()' will work from inside the main JFrame body if assigned to a button (such as the example position denoted by HERE in the code), but that is undesirable as it requires the user to refresh manually every time they add a new ingredient. what i need is a method that can be called from another class/method/whatever.
    thankyou for any help you can offer, it is much appreciated

    The code you offered did not solve my problem. I have since entered the followinginto the actionlistener of a button on the JFrame,
    refreshMenu = new JButton("Refresh Menu");
    refreshMenu.addActionListener(
             new ActionListener() { 
                // display message dialog when user selects Preview...
                public void actionPerformed( ActionEvent event )
    fileMenu.removeAll();
    fileMenu.add(menus());
    bar.add( fileMenu );          
    );This does what i need, but i need these statements to be made from an external class, not a JButton,

  • Developing a Dynamic GUI with SDK 1.3.1

    For my master's project, I am developing a system which needs to read a file, and depending on the number of fields the file contains and their titles, dynamically add jCheckBoxes to a pane as part of a tabbed pane. Different files can be loaded by the user at runtime, recreating and updating this pane to reflect the new information. What is the best way of going about this? I tried to use a vector to store the checkboxes at first, but it returns a generic object and not a checkbox. I can get it to work with a checkbox array, but this is a bit messy, and requires the array size to be specified. What is the best way of developing such a system?

    For my master's project, I am developing a system which needs to read a file, and depending on the number of fields the file contains and their titles, dynamically add jCheckBoxes to a pane as part of a tabbed pane. Different files can be loaded by the user at runtime, recreating and updating this pane to reflect the new information. What is the best way of going about this? I tried to use a vector to store the checkboxes at first, but it returns a generic object and not a checkbox. I can get it to work with a checkbox array, but this is a bit messy, and requires the array size to be specified. What is the best way of developing such a system?

  • Checking Unchecking of JCheckBox value  inside JTable cell

    My problem is that i have jtable which has table data. In that first column has jcheckbox values which are there because of the tabledata has firstcolumn values as boolean, to know the no of checks in jcheckboxes in jtable, there is count variable which needs to be dynamic. When i first check the box the variable that i have set to know the check i.e count increases by one, then next jcheckbox if i check then count goes to 2, but real problem is when i do some 2 events on same checkbox then ie. if i check the jcheckbox , the count increases but after that the jcheckbox doesnot listen to events fired. Any help is appreciated

    The example from above shows how to add Objects to a table. If you want a column of checkBoxes then simply replace the Objects in one of the columns with:
    new Boolean(false)
    Read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/table.html]How to Use Tables for more information.

  • How to name Objects dynamically?

    Hi ,
    i have a scenario where i need to create many JCheckBox objects
    i need to name the JCheckBox objects as jcb1,jcb2,jcb3,jcb4,jcb5..................
    in a loop how to make the JCheckBox objects with the name appended with 1,2,3 (based on the loop)
    please any body help me.............

    LoveOpensource wrote:
    Hi ,
    i have a scenario where i need to create many JCheckBox objects
    i need to name the JCheckBox objects as jcb1,jcb2,jcb3,jcb4,jcb5..................
    in a loop how to make the JCheckBox objects with the name appended with 1,2,3 (based on the loop)
    please any body help me.............Objects don't have a name. A variable is not a name, and cannot be "dynamically" generated.
    Use a Collection as already suggested.

  • Dynamically changing/updating a JTable

    I have a blank JTable that will add rows as the user clicks the "add rows". My dilemma is some of the objects in the rows are comprised of JCheckBoxes. I need to know how to create an actual checkbox in those spots, without creating a sublass the extends DefaultTableModel. Also i can get everything to display on the table when the button is pushed but i just cant render the components.
    I do know how to add the check boxes in the rows if the JTable is setup and never chaned from the beginning but I dont understand how to over come this problem for a dynamic table.
    Thanks in advance
    Chris
    Some code snippets.
    private static DefaultTableModel model = new DefaultTableModel();
    private JTable jTable = new JTable(model);
    //below is what is called when the "add row" button has just been pushed
    public static void setPricingTab()
        model.addRow(getRowInfo());
      }//end public static void setPricingTab()
      public static Object[] getRowInfo()
        list[0]=ConsecCheckBox.getBoxName(); //get most recent selected edition
        list[1]=new Boolean(false);
        list[2]="Monday";
        list[3]="Tuesday";
        list[4]="Wednesday";
        list[5]="Thursday";
        list[6]="Friday";
        list[7]="Saturday";
        list[8]=new JTextArea("Price",10,10);
        list[8]=new Boolean(false);
        list[10]=null;
        return list;
    //im sure i should be rendering here or in the setPricingTab()
    //but this is where i am stuck
      }

    Since you only post snippets of code its hard to tell whats wrong. Here is a simple example that I think does what you want:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableBoolean extends JFrame
        private final static String LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        JTable table;
        DefaultTableModel model;
        public TableBoolean()
            //  Create table
            Object[][] data = { {"A", new Boolean(false)}, {"B", new Boolean(true)} };
            String[] columnNames = {"String","Boolean"};
            model = new DefaultTableModel(data, columnNames);
            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();
                public boolean isCellEditable(int row, int column)
                    return true;
            //  Add table and a Button panel to the frame
            JScrollPane scrollPane = new JScrollPane( table );
            getContentPane().add( scrollPane );
            JButton button = new JButton( "Add Row" );
            button.addActionListener( new ActionListener()
                public void actionPerformed(ActionEvent e)
                    Object[] newRow = new Object[2];
                    int row = table.getRowCount() + 1;
                    newRow[0] = LETTERS.substring(row-1, row);
                    newRow[1] = (row % 2 == 0) ? new Boolean(true) : new Boolean(false);
                    model.addRow( newRow );
            getContentPane().add( button, BorderLayout.SOUTH );
        public static void main(String[] args)
            TableBoolean frame = new TableBoolean();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setVisible(true);
    }

  • Jcheckbox problem...

    hi all ..
    i wrote an application in swing to generate a Html form dynamically and save to a folder,but in my application,i could only generate and save only one name from the listbox
    Now all that is i need a checkbox besides each formname in the listbox and when i check the names and click generate button,multiple forms should be generated and saved....can any one please throw their knowledge on this and solve for me...
    Thanks in advance
    *********** here is my applicaiton
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    import java.lang.*;
    import java.sql.*;
    public class MyAppFrame extends JFrame implements ActionListener{
         //-- class members
         JTextField jtf_Text;
         JButton jb_Button,G_Button;
         JList j1_List;
         JCheckBox Jb;
         Vector v;
    private JScrollPane jpane;
    Connection con;
    Statement st,st1;
    ResultSet rs,rs1;
    final JFileChooser fc = new JFileChooser();
    String temp = "";
    String FormCode;
    String SectionCode;
    String SQL_sectionCode;
    int i;
    MyAppFrame(String title) {
         super(title);
         setSize(600,500);
         Container contentPane = getContentPane();
         contentPane.setLayout(new BorderLayout());
              JPanel panel = new JPanel();
         panel.setLayout(new FlowLayout());
              panel.add(new JLabel("Target Folder: "));
    panel.add(jtf_Text = new JTextField(10));
    jb_Button=new JButton("List");
    jb_Button.addActionListener(this);
    panel.add(jb_Button);
    G_Button=new JButton("Generate");
    panel.add(G_Button);
    G_Button.addActionListener(this);
    contentPane.add(panel,BorderLayout.NORTH);
    panel = new JPanel();
              panel.setLayout(new GridLayout(2,1));
              panel.add(new JLabel("Selected Forms:"));
    v=new Vector();
    panel.add(j1_List = new JList());
    //j1_List.setCellRenderer(new CheckListRenderer());
    j1_List.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    j1_List.setBorder(new EmptyBorder(0,4,0,0));
    // j1_List.addMouseListener(new MouseAdapter();
    jpane = new JScrollPane();
    jpane.getViewport().add(j1_List);
    contentPane.add(panel, BorderLayout.CENTER);
    panel.add(jpane);
              addWindowListener(new ExitListener());
         setVisible(true);
         public static void main(String[] args) {
         MyAppFrame maf = new MyAppFrame("Form Selection");
    class ExitListener extends WindowAdapter{
    public void windowClosing(WindowEvent event) {
    System.exit(0);
    private void con(JList ref){
         try{
         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         con = DriverManager.getConnection("jdbc:odbc:satya");
         System.out.println("Set Connection");
         st=con.createStatement();
         st1=con.createStatement();
         String query="select form_name from form";
         System.out.println(query);
    rs=st.executeQuery(query);
    while(rs.next()){
              String name = rs.getString("form_name");
              v.add(name);
                   j1_List.setListData(v);
                   rs.close();
                   catch(Exception e)
    e.printStackTrace();
    public void actionPerformed(ActionEvent e) {
    String flag = e.getActionCommand();
    if(flag.equals("List")){
    this.con(j1_List);
    jb_Button.setEnabled(false);
    else
         try{
    rs=st.executeQuery("select title,form_code from form where form_name='"+(String)j1_List.getSelectedValue()+"'");
         while(rs.next()){
         temp=rs.getString(1);
         FormCode=rs.getString(2);
    rs.close();
    }catch(Exception e3){System.out.println("here"+e3);}
         //rs=st.executeQuery("SELECT form_section_rel.form_code, section.section_title, form_section_rel.section_code, form_section_rel.order_id FROM section INNER JOIN form_section_rel ON section.section_code = form_section_rel.section_code where form_code = '" + FormCode + "'ORDER BY form_section_rel.form_code, form_section_rel.order_id");
         //rs1=st1.executeQuery("
         StringBuffer sb = new StringBuffer();
         sb.append("<html>");
         sb.append("<style>");
         sb.append("td{");
         sb.append("font-family : Arial,Helvetica,Sans-serif");
         sb.append("font-size : 12px");
         sb.append("color : #000000");
         sb.append("}");
         sb.append("</style>");
         sb.append("<HEAD><META HTTP-EQUIV=\"PRAGMA\" CONTENT=\"NO-CACHE\">");
         sb.append("<META HTTP-EQUIV=\"EXPIRES\" CONTENT=\"0\">");
         sb.append("<TITLE>Service Window Document </TITLE>");
         sb.append("<link rel=\"stylesheet\" href=\"main.css\">");
         sb.append("</HEAD><body bgcolor=\"#ffffff\" bgproperties=\"fixed\" text=\"#000000\" leftmargin=\"0\" topmargin=\"0\" margin width=\"0\" margin height=\"0\">");
    sb.append("<TABLE width=\"100%\" border=\"0\" cell spacing=\"0\" cell padding=\"0\">");
         sb.append("<TR>");
         sb.append("<TD bgcolor=\"#ffffff\" align=\"top\">");
         sb.append("<TABLE align=\"left\" width=\"100%\">");
         sb.append("<TR align=\"top\">");
         sb.append("<the><font color=\"#ff0000\"></font></th>");
         sb.append("</TR>");
         sb.append("<TR align=\"top\">");
         sb.append("<TD row span=\"2\">");
         sb.append("<form name=\"sw_form\" method= post action=\"post\">");
         sb.append("<table border=0 cell spacing=\"0\" cell padding=\"0\" border color=\"#000000\" width=\"450\">");
         sb.append("<tr><td>");
         sb.append("<table border=0 cell spacing=\"0\" cell padding=\"0\" border color=\"#000000\" width=\"450\">");
         sb.append("<div align=\"center\">");
         sb.append("<tr>");
         sb.append("<td colspan=\"2\">");
         sb.append("<table border=\"1\" border color=\"#ffffff\" width=\"450\" cell spacing =\"0\" cell padding=\"3\">");
         sb.append("<tr>");
         sb.append("<th align=\"center\" bgcolor=\"#990000\"><font color=\"#ffcc00\"><b>"+temp+"</b></font></th>");
    sb.append("</tr>");
         sb.append("</table>");
         sb.append("</td>");
         sb.append("</tr>");
         sb.append("</table>");
         sb.append("</td></tr>");
    try{
    rs=st.executeQuery("SELECT form_section_rel.form_code, section.section_title, form_section_rel.section_code, form_section_rel.order_id FROM section INNER JOIN form_section_rel ON section.section_code = form_section_rel.section_code where form_code = '" + FormCode + "'ORDER BY form_section_rel.form_code, form_section_rel.order_id");
    rs.next();
    do{
         sb.append("<table width=\"\">");
         sb.append("<tr><td bordercolor=\"#FFFFCC\"> </td></tr>");
         sb.append("<tr><td colspan=2 width=450>");
         sb.append("<fieldset><legend>");
         sb.append(rs.getString("section_title"));
         SectionCode = rs.getString("section_code");
         System.out.println(SectionCode);
         i=Integer.parseInt(SectionCode);
         sb.append("</legend>");
         sb.append("<table width=\"\">");
         sb.append("<tr><td bordercolor=\"#FFFFCC\">  </td></tr>");
         SQL_sectionCode ="SELECT SectionUI_Rel.SectionCode, SectionUI_Rel.OrderID, ui_components.* FROM ui_components INNER JOIN SectionUI_Rel ON ui_components.pid = SectionUI_Rel.ComponentID WHERE (((SectionUI_Rel.SectionCode)='"+SectionCode+"'))";
         rs1 =st1.executeQuery(SQL_sectionCode);
         while(rs1.next())
         String type=rs1.getString("ui_type");
         String val=rs1.getString("validationtype");
         int len=val.length();
         val=val.substring(3,len);
         String man=rs1.getString("mandatory");
         if(type.equals("textbox") && man.equals("1")){
         sb.append("<TR><TD>"+rs1.getString("labelname")+":</TD><TD><input type="+type+" name="+rs1.getString("fieldname")+" maxlength ="+val +"> <font color=\"#ff0000\">*</font></TD></TR>");
         else if(man.equals("0")) {
    sb.append("<TR><TD>"+rs1.getString("labelname")+":</TD><TD><input type="+type+" name="+rs1.getString("fieldname")+" maxlength ="+val +"></TD></TR>");
    else if(type.equals("dropdown")){
         sb.append("<TR><TD>"+rs1.getString("labelname")+":</TD><TD><select name="+type+" name="+rs1.getString("fieldname")+" </select></TD></TR>");
         else if(type.equals("static")){
         sb.append("<TR><TD>"+rs1.getString("labelname")+":</TD></TR>");
    else if(type.equals("textarea")){
         sb.append("<TR><TD>"+rs1.getString("labelname")+":</TD><TD><textarea name="+rs1.getString("fieldname")+"></textarea></TD></TR>");
    else if(type.equals("radio")){
         sb.append("<TR><TD>"+rs1.getString("labelname")+":</TD><TD><input type="+type+" name="+rs1.getString("fieldname")+"></TD></TR>");
    else if(type.equals("checkbox")){
         sb.append("<TR><TD>"+rs1.getString("labelname")+":</TD><TD><input type="+type+" name="+rs1.getString("fieldname")+"></TD></TR>");
         sb.append("</table>");
         sb.append("</fieldset>");
         sb.append("</td></tr>");
         sb.append("</table>");
         } while( rs.next());
    //sb.append("</form></body></html>");
    }catch(Exception e4){
    System.out.println(e4);
    sb.append("</form></body></html>");
         String formname=(String)j1_List.getSelectedValue();
         String Dir=jtf_Text.getText();
         Dir +="/"+formname+".html";
         if(formname!=null && Dir !=null)
         try
         PrintWriter out= new PrintWriter(new FileWriter(Dir));
    BufferedWriter br=new BufferedWriter(out);
         out.println(sb +"\n");
         out.close();
    catch(Exception e1)
    System.out.println(e1);
    //jb_Button.setEnabled(false);

    Huh?
    1) If you want to use a method, you shouldn't override it
    2) I don't see any reason to extend JCheckBox at all
    3) What do you want your method to do that isSelected() doesn't already do?
    4) if (box.isSelected()) suffices - no reason to compare true or false with true.
    5) in this case "return box.isSelected()" suffices for the entire method.
    I totally don't understand your problem. Updating the table can be done with or without a SwingWorker in the button's ActionListener.

  • TextBlock, TextElement changing color dynamically

    So I decided try out the TextBlock and TextElement in my project, but I can't seem to change the color dynamically.  Here is the code:
    //show the name of the node in a textSprite label
            private function addNameLabel():void
                trace('addNamelabel called');
                textSpriteHolder = new Sprite;
                var scAmt:Number = Math.round(11 * _scaleFactor);
                var temp:String = _nodedata.name;
                var whitespace:RegExp = /(\-)/g;
                temp = temp.replace( whitespace, '_' ); 
                txt = truncateTextField( temp as String );
                var fd:FontDescription = new FontDescription();
                fd.fontLookup = FontLookup.EMBEDDED_CFF;
                fd.fontName = "Arial, Helvetica, _sans";
                var ef:ElementFormat = new ElementFormat(fd);
                ef.fontSize = 22;
                ef.color = 0x000000;
                te = new TextElement(txt, ef);
                tb = new TextBlock();
                tb.content = te;
                textsprite = tb.createTextLine(null, 300);
                var baremin:Number = Math.max( graphNode.width, 73 );
                textsprite.x    = ( baremin / 2) + 10;
                textsprite.y    = -5;
                textsprite.name = "label";
                textsprite.mouseEnabled = false;
                textsprite.mouseChildren = false;
                textsprite.alpha = 1;
                textSpriteHolder.addChild(textsprite);
                graphNode.addChild(textSpriteHolder);
    Anyone know how to change the color of the text, later on say when a threshold is met (aka not during instantiation).

    Actually, i have the setOpaque Command already. The problem is that the code to render other cells does not get executed when i click the jcheckbox. It will only happen if i resize the table, or move the mouse over those columns etc. So i want a definite way to invoke all the cell renderers when i click on the boolean column.
    PK

  • Container resizing when dynamically showing/hiding components

    I work with Swing for quite some time, but there's one thing that's bugging me all the time - when you dynamically show/hide some components, the container is not resized appropriately. That means that some components are cut off or hidden beyond the container edge. Maybe I'm just doing something wrong, can somebody help me?
    The easiest example is here. I'll create a label that is hidden by default. When I dynamically show it, the frame/panel is not enlarged and therefore the label is not visible until the user manually resizes the frame/panel. Only after that you can see it.
    (Usually I use the layout manager used when designing UIs in NetBeans, but I hope these default layout managers will demonstrate the same problem.)
    import java.awt.event.*;
    import javax.swing.*;
    public class DynamicComponentDemo {
        private static void createAndShowGUI() {
            final JFrame frame = new JFrame("Dynamic Component Demo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
            final JPanel panel = new JPanel();
            frame.add(panel);
            final JCheckBox checkbox = new JCheckBox("Show label");
            final JLabel label = new JLabel("This is a label!");
            checkbox.addItemListener(new ItemListener() {
                public void itemStateChanged(ItemEvent e) {
                    label.setVisible(checkbox.isSelected());
            label.setVisible(false);
            panel.add(checkbox);
            panel.add(label);
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }What can I do to force the frame/panel to resize appropriately when some new component is shown? Moreover, can you point me to some documentation regarding these matters?
    Thanks.

    Kleopatra wrote:
    no. no. no. no. Never-never-ever call setXXSize - XX for min/pref/max - in application code.Thanks for the correction.
    Unfortunately,
    http://wiki.java.net/bin/view/Javadesktop/SwingLabsImperialRules
    is a dead link, so I'm not sure if this is better than my previous example :(
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class DynamicComponentDemo3 {
      private static void createAndShowGUI() {
        final JFrame frame = new JFrame("Dynamic Component Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        final JPanel panel = new JPanel(new FlowLayout() {
          @Override public Dimension preferredLayoutSize(Container target) {
            //synchronized (target.getTreeLock()) {
            Dimension ps = super.preferredLayoutSize(target);
            Dimension cs = target.getSize();
            ps.width  = Math.max(cs.width,  ps.width);
            ps.height = Math.max(cs.height, ps.height);
            return ps;
        frame.add(panel);
        final JCheckBox checkbox = new JCheckBox("Show label");
        final JLabel label = new JLabel("This is a label!");
        checkbox.addItemListener(new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
              label.setVisible(checkbox.isSelected());
              frame.pack();
        panel.add(checkbox);
        panel.add(label);
        frame.pack();
        label.setVisible(false);
        frame.setVisible(true);
      public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            createAndShowGUI();
    }

  • How can I dynamicly add control elements to a  form

    Hello,
    I want to dynamicly add elements to a JPanel.
    The elements with the properties are stored in a database
    each record contains one element
    Label
    Combobox
    Checkbox
    I`m programming in NetBeans 5.5
    Something like:
    public void test()
    try
    stmt = GeneralDBConnect.createStatement();
    ResultSet rs = stmt.executeQuery("select device_option_id, objecttype, device_option, size, location, tooltip from device_option where ...");
    int i = 0;
    if(rs.next())
    i = i + 1;
    switch(rs.getString(2))
    case "Label" : JLabel Element[i] = new JLabel();
    Element.setText(rs.getString(3));
    break;
    case "Textbox" : JTextField Element[i] = new JTextField();
    break;
    case "Combobox" : JComboBox Element[i] = new JCombobox();
    Element[i].setToolTipText(rs.getString(6));
    ResultSet List = stmt.executeQuery("select device_option_value_id, option_value from device_option_value where ...");
    while(List.next)
    Element[i].addItem(List.getString(2));
    List.close();
    break;
    case "Checkbox" : JCheckBox Element[i] = new JCheckBox();
    break;
    jPanel_Device_Option.add(Element[i])
    rs.close();
    stmt.close();
    catch (SQLException ex)
    ex.printStackTrace();
    I know the Element[i] is wrong code but I need to give the elements an unique name.
    Can anyone assist me in this matter

    Hello everybody,
    I figured it out. I had to change the layout model of the JPanel.
    I`ve chosen to use the gridbaglayout because its very flexibel. See http://java.sun.com/docs/books/tutorial/uiswing/layout/gridbag.html
    Here is my code:
    Description:
    Whenever an item in a Combobox is changed (representing devices) the optional elements (a collection of Textfields, checkboxes, comboboxes) are shown in a JPanel.
    Which Elements are shown is stored in a database. (Tabels device, device_option and device_option_value (stores the JCombobox items))
    First create a JPanel in the graphical editor and right click it choose set layout\gridbaglayout
            jPanel_Device_Option.setLayout(new java.awt.GridBagLayout());
            jPanel_Device_Option.setBorder(javax.swing.BorderFactory.createTitledBorder("Device Options"));
            jPanel_Device_Option.setAutoscrolls(true);Then to create an empty border so the elements don`t clip to the edge of the JPanel add the following code in the properties window in the code section under node "Post-Init code"
            Border bBorder = jPanel_Device_Option.getBorder();
            Border bMargin = new EmptyBorder(0,10,0,10);
            jPanel_Device_Option.setBorder(new CompoundBorder(bBorder, bMargin));Then declare the public variables at the beginning of the code
        public static ArrayList aDatasetElements;
        public static JLabel[] aLabel;
        public static JLabel[] aTextfieldLabel;
        public static JTextField[] aTextfield;
        public static JLabel[] aComboboxLabel;
        public static JComboBox[] aCombobox;
        public static JLabel[] aCheckboxLabel;
        public static JCheckBox[] aCheckbox;And now the method that`s creating the elements
      public void setOutputSettings()
          jPanel_Device_Option.removeAll();//Clear all existing elements from the JPanel
          jPanel_Device_Option.repaint();//Refresh the JPanel
          if(jComboBox_Output.getSelectedItem().toString().length() > 0)//Check if any elements should be added
              GridBagConstraints gbConstraint = new GridBagConstraints();//Create a new gridbagcontraint (properties of layout) check http://java.sun.com/docs/books/tutorial/uiswing/layout/gridbag.html
              gbConstraint.fill = GridBagConstraints.HORIZONTAL;
              gbConstraint.anchor = GridBagConstraints.PAGE_START;
              gbConstraint.weightx = 0.5;
              try
                  stmt = GeneralDBConnect.createStatement();
                  /*Collect data from the database (Which elements should be displayed)  
                      deviceoption: The name of the option this is displayed in the elements label as text
                      tooltip: Show a tooltip on both label and element
                      device_optio_id: gets the ID needed to get the list values for a combobox also easy to use when getting the data afterwards (stored in a public variable
                      objecttype: Label, Textfield, Checkbox, Combobox*/
                  ResultSet rsElements = stmt.executeQuery("select device_option, tooltip, device_option_id, objecttype from device_option where deviceid = (select device_id from device where devicename = \'" + jComboBox_Output.getSelectedItem() + "\') order by sequence_order asc");
                  aDatasetElements = new ArrayList(); // Makes an array
                  while(rsElements.next()) //get data in arraylist (a resultset closes after a while (garbitch collector) resulting in errors I recieved some errors resulset allready closed. Also needed to acces data afterwards
                      aDatasetElements.add(new String(rsElements.getString(1)) + " ;" + new String(rsElements.getString(2)) + ";" + new Integer(rsElements.getInt(3)) + ";" + new String(rsElements.getString(4)));
                  rsElements.close();
                  aLabel = new JLabel[aDatasetElements.size()];          //Makes an array
                  aTextfieldLabel = new JLabel[aDatasetElements.size()]; //Makes an array
                  aTextfield = new JTextField[aDatasetElements.size()];  //Makes an array
                  aCheckboxLabel = new JLabel[aDatasetElements.size()];  //Makes an array
                  aCheckbox = new JCheckBox[aDatasetElements.size()];    //Makes an array
                  aComboboxLabel = new JLabel[aDatasetElements.size()];  //Makes an array
                  aCombobox = new JComboBox[aDatasetElements.size()];    //Makes an array
                  for(int i = 0; i < aDatasetElements.size(); i++) //loop through the foundset
                      String sDatasetElements = aDatasetElements.get(i).toString(); //get the data from the array
                      //Creation of Elements of type Label
                      if(sDatasetElements.split(";")[3].equals("Label")) //Check objecttype
                          gbConstraint.gridx = 0; //X position in layout (Label)
                          gbConstraint.gridy = i; //Y position in layout (Label)
                          aLabel[i] = new JLabel(sDatasetElements.split(";")[0], aLabel.TRAILING); //Makes a JLabel at an array place
    aLabel[i].setToolTipText(sDatasetElements.split(";")[1]);
    jPanel_Device_Option.add(aLabel[i], gbConstraint); //Adds a JLabel to the JPanel
    //Creation of Elements of type TextField
    if(sDatasetElements.split(";")[3].equals("Textfield"))
    gbConstraint.gridx = 0; //X position in layout (Label)
    gbConstraint.gridy = i; //Y position in layout (Label)
    aTextfieldLabel[i] = new JLabel(sDatasetElements.split(";")[0], aTextfieldLabel[i].TRAILING); //Makes a JTextfield at an array place
    aTextfieldLabel[i].setToolTipText(sDatasetElements.split(";")[1]);
    jPanel_Device_Option.add(aTextfieldLabel[i], gbConstraint); //Adds a JLabel to the JPanel
    gbConstraint.gridx = 1; //X position in layout (Element)
    gbConstraint.gridy = i; //Y position in layout (Element)
    aTextfield[i] = new JTextField(); //Makes a JTextfield at an array place
    aTextfield[i].setToolTipText(sDatasetElements.split(";")[1]);
    jPanel_Device_Option.add(aTextfield[i], gbConstraint); //Adds a JTextField to the JPanel
    //Creation of Elements of type Checkbox
    if(sDatasetElements.split(";")[3].equals("Checkbox"))
    gbConstraint.gridx = 0; //X position in layout (Label)
    gbConstraint.gridy = i; //Y position in layout (Label)
    aCheckboxLabel[i] = new JLabel(sDatasetElements.split(";")[0], aCheckboxLabel[i].TRAILING); //Makes a JLabel at an array place
    aCheckboxLabel[i].setToolTipText(sDatasetElements.split(";")[1]);
    jPanel_Device_Option.add(aCheckboxLabel[i], gbConstraint); //Adds a JLabel to the JPanel
    gbConstraint.gridx = 1; //X position in layout (Element)
    gbConstraint.gridy = i; //Y position in layout (Element)
    aCheckbox[i] = new JCheckBox(); //Makes a JCheckbox at an array place
    aCheckbox[i].setToolTipText(sDatasetElements.split(";")[1]);
    jPanel_Device_Option.add(aCheckbox[i], gbConstraint); //Adds a JCheckbox to the JPanel
    //Creation of Elements of type Combobox
    if(sDatasetElements.split(";")[3].equals("Combobox"))
    gbConstraint.gridx = 0; //X position in layout (Label)
    gbConstraint.gridy = i; //Y position in layout (Label)
    aComboboxLabel[i] = new JLabel(sDatasetElements.split(";")[0], aComboboxLabel[i].TRAILING); // Makes a JLabel at an array place
    aComboboxLabel[i].setToolTipText(sDatasetElements.split(";")[1]);
    jPanel_Device_Option.add(aComboboxLabel[i], gbConstraint); //Adds a JLabel to the JPanel
    gbConstraint.gridx = 1; //X position in layout (Element)
    gbConstraint.gridy = i; //Y position in layout (Element)
    aCombobox[i] = new JComboBox(); //Makes a JCombobox at an array place
    aCombobox[i].setToolTipText(sDatasetElements.split(";")[1]);
    jPanel_Device_Option.add(aCombobox[i], gbConstraint); //Adds a JCombobox to the JPanel
    //Get the listvalues from the database option_value is the value that is shown in the list
    ResultSet rsValuelist = stmt.executeQuery("select option_value from device_option_value where device_optionid = " + sDatasetElements.split(";")[2] + " and (option_state = " + iOptionState + " or option_state = 40) order by sequence_order");
    while(rsValuelist.next())
    if(rsValuelist.getString(1) == null)
    aCombobox[i].addItem("");
    else
    aCombobox[i].addItem(rsValuelist.getString(1));
    rsValuelist.close();
    //Place an empty label at the bottom otherwice the labels are centered in the JPanel
    gbConstraint.anchor = GridBagConstraints.PAGE_END;
    gbConstraint.weighty = 1.0;
    gbConstraint.gridx = 0;
    gbConstraint.gridy = aDatasetElements.size() + 1;
    jPanel_Device_Option.add(new JLabel(""), gbConstraint); //Adds an empty JLabel to the JPanel
    catch (SQLException ex)
    ex.printStackTrace();
    The is triggered in the init method and the event Item changed of the JCombobox
    private void jComboBox_Output_ItemStateChanged(java.awt.event.ItemEvent evt) {                                                  
          //Removed some irrelevant code here
          setOutputSettings();
        }To collect the data that the user has entered in the elements
    private void jButton_Collect_User_Data_ActionPerformed(java.awt.event.ActionEvent evt) {                                              
          String sList = "";
          for(int i = 0; i < aDatasetElements.size(); i++)
              String sDatasetElements = aDatasetElements.get(i).toString();
              if(sDatasetElements.split(";")[3].equals("Label"))
                  sList = sList + aLabel.getText() + "\n";
    if(sDatasetElements.split(";")[3].equals("Textfield"))
    sList = sList + aTextfield[i].getText() + "\n";
    if(sDatasetElements.split(";")[3].equals("Checkbox"))
    sList = sList + aCheckbox[i].isSelected() + "\n";
    if(sDatasetElements.split(";")[3].equals("Combobox"))
    sList = sList + aCombobox[i].getSelectedItem().toString() + "\n";
    JOptionPane.showMessageDialog(null, sList);
    I hope ths is helpfull information.
    Since I`m totally new to Java it is possible that a different approach is better however this is working for me.
    I`m open for any remarks on the code and feel free to give any comments.
    Kind Regards Rene

Maybe you are looking for

  • Radio button condition

    Hi all, I have two items on a page: a radio button ('yes' and 'no' options) and a text item. If I select 'yes' for the radio button item, I want the text item to become read-only. How would I do that? Thank you! Adina

  • NI LabVIEW Run-Time Engine + TCP/IP

    Hello, Anybody knows how to activate TCP/IP service on PC with standard NI LabView Run-Time Engine installed. If I trying communicate with server from my PC (LVRTE) its works correctly.   However, when I am trying interchange client and server applic

  • Two iterators browsing the same data (a table and a tree) problem

    I have an ADF UIX application with a navigation tree and a central page with a table of the records of a Works view object. There is a hierarchical relationship of Works ->Subworks-> Tasks which is shown in the tree. In the central part of the page,

  • External Hard drive will not show up on startup

    Hello, When i leave my external hard drive (that I use to back up my system) in, it will not show up on the desktop. Is there any solutions i could try? Thanks for your help Brad

  • Iphone - languages.. is it possible to get another language than English?

    Iphone - languages.. is it possible to get another language than English?