Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Java (http://www.go4expert.com/forums/java/)
-   -   Add button to every new jtable row during runtime (http://www.go4expert.com/forums/add-button-jtable-row-runtime-t26778/)

rajasohaibmaroof 24Sep2011 19:52

Add button to every new jtable row during runtime
 
hi all i have been give a task to add button of delete and update to every row of the jtable ! for example if a new row is added add and update button should be added along them ! any help will be appreciated thanx in advance:confused:

ewaldhorn 26Sep2011 15:00

Re: Add button to every new jtable row during runtime
 
Hi.

How about showing us the code you use to create your table, with your attempt at adding the button.

Here's hint - you are going to need two more columns in each row, one for add and one for update. That's one possible solution, but yours might differ.

In general, people won't help you unless you put in some effort, so at the very least, share your code, nobody will laugh at your efforts, they just want to see that you've really tried to do the work first.

Good luck,
Ewald

rajasohaibmaroof 26Sep2011 22:48

Re: Add button to every new jtable row during runtime
 
Hi m glad that u people are here to help . so far im able to add buttons to two of my columns, but the problem is that im unable to give them sepereate name and also I m unable to make them delete and update the particular row ! I have code to update n delete the row but I’m unable to use that code for buttons inside the jtable ! I m going to past the code of gui and cell renders n editors , also for delete button and edit buttons actions code which they should perform when they are pressed….plz help me n edit them so that
1.they show distant name according to their columns. Delete column should show buttons with delete written on them
2.i show distant name according to their columns. edit column should show buttons with edit written on them.
3.perform deletion n update function each of their respective rows.

rajasohaibmaroof 26Sep2011 22:49

Re: Add button to every new jtable row during runtime
 
]
Code:


package com.company.librarySystem.bm.ui;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
 
/**
 * @version 1.0 11/09/98
 */
public class ButtonRenderer extends JButton implements TableCellRenderer {
 
  public ButtonRenderer() {
    setOpaque(true);
  }
 
  public Component getTableCellRendererComponent(JTable table, Object value,
                  boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected) {
      setForeground(table.getSelectionForeground());
      setBackground(table.getSelectionBackground());
    } else{
      setForeground(table.getForeground());
      setBackground(UIManager.getColor("Button.background"));
    }
    setText( (value ==null) ? "" : value.toString() );
    return this;
  }
}


rajasohaibmaroof 26Sep2011 22:50

Re: Add button to every new jtable row during runtime
 
]
Code:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.company.librarySystem.bm.ui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
 
/**
 * @version 1.0 11/09/98
 */
public class ButtonEditor extends DefaultCellEditor {
  protected JButton button;
  private String    label;
  private boolean  isPushed;
 
  public ButtonEditor(JCheckBox checkBox) {
    super(checkBox);
    button = new JButton();
    button.setOpaque(true);
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        fireEditingStopped();
      }
    });
  }
 
  public Component getTableCellEditorComponent(JTable table, Object value,
                  boolean isSelected, int row, int column) {
    if (isSelected) {
      button.setForeground(table.getSelectionForeground());
      button.setBackground(table.getSelectionBackground());
    } else{
      button.setForeground(table.getForeground());
      button.setBackground(table.getBackground());
    }
    label = (value ==null) ? "" : value.toString();
    button.setText( label );
    isPushed = true;
    return button;
  }
 
  public Object getCellEditorValue() {
    if (isPushed)  {
      //
      //
      JOptionPane.showMessageDialog(button ,label + ": Ouch!");
      // System.out.println(label + ": Ouch!");
    }
    isPushed = false;
    return new String( label ) ;
  }
 
  public boolean stopCellEditing() {
    isPushed = false;
    return super.stopCellEditing();
  }
 
  protected void fireEditingStopped() {
    super.fireEditingStopped();
  }
}

Code:

private void UpdateMouseClicked(java.awt.event.MouseEvent evt) {                                   
    UpdateController updateController = new com.company.librarySystem.bm.controller.UpdateController();
    Book book = new Book();
  // book.setBookName(bokName.getText());
    //book.setAuthorName(authorName.getText());
    book.setSelectedRowValueOfColumnSecond(jTable1.getValueAt(jTable1.getSelectedRow(), 1));
    book.setSelectedRowValueOfColumnFirst(jTable1.getValueAt(jTable1.getSelectedRow(), 0));
    updateController.update(book);
}                                 

private void DeleteMouseClicked(java.awt.event.MouseEvent evt) {                                   
    DeleteController deleteController = new DeleteController();
    Book book = new Book();
    book.setSelectedRowValueOfColumnFirst(jTable1.getValueAt(jTable1.getSelectedRow(), 0));
    deleteController.delete(book);
    defaultTableModel.removeRow(jTable1.getSelectedRow());
   
 
   
   
}

unable to post gui 's whole code dnt knw its not letting me insert that i will just past the related code plzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz help me now [IMG]file:///C:/DOCUME%7E1/ADMINI%7E1/LOCALS%7E1/Temp/msohtmlclip1/01/clip_image001.gif[/IMG][IMG]file:///C:/DOCUME%7E1/ADMINI%7E1/LOCALS%7E1/Temp/msohtmlclip1/01/clip_image002.gif[/IMG]

rajasohaibmaroof 26Sep2011 22:51

Re: Add button to every new jtable row during runtime
 
Code:

public class NewJFrame extends javax.swing.JFrame {
        javax.swing.table.DefaultTableModel defaultTableModel = new javax.swing.table.DefaultTableModel();
    AddController addController = new AddController();


