Add CheckBox to JTable

How to add a checkBox in a column of my table?
I would like to add a checkbox in column 3. Where should I add the Listener to?

Here's a simple example using a JCheckBox as a renderer:
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
import java.text.*;
public class TableRenderer extends JFrame
    public TableRenderer()
        String[] columnNames = {"Date", "String", "Integer", "Decimal", "Boolean"};
        Object[][] data =
            {new Date(), "A", new Integer(1), new Double(5.1), new Boolean(true)},
            {new Date(), "B", new Integer(2), new Double(6.2), new Boolean(false)},
            {new Date(), "C", new Integer(3), new Double(7.3), new Boolean(true)},
            {new Date(), "D", new Integer(4), new Double(8.4), new Boolean(false)}
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        JTable table = new JTable( model )
            //  Returning the Class of each column will allow different
            //  renderers to be used based on Class
            public Class getColumnClass(int column)
                return getValueAt(0, column).getClass();
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane( table );
        getContentPane().add( scrollPane );
        //  Create cell renderer
        TableCellRenderer centerRenderer = new CenterRenderer();
        //  Use renderer on a specific column
        TableColumn column = table.getColumnModel().getColumn(3);
        column.setCellRenderer( centerRenderer );
        //  Use renderer on a specific Class
        table.setDefaultRenderer(String.class, centerRenderer);
          scrollPane.getViewport().setBackground(Color.red);
    public static void main(String[] args)
        TableRenderer frame = new TableRenderer();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setVisible(true);
    **  Center the text and highlight the focused cell
    class CenterRenderer extends DefaultTableCellRenderer
        public CenterRenderer()
            setHorizontalAlignment( CENTER );
        public Component getTableCellRendererComponent(
            JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            if (hasFocus)
                setBackground( Color.cyan );
            else if (isSelected)
                setBackground( table.getSelectionBackground() );
            else
                setBackground( table.getBackground() );
            return this;
}For more information on "Using Tables" see the Swing tutorial:
http://java.sun.com/docs/books/tutorial/uiswing/components/table.html

