Solved

How do I display entered data in a JTable

Posted on 2009-04-03
3
459 Views
Last Modified: 2013-12-29
Hi, I need code-fixing in a small java program.

This will help me understand how to add objects into an array or vector and display it in a simple JTable.

The program displays entered data in a simple JTable.
I have 2 classes with incomplete code that has errors. I require a few lines of code-fixing to get the programming working correctly.

Code  has a Data class for retrieving data with setters and getters, and Demo class to run the program.

It has a name and income JTextField for input. Input and Report as action buttons.

Each time the input button is clicked the entered information is saved into an array of objects or vector for storage. After several inputs when the report button is clicked it should show the stored array or vector in a simple JTable for display.

public class Data{
 
        private String m_name;
        private double m_income;
        
        public Data(){
        }
        public Data(String name, double income){
            m_name = name;
            m_income = income;
        }       
        public String getName(){
            return m_name;
        }
        public void setName(String name){
            m_name = name;
        }
        public double getIncome(){
            return m_income;
        }
        public void setIncome(double income){
            m_income = income;
        }
    }
 
 
import javax.swing.*;
import java.awt.*;
import java.awt.event.*; 
 
public class Demo extends JFrame{
    private JTable table; 
    private Data tableData;
    private Data array[];
    private Data data[][];
    JTextField tfName, tfIncome;
 