    /** Creates new form NewJFrame */
    public NewJFrame() {
        initComponents();
        jTable1.setModel(defaultTableModel);
        defaultTableModel.addColumn((Object) "Sr.no");
        defaultTableModel.addColumn((Object) "Book Title");
        defaultTableModel.addColumn((Object) "Author Name");
        defaultTableModel.addColumn((Object) "Delete");
        defaultTableModel.addColumn((Object) "Edit");
       
       
        addController.selectAll();
        jTable1.setModel(defaultTableModel);
     
       
        for (Book book : addController.selectAll()) {
          defaultTableModel.addRow(new String[]{book.srNo,book.BookName, book.AuthorName});
         
        }
    jTable1.getColumn("Delete").setCellRenderer(new ButtonRenderer());
    jTable1.getColumn("Delete").setCellEditor(new ButtonEditor(new JCheckBox()));
    jTable1.getColumn("Edit").setCellRenderer(new ButtonRenderer());
    jTable1.getColumn("Edit").setCellEditor(new ButtonEditor(new JCheckBox()));
     
       
   
    }

    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        bookName = new javax.swing.JTextField();
        authorName = new javax.swing.JTextField();
        Add = new javax.swing.JButton();
        Delete = new javax.swing.JButton();
        Update = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel2.setText("Add Book");

        jLabel3.setText("Book Name");

        jLabel4.setText("Author Name");

        Add.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/company/librarySystem/bm/ui/database_add.png"))); // NOI18N
        Add.setText("Add");
        Add.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                AddMouseClicked(evt);
            }
        });

        Delete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/company/librarySystem/bm/ui/database_delete.png"))); // NOI18N
        Delete.setText("Delete");

        Update.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/company/librarySystem/bm/ui/database_edit.png"))); // NOI18N
        Update.setText("Update");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(bookName, javax.swing.GroupLayout.DEFAULT_SIZE, 277, Short.MAX_VALUE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(Add)
                                .addGap(18, 18, 18)
                                .addComponent(Delete)
                                .addGap(18, 18, 18)
                                .addComponent(Update))
                            .addComponent(authorName, javax.swing.GroupLayout.DEFAULT_SIZE, 277, Short.MAX_VALUE))))
                .addContainerGap(64, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel2)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(bookName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(authorName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(Add)
                    .addComponent(Delete)
                    .addComponent(Update))
                .addContainerGap(36, Short.MAX_VALUE))
        );

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel5.setText("Edit Book");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "Sr.no", "Book Title", "Author Name", "Delete", "Edit"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                true, true, true, true, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setColumnSelectionAllowed(true);
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 422, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(32, Short.MAX_VALUE))
        );

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14));
        jLabel1.setText("Book Management");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addGap(17, 17, 17)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>                       

    private void AddMouseClicked(java.awt.event.MouseEvent evt) {                               
          Book book = new Book();
    book.setBookName(bookName.getText());
    book.setAuthorName(authorName.getText());
    addController.add(book);
   
    defaultTableModel.addRow(new String[]{book.srNo,book.BookName, book.AuthorName});

    //add value to table OR refresh table automatically

    }


ewaldhorn 27Sep2011 12:40

Re: Add button to every new jtable row during runtime
 
Hi.

I think you might be better served if you attached the code in a ZIP archive, that way whoever helps you can be sure to get it right.

You are going to have to put the buttons in some kind of ARRAY, or LIST : upload the code in the ZIP and I'll take a look at it.

Best regards,
Ewald

rajasohaibmaroof 27Sep2011 14:34

Re: Add button to every new jtable row during runtime
 
1 Attachment(s)
hi ok im going to attach the rar file ! i have set name to them now the problem is that i want to add the actionlistner .....thanx in advance

ewaldhorn 27Sep2011 14:56

Re: Add button to every new jtable row during runtime
 
Awesome!

You are very close to an answer. I don't think giving you exact code is going to help you learn something, but I have a handy hint for you that's going to push you in the right direction:

The following section of code displays a main panel, filled with some buttons. If you click on one, it identifies itself. The buttons are added to a list at runtime, so, in theory, you can have as many buttons as you want. Using this, you can do the same in your code. Believe it or not, this piece of code creates 150 buttons :)

Please let me know if you managed to get your code working.

Best regards,
Ewald



package lotsofbuttons;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class LotsOfButtons
extends JFrame
implements ActionListener
{
private static final int BUTTONS = 150;
private List<JButton> buttons = new LinkedList<JButton>();

public LotsOfButtons()
{
setupFrame();
setupButtons();
}


protected void setupFrame()
{
this.setSize(640, 480);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
this.setLayout(new FlowLayout(FlowLayout.LEFT));
}

/**
* Create all of our buttons, add the action listener,
* add them to the list and then add them to the main panel.
*/
protected void setupButtons()
{
for (int i = 0; i < BUTTONS; i++)
{
JButton button = new JButton("" + i);
button.addActionListener(this);
buttons.add(button);

this.add(button);
}
}

/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
LotsOfButtons app = new LotsOfButtons();
app.setVisible(true);
}


/**
* Loop through all our buttons, if it's the one
* that was clicked, display the correct message
* @param e
*/
public void actionPerformed(ActionEvent e)
{
for (JButton jButton : buttons)
{
if (e.getSource().equals(jButton))
{
JOptionPane.showMessageDialog(this, "You pressed " + jButton.getText());
break;
}
}
}
}

rajasohaibmaroof 27Sep2011 15:41

Re: Add button to every new jtable row during runtime
 
no it didn't ring a bell :nonod::nonod:adding buttons is working fine .but giving them separate actionlister is difficult just give me hint where n how to put actionlistner in my code m stuck in it :embarasse.for example when i press the delete button of particular row it deletes it.and when i press the update button of particular row it should let me do hat i want to do... plz help me in a way that i should learn something . i agree with u that giving me exact code is not a good idea but atleast make me move in right direction .:confused:


All times are GMT +5.5. The time now is 10:36.