Similar Messages

  • How to Add Checkbox and icon in ALVGRID

    Hi Experts,
      i have one Requirement. i need to add Checkbox, Selectall,icon(Unlock or inactive) infront of Contracts of ALV GRID.How to achive that.
    Thanks,
    Venkat.

    Hi
    For check box
    At declaring field catalog using structure LVC_S_FCAT
    mark CHECKBOX = 'X' and also EDIT = 'X'.
    For reference check below subroutine in program BCALV_EDIT_05.
    form build_fieldcat changing pt_fieldcat type lvc_t_fcat.
    data ls_fcat type lvc_s_fcat.
    call function 'LVC_FIELDCATALOG_MERGE'
    exporting
    i_structure_name = 'SFLIGHT'
    changing
    ct_fieldcat = pt_fieldcat.
    *§A2.Add an entry for the checkbox in the fieldcatalog
    clear ls_fcat.
    ls_fcat-fieldname = 'CHECKBOX'.
    * Essential: declare field as checkbox and
    * mark it as editable field:
    ls_fcat-checkbox = 'X'.
    ls_fcat-edit = 'X'.
    * do not forget to provide texts for this extra field
    ls_fcat-coltext = text-f01.
    ls_fcat-tooltip = text-f02.
    ls_fcat-seltext = text-f03.
    * optional: set column width
    ls_fcat-outputlen = 10.
    append ls_fcat to pt_fieldcat.
    endform.
    For Icon:
    CONSTANTS:
         icon_id_failure            LIKE icon-id   VALUE ' ((Content component not found.)) @',
         icon_id_okay              LIKE icon-id   VALUE ' ((Content component not found.)) @'.
    TYPES: BEGIN OF ls_tab,
           matnr LIKE equi-matnr,
           maktx LIKE makt-maktx,
           b_werk  LIKE equi-werk,
           b_lager LIKE equi-lager,
           lgobe LIKE t001l-lgobe,
           sernr LIKE equi-sernr,
           icon LIKE icon-id,
           objnr LIKE equi-objnr,
          END OF   ls_tab.
    *Table that display the data for the ALV.
    DATA: itab  TYPE ls_tab OCCURS 0 WITH HEADER LINE.
        PERFORM get_h_date .
        IF h_date => sy-datum .
          itab-icon = icon_id_okay.
        ELSE .
          itab-icon = icon_id_failure.
         ENDIF.
    Regards
    Sudheer

  • Add Jcombo in Jtable at run time

    hello,
    i want to add jcombo box in jtable every cell & i also add column in run time.proble is when i add new column that time last column combo is add but prievious column its remove automatic.
    so give me some code & where i can get see good example for add combo in jtable.
    thanks

    hi j-rg,
    It was really appreaciating to c ur reply, regarding the specific problem.Actually wht i was facing the peoblem, Am adding a colomn in the run time and in that column am adding a combo in each cells of that column.AS i was expecting am able to add a new colum in th erum time with the combo in each cells of that column,now when am adding another column in the run time am getting all the required things,but the problem is " in the previous cloumn am not getting that combo"(only the combo is been added in the last column).
    What am expecting is the combo should be there in each cell of the column(all columns)
    Am also sending the code wht am using, plz have a look below,
    df1.addColumn(result);
         TableColumn aa= tb1.getColumnModel().getColumn(tb1.getColumnCount()-1);
         aa.setCellEditor(new DefaultCellEditor(comboBox));
    wating for ur reply
    thanks and regards
    sandeep

  • Need to add checkbox in alv header Not  in grid

    Dear Guru's,
                       My question is i want to add checkbox on top of alv grid ie on top of page .
    my requriement is for SD module- status of order -Mass Update.
    suppose status checkbox on header is HFSC is checked ( check box),
    for all the sales order which are showed on the alv grid must be updated with this status for which i am calling trasaction VA02 in program and doing changes but i am not able to create checkbox on header .
    Again i have already used ALV without classesso please give me solution accordinglly . Thanks in advance.

    Hi,
    For working with top of page we generally use SLIS_LISTHEADER right.
    In this type the first field is
    type - which can accept values as follows
               H - Heading
               S - Selection
               A - Action
    May be the options Selection or Action may help u.

  • Add checkbox on the nodes of Hierarchical tree in oracle forms 9i

    Hi,
    I am working on oracle forms 9i.I have to add checkbox at the place of node(+/-) in Hierarchical tree so,
    that user can select or deselect the Tree.That can do in oracle forms but how i don't know.
    can anybody help me.....
    Regards,
    Hemant

    You can't change this aspect of the Tree Control in Oracle Forms using built-in functionality. You might be able to extend the Tree Control using Java, but you have to do this yourself. : (
    Craig...

  • Hi Experts, oo hierarchical alv, how to add checkbox on every header?

    Hi Experts,
    I am working on oo hierarchical alv, how can I add checkbox on every header? thanks in advance!
    Kind regards
    Dawson

    Hi Dawson,
    Just refer the below program & pass the check box functionality (mentioned in bold) in REUSE_ALV_HIERSEQ_LIST_DISPLAY in your program.
    TYPE-POOLS : slis.
    Data
    DATA : BEGIN OF itab OCCURS 0.
    INCLUDE STRUCTURE t001.
    DATA : flag tyPE c,
    END OF itab.
    DATA : alvfc TYPE slis_t_fieldcat_alv.
    DATA : alvly TYPE slis_layout_alv.
    Select Data
    SELECT * FROM t001 INTO TABLE itab.
    *------- Field Catalogue
    CALL FUNCTION 'REUSE_ALV_FIELDCATALOG_MERGE'
    EXPORTING
    i_program_name = sy-repid
    i_internal_tabname = 'ITAB'
    i_inclname = sy-repid
    CHANGING
    ct_fieldcat = alvfc
    EXCEPTIONS
    inconsistent_interface = 1
    program_error = 2
    OTHERS = 3.
    Display
    alvly-box_fieldname = 'FLAG'.
    CALL FUNCTION 'REUSE_ALV_LIST_DISPLAY'
    EXPORTING
    it_fieldcat = alvfc
    i_callback_program = sy-repid "<-------Important
    i_callback_user_command = 'ITAB_USER_COMMAND' "<------ Important
    is_layout = alvly
    TABLES
    t_outtab = itab
    EXCEPTIONS
    program_error = 1
    OTHERS = 2.
    CALL BACK FORM
    FORM itab_user_command USING whatcomm TYPE sy-ucomm whatrow TYPE
    slis_selfield.
    LOOP AT itab.
    itab-flag = 'X'.
    MODIFY itab.
    ENDLOOP.
    IMPORTANT.
    WHATROW-REFRESH = 'X'.
    ENDFORM. "ITAB_user_command
    Regards
    Abhii...

  • Suggestions to add checkbox to Report

    Version : 4.1.0
    Hi There,
    We have a classic report on an SQL. Now there is a requirement to add some sort of a check box against each report row where the user if selected, it marks that record as a favorite. That checkbox value will be stored in the table.
    If it was a tabular form, I could have just added that as a checkbox and a DB column and it would get updated when the user hit the submit button, any suggesstions on how to do this on a report? Or the only way would be to convert the report to a tabular form ? Not sure, how to capture the Radio values. Any better suggestions are also welcome.
    thanks,
    Ryan

    Hi ryansun
    you can add checkbox to your report.
    Suppose this is your query report
    SELECT empno,
           ename,
           job
    FROM   empyou want to add checkbox to your report then try the below code
    SELECT APEX_ITEM.CHECKBOX(1,empno) " ",
           ename,
           job
    FROM   emp
    Click on report attributes then edit the checkbox column
    under column attributes
    set Display as = Standard Report Column
    For detail information follow the link given below
    http://docs.oracle.com/cd/E10513_01/doc/apirefs.310/e12855/apex_item.htm#CHDDCHAF
    Hope this will solve your problem.
    Regards,
    Jitendra

  • How to add Checkbox in Table

    Hi,
    I want to add CheckBox in Table. my requirement is multiselection. I Implemented the following steps, but it's not working. anyone can tell me,what mistake i did?
    I created two "Value Attribute"(check,Name) under a "Value Node"(Student) in context.
    check - Boolean
    Name - mapped a Dictionary simple Type(5 values)
    Include a Table in Layout and select Create Binding on right clicking of Table.
    Checked only Student and check -> Next
    Selected the Editor as checkbox -> Finish
    Selected Name from context and assigned to checkbox text property.
    Then I deployed the application. But only one checkbox is displayed in Table without any text.
    Please give me the suggestion, how to do this.
    Thanks in Advance
    Rajakumar

    Hello,
    I think you have a fundamental misunderstanding on how Checkboxes work. A Checkbox triggers a boolean value with true (checked) or false (uncheked).
    When you map your name attribut to text you will see the content of that attribute as text behind. But not the metadata.
    You may want to use a RadiobuttonGroup or CheckboxGroup for your purpose.
    Frank

  • How to add data into JTable

    How can I add data into JTable, for instance ("Mike", "Gooler", 21).

    How can I add data into JTable, for instance ("Mike",
    "Gooler", 21).You will have very good results if you segregate out the table model as a seperate user class and provide a method to add a row there. In fact, if you use the table to reflect a database table you can add the row inplace using the existing cursor. I believe it's TableExample2 in the jdk\demo\jfc\TableExamples that has a very good example of this.
    Walt

  • How to use checkboxes in jtable ?

    I am trying to use checkboxes in
    JTable,I set the property in the jtable column to boolean.The proplem is that i do no know how to use this property in java program.My intension is that,I will have a java form and a java button on it,by clicking the button, i will have to write a code,for example a code that fetches records from a table and displays them on the jtable(on the user interface),when I select the check box corresponding to any row,It should let me either delete or edit that row and this modification has to be reflected to the table in the database. At this time,i can fetch and display but i can not delete or modify any row because I do no know how to use the check box inside the jtable.
    Thank you for your help!

    Multi-post: http://forum.java.sun.com/thread.jspa?threadID=5273661&tstart=0

  • Add JTree in JTable

    How to add JTree in JTable?
    Please tell me?

    you need to use a TableCellRenderer, that implements your JTree, for cell renderers see http://java.sun.com/docs/books/tutorial/uiswing/components/table.html and http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#renderer
    thomas

  • Add checkbox on header level Tab Org.data

    Dear All,
    My requirement is I need to add checkbox on header level Tab Org.data in ME21n or ME21.
    And if checkbox is checked in the tab Org.data, it should display Terms and Conditions in the print preview.
    Please suggest how to write code? Is there any user exit for transactions ME21N or ME21.
    Thanks,
    Rana.

    hi praveen,
    search this forum on how to implement a badi if you haven't done one before. also, go to transation SE18 and read the documentation on badi_fdcb_subbas01 which clearly says that its used for FB60... see the example how they have used it by going to menubar Implementation->Overview then choose FI_FDCB_SUBBAS01_EX (Example for Screen Enhancement 1 on FDCB Basic Data Screen)...you should look at the method PUT_DATA_TO_SCREEN_OBJECT and tab Subscreens where the screen exits are available to use.
    In FB60, if you go to menubar System->Status and check the Program (Subscreen) and Screen Number, you'll see it'll match the program name and screen no. provided in the Subscreen tab of the BADI.
    Hope this helps.
    Cheers,
    Sougata.

  • Code for complete JTree of mycomputer (dynamic) but need to add checkboxes

    //the bug is where i am sending the value to the checkbox.. if somebody can add checkboxes to every node plz reply soon
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Font;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import java.awt.event.MouseEvent;
    import java.util.EventObject;
    import java.util.Vector;
    import javax.swing.AbstractCellEditor;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.UIManager;
    import javax.swing.event.ChangeEvent;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.TreeCellEditor;
    import javax.swing.tree.TreeCellRenderer;
    import javax.swing.tree.TreePath;
    public class CheckBoxNodeTreeSample {
    public static void main(String args[]) {
    JFrame frame = new JFrame("CheckBox Tree");
    /* CheckBoxNode accessibilityOptions[] = {
    new CheckBoxNode(
    "Move system caret with focus/selection changes", false),
    new CheckBoxNode("Always expand alt text for images", true) };
    CheckBoxNode browsingOptions[] = {
    new CheckBoxNode("Notify when downloads complete", true),
    new CheckBoxNode("Disable script debugging", true),
    new CheckBoxNode("Use AutoComplete", true),
    new CheckBoxNode("Browse in a new process", false) };
    Vector accessVector = new NamedVector("Accessibility",
    accessibilityOptions);
    Vector browseVector = new NamedVector("Browsing", browsingOptions);
    Object rootNodes[] = { accessVector, browseVector };
    Vector rootVector = new NamedVector("Root", rootNodes);
    setLayout(new GridLayout(1,1));
    //create the top node
    MutableTreeNode root = new DefaultMutableTreeNode("Computer");
    //get all nodes for top file systems or disks
    //On Linux/Unix this will only be '/'
    //while on Window there will typically be more: 'A:', 'C:' etc.
    File roots[] = File.listRoots();
    //loop through all these nodes and add them to the root Computer node
    int i = 0;
    for(File f : roots) {
    DefaultMutableTreeNode node = new DefaultMutableTreeNode(f.getAbsoluteFile().toString());
    root.insert(node, i++);
    //create a tree model with the Computer node as root
    model = new DefaultTreeModel(root);
    JTree tree = new JTree(model);
    CheckBoxNodeRenderer renderer = new CheckBoxNodeRenderer();
    tree.setCellRenderer(renderer);
    tree.setCellEditor(new CheckBoxNodeEditor(tree));
    tree.setEditable(true);
    JScrollPane scrollPane = new JScrollPane(tree);
    frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 150);
    frame.setVisible(true);
    class CheckBoxNodeRenderer implements TreeCellRenderer {
    private JCheckBox leafRenderer = new JCheckBox();
    private DefaultTreeCellRenderer nonLeafRenderer = new DefaultTreeCellRenderer();
    Color selectionBorderColor, selectionForeground, selectionBackground,
    textForeground, textBackground;
    protected JCheckBox getLeafRenderer() {
    return leafRenderer;
    public CheckBoxNodeRenderer() {
    Font fontValue;
    fontValue = UIManager.getFont("Tree.font");
    if (fontValue != null) {
    leafRenderer.setFont(fontValue);
    Boolean booleanValue = (Boolean) UIManager
    .get("Tree.drawsFocusBorderAroundIcon");
    leafRenderer.setFocusPainted((booleanValue != null)
    && (booleanValue.booleanValue()));
    selectionBorderColor = UIManager.getColor("Tree.selectionBorderColor");
    selectionForeground = UIManager.getColor("Tree.selectionForeground");
    selectionBackground = UIManager.getColor("Tree.selectionBackground");
    textForeground = UIManager.getColor("Tree.textForeground");
    textBackground = UIManager.getColor("Tree.textBackground");
    public Component getTreeCellRendererComponent(JTree tree, Object value,
    boolean selected, boolean expanded, boolean leaf, int row,
    boolean hasFocus) {
    Component returnValue;
    if (leaf) {
    String stringValue = tree.convertValueToText(value, selected,
    expanded, leaf, row, false);
    leafRenderer.setText(stringValue);
    leafRenderer.setSelected(false);
    leafRenderer.setEnabled(tree.isEnabled());
    if (selected) {
    leafRenderer.setForeground(selectionForeground);
    leafRenderer.setBackground(selectionBackground);
    } else {
    leafRenderer.setForeground(textForeground);
    leafRenderer.setBackground(textBackground);
    if ((value != null) && (value instanceof DefaultMutableTreeNode)) {
    Object userObject = ((DefaultMutableTreeNode) value)
    .getUserObject();
    if (userObject instanceof CheckBoxNode) {
    CheckBoxNode node = (CheckBoxNode) userObject;
    leafRenderer.setText(node.getText());
    leafRenderer.setSelected(node.isSelected());
    returnValue = leafRenderer;
    } else {
    returnValue = nonLeafRenderer.getTreeCellRendererComponent(tree,
    value, selected, expanded, leaf, row, hasFocus);
    return returnValue;
    class CheckBoxNodeEditor extends AbstractCellEditor implements TreeCellEditor {
    CheckBoxNodeRenderer renderer = new CheckBoxNodeRenderer();
    ChangeEvent changeEvent = null;
    JTree tree;
    public CheckBoxNodeEditor(JTree tree) {
    this.tree = tree;
    public Object getCellEditorValue() {
    JCheckBox checkbox = renderer.getLeafRenderer();
    CheckBoxNode checkBoxNode = new CheckBoxNode(checkbox.getText(),
    checkbox.isSelected());
    return checkBoxNode;
    public boolean isCellEditable(EventObject event) {
    boolean returnValue = false;
    if (event instanceof MouseEvent) {
    MouseEvent mouseEvent = (MouseEvent) event;
    TreePath path = tree.getPathForLocation(mouseEvent.getX(),
    mouseEvent.getY());
    if (path != null) {
    Object node = path.getLastPathComponent();
    if ((node != null) && (node instanceof DefaultMutableTreeNode)) {
    DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) node;
    Object userObject = treeNode.getUserObject();
    returnValue = ((treeNode.isLeaf()) && (userObject instanceof CheckBoxNode));
    return returnValue;
    public Component getTreeCellEditorComponent(JTree tree, Object value,
    boolean selected, boolean expanded, boolean leaf, int row) {
    Component editor = renderer.getTreeCellRendererComponent(tree, value,
    true, expanded, leaf, row, true);
    // editor always selected / focused
    ItemListener itemListener = new ItemListener() {
    public void itemStateChanged(ItemEvent itemEvent) {
    if (stopCellEditing()) {
    fireEditingStopped();
    if (editor instanceof JCheckBox) {
    ((JCheckBox) editor).addItemListener(itemListener);
    return editor;
    class CheckBoxNode {
    String text;
    boolean selected;
    public CheckBoxNode(String text, boolean selected) {
    this.text = text;
    this.selected = selected;
    public boolean isSelected() {
    return selected;
    public void setSelected(boolean newValue) {
    selected = newValue;
    public String getText() {
    return text;
    public void setText(String newValue) {
    text = newValue;
    public String toString() {
    return getClass().getName() + "[" + text + "/" + selected + "]";
    class NamedVector extends Vector {
    String name;
    public NamedVector(String name) {
    this.name = name;
    public NamedVector(String name, Object elements[]) {
    this.name = name;
    for (int i = 0, n = elements.length; i < n; i++) {
    add(elements);
    public String toString() {
    return "[" + name + "]";

    Between when you posted the question and the entire 50 minutes you waited for an answer, I tried compiling that code you posted, with a view to help out.
    What I found was..
    That code did not compile as posted.
    - It was missing imports
    - There was a direct reference to setLayout that applied to no member
    - model was not declared properly
    It also shows unchecked add warnings, please fix those before posting.
    BTW - please do not remove indenting from posted code, it makes it very hard to read, replace any tabs in the source for 2-4 spaces instead. Also, code is easier to examine when it is enclosed in 'code' tags - this can be achieved by selecting the code and pressing the 'code' button above the form field we type the messages.
    On the subject of what you are trying to do, please trim your example down to something that tries to create this tree form any directory structure the user might specify with a JFileChooser, because I am running a slow machine with large drives, and creating a JTree of the entire file system would take far too long.
    Fix those things, and I'll take a second look.
    As an aside. If you wish to get answers 'within the hour', you will probably need a consultant or a help desk. If you post to these forums, you need to be more patient.

  • How to add CheckBoxs to a scrollPane

    I have a file I�m getting user info out of and finding certain information the
    User enters, I�m making a query, I�m taking the found items and making an array of Checkboxes out of them witch is working my problem is adding the Checkboxes to the scroll Pane
    public class Frame1 extends JFrame{
    public static Panel listan = new Panel();
    JCheckBox[] jCheckBox1 ;
    JScrollPane scrollPane1 = new JScrollPane(list);
    //other Window objects
    //first method
    private void jbInit() throws Exception {
    //puts all window objects together
    // Constructs user screen
    list.setLayout(verticalFlowLayout1);
    panel1.add(scrollPane1, new XYConstraints(118, 32, 128, 195));
    // i have a find buttion that takes all infoamtion out of file
    // and puts in an array then finds user enterd infomation
    // this is just example code that just adds CheckBoxs to the scrollPane
    // and is Basically the same way the other program does
    // second method
    void addcheckbox_actionPerformed(ActionEvent e) {
    jCheckBox1 = new JCheckBox[50];
    for (int i = 0; i < 50; i++) {
    String checkboxText = ("Checkbox #: " + (i + 1));
    jCheckBox1[i] = new JCheckBox(checkboxText);
    for (int i = 0; i < 50; i++) {
    list.add(jCheckBox1, null);
    My problem is that I can�t add the checkboxes at the second method but it works in the first, I can add in the first because I initialize in the second.

    If you want something to compile here is all my example code
    I will incorporate it to my 30 page program
    Here is what I want my code to do
    package list;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import com.borland.jbcl.layout.*;
    import java.awt.Checkbox;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2008</p>
    * <p>Company: </p>
    * @author not attributable
    * @version 1.0
    public class Frame1 extends JFrame {
      public static boolean ch=true;
      JPanel contentPane;
      GridLayout gridLayout1 = new GridLayout();
      JPanel panel1 = new JPanel();
      XYLayout xYLayout1 = new XYLayout();
      JButton jButton1;
      JButton jButton2;
      JButton addcheckbox;
      JCheckBox[] jCheckBox1 ;
      JScrollPane scrollPane1 = new JScrollPane();
      JPanel list = new JPanel();
      VerticalFlowLayout verticalFlowLayout1 = new VerticalFlowLayout();
      //Construct the frame
      public Frame1() {
        enableEvents(AWTEvent.WINDOW_EVENT_MASK);
        try {
          jbInit();
        catch (Exception e) {
          e.printStackTrace();
      //Component initialization
    // method one
      private void jbInit() throws Exception {
        contentPane = (JPanel)this.getContentPane();
        jButton1 = new JButton();
        jButton2 = new JButton();
        addcheckbox = new JButton();
        this.setContentPane(contentPane);
        this.setLocale(java.util.Locale.getDefault());
        this.setResizable(false);
        this.setSize(new Dimension(400, 300));
        this.setState(Frame.NORMAL);
        this.setTitle("Frame Title");
        contentPane.setOpaque(true);
        contentPane.setRequestFocusEnabled(true);
        contentPane.setLayout(gridLayout1);
        panel1.setLayout(xYLayout1);
        jButton1.setSelected(false);
        jButton1.setText("Print");
        jButton1.addActionListener(new Frame1_jButton1_actionAdapter(this));
        jButton2.setText("select all/none");
        jButton2.addActionListener(new Frame1_jButton2_actionAdapter(this));
        addcheckbox.setBorderPainted(true);
        addcheckbox.setText("add");
        addcheckbox.addActionListener(new Frame1_addcheckbox_actionAdapter(this));
        scrollPane1.setLocale(java.util.Locale.getDefault());
        list.setLayout(verticalFlowLayout1);
        contentPane.add(panel1, null);
        panel1.add(scrollPane1, new XYConstraints(118, 32, 128, 195));
        scrollPane1.getViewport().add(list, null);
        //scrollPane1.add(listan, null);
        panel1.add(jButton1, new XYConstraints(261, 92, 90, 39));
        panel1.add(jButton2,   new XYConstraints(262, 152, 108, 30));
        panel1.add(addcheckbox, new XYConstraints(25, 49, -1, 35));
      //Overridden so we can exit when window is closed
      protected void processWindowEvent(WindowEvent e) {
        super.processWindowEvent(e);
        if (e.getID() == WindowEvent.WINDOW_CLOSING) {
          System.exit(0);
      void jButton1_actionPerformed(ActionEvent e) {
        String checkprint = "selected:\n";
        for (int x = 0; x < jCheckBox1.length; x++) {
          if (jCheckBox1[x].isSelected()) {
             checkprint = checkprint + jCheckBox1[x].getText()+"\n";
        System.out.println(checkprint);
      void jButton2_actionPerformed(ActionEvent e) {
        for (int x = 0; x < jCheckBox1.length; x++) {
          if (ch == true) {
            jCheckBox1[x].setSelected(true);
          else{
            jCheckBox1[x].setSelected(false);
    if (ch == true)
          ch=false;
        else
          ch=true;
    //method two
      void addcheckbox_actionPerformed(ActionEvent e) {
        jCheckBox1 = new JCheckBox[50];
            for (int i = 0; i < 50; i++) {
              String checkboxText = ("Checkbox #: " + (i + 1));
              jCheckBox1[i] = new JCheckBox(checkboxText);
            for (int i = 0; i < 50; i++) {
             list.add(jCheckBox1, null);
    class Frame1_jButton1_actionAdapter implements java.awt.event.ActionListener {
    Frame1 adaptee;
    Frame1_jButton1_actionAdapter(Frame1 adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.jButton1_actionPerformed(e);
    class Frame1_jButton2_actionAdapter implements java.awt.event.ActionListener {
    Frame1 adaptee;
    Frame1_jButton2_actionAdapter(Frame1 adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.jButton2_actionPerformed(e);
    class Frame1_addcheckbox_actionAdapter implements java.awt.event.ActionListener {
    Frame1 adaptee;
    Frame1_addcheckbox_actionAdapter(Frame1 adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.addcheckbox_actionPerformed(e);
    }doesn�t work but if I take all of method two and put it in one it workspackage list;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import com.borland.jbcl.layout.*;
    import java.awt.Checkbox;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2008</p>
    * <p>Company: </p>
    * @author not attributable
    * @version 1.0
    public class Frame1 extends JFrame {
    public static boolean ch=true;
    JPanel contentPane;
    GridLayout gridLayout1 = new GridLayout();
    JPanel panel1 = new JPanel();
    XYLayout xYLayout1 = new XYLayout();
    JButton jButton1;
    JButton jButton2;
    JButton addcheckbox;
    JCheckBox[] jCheckBox1 ;
    JScrollPane scrollPane1 = new JScrollPane();
    JPanel list = new JPanel();
    VerticalFlowLayout verticalFlowLayout1 = new VerticalFlowLayout();
    //Construct the frame
    public Frame1() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
    jbInit();
    catch (Exception e) {
    e.printStackTrace();
    //Component initialization
    private void jbInit() throws Exception {
    // this is the same code in method two
    jCheckBox1 = new JCheckBox[50];
    for (int i = 0; i < 50; i++) {
    String checkboxText = ("Checkbox #: " + (i + 1));
    jCheckBox1[i] = new JCheckBox(checkboxText);
    for (int i = 0; i < 50; i++) {
    list.add(jCheckBox1[i], null);
    contentPane = (JPanel)this.getContentPane();
    jButton1 = new JButton();
    jButton2 = new JButton();
    addcheckbox = new JButton();
    this.setContentPane(contentPane);
    this.setLocale(java.util.Locale.getDefault());
    this.setResizable(false);
    this.setSize(new Dimension(400, 300));
    this.setState(Frame.NORMAL);
    this.setTitle("Frame Title");
    contentPane.setOpaque(true);
    contentPane.setRequestFocusEnabled(true);
    contentPane.setLayout(gridLayout1);
    panel1.setLayout(xYLayout1);
    jButton1.setSelected(false);
    jButton1.setText("Print");
    jButton1.addActionListener(new Frame1_jButton1_actionAdapter(this));
    jButton2.setText("select all/none");
    jButton2.addActionListener(new Frame1_jButton2_actionAdapter(this));
    addcheckbox.setBorderPainted(true);
    addcheckbox.setText("add");
    addcheckbox.addActionListener(new Frame1_addcheckbox_actionAdapter(this));
    scrollPane1.setLocale(java.util.Locale.getDefault());
    list.setLayout(verticalFlowLayout1);
    contentPane.add(panel1, null);
    panel1.add(scrollPane1, new XYConstraints(118, 32, 128, 195));
    scrollPane1.getViewport().add(list, null);
    //scrollPane1.add(listan, null);
    panel1.add(jButton1, new XYConstraints(261, 92, 90, 39));
    panel1.add(jButton2, new XYConstraints(262, 152, 108, 30));
    panel1.add(addcheckbox, new XYConstraints(25, 49, -1, 35));
    //Overridden so we can exit when window is closed
    protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
    System.exit(0);
    void jButton1_actionPerformed(ActionEvent e) {
    String checkprint = "selected:\n";
    for (int x = 0; x < jCheckBox1.length; x++) {
    if (jCheckBox1[x].isSelected()) {
    checkprint = checkprint + jCheckBox1[x].getText()+"\n";
    System.out.println(checkprint);
    void jButton2_actionPerformed(ActionEvent e) {
    for (int x = 0; x < jCheckBox1.length; x++) {
    if (ch == true) {
    jCheckBox1[x].setSelected(true);
    else{
    jCheckBox1[x].setSelected(false);
    if (ch == true)
    ch=false;
    else
    ch=true;
    void addcheckbox_actionPerformed(ActionEvent e) {
    class Frame1_jButton1_actionAdapter implements java.awt.event.ActionListener {
    Frame1 adaptee;
    Frame1_jButton1_actionAdapter(Frame1 adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.jButton1_actionPerformed(e);
    class Frame1_jButton2_actionAdapter implements java.awt.event.ActionListener {
    Frame1 adaptee;
    Frame1_jButton2_actionAdapter(Frame1 adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.jButton2_actionPerformed(e);
    class Frame1_addcheckbox_actionAdapter implements java.awt.event.ActionListener {
    Frame1 adaptee;
    Frame1_addcheckbox_actionAdapter(Frame1 adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.addcheckbox_actionPerformed(e);
    }Edited by: deme on Feb 27, 2008 6:48 AM
    Edited by: deme on Feb 27, 2008 6:51 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to add checkboxes to frames?

    Hi,
    I am trying to add checkboxes to a frame which will then be instantiated from an applet. I can launch the frame correctly from my applet but it always displays the last checkbox added only. So in my code below it would always display the 'Black' checkbox.
    Could anyone please tell me what I am doing wrong or not doing here?
    import java.awt.*;
    import java.applet.*;
    class Chooser extends Frame {
         Chooser(String title) {
              super(title);
              Checkbox cRed;
              Checkbox cBlack;
              CheckboxGroup cbg = new CheckboxGroup( );
              cRed = new Checkbox("Red", cbg, true);
              cBlack = new Checkbox("Black", cbg, false);
              add(cRed);
              add(cBlack);
            public boolean handleEvent(Event evtObj) {
              if (evtObj.id == Event.WINDOW_DESTROY) {
                   hide( );
                   return true;
              return super.handleEvent(evtObj);
         public void paint(Graphics g) {
              g.drawString("Chooser Frame",10,40);
    }Thanks
    Avi
    Message was edited by:
    avi22
    Message was edited by:
    avi22

    add a pack() statement to your Chooser constructor as the last statement before the end of the constructor
      Chooser(String title){
    //    your code here
        this.pack();

Maybe you are looking for

  • Unreadable Book Titles in iOS 8 Books App

    There seems to have been an "enhancement" to Books in iOS 8 that renders the book titles nearly ureadable in My Books view. Unfortunately, there is a new background effect that uses a grayed out version of the home screen. In addition, the book title

  • Cannot install Framemaker 8 on Windows server 2008R2

    Hello, I try to install Framemaker 8 on WS2008R2 and it goes until the application registration and fails and then rolls back to remove it. In the event viewer I have : Event ID 11708      Product: Adobe FrameMaker v8 -- Installation operation failed

  • Append date to exporting file name in SQL reporting service

    When exporting a report to another format, say excel,PDF; the file name is always set to the report name. Our client has a requirement where whenever a user exports a report to pdf, the timestamp of when the data of the report was made should be appe

  • 10.2.0.3 high concurrency wait event

    I have a new 64bit windows 10g 10.2.0.3 VM server doing nothing but spinning its wheels. I intalled Oracle on it Friday and when I checked it tonight I see it is getting high concurrency wait events. Looks like every 10 minutes concurrency goes up to

  • VAT Clearing in SAP?

    Hi , I would like to know what is  VAT clearing  in SAP System(version: 4.7ee)? and how can we clear VAT in SAP.