JTable in a JDialog doesn't appear - java

I wanted to set a JTable of ArrayList content in a new JDialog. I debugged the code and the table model has its columns and rows set up, but JDialog doesn't show anything. I checked the similar questions and they all point that setVisible(true) should be being at the end. In my case, it already is. How can I show the JTable in that JDialog (including the data which comes from the ArrayList - that part should already be working), basically it's currently empty, there is no table at all.
public class Main {
public static void main(String[] args) {
MainWindow wnd = new MainWindow();
}
}
public class MainWindow extends JFrame implements ActionListener {
private List<Movie> movies = new ArrayList<Movie>();
// Създаване на променливи за отделните контроли
private JLabel label1;
private JTextField tf1;
private JLabel label2;
private JTextField tf2;
private JLabel label3;
private JTextField tf3;
private JLabel label4;
private JComboBox combo1;
private JLabel label5;
private JTextField tf5;
private JButton btn1;
private JButton btn2;
public MainWindow() {
setSize(500, 300);
// при натискане на Х на проореца, да се затвори приложението
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new GridLayout(0, 2, 10, 10));
// Добавяме инв. номер в контейнера
label1 = new JLabel("Инвертарен номер");
tf1 = new JTextField();
window.add(label1);
window.add(tf1);
// Добавяме заглавие в контейнера
label2 = new JLabel("Заглавие");
tf2 = new JTextField();
window.add(label2);
window.add(tf2);
// Добавяме режисьор в контейнера
label3 = new JLabel("Режисьор");
tf3 = new JTextField();
window.add(label3);
window.add(tf3);
// Добавяме жанр в контейнера
label4 = new JLabel("Жанр");
String[] items = { "Комедия", "Екшън", "Драма" };
combo1 = new JComboBox(items);
window.add(label4);
window.add(combo1);
// Добавяме година на излизане в контейнера
label5 = new JLabel("Година на излизане");
tf5 = new JTextField();
window.add(label5);
window.add(tf5);
// Добавяме бутоните в контейнера
btn1 = new JButton("Справка");
btn2 = new JButton("Добави");
window.add(btn1);
window.add(btn2);
// При кликването върху бутоните, добавя евент, който се хендълва по-долу
btn1.addActionListener(this);
btn2.addActionListener(this);
setVisible(true);
}
// Извиква се при натискане на бутон, регистриран с addActionListener(this)
public void actionPerformed(ActionEvent e) {
// Извиква се, когато се кликне на бутон `Справки`.
if (e.getSource() == btn1)
{
// Показване на диалогов прозорец
new Dialog(movies);
}
// Извиква се, когато се кликне на бутон `Добавяне`.
else if (e.getSource() == btn2)
{
// Запазване на въведените данни в динамичния масив `movies`.
String id = tf1.getText();
String title = tf2.getText();
String director = tf3.getText();
String genre = tf5.getText();
String year = combo1.getSelectedItem().toString();
System.out.println("Инвертарен номер: " + id);
System.out.println("Заглавие: " + title);
System.out.println("Режисьор: " + director);
System.out.println("Жанр: " + genre);
System.out.println("Година на излизане: " + year);
Movie movie = new Movie();
movie.setId(id);
movie.setTitle(title);
movie.setDirector(director);
movie.setGenre(genre);
movie.setYear(year);
movies.add(movie);
System.out.println("Успешно добавен!");
}
}
}
public class Movie {
private String id;
private String title;
private String director;
private String genre;
private String year;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
}
public class Dialog extends JDialog {
private JTable table1;
public Dialog(List<Movie> movies) {
setTitle("Справка");
setSize(500, 300);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
Container window = getContentPane();
window.setLayout(null);
String[] col = new String[] { "Инв. номер", "Заглавие", "Режисьор", "Жанр", "Година на излизане" };
DefaultTableModel tableModel = new DefaultTableModel(col, 0);
for (int i = 0; i < movies.size(); i++) {
String id = movies.get(i).getId();
String title = movies.get(i).getTitle();
String director = movies.get(i).getDirector();
String genre = movies.get(i).getGenre();
String year = movies.get(i).getYear();
Object[] data = { id, title, director, genre, year };
tableModel.addRow(data);
}
//TableModel tableModel = new DefaultTableModel(movies.toArray(new Object[][] {}), columns.toArray());
table1 = new JTable(tableModel);
window.add(table1);
setVisible(true);
}
}

Here are a few things that I would change in your code. (Only considering the part regarding your dialog)
window.setLayout(null); // (1)
Don't use null layout. Learn to use appropriate Layout Managers, as swing was designed to be used with in conjunction with these. In your case, you can simply keep the default layout used by the JDialog, as you only have the JTable displayed anyways.
window.add(table1); // (2)
JTables are best used in combination in a JScrollPane, as this will automatically display the table header without you having to worry about it. Also, consider the How to Use Tables section of the Oracle Swing tutorial for more information on JTable usage.
Also (3), Java Swing applications should be run on the Event Dispatch Thread (see Concurrency in Swing).
Container window = getContentPane();
In your case, there is no need to explicitly retrieve the content pane from the dialog. This is just unnecessary overhead which you should not worry about. Calling add() on the dialog is enough in this case to add the component without having to deal with the content pane.
I took the "Dialog" portion of your code, including a excerpt of your Movie class and created a small working example (while trying not to change too much of your original code):
import java.util.Arrays;
import java.util.List;
import javax.swing.JDialog;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> { // (3) - run on EDT
Test t = new Test();
List<Movie> movies = Arrays.asList(t.new Movie("Movie1", "Title1"), t.new Movie("Movie2", "Title2"));
MyDialog dialog = t.new MyDialog(movies);
});
}
public class MyDialog extends JDialog {
public MyDialog(List<Movie> movies) {
setTitle("Title");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
String[] col = new String[] { "ID", "Title" };
DefaultTableModel tableModel = new DefaultTableModel(col, 0);
for (int i = 0; i < movies.size(); i++) {
String id = movies.get(i).getId();
String title = movies.get(i).getTitle();
Object[] data = { id, title };
tableModel.addRow(data);
}
JTable table = new JTable(tableModel);
add(new JScrollPane(table)); // (2) - use a JScrollPane to display the table
pack(); // pack the dialog, components are sized according to their preferred size
setVisible(true);
}
}
class Movie {
private String id;
private String title;
public Movie(String id, String title) {
this.id = id;
this.title = title;
}
public String getId() {
return id;
}
public String getTitle() {
return title;
}
}
}
Result:
Considering these changes, you should be able to update your code to correctly display the JTable in your JDialog.
Sidenote:
I also don't really see a need here to extends JDialog. In your case, it would probably suffice to use a normal JDialog and simply add the JTable to it.

