Clear contents in jtable swing

How to clear contents from jtable in java swing?

Remove them from your data model and update the view...

Similar Messages

  • Clear and update JTable.

    Hi. this is a follow up from [Original Tread in "New To Java"|http://forums.sun.com/thread.jspa?messageID=10886612�]
    Hope you can help me here. For you who dont read the link. This application is build only to lay up here. So the Layout aint pretty. It compiles and run tho. What i want and cant get to work is to reload table when i push my JTabbedPane.
    Main Class
    package test;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Main {
        public Main() {
            run();
        public void run(){
         frame();
        // clear and update JTable in class three
        public void clearThree() {
            Three t = new Three();
             t.clearVector();
        public JFrame frame() {
            JFrame frame = new JFrame();
            JTabbedPane tab = new JTabbedPane();
            tab.addTab("two",new Two());
            tab.addTab("three", new Three());
            tab.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                    clearThree();// this dont work
            frame.add(tab);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(800,400);
             frame.setVisible(true);
             frame.pack();
            return frame;
        public static void main(String[] args) {
             java.awt.EventQueue.invokeLater(new Runnable() {
                         public void run(){
           new Main();
    }// class two
    package test;
    import java.awt.event.*;
    import java.util.Vector;
    import javax.swing.*;
    // class twoś only purpose is to  call clear() in class Three
    public class Two extends JPanel{
    public Two(){
    toolBar();
      public void clearThree () {
       Three t = new Three();
       t.clearVector();
      public void toolBar(){
      JToolBar bar = new JToolBar();
      JButton button = new JButton("clear");
      button.addActionListener(new ActionListener (){
          public void actionPerformed(ActionEvent e){
          clearThree(); // this dont work
    bar.add(button);
    add(bar);
    }// class three hold the table.
    package test;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.table.DefaultTableModel;
    public class Three extends JPanel{ 
            DefaultTableModel model;
            JTable table;
            Vector v = new Vector();
            Vector a = new Vector();
            Vector<Vector> r = new Vector<Vector>();
        public Three() {
            jBar();
            jTable();
        public void clearVector(){
            v.removeAllElements();
            a.removeAllElements();
            r.removeAllElements();
            model.fireTableDataChanged();
        public void jBar() {
            JToolBar bar = new JToolBar();
            JButton button =  new JButton("clear");
            button.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    clearVector();// this does work
            bar.add(button);
            add(bar);
        public JScrollPane jTable(){
            v.addElement("ID");
            v.addElement("Name");
            a.addElement("01");
            a.addElement("Magnus");
            r.add(a);
            model = new DefaultTableModel(r,v);
            table = new JTable(model);
             JScrollPane pane = new JScrollPane(table);
             add(pane);
             return pane;
    }

    Thank you for your replay, I have taken all of your tips and modifed my original application. but the problem is still there. This has been a very messy thread. and it is becouse i thougth it were a table/model problem. But it&#347; not. In the code below I have a JTextField. When i push the JTabbedPanes i want the setText(); to kick in. this compile and run.
    // class One
    package test;
    import javax.swing.*;
    import javax.swing.event.*;
    public class Main {
        public Main() {
            run();
        public void run(){
         frame();
        public JFrame frame() {
            JTabbedPane tab = new JTabbedPane();
            final  Three t = new Three();
            JFrame frame = new JFrame();
            JPanel panel = new JPanel();
            tab.addTab("two",new Two());
            tab.addTab("three", new Three());
            tab.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                      t.setText(); // should call setText() in class Three.
            frame.add(panel);
            frame.add(tab);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(800,400);
             frame.setVisible(true);
             frame.pack();
            return frame;
        public static void main(String[] args) {
             java.awt.EventQueue.invokeLater(new Runnable() {
                         public void run(){
           new Main();
    }class Two. Does nothing more then holding an empty tab
    package test;
    import javax.swing.*;
    public class Two extends JPanel{
    public Two(){
    emptyPane();
      public void emptyPane () {
      JLabel  label = new JLabel("Just an empty JTabbedPane");
      add(label);
      }class Three
    package test;
    import javax.swing.*;
    public class Three extends JPanel{ 
             JTextField text;
        public Three() {
            text();
        public void setText() {
            text.setText("Hello"); // this piece of code i want to insert in my JTextField
            validate();                // when i push the JTabbedPanes.
            repaint();
            updateUI();
        public JTextField text(){
             JToolBar bar = new JToolBar();
            text = new JTextField("",20);
            bar.add(text);
            add(bar);
            return text;
    }

  • Saving the content of JTable into a ascii file?

    Suppose I have a JTable with certain cols and rows, is there an easy way to retrieve the table contents and save them into a ascii file on disk?
    Thanks for your help.
    helen

    If colCount or rowCount is quite big, the "for loop" will spend some time to get the table content. Is there other way (not doing "for loops") to get the contents of JTable?
    Thanks,
    Helen
    TableModel model = mytable.getModel()
    PrintWriter writer = new
    PrintWriter(BufferedWriter(new
    FileWriter("test.dat")));
    int colCount = col < model.getColumnCount();
    int rowCount = model.getRowCount();
    for (int row=0; row < rowCount; row++)
    for (int col=0; col < colCount; col++)
    Object value = model.getValueAt(row, col);
    if (value != null)
    ll) writer.print(value.toString());
    if (col < rowCount - 1) writer.print("\t");
    writer.println();
    writer.close();What's so difficult with this, that the question pops
    up every week ?
    Thomas

  • How to select more than one row in a JTable swing adf adf?

    how to select more than one row in a JTable swing adf adf?

    // Allow selection to span one contiguous set of rows, visible columns, or block of cells
    table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    // Allow multiple selections of rows, visible columns, or cell blocks
    table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

  • Generate reports and sub-reports based on JTable Swing.

    Hello everybody...
    Anyone know like to generate report and subreport dinamicaly using the tool jasper?
    The report will be based on a JTable Swing.
    Java Swing.

    As far as your target platform is supported by Crystal Reports, use it via free API at http://www.must.de/Jareport.htm

  • Copy the contents of Jtabl with line breaks to Excel

    Hi every one,
    In my stand alone application,I am copying the contents of Jtable i.e contents having the line breaks(\n).
    While copying and pasting the contents to Jtable,instead of linebreaks, a square symbol is appearing in the excel along with the line break.line break functionality is happening,but the additional symbol(empty square box) is appearing.
    here is my code:
    S = (String) "\""+mProcessQuestionTestItemTable.getValueAt(rowsselected, colsselected[j])+"\""; S=S.replace("\r\n", "\n").replace("\n", "\r\n");
    stringbuffered.append(S);can anyone help me in this?
    thank you!!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Hi,
    I want to copy the contents of Jtable(contents having Line breaks(\n)) and pasting to Excel.
    While pasting the contents to Excel, a box is appearing in the excel.
    To remove the empty square box, i tried the sample code:
    originalstr =(String)"\""+ mProcessQuestionTestItemTable.getValueAt(rowsselected, colsselected[j])+"\"";
    originalstr=originalstr.replace("\r\n", "\n").replace("\n", "\r\n");
    strngBuffere.append(S);
    There will be no box,If i copy the contents of Jtable and pasting in notepad.
    the box is appearing in Excel only.
    can you suggest something to solve this..
    Thank you.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • I wish to clear content

    I wish to clear content from my mac book pro

    Hi Fensta,
    I apologize, I'm a bit unclear on the exact nature or scope of your question. If you mean that you are looking to free up additional disk space on your MacBook Pro, you may find the information in the following article helpful:
    OS X Yosemite: Increase disk space
    Regards,
    - Brenden

  • Clear content pane problems

    can anyone tell why can't I clear the content pane in the following code or a method to achieve this thing?
    thank you.
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package librabrymanagementf;
    import java.awt.event.ActionEvent;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import javax.swing.SwingUtilities;
    import java.io.*;
    import java.io.File;
    import java.lang.Object;
    * @author emi
    public class Main {
         * @param args the command line arguments
        public static void main(String[] args) {
                  // Creates a model of the system logic.
            libraryModel model = new libraryModel();
            // Creaties a view for the system logic.
            libraryView view = new libraryView();
            // Creates a controller that links the two.
            libraryController controller = new libraryController(model, view);
      class libraryModel{
       public void addToFile(String title, String author, String ID){
       try{   
        FileWriter fw= new FileWriter("file.txt",true);
        fw.write(title+"\t"+author+"\t"+ID);
        fw.write("\r\n");
        fw.close();}
        catch (IOException e)
                   System.err.println ("Unable to write to file");
                   System.exit(-1);
      class libraryView{
          libraryModel model= new libraryModel();
         JFrame frame = new JFrame("[=] JMenuBar [=]");
        JMenuItem addBook = new JMenuItem("Add Book");
        JMenuItem deleteBook = new JMenuItem("Delete Book");
        JMenu modifyBook = new JMenu("Modify Book");
        JMenuItem modifyByTitle = new JMenuItem("Modify by Title");
        JMenuItem modifyByAuthor = new JMenuItem("Modify by Author");
        JMenu searchBook = new JMenu("Search Book");
        JMenuItem searchByTitle = new JMenuItem("Search by Title");
        JMenuItem searchByAuthor = new JMenuItem("Search by Author");
        JMenuItem searchByID = new JMenuItem("Search by ID");
        JMenuItem bookListing = new JMenuItem("Book Listing");
        JMenuBar menuBar = new JMenuBar();
        JMenu menu = new JMenu("Options");
        JPanel panel;
        JPanel textPanel, panelForTextFields, completionPanel;
        JLabel titleLabel, authorLabel, IDLabel, bookTitleLabel, passLabel;
        JTextField bookTitleField, authorField, IDField;
        JButton loginButton;
    public libraryView(){
         createAndShowGUI();
    public void CreateMenuBar()
          menuBar.add(menu);
          menu.add(addBook);
          menu.add(deleteBook);
          modifyBook.add(modifyByTitle);
          modifyBook.add(modifyByAuthor);
          menu.add(modifyBook);
          searchBook.add(searchByTitle);
          searchBook.add(searchByAuthor);
          searchBook.add(searchByID);
          menu.add(searchBook);
          menu.add(bookListing);
          frame.setJMenuBar(menuBar);
       public void createAndShowGUI(){
          frame.setSize(400,400);
          frame.setVisible(true);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          CreateMenuBar();
       public void addBookForm(){
            JPanel panel = new JPanel();
            clear(panel);
            panel.setLayout(null);
            titleLabel = new JLabel("Add Book");
            titleLabel.setLocation(0,0);
            titleLabel.setSize(290, 30);
            titleLabel.setHorizontalAlignment(0);
            panel.add(titleLabel);
            // Creation of a Panel to contain the JLabels
            textPanel = new JPanel();
            textPanel.setLayout(null);
            textPanel.setLocation(10, 35);
            textPanel.setSize(70, 150);
            panel.add(textPanel);
            // Book title Label
            bookTitleLabel = new JLabel("Title");
            bookTitleLabel.setLocation(0, 0);
            bookTitleLabel.setSize(70, 40);
            bookTitleLabel.setHorizontalAlignment(4);
            textPanel.add(bookTitleLabel);
          // Book author Label
            authorLabel = new JLabel("Author");
            authorLabel.setLocation(0, 40);
            authorLabel.setSize(70, 40);
            authorLabel.setHorizontalAlignment(4);
            textPanel.add(authorLabel);
             // Book ID Label
            IDLabel = new JLabel("ID");
            IDLabel.setLocation(0, 80);
            IDLabel.setSize(70, 40);
            IDLabel.setHorizontalAlignment(4);
            textPanel.add(IDLabel);
             // TextFields Panel Container
            panelForTextFields = new JPanel();
            panelForTextFields.setLayout(null);
            panelForTextFields.setLocation(110, 47);
            panelForTextFields.setSize(200, 130);
            panel.add(panelForTextFields);
            // book title Textfield
            bookTitleField = new JTextField(8);
            bookTitleField.setLocation(0, 0);
            bookTitleField.setSize(200, 20);
            panelForTextFields.add(bookTitleField);
            // book author Textfield
            authorField = new JTextField(8);
            authorField.setLocation(0, 40);
            authorField.setSize(200, 20);
            panelForTextFields.add(authorField);
            //book id Textfield
            IDField = new JTextField(8);
            IDField.setLocation(0, 80);
            IDField.setSize(200,20);
            panelForTextFields.add(IDField);
             // Button for Submit
            loginButton = new JButton("Submit");
            loginButton.setLocation(170, 180);
            loginButton.setSize(80, 20);
            loginButton.addActionListener(new ActionListener() {
                 public void actionPerformed(ActionEvent e) {
                     String bookTitle = bookTitleField.getText().trim();
                     String bookAuthor = authorField.getText().trim();
                     String bookID = IDField.getText().trim();
                     int intBookID = Integer.parseInt(bookID);
                     model.addToFile(bookTitle, bookAuthor, bookID);
            panel.add(loginButton);
            panel.setOpaque(true);   
            frame.getContentPane().add(panel, BorderLayout.CENTER);
            frame.setVisible(true);
              clear(panel);
       public void deleteBookForm(){
            JPanel panel = new JPanel();
            panel.setLayout(null);
            titleLabel = new JLabel("Delete Book");
            titleLabel.setLocation(0,0);
            titleLabel.setSize(290, 30);
            titleLabel.setHorizontalAlignment(0);
            panel.add(titleLabel);
             panel.setOpaque(true);   
             frame.getContentPane().add(panel, BorderLayout.CENTER);
            frame.setVisible(true);
        clear(panel);
       public void clear(JPanel panel){
           panel.removeAll();
           panel.validate();
        public void MenuActionListeners(ActionListener al) {
            addBook.setActionCommand("addBook");
            addBook.addActionListener(al);
            deleteBook.setActionCommand("deleteBook");
            deleteBook.addActionListener(al);
            modifyByTitle.setActionCommand("modifyByTitle");
            modifyByTitle.addActionListener(al);
            modifyByAuthor.setActionCommand("modifyByAuthor");
            modifyByAuthor.addActionListener(al);
            searchByTitle.setActionCommand("searchByTitle");
            searchByTitle.addActionListener(al);
            searchByAuthor.setActionCommand("searchByAuthor");
            searchByAuthor.addActionListener(al);
            searchByID.setActionCommand("searchByID");
            searchByID.addActionListener(al);
            bookListing.setActionCommand("bookListing");
            bookListing.addActionListener(al);
    class libraryController implements ActionListener{
         libraryModel model;
         libraryView view;
       public libraryController (libraryModel model, libraryView view) {
            this.model = model;
            this.view  = view;
          //  this.view.init_view();
            view.MenuActionListeners(this);
         //   view.addBookListeners(this);
       public void actionPerformed(ActionEvent ae)
        String action_com = ae.getActionCommand();
            if (action_com.equals("addBook")){
            // view.clear();
             view.addBookForm();
            else if (action_com.equals("deleteBook")){
          //  view.clear();
            view.deleteBookForm();
            System.out.println("kk");
            else if (action_com.equals("modifyByTitle")){
                 System.out.println(action_com);
            else if (action_com.equals("modifyByAuthor")){
                 System.out.println(action_com);
            else if (action_com.equals("searchByTitle")){
                 System.out.println(action_com);
            else if (action_com.equals("searchByAuthor")){
                 System.out.println(action_com);
            else if (action_com.equals("searchByID")){
                 System.out.println(action_com);
            else if (action_com.equals("bookListing")){
                 System.out.println(action_com);
        Thanks!

    Please pare down your code to a manageable amount. You don't need 3/4 of that code to demonstrate your problem, so why should you ask us to read it??

  • Clearing contents of a field when updating using an XML document.

    When trying to update a document using XML and the DI API, how can you clear the contents of a field in the document? This in particularly is a nvarchar field.

    >
    Michaela Pfeifer wrote:
    > Hi,
    >
    > we are using the XIF-Adapter to receive business partners from a third party system. The third party system send the data in xml via http.
    >
    > My question is now. Is there any possibility to do a mapping of the data before processing. As i understand I can use the LSMW to do the mapping when receiving iDoc-Files. Is that also possible for XML?
    >
    > Thanks
    > Michaela
    Hi Michael,
    I have to migrate third party data in XML format, pls provide me the configuration guide regarding that.
    Thanks a lot.
    #shobhit(DOT)techy(AT)(gmail).com

  • Setting alignment of cell content in jtable??

    hi,
    does anybody know how i can set the content of my jTable cells to the center of each cell. thanx, mischa.

    Did you search the forum???
    Using keywords "+jtable +center" would be a good place to start.

  • Problem in Printing jtable swing component using dot martix Epson printer

    Hello,
         I am devoloping desktop aplication using swing.In which i want to prit jtable on paper using dot matrix printer.
    It works well if i am not chnging the font.But if i changed the font (to my local language or any any other language)
    the printing text in table gets Blur (Characters in the text get ovewrites to each other and it become hard to recognize).
    Please help me in this problem.I am trying this from more than two days but not yet found the solution.
    Thank you,
    Dattatray

    Joerg22 wrote:
    Windows allows to change the keyboard to Hindi, but not to Marathi.
    But I wonder why you are changing the focus. The problem arose when you were setting a particular font. So the first question is: Can you do without that font? Meaning: are the Devanagari characters an option?No Devanagari characters are not option.I have to use Marathi language in my application for displaying to the user and taking value from user.See perblem come into picture when i am using setFont method.i did one expriment using characters 0900-097F.For one jtext field i have set text as "\u0937\u0937\0937".In gui i saw the corresponding marathi characters for it (here i did not used any set font method).Also after printuing that on paper i saw marathi text.As i mentioned in previous post i was not able to use "\u0937\u0937\0937" this in table.It might be some mistake in string formation.But i am sure it will work.Only need to check how to form string.
    In this case Only problem is that how to take input from user.As user will not gonna input "\u0900".He will laways enter abcd....I have to interprete them into unicode.Please correct me if i am thinking wrong.
    I will try by changing the language of keyboard to hindi and get back.
    Edited by: Ashtekar on Aug 9, 2010 2:13 AM
    Edited by: Ashtekar on Aug 9, 2010 2:13 AM

  • How can I change the content of JTable?

    Dear friends.
    I have an JTable. I create tablemodel for it and fill out it by data.
    In application at the run time I always need to change the content of whole table. For example I have a frame with JTree and JTable. When I click on the tree node I need to retrieve the data about this node in the JTable.
    Advice me please how can I do that and give an example please.
    Thank you.

    SOL I:
    There solution can be simple if u've written a model for it.
    If u are updating the data of the table by the setValueAt() method of the tableModel, in ur calling(mutating code), then just append a sinle line at the end of the method. U just need to fire a data change event corresponding to the event that has happened.
    void setValueAt(Object aValue, int rowIndex, int columnIndex) {
    - - - - - - - ur code
    //then last line can be
    fireTableDataChanged() ;
    OR
    fireTableCellUpdated(int row, int column);
    OR
    fireTableStructureChanged() ;
    depending uopn what has happened.
    SOL II:
    U may also try calling the method fireTableDataChanged(); from the place where the table data is getting mutated.
    like:
    ((AbstractTableModel) table.getModel()).fireTableDataChanged();
    [email protected]

  • Cleared content and settings in iPod touch, now computer says it has malfunctioned

    My ipod touch was working perfectly fine, but i was going to give it to a friend and so i decided to go into settings and clear the content and settings, so that it was a fresh ipod.  Well now it says connect to iTunes, but when i connect it to the computer it says that "USB device not recognized: the Device has malfunctioned and cannot be recognized" something like that.  And then it says it failed to install drivers and disconnects.  I do not know what is wrong and why it wont connect to my computer and iTunes.
    I need some help.

    Yes.  So try the following to et iTunes to see the iPod;
    - Place the iPod in recovery mode. See:
    iPhone and iPod touch: Unable to update or restore
    - Place the iPod in DFU mode.
    How to put iPod touch / iPhone into DFU mode « Karthik's scribblings

  • Time taken to clear content and data

    I have just cleared the content and data from my 64G Ipad1, and it has been showing the Apple icon with progress bar (with no progress at all) for the past 3 hours.  May I enquire how long does it usually take??
    THe ipad does not respond at all now and it worries me.  Is it normal??
    Thanks in advance for the inputs.

    It shouldn't take but a minute or two.
    You need to restore the device.
    iTunes: Backing up, updating, and restoring your iPhone, iPad, or iPod touch software

  • How to clear contents of a file

    Hello,
    I have a file which has some  characters written into it, I want to clear the file how can I do this?
    Say I have word called "LabVIEW" , I need to clear this word and final result should be empty file.
    or I need to replace the contents by writing "NI" into the file, but when I do this I still find other characters from LabVIEW word.
    Thanks in advance
    Solved!
    Go to Solution.

    ab
    Attachments:
    clear.png ‏2 KB

Maybe you are looking for