I'm trying to create a simple grocery list GUI using JTable, before I go to the problem here is my code:
package com.main;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.event.*;
public class Whatttt extends JFrame implements ActionListener {
JTable table;
JScrollPane scrollpane;
JButton addItem;
JTextField itemName, itemAmount, itemPrice;
DefaultTableModel model;
public Whatttt(){
super("List n\' Go");
setResizable(false);
setLayout(new FlowLayout());
itemName = new JTextField("Enter Item Name");
add(itemName);
itemAmount = new JTextField("Enter Item Amount");
add(itemAmount);
itemPrice = new JTextField("Enter Item Price");
add(itemPrice);
addItem = new JButton("Add Item");
add(addItem);
addItem.addActionListener(this);
String [] columnnames = {"Item name", "Item Amount", "Item Price","Total Price"};
String [] [] data = {{"test", "test", "test","test"}};
model = new DefaultTableModel(data, columnnames);
table = new JTable(model);
table.setPreferredScrollableViewportSize(new Dimension(450,500));
table.setFillsViewportHeight(true);
table.getColumnModel().getColumn(0).setPreferredWidth(300);
table.getColumnModel().getColumn(1).setPreferredWidth(100);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setPreferredWidth(100);
scrollpane =new JScrollPane(table);
add(scrollpane);
}
public static void main (String []args){
Whatttt mainpage = new Whatttt();
mainpage.setDefaultCloseOperation(EXIT_ON_CLOSE);
mainpage.setSize(600,800);
mainpage.setVisible(true);
mainpage.setResizable(false);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == addItem){
String item = itemName.getText();
String amount= itemAmount.getText();
String price = itemPrice.getText();
String totalPrice = itemPrice.getText();
model.insertRow(table.getRowCount(),new Object[]{item, amount, price, totalPrice});
}
}
}
The problem is I want to set a specific column to accept only 1 data type, for example the column "Item amount" will only accept int values, and the "price amount" will only accept double values from the user input.
also how do you get the values from from a column? for example I want to get the value from "Item amount" and "price amount", multiply it and add it to column "Total Price. I'm still trying to learn and this serves as a practice for me, any kind of help is much appreciated.