Related

How to I get the object's information and then display it all into a GUI frame?

I have a student class and I've implemented all my methods correctly. However, I do not know how to get the information out of the object to display them into the GUI, such as the image file and also the texts to be shown.
So, in the GUI Frame I have their name, title, group and demowhat as labels and then the imageFile to actually show the image from the link.
class PersonInfo
{
protected String name;
protected String title;
protected String imageFile;
public PersonInfo(String name, String title, String imageFile)
{
this.name = name;
this.title = title;
this.imageFile = imageFile;
}
public PersonInfo(PersonInfo pi)
{
this(pi.name, pi.title, pi.imageFile);
}
public String getName()
{ return name; }
public String getTitle()
{ return title; }
public String getImageFile()
{ return imageFile; }
public void SetInfo(String name, String title, String imageFile)
{
this.name = name;
this.title = title;
this.imageFile = imageFile;
}
#Override public String toString()
{
return String.format("name: %s%ntitle: %s%nimageFile:%s%n", name, title, imageFile);
}
}
class Student extends PersonInfo
{
private String group;
private String demoWhat;
public Student(String name, String title, String imageFile, String group, String demoWhat)
{
super(name, title, imageFile);
this.group = group;
this.demoWhat = demoWhat;
}
public Student(Student s)
{
super(s);
}
public String getGroup()
{
return group;
}
public String getDemoWhat()
{
return demoWhat;
}
public void SetInfo(String name, String title, String imageFile, String group, String demoWhat)
{
super.SetInfo(name, title, imageFile);
this.group = group;
this.demoWhat = demoWhat;
}
#Override
public String toString()
{
return String.format ("%s" + "group: %s%n" + "demoWhat: %s%n", super.toString (), group, demoWhat);
}
}
class GUI2 extends JFrame
{
private JLabel label1;
private final JLabel image2;
public GUI2()
{
super("Welcome to 121 Demo System");
setLayout( new FlowLayout());
JButton plainJButton = new JButton("Refresh button to get the next student");
add(plainJButton);
ImageIcon image = new ImageIcon(getClass().getResource("images/xx.png"));
Image imageSIM = image.getImage();
Image imageSIMResized = imageSIM.getScaledInstance(260, 180, DO_NOTHING_ON_CLOSE);
image = new ImageIcon(imageSIMResized);
image2 = new JLabel(image);
add(image2);
ButtonHandler handler1 = new ButtonHandler();
plainJButton.addActionListener(handler1);
}
class ButtonHandler implements ActionListener //call student here
{
#Override
public void actionPerformed(ActionEvent event)
{
GUI3 gui3 = new GUI3();
setLayout( new FlowLayout());
gui3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui3.setSize(450,400);
gui3.setVisible(true);
**//I WANT THE GUI TO POP UP WITH THE NAME, TITLE, IMAGEFILE, GROUP AND DEMOWHAT**
Student student1 = new Student("name", "full time student","images/xxx.JPG", "I am from group 12", "I wish to demo A1");
add(label1);
}
}
}
class GUI3 extends JFrame //firststudent
{
private final JLabel image3;
public GUI3()
{
super("Let us welcome xxx");
JButton plainJButton = new JButton("OK");
add(plainJButton);
//ImageIcon image = new ImageIcon(getClass().getResource("images/xxx.JPG"));
//Image imagexxx= image.getImage();
//Image xxxResized = imagexxx.getScaledInstance(210, 280, DO_NOTHING_ON_CLOSE);
//image = new ImageIcon(xxxResized);
//image3 = new JLabel(image);
//add(image3);
ButtonHandler handler2 = new ButtonHandler();
plainJButton.addActionListener(handler2);
}
}
I tried making the student object in the ButtonHandler class, but then I don't know what to do from here.
Create a JPanel that renders your student. Here is a small example, based on your student class:
class StudentPanel extends JPanel {
JTextField tfGroup;
public StudentPanel() {
add(new JLabel("Group"));
tfGroup = new JTextField();
add(tfGroup);
}
public void setStudent(Student student) {
tfGroup.setText(student.getGroup());
}
}
You will want to add more fields and look at the sizing and arrangement of fields and labels. Maybe your application needs more than one way to render a student (short, full, list).
Once you have such a view, use it like so:
public static void main(String[] args) {
Student student = ... // populate the data you want to show somehow
JFrame f = new JFrame();
StudentPanel panel = new StudentPanel();
panel.setStudent(student);
f.add(panel);
f.pack();
f.setVisible(true);
}

How do I add an ActionListener to a JCheckBox?

Problem
So my program takes in a .csv file and loads the data and displays it. When data is loaded in, it creates a new JCheckBox for every column header there is in the data. How do I add an ActionListener such that when the user ticks/unticks any of the boxes, it should do a certain function?
When data is loaded in, it updates the JPanel by the code:
public void updateChecklistPanel(){
checklistPanel.removeAll();
checklistPanel.setLayout(new GridLayout(currentData.getColumnNames().length, 1, 10, 0));
for (String columnName : currentData.getColumnNames()){
JCheckBox checkBox = new JCheckBox();
checkBox.setText(columnName);
checklistPanel.add(checkBox);
}
checklistPanel.revalidate();
checklistPanel.repaint();
}
I also have the following at the bottom:
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == newDataFrameItem){
newFile();
System.out.println("New DataFrame Loaded in");
}
if (e.getSource() == loadDataFrameItem){
loadFile();
System.out.println(".csv Data loaded into DataFrame.");
}
if (e.getSource() == saveDataFrameItem){
System.out.println("Saved the data to a .csv file");
}
}
What I'm trying to do is that when a checkbox is unticked, it should hide a column in the JTable and when ticked, it should redisplay the column.
Current Solution
The solution that I have come up with is to make a variable allColumnHeaders that is an ArrayList of Strings. I then also have a variable shownColumnHeaders that is an ArrayList of Booleans. When the user wants to show/hide a column, the showColumn(String columnName) and hideColumn(String columnName) function finds the index of the column Name in allColumnHeaders and sets the Boolean value of the index in shownColumnHeaders to either true/false.
It the proceeds to create a new table model where the columns are only added if the Boolean value for that column is true. It will then set the model for the table to the new table model.
The code for the following is show below:
import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class MRE extends JPanel {
private static JTable table;
private static ArrayList<String> allColumnHeaders = new ArrayList<>();
private static ArrayList<Boolean> shownColumnHeaders = new ArrayList<>();
private static void createAndShowGUI()
{
table = new JTable(5, 7);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
JPanel buttons = new JPanel( new GridLayout(0, 1) );
for (int i = 0; i < table.getColumnCount(); i++) {
String column = table.getColumnName(i);
allColumnHeaders.add(column);
JCheckBox checkBox = new JCheckBox(column);
checkBox.addActionListener(event -> {
JCheckBox cb = (JCheckBox) event.getSource();
if (cb.isSelected()) {
System.out.println(checkBox.getText() + " is now being displayed");
showColumn(checkBox.getText());
} else {
System.out.println(checkBox.getText() + " is now being hidden");
hideColumn(checkBox.getText());
}
table.setModel(createTableModel());
});
checkBox.setSelected( true );
buttons.add( checkBox );
shownColumnHeaders.add(true);
}
JPanel wrapper = new JPanel();
wrapper.add( buttons );
JFrame frame = new JFrame("MRE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(wrapper, BorderLayout.LINE_END);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static DefaultTableModel createTableModel(){
DefaultTableModel tableModel = new DefaultTableModel(0, 0);
String[] columnValues = new String[1];
for (int i = 0; i < shownColumnHeaders.size(); i++){
if (shownColumnHeaders.get(i)){
tableModel.addColumn(allColumnHeaders.get(i), columnValues);
}
}
return tableModel;
}
public static void showColumn(String columnName){
for (int i = 0; i < allColumnHeaders.size(); i++) {
if (allColumnHeaders.get(i).equals(columnName)){
shownColumnHeaders.set(i, true);
}
}
}
public static void hideColumn(String columnName){
for (int i = 0; i < allColumnHeaders.size(); i++) {
if (allColumnHeaders.get(i).equals(columnName)){
shownColumnHeaders.set(i, false);
}
}
}
public static void main(String[] args) throws Exception
{
SwingUtilities.invokeLater( () -> createAndShowGUI() );
}
}
Introduction
It took me a while, but I came up with the following JTable GUI. Here's the starting display.
Here's the GUI after I remove the item description.
Here's the GUI after I remove the item price.
Here's the GUI after I add the columns back.
Explanation
I created an Item class to hold one item.
I created an Inventory class to hold a List of Item instances and a String array of the column headers.
I created the JFrame and two JPanels. One JPanel holds the JTable and the other holds the JCheckBoxes. I used Swing layout managers to create the JPanels.
So far, so basic. Creating the JTable took a bit of effort. I wanted to display the item price as currency, but that wasn't important for this example GUI.
I created an ActionListener to add and remove columns from the JTable. I had to experiment a bit. The TableColumnModel addColumn method appends the column to the table.
I had to create a DisplayTableColumn class to hold a TableColumn and a boolean that tells me whether or not to display the TableColumn. I wound up removing all the columns from the JTable and adding all the columns back to the JTable so that I could maintain the column sequence. I probably ran 100 tests before I could get this code to work.
Code
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
public class JCheckBoxTableGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JCheckBoxTableGUI());
}
private final Inventory inventory;
private final InventoryTableModel tableModel;
private JFrame frame;
private JTable table;
public JCheckBoxTableGUI() {
this.tableModel = new InventoryTableModel();
this.inventory = new Inventory();
String[] columns = inventory.getTableHeader();
for (String column : columns) {
tableModel.addColumn(column);
}
List<Item> items = inventory.getInventory();
for (Item item : items) {
Object[] object = new Object[5];
object[0] = item.getItemNumber();
object[1] = item.getItemName();
object[2] = item.getItemDescription();
object[3] = item.getItemQuantity();
object[4] = item.getItemPrice();
tableModel.addRow(object);
}
}
#Override
public void run() {
frame = new JFrame("JCheckBox Table GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTablePanel(), BorderLayout.CENTER);
frame.add(createSelectionPanel(), BorderLayout.AFTER_LINE_ENDS);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createTablePanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
table = new JTable(tableModel);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.getColumnModel().getColumn(0).setPreferredWidth(100);
table.getColumnModel().getColumn(1).setPreferredWidth(150);
table.getColumnModel().getColumn(2).setPreferredWidth(150);
table.getColumnModel().getColumn(3).setPreferredWidth(100);
table.getColumnModel().getColumn(4).setPreferredWidth(100);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(new Dimension(620, 300));
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
private JPanel createSelectionPanel() {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JPanel innerPanel = new JPanel(new GridLayout(0, 1, 5, 5));
ColumnListener listener = new ColumnListener(this);
String[] columns = inventory.getTableHeader();
for (String column : columns) {
JCheckBox checkBox = new JCheckBox("Display " + column);
checkBox.addActionListener(listener);
checkBox.setActionCommand(column);
checkBox.setSelected(true);
innerPanel.add(checkBox);
}
panel.add(innerPanel);
return panel;
}
public JTable getTable() {
return table;
}
public JFrame getFrame() {
return frame;
}
public class ColumnListener implements ActionListener {
private final JCheckBoxTableGUI frame;
private final List<DisplayTableColumn> displayColumns;
public ColumnListener(JCheckBoxTableGUI frame) {
this.frame = frame;
this.displayColumns = new ArrayList<>();
TableColumnModel tcm = frame.getTable().getColumnModel();
for (int index = 0; index < tcm.getColumnCount(); index++) {
TableColumn tc = tcm.getColumn(index);
displayColumns.add(new DisplayTableColumn(tc, true));
}
}
#Override
public void actionPerformed(ActionEvent event) {
JCheckBox checkBox = (JCheckBox) event.getSource();
String column = event.getActionCommand();
TableColumnModel tcm = frame.getTable().getColumnModel();
for (int index = 0; index < displayColumns.size(); index++) {
DisplayTableColumn dtc = displayColumns.get(index);
if (dtc.isShowTableColumn()) {
tcm.removeColumn(dtc.getTableColumn());
}
}
int columnIndex = getColumnIndex(column);
displayColumns.get(columnIndex).setShowTableColumn(
checkBox.isSelected());
for (int index = 0; index < displayColumns.size(); index++) {
DisplayTableColumn dtc = displayColumns.get(index);
if (dtc.isShowTableColumn()) {
tcm.addColumn(dtc.getTableColumn());
}
}
frame.getFrame().pack();
}
private int getColumnIndex(String column) {
for (int index = 0; index < displayColumns.size(); index++) {
DisplayTableColumn dtc = displayColumns.get(index);
if (column.equals(dtc.getTableColumn().getHeaderValue())) {
return index;
}
}
return -1;
}
}
public class DisplayTableColumn {
private boolean showTableColumn;
private final TableColumn tableColumn;
public DisplayTableColumn(TableColumn tableColumn, boolean showTableColumn) {
this.tableColumn = tableColumn;
this.showTableColumn = showTableColumn;
}
public boolean isShowTableColumn() {
return showTableColumn;
}
public void setShowTableColumn(boolean showTableColumn) {
this.showTableColumn = showTableColumn;
}
public TableColumn getTableColumn() {
return tableColumn;
}
}
public class InventoryTableModel extends DefaultTableModel {
private static final long serialVersionUID = 1L;
#Override
public Class<?> getColumnClass(int columnIndex) {
if (columnIndex <= 2) {
return String.class;
} else if (columnIndex == 3) {
return Integer.class;
} else {
return Integer.class;
}
}
}
public class Inventory {
private final List<Item> inventory;
private final String[] tableHeader;
public Inventory() {
this.tableHeader = new String[] { "Item Number", "Item Name",
"Item Description", "Item Quantity",
"Item Price" };
this.inventory = new ArrayList<>();
inventory.add(new Item("X101111", "Samsung Camera", " ", 20, 69.99));
inventory.add(new Item("X101112", "Samsung Monitor", " ", 10, 279.99));
inventory.add(new Item("X101113", "Samsung Smartphone", " ", 110, 599.99));
inventory.add(new Item("X101114", "Apple Watch", " ", 20, 1259.99));
inventory.add(new Item("X101115", "Sony Playstation 5", " ", 0, 399.99));
}
public String[] getTableHeader() {
return tableHeader;
}
public List<Item> getInventory() {
return inventory;
}
}
public class Item {
private int itemPrice;
private int itemQuantity;
private final String itemNumber;
private final String itemName;
private final String itemDescription;
public Item(String itemNumber, String itemName,
String itemDescription, int itemQuantity, double itemPrice) {
this.itemNumber = itemNumber;
this.itemName = itemName;
this.itemDescription = itemDescription;
this.itemQuantity = itemQuantity;
setItemPrice(itemPrice);
}
public int getItemPrice() {
return itemPrice;
}
public void setItemPrice(double itemPrice) {
this.itemPrice = (int) Math.round(itemPrice * 100.0);
}
public int getItemQuantity() {
return itemQuantity;
}
public void setItemQuantity(int itemQuantity) {
this.itemQuantity = itemQuantity;
}
public String getItemNumber() {
return itemNumber;
}
public String getItemName() {
return itemName;
}
public String getItemDescription() {
return itemDescription;
}
}
}
This only demonstrates how to create a basic MRE:
the csv file is irrelevant.
data in the model is irrelevant.
your loadFile, newFile and saveFile buttons are irrelevant.
the TableModel is irrelevant
Your question is about adding an ActionListener to dynamically created checkboxes based on the columns of the table.
So all you need is a table with some columns and the resulting checkboxes.
import java.awt.*;
import javax.swing.*;
public class MRE extends JPanel
{
private static void createAndShowGUI()
{
JTable table = new JTable(5, 7);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
JPanel buttons = new JPanel( new GridLayout(0, 1) );
for (int i = 0; i < table.getColumnCount(); i++)
{
String column = table.getColumnName(i);
JCheckBox checkBox = new JCheckBox("Display " + column);
checkBox.setSelected( true );
buttons.add( checkBox );
}
JPanel wrapper = new JPanel();
wrapper.add( buttons );
JFrame frame = new JFrame("MRE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(wrapper, BorderLayout.LINE_END);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args) throws Exception
{
SwingUtilities.invokeLater( () -> createAndShowGUI() );
}
}
If you can modify this to demonstrate how to use your "reusable class" to manage column visibility, then I will update the above code to use my reusable class with 4 additional lines of code.
Edit:
Suggested improvements to your code:
Make the code reusable and self contained
Don't use static methods
Don't change the data.
Your original question was:
How do I add an ActionListener to a JCheckBox?
So to do that you need a class that:
implements an ActionListener
is self contained to implement the functionality you require.
So the basic structure could be like the following:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SomeFunction implements ActionListener
{
private JTable table;
public SomeFunction(JTable table)
{
this.table = table;
}
#Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() instanceof AbstractButton)
{
String command = e.getActionCommand();
AbstractButton button = (AbstractButton)e.getSource();
if (button.isSelected())
doSelected( command );
else
doUnselected( command );
}
}
private void doSelected(String command)
{
System.out.println(command + " selected");
}
private void doUnselected(String command)
{
System.out.println(command + " unselected");
}
private static void createAndShowGUI()
{
JTable table = new JTable(5, 7);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
JPanel buttons = new JPanel( new GridLayout(0, 1) );
SomeFunction listener = new SomeFunction( table ); // added
// TableColumnManager listener = new TableColumnManager(table, false);
// ColumnListener listener = new ColumnListener();
for (int i = 0; i < table.getColumnCount(); i++)
{
String column = table.getColumnName(i);
JCheckBox checkBox = new JCheckBox("Display " + column);
checkBox.setSelected( true );
checkBox.setActionCommand( column ); // added
checkBox.addActionListener( listener ); // added
buttons.add( checkBox );
}
JPanel wrapper = new JPanel();
wrapper.add( buttons );
JFrame frame = new JFrame("MRE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(wrapper, BorderLayout.LINE_END);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args) throws Exception
{
SwingUtilities.invokeLater( () -> createAndShowGUI() );
}
}
Whatever your function does it only needs to know about the table it should act upon.
So try to restructure your code into a reusable class.
If you want to use Gilberts code, then you need to restructure the ColumnListener class into a separate reusable self contained class.
Finally you can also try my reusable class. Check out Table Column Manager for the class to download.
Whatever reusable class you decide to use, you will only need to change a single line of code from the above example (once your functionality is contained in a reusable class).
Note the static methods would not be part of the final class. They are only there so simplify testing and posting of an MRE in a single class file.
Hope this helps with future design considerations.

How to count data in jtable and show on the bottom of my gui

I have such an api. It shows JTable with 3 columns. I want that when I insert price and quantity to the jtable result will be seen on the bottom of my jframe. For example I insert data like on the picture and then get the result (2*5)+(2*5)=20. My result will be 20. And this result will be seen on the bottom of the gui window.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class Demo extends JFrame implements ActionListener{
private static void createAndShowUI() {
JFrame frame = new JFrame("Customer Main");
frame.getContentPane().add(new FuGui(), BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
class FuGui extends JPanel {
FuDisplayPanel displayPanel = new FuDisplayPanel();
FuButtonPanel buttonPanel = new FuButtonPanel();
FuInformationPanel informationPanel = new FuInformationPanel();
public FuGui() {
//JTextField textField;
//textField = new JTextField(20);
//textField.addActionListener(this);
JPanel bottomPanel = new JPanel();
bottomPanel.add(buttonPanel);
bottomPanel.add(Box.createHorizontalStrut(10));
bottomPanel.add(informationPanel);
setLayout(new BorderLayout());
add(displayPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.SOUTH);
buttonPanel.addInfoBtnAddActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = informationPanel.getName();
String price = informationPanel.getPrice();
String quantity = informationPanel.getQuantity();
displayPanel.addRow(name, price, quantity);
}
});
}
}
class FuDisplayPanel extends JPanel {
private String[] COLUMNS = {"Name", "Price", "Quantity"};
private DefaultTableModel model = new DefaultTableModel(COLUMNS, 1);
private JTable table = new JTable(model);
public FuDisplayPanel() {
setLayout(new BorderLayout());
add(new JScrollPane(table));
}
public void addRow(String name, String price, String quantity) {
Object[] row = new Object[3];
row[0] = name;
row[1] = price;
row[2] = quantity;
model.addRow(row);
}
}
class FuButtonPanel extends JPanel {
private JButton addInfoButton = new JButton("Add Information");
public FuButtonPanel() {
add(addInfoButton);
}
public void addInfoBtnAddActionListener(ActionListener listener) {
addInfoButton.addActionListener(listener);
}
}
class FuInformationPanel extends JPanel {
private JTextField nameField = new JTextField(10);
private JTextField priceField = new JTextField(10);
private JTextField quantityField = new JTextField(10);
public FuInformationPanel() {
add(new JLabel("Kwota:"));
add(nameField);
add(Box.createHorizontalStrut(10));
// add(new JLabel("Price:"));
// add(priceField);
//add(new JLabel("Quantity:"));
// add(quantityField);
}
public String getName() {
return nameField.getText();
}
public String getPrice() {
return priceField.getText();
}
public String getQuantity() {
return quantityField.getText();
}
}
update your addRow method in class FuDisplayPanel to return the total like this and
public int addRow(String name, String price, String quantity) {
Object[] row = new Object[3];
row[0] = name;
row[1] = price;
row[2] = quantity;
model.addRow(row);
int total = 0;
for (int count = 0; count < model.getRowCount(); count++){
price = model.getValueAt(count, 1).toString();
quantity = model.getValueAt(count, 2).toString();
if(price != null && !price.trim().equals("") && quantity != null && !quantity.trim().equals("")) {
total += Integer.parseInt(price) * Integer.parseInt(quantity);
}
}
return total;
}
public class FuButtonPanel extends JPanel {
private JButton addInfoButton = new JButton("Add Information");
public JLabel total = new JLabel("Total : ");
public FuButtonPanel() {
add(addInfoButton);
add(total);
}
public void addInfoBtnAddActionListener(ActionListener listener) {
addInfoButton.addActionListener(listener);
}
public void setTotal(int total) {
this.total.setText("Total : " + total);
}
}
and do this at FuGui.class
int total = displayPanel.addRow(name, price, quantity);
buttonPanel.setTotal(total);
Access the underlying data in the table via the model (Swing fundamental):
TableModel model = table.getModel();
Add a listener to the table model to do the automatic updates:
TableModelListener listener = new TableModelListener(tableChanged(TableModelEvent e) {
// update code here
}};
table.getModel().addTableModelListener(listener);

How can I read a String array index from a JComboBox into a JLabel?

I have a ComboBox holding a String[]'s values. I have several other String[]'s holding numbers. I want the user to be able to select a item from the ComboBox(holding my String[] names) and according to which one they pick, I want that index associated with one of my other arrays to be printed out in a JLabel for display. Here's what I have so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class NewBuild extends JFrame
{
private static final int WIDTH = 900;
private static final int HEIGHT = 350;
//Create array constants
private static final String[] WARRIOR = {"7","6","6","5","15","11","5","5","5"};
private static final String[] KNIGHT = {"12","6","7","4","11","8","9","3","6"};
private static final String[] SWORDSMAN = {"4","8","4","6","9","16","6","7","5"};
private static final String[] BANDIT = {"9","7","11","2","9","14","3","1","8"};
private static final String[] CLERIC = {"10","3","8","10","11","5","4","4","12"};
private static final String[] SORCERER = {"5","6","5","12","3","7","8","14","4"};
private static final String[] EXPLORER = {"7","6","9","7","6","6","12","5","5"};
private static final String[] DEPRIVED = {"6","6","6","6","6","6","6","6","6"};
private static final String[] CLASS_NAMES = {" ", "Warrior", "Knight", "SwordsMan", "Bandit", "Cleric", "Sorcerer", "Explorer", "Deprived"};
private int num;
private int count = 0;
private String classes;
Container newBuildWindow = getContentPane();
private JLabel lblBuildName, lblStartingClass, lblDisplayStartingStats;
private JTextField txtBuildName;
private JComboBox cStartingClasses;
public NewBuild()
{
GUI();
}//End of Constructor
public void GUI()
{
this.setSize(WIDTH, HEIGHT);
newBuildWindow.setBackground(Color.DARK_GRAY);
setTitle("New Build");
setLayout(new GridLayout(5,2));
setVisible(true);
// setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
JPanel panel1 = new JPanel(new GridLayout());
JPanel panel2 = new JPanel(new GridLayout(2,3));
lblBuildName = new JLabel("Build Name");
lblBuildName.setForeground(Color.YELLOW);
panel1.setBackground(Color.DARK_GRAY);
panel1.add(lblBuildName);
txtBuildName = new JTextField(15);
txtBuildName.setBackground(Color.LIGHT_GRAY);
panel1.add(txtBuildName);
lblStartingClass = new JLabel("Pick a starting class:");
lblStartingClass.setForeground(Color.YELLOW);
lblDisplayStartingStats = new JLabel("Default");
lblDisplayStartingStats.setForeground(Color.YELLOW);
cStartingClasses = new JComboBox(CLASS_NAMES);
cStartingClasses.addItemListener(new itemChangeListener());
panel2.setBackground(Color.DARK_GRAY);
panel2.add(lblStartingClass);
panel2.add(cStartingClasses);
panel2.add(lblDisplayStartingStats);
//add panels to pane
newBuildWindow.add(panel1);
newBuildWindow.add(panel2);
// pack();
}//End of GUI method
class itemChangeListener implements ItemListener
{
#Override
public void itemStateChanged(ItemEvent e)
{
if(e.getStateChange() == ItemEvent.SELECTED)
{
}
}
}
}//End of class NewBuild
Any help would be very much appreciated...Please don't just post a solution, I want to understand the code not copy it.
First, create a "wrapper" class which can bind the String values to a particular name (before anyone rushes at me says you can use a Map of some kind, you could, but this "carries" the associated information within a neat package)
public class ClassType {
private String description;
private String[] values;
public ClassType(String description, String[] values) {
this.description = description;
this.values = values;
}
public String[] getValues() {
return values;
}
#Override
public String toString() {
return description;
}
}
Build an array of these ClassTypes and give this to the JComboBox
ClassType[] types = new ClassType[]{
new ClassType("Warrior", WARRIOR),
new ClassType("Knight", KNIGHT),
new ClassType("Swordsman", SWORDSMAN),
new ClassType("Bandit", BANDIT),
new ClassType("Cleric", CLERIC),
new ClassType("Socerer", SORCERER),
new ClassType("Explorer", EXPLORER),
new ClassType("Deprived", DEPRIVED)
};
cStartingClasses = new JComboBox(types);
And when the ItemListener is notified, extract the values from the selected item...
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
ClassType classType = (ClassType) ((JComboBox)e.getSource()).getSelectedItem();
if (classType != null) {
String values[] = classType.getValues();
}
}
}
You can get the index and item as:
public void itemStateChanged(ItemEvent e)
{
if(e.getStateChange() == ItemEvent.SELECTED)
{
int index = cStartingClasses.getSelectedIndex();
String item = String.valueOf(cStartingClasses.getSelectedItem());
}
}
Here cStartingClasses is JcomboBox.

Java: Copying data from dialog box text field to JTable

This project requires that a user inputs data into text fields on a dialog box accessed from a menu bar and places the data from the text fields into a JTable. The problem is that once the user clicks okay on the dialog box after putting the information into the text field, the dialog box is no longer visible, but nothing appears in the JTable. The JTable headers are there, but the info just submitted is not.
It is a camping registration program, and all of the classes compile okay. I am only working on taking information from an RV reservation first, but will eventually do the same for a tent reservation. Here are the classes that correspond to an RV check in. There is an RV constructor that has parameters (String (name), String (check in day), int (days staying), String (leave day), int (site number), int (power needed)).
First the dialog box class:
package campingPrj;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DialogCheckInRv extends javax.swing.JDialog implements ActionListener {
private static final long serialVersionUID = 1L;
private javax.swing.JTextField nameTxt;
private javax.swing.JTextField dateIn;
private javax.swing.JTextField stayingTxt;
private javax.swing.JTextField siteNumberTxt;
private javax.swing.JTextField checkOutDate;
private javax.swing.JTextField powerTxt;
private javax.swing.JButton okButton;
private javax.swing.JButton cancelButton;
private boolean cancel;
private boolean okay;
public DialogCheckInRv(java.awt.Frame parent) {
super(parent, true);
setupDialog();
setTitle("RV Check In");
}
private void setupDialog() {
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
nameTxt = new javax.swing.JTextField(27);
dateIn = new javax.swing.JTextField(25);
stayingTxt = new javax.swing.JTextField(25);
siteNumberTxt = new javax.swing.JTextField(27);
powerTxt = new javax.swing.JTextField(27);
okButton = new javax.swing.JButton("Ok");
okButton.addActionListener(this);
cancelButton = new javax.swing.JButton("Cancel");
cancelButton.addActionListener(this);
setLayout(new GridLayout(6, 1));
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("Name Reserving:"));
panel.add(nameTxt);
add(panel);
panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("Start Date (mm/dd/yy) :"));
panel.add(dateIn);
add(panel);
panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("Days Planning on Staying:"));
panel.add(stayingTxt);
add(panel);
panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("Requested Site Number:"));
panel.add(siteNumberTxt);
add(panel);
panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("Power Needed (in AMPs):"));
panel.add(powerTxt);
add(panel);
panel = new JPanel();
panel.add(okButton);
panel.add(cancelButton);
add(panel);
pack();
setLocationRelativeTo(null);
}
public void actionPerformed(java.awt.event.ActionEvent event) {
if (event.getSource() == okButton) {
okay = true;
cancel = false;
setVisible(false);
}
if (event.getSource() == cancelButton) {
okay = false;
cancel = true;
setVisible(false);
}
}
public boolean isOk() {
return okay;
}
public boolean isCancel() {
return cancel;
}
public String getName() {
return nameTxt.getText();
}
public String getDateIn() {
return dateIn.getText();
}
public String getDaysStaying() {
return stayingTxt.getText();
}
public String getCheckOutDate() {
return checkOutDate.getText();
}
public String getPower() {
return powerTxt.getText();
}
public String getSiteNumber() {
return siteNumberTxt.getText();
}
public void clear() {
nameTxt.setText(null);
dateIn.setText(null);
stayingTxt.setText(null);
dateIn.setText(null);
powerTxt.setText(null);
siteNumberTxt.setText(null);
}
}
The GUI with the table (where I'm guessing the problem is in the actionPerformed method):
package campingPrj;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class GUICampingReg extends javax.swing.JFrame implements ActionListener {
private JMenuItem openSerialFileItem = new JMenuItem("Open Serialized File");
private JMenuItem openTextFileItem = new JMenuItem("Open Text File");
private JMenuItem saveSerialFileItem = new JMenuItem("Save Serialized File");
private JMenuItem saveTextFileItem = new JMenuItem("Save Text File");
private JMenuItem exitItem = new JMenuItem("Exit");
private JMenuItem checkInTentItem = new JMenuItem("Check in tent");
private JMenuItem checkInRVItem = new JMenuItem("Check in RV");
private JMenuItem checkOutItem = new JMenuItem("Date Leaving");
private JTextField nameReservingTxt;
private JTextField dateInTxt;
private JTextField daysStayingTxt;
private JTextField checkOutOnTxt;
private JTextField siteNumberTxt;
private JTextField powerTxt;
private JFrame frame;
private JTable table;
private SiteModel model;
private JScrollPane scrollPane;
private DialogCheckInRv newRv;
public GUICampingReg() {
setupFrame();
newRv = new DialogCheckInRv(this);
model = new SiteModel();
table.setModel(model);
}
private void setupFrame() {
frame = new JFrame();
frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
frame.setTitle("Camping Registration Program");
scrollPane = new JScrollPane();
table = new JTable();
JMenuBar menubar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.add(openSerialFileItem);
fileMenu.add(openTextFileItem);
fileMenu.add(saveSerialFileItem);
fileMenu.add(saveTextFileItem);
fileMenu.add(exitItem);
JMenu checkInMenu = new JMenu("Check In");
checkInMenu.add(checkInRVItem);
checkInMenu.add(checkInTentItem);
JMenu checkOutMenu = new JMenu("Check Out");
checkOutMenu.add(checkOutItem);
menubar.add(fileMenu);
menubar.add(checkInMenu);
menubar.add(checkOutMenu);
openSerialFileItem.addActionListener(this);
openTextFileItem.addActionListener(this);
saveSerialFileItem.addActionListener(this);
saveTextFileItem.addActionListener(this);
exitItem.addActionListener(this);
checkInTentItem.addActionListener(this);
checkInRVItem.addActionListener(this);
checkOutItem.addActionListener(this);
frame.setJMenuBar(menubar);
scrollPane
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
table.setToolTipText("");
table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
table.getTableHeader().setReorderingAllowed(false);
table.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tableMouseClicked();
}
});
scrollPane.setViewportView(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void tableMouseClicked() {
// TODO Auto-generated method stub
}
public void actionPerformed(ActionEvent evt) {
Object pressed = evt.getSource();
if (pressed == exitItem) {
System.exit(0);
}
if (pressed == openSerialFileItem) {
}
if (pressed == openTextFileItem) {
}
if (pressed == saveSerialFileItem) {
}
if (pressed == saveTextFileItem) {
}
if (pressed == checkInTentItem) {
}
if (pressed == checkInRVItem) {
newRv.clear();
newRv.setVisible(true);
if (newRv.isOk()) {
String nameReserving = nameReservingTxt.getText();
String checkIn = dateInTxt.getText();
int daysStaying = Integer.parseInt(daysStayingTxt.getText());
String checkOutOn = checkOutOnTxt.getText();
int siteNumber = Integer.parseInt(siteNumberTxt.getText());
int power = Integer.parseInt(powerTxt.getText());
RV rv = new RV (nameReserving, checkIn, daysStaying, checkOutOn, siteNumber, power);
model.add(rv);
}
}
if (pressed == checkOutItem) {
}
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GUICampingReg();
}
});
}
}
The site model class:
package campingPrj;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
public class SiteModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private ArrayList<Site> listSites;
private String[] columnNames = { "Name Reserving", "Checked in Date",
"Days Staying", "Site #", "Tenters/RV Power Needed" };
public SiteModel() {
listSites = new ArrayList<Site>();
}
public String getColumnName(int col) {
return columnNames[col];
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return listSites.size();
}
public Object getValueAt(int row, int col) {
Object val = null;
switch (col) {
case 0:
val = listSites.get(row).getNameReserving();
break;
case 1:
val = listSites.get(row).getCheckIn();
break;
case 2:
val = listSites.get(row).getDaysStaying();
break;
case 3:
val = listSites.get(row).getSiteNumber();
break;
case 4:
val = listSites.get(row).getCheckOutOn();
break;
}
return val;
}
public Site get(int index) {
return listSites.get(index);
}
public int indexOf(Site s) {
return listSites.indexOf(s);
}
public void add(Site s) {
if (s != null) {
listSites.add(s);
fireTableRowsInserted(listSites.size() - 1, listSites.size() - 1);
}
}
public void add(int index, Site s) {
if (s != null) {
listSites.add(index, s);
fireTableRowsInserted(index, index);
}
}
public void remove(int index) {
listSites.remove(index);
fireTableRowsDeleted(index, index);
return;
}
public void remove(Site s) {
remove(indexOf(s));
}
public void saveAsSerialized(String filename) throws IOException {
FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(listSites);
os.close();
}
#SuppressWarnings("unchecked")
public void loadFromSerialized(String filename) throws IOException,
ClassNotFoundException {
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream is = new ObjectInputStream(fis);
listSites = (ArrayList<Site>) is.readObject();
is.close();
}
}
So, how do I get the information to show up in JTable?
Maybe I'm misinterpreting your code, but I don't see where you areextracting the information that the user enters into the dialog. For example here:
if (newRv.isOk()) {
String nameReserving = nameReservingTxt.getText();
String checkIn = dateInTxt.getText();
int daysStaying = Integer.parseInt(daysStayingTxt.getText());
String checkOutOn = checkOutOnTxt.getText();
int siteNumber = Integer.parseInt(siteNumberTxt.getText());
int power = Integer.parseInt(powerTxt.getText());
RV rv = new RV (nameReserving, checkIn, daysStaying, checkOutOn, siteNumber, power);
model.add(rv);
}
You appear to be extracting information from the fields held by the GUICampingReg, not by the newRv object. Shouldn't you be calling methods of newRv to extract the data needed to create your RV object?
for example,
if (newRv.isOk()) {
String nameReserving = newRv.getName();
String checkIn = newRv.getDateIn();
// .... etc
RV rv = new RV (nameReserving, checkIn, daysStaying, checkOutOn, siteNumber, power);
model.add(rv);
}

Categories