Search code examples
javaswingjtablejtextarea

How do I store and display values to be displayed in a JTextBox or JTable?


I have to store the variables: itemName, origPrice, salesPrice, and department and then display all the records in a JTextBox or JTable. Whatever displays the values has to be able to be added to a container, which has a getContentPane();

I have no idea how to store the variables. Does java come with a database when you install a JDK?

Also, the variables are stored in one action listener and the display values button has a different action listener.

    //Calculate action listener
    buttonCalc.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {

        itemName = fieldItem.getText();            
        originalPrice = Double.parseDouble(fieldOrigPrice.getText());
        discount = Double.parseDouble(fieldDiscount.getText());            
        salesPrice = originalPrice - (originalPrice * discount);   

        //store these values 

         // sales price label
        JLabel label = new JLabel();        
         ...
        container.add( label );         

      }
    });

    //Display values action listener
     buttonDisplay.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
           /*Must use a JTextArea or JTable to display all the stored values for:
            * 
            * Item name 
                Department
                Original price
                Sale price 
            */
        }
    });

Edit: The user inputs an item name, department, original price, and a percentage discount. I have to display every itemName, department, originalPrice, and salesPrice in a JTextArea or JTable that the user has entered while the JFrame is open.


Solution

  • You don't need a database or any such entity for this since you're not worrying about data persisting after the program closes. What you need is a TableModel to hold your data such as a DefaultTableModel object if it's simple or a class that extends AbstractTableModel if you want a little more flexibility. When new data is entered, you add a new row to your TableModel and (if not a DefaultTableModel) call one of the fire data change methods.

    For more details, please check out How to use Tables.