    public Demo(){
        //create user entry fields
        tableData = new Data();
        JLabel lbName = new JLabel("Name:");
        JLabel lbIncome = new JLabel("Income:");        
        tfName = new JTextField("");
        tfIncome = new JTextField("");
        final JButton btInput = new JButton("Input");
        JButton btReport = new JButton("Report");
        JPanel p1 = new JPanel(new GridLayout(1,2));
        p1.add(lbName, BorderLayout.WEST); 
        p1.add(tfName, BorderLayout.EAST);
        JPanel p2 = new JPanel(new GridLayout(1,2));
        p2.add(lbIncome, BorderLayout.WEST); p2.add(tfIncome, BorderLayout.EAST);
        JPanel p3 = new JPanel(new GridLayout(1,2));
        p3.add(btInput, BorderLayout.WEST); p3.add(btReport, BorderLayout.EAST);
        add(p1, BorderLayout.NORTH); add(p2, BorderLayout.CENTER);
        add(p3, BorderLayout.SOUTH);
        //button actions
        btInput.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                doInput();
            }
        });
        btReport.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                doReport();
            }});        
    }
    
    public void doInput(){
         String strName = tfName.getText();
         String strIncome = tfIncome.getText();
         double dbIncome = (Double.parseDouble(strIncome));
         tableData = new Data(strName, dbIncome);
         array = new Data[4];
         for(int i = 0; i< array.length; i++){
         array[i] = new Data(tableData.getName(), tableData.getIncome());
         }
        //         for(int i = 0; i<array.length; i++){
        //             System.out.println(array[i].getName()+ " " + array[i].getIncome());
        //         }
    }
    public  void createArray()
    {
 
        data = new Data[10][];
 
        final int ROWS = 10;
        final int COLS = 1;
 
        data = new Data[ROWS][COLS];
        for (int row = 0; row<data.length; row++)
        {
            for (int col = 0; col< COLS; col++)
            {
        //                data[ROWS][COLS] = array;
            }
        }
    }
 
    public void doReport()
    {            
        tfName.setText("");
        tfIncome.setText("");   
        tfName.requestFocus();        
        String columnNames[] = {"FullName", "Income"};
        //        table = new JTable(multiArray, columnNames);
        JScrollPane  scrollPane = new JScrollPane(table);
        final JFrame frame = new JFrame();
        frame.add(scrollPane, BorderLayout.CENTER);      
        frame.setBounds(100,100,900,400);
        frame.setResizable(true);
        frame.setVisible(true);
    }  
 
    public static void main(String[] args){    
           
        Demo objDemo = new Demo();
        objDemo.setBounds(700,200,280,100);
        objDemo.setVisible(true);
        objDemo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Open in new window

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

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

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 26

Expert Comment

by:ksivananth
ID: 24058795
check this example, http://www.roseindia.net/java/example/java/swing/InsertRows.shtml

where it shows how to insert the row using table model. instead of insertRow, you can call addRow method for your case!
0
 
LVL 26

Accepted Solution

by:
ksivananth earned 500 total points
ID: 24058976
check this one,

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

public class TableAddRow extends JFrame{
    private JTable table;
    private Data tableData;
    private Data array[];
    private Data data[][];
    private Vector<Data> dataVector = new Vector<Data>() ;
    JTextField tfName, tfIncome;
    JDialog tableDialog ;
 
    public TableAddRow(){
        //create user entry fields
        tableData = new Data();
        JLabel lbName = new JLabel("Name:");
        JLabel lbIncome = new JLabel("Income:");        
        tfName = new JTextField("");
        tfIncome = new JTextField("");
        final JButton btInput = new JButton("Input");
        JButton btReport = new JButton("Report");
        JPanel p1 = new JPanel(new GridLayout(1,2));
        p1.add(lbName, BorderLayout.WEST);
        p1.add(tfName, BorderLayout.EAST);
        JPanel p2 = new JPanel(new GridLayout(1,2));
        p2.add(lbIncome, BorderLayout.WEST); p2.add(tfIncome, BorderLayout.EAST);
        JPanel p3 = new JPanel(new GridLayout(1,2));
        p3.add(btInput, BorderLayout.WEST); p3.add(btReport, BorderLayout.EAST);
        add(p1, BorderLayout.NORTH); add(p2, BorderLayout.CENTER);
        add(p3, BorderLayout.SOUTH);
        //button actions
        btInput.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                doInput();
            }
        });
        btReport.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                doReport();
            }});        

        Vector<String> colnames = new Vector<String>() ;
        colnames.add( "FullName" ) ;
        colnames.add( "Income" ) ;
        DefaultTableModel model = new DefaultTableModel( dataVector, colnames ){
              public Object getValueAt( int row, int col ){
                    Data data = ( Data )getDataVector().get( row ) ;
                    if( col == 0 ) return data.getName() ;
                    else return data.getIncome() ;
              }
        };
        table = new JTable( model );
        JScrollPane  scrollPane = new JScrollPane(table);
        tableDialog = new JDialog( this );
        tableDialog.add(scrollPane, BorderLayout.CENTER);      
        tableDialog.setBounds(100,100,900,400);
        tableDialog.setResizable(true);
    }
   
    public void doInput(){
         String strName = tfName.getText();
         String strIncome = tfIncome.getText();
         double dbIncome = (Double.parseDouble(strIncome));
         tableData = new Data(strName, dbIncome);
         dataVector.add( tableData ) ;
         array = new Data[4];
         for(int i = 0; i< array.length; i++){
         array[i] = new Data(tableData.getName(), tableData.getIncome());
         }
        //         for(int i = 0; i<array.length; i++){
        //             System.out.println(array[i].getName()+ " " + array[i].getIncome());
        //         }
    }
    public  void createArray()
    {
 
        data = new Data[10][];
 
        final int ROWS = 10;
        final int COLS = 1;
 
        data = new Data[ROWS][COLS];
        for (int row = 0; row<data.length; row++)
        {
            for (int col = 0; col< COLS; col++)
            {
        //                data[ROWS][COLS] = array;
            }
        }
    }
 
    public void doReport()
    {            
        tfName.setText("");
        tfIncome.setText("");  
        tfName.requestFocus();  
        ( ( DefaultTableModel )table.getModel() ).fireTableDataChanged() ;
        tableDialog.setVisible(true);
    }  
 
    public static void main(String[] args){    
           
          TableAddRow objDemo = new TableAddRow();
        objDemo.setBounds(700,200,280,100);
        objDemo.setVisible(true);
        objDemo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

class Data{
      
    private String m_name;
    private double m_income;
   
    public Data(){
    }
    public Data(String name, double income){
        m_name = name;
        m_income = income;
    }      
    public String getName(){
        return m_name;
    }
    public void setName(String name){
        m_name = name;
    }
    public double getIncome(){
        return m_income;
    }
    public void setIncome(double income){
        m_income = income;
    }
}
0
 

Author Closing Comment

by:tolgss
ID: 31566187
Thanks for your prompt solution. Really appreciate it.
0

Featured Post

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

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

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

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

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

Join & Ask a Question