Unable to open an other frame from button - java

I have created a button and when I click it I want to open another frame. The button was working before but now it won't open the frame.
First program:
// By: Qamar, Dimitri and Ehsan
// Date: 21/12/2017
// Description: This is the front page of the Address Book
import javax.swing.*;
import java.awt.event.*;
import java.awt. *;
import java.io.*;
public class AddressBook implements ActionListener // Create a new class Address Book
{
JFrame Start=new JFrame("Address Book"); // Set name of Frame
JButton Open; // Create a new button Open
{
Open=new JButton("OPEN"); // set name of button
Start.setSize(500,600); // set size of frame
Start.add(new JLabel(new ImageIcon("backgroundforlab.jpg"))); // add background picture
Start.setVisible(true); // make the frame visible
Start.setLayout(null);
Start.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
Start.getContentPane().add(Open); //add button to frame
Open.setBounds(100,385,295,88); // set size of button
Open.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
Start.dispose(); // When button is clicked close frame and open book222
Book c=new Book();
}
public static void main(String ag[])
{
AddressBook A=new AddressBook(); // Run AddressBook
}
}
Now, the frame I want to open:
import javax.swing.*;
import java.awt.event.*;
import java.awt. *;
import java.io.*;
import java.io.FileWriter; // Importing all necessary packages/extensions
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
// Created By: Qamar Irfan, Dimitri Kolechi and Ehsan Saleh
// Date: 21/12/2017
// Description: This is the main program of Address Book. You can Create, Delete, Save and import contacts to this book.
public class Book {
public static void main(String[] args){
// Making the layout of the frame and adding all buttons and labels
JFrame Start=new JFrame("Creating Contacts"); // Create frame
JTable table = new JTable(); // Create Table
FileWriter read; // Ceate new fileWriter
JButton Create;
JButton Quit; // Create new buttons
JButton Delete;
JButton Save;
JButton Import;
JButton Help;
JLabel name1 = new JLabel("Last Name");
JLabel name2= new JLabel ("First Name");
JLabel phone= new JLabel ("Phone Number"); // Create Labels
JLabel address= new JLabel ("Address");
JLabel pcode= new JLabel ("Postal Code");
JLabel eaddress= new JLabel ("Email Address");
JLabel note= new JLabel ("Note");
JTextField lastName = new JTextField();
JTextField firstName= new JTextField();
JTextField phoneNumber= new JTextField();
JTextField addressLocation= new JTextField(); // Create Text Fields
JTextField postalCode= new JTextField();
JTextField emailAddress= new JTextField();
JTextField noteMemo= new JTextField();
{
Create=new JButton("Create Contact");
Quit= new JButton ("Quit"); // set name of buttons
Delete= new JButton ("Delete a Contact");
Save= new JButton ("Save Contacts");
Import= new JButton ("Import Saved Contacts");
Help= new JButton ("Instructions");
Start.setSize(1215,600); // set size of frame
Start.setVisible(true); // make the frame visible
Start.setLayout(null);
Start.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
Start.getContentPane().add(Create);
Start.getContentPane().add(Quit); // add all buttons to frame
Start.getContentPane().add(Delete);
Start.getContentPane().add(Save);
Start.getContentPane().add(Import);
Start.getContentPane().add(Help);
Start.getContentPane().add(name1);
Start.getContentPane().add(name2);
Start.getContentPane().add(phone);
Start.getContentPane().add(address); // add all Labels
Start.getContentPane().add(pcode);
Start.getContentPane().add(eaddress);
Start.getContentPane().add(note);
Start.getContentPane().add(lastName);
Start.getContentPane().add(firstName);
Start.getContentPane().add(phoneNumber);
Start.getContentPane().add(addressLocation); // add all Text Field
Start.getContentPane().add(postalCode);
Start.getContentPane().add(emailAddress);
Start.getContentPane().add(noteMemo);
Help.setBounds(820,150,200,30);
Create.setBounds(700,20,200,30); // set size of buttons
Delete.setBounds(700,90,200,30);
Save.setBounds(950,90,200,30);
Import.setBounds(950,20,200,30);
Quit.setBounds(820,200,200,30);
name1.setBounds(40,11,100,100);
name2.setBounds(250,11,100,100);
phone.setBounds(460,11,100,100); // set location of all Labels
address.setBounds(40,75,100,100);
pcode.setBounds(250,75,100,100);
eaddress.setBounds(460,75,100,100);
note.setBounds(160,150,100,100);
lastName.setBounds(105,50,100,25);
firstName.setBounds(320,50,100,25);
phoneNumber.setBounds(550,50,100,25);
addressLocation.setBounds(105,114,100,25); // set location of all Text Fields
postalCode.setBounds(320,114,100,25);
emailAddress.setBounds(550,114,100,25);
noteMemo.setBounds(200,180,300,50);
// Creating The Table
Object[] columns = {"Last Name","First Name","Phone Number","Address","Postal Code","Email Address","Note"};
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columns); // making the table
table.setModel(model);
table.setBackground(Color.LIGHT_GRAY);
table.setForeground(Color.black);
Font font = new Font("",4,12); // setting the table up
table.setFont(font);
table.setRowHeight(30);
JScrollPane pane = new JScrollPane(table);
pane.setBounds(0, 275, 1200, 700); // setting size and location of table
Start.setLayout(null); // adding table to frame
Start.add(pane);
Object[] row = new Object[7];
// Setting the functions of all buttons
Quit.addActionListener(new ActionListener(){
#Override // setting the quit buttons function
public void actionPerformed(ActionEvent e) {
System.exit(0); // When Quit is clicked close frame
}
});
Help.addActionListener(new ActionListener(){
#Override // setting the Help buttons function
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Type the credentials in the fields, make sure to add '/' at end of every field. after typing, click create, make sure everytime create a contact to save it. once saved delete contact and then save another contact.","Instructions", JOptionPane.INFORMATION_MESSAGE);
// When Help is clicked open pop up box with instructions
}
});
Delete.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
int i = table.getSelectedRow(); // setting the delete buttons function
if(i >= 0){
model.removeRow(i); // delete the selected row
}
else{
System.out.println("Please select a Contact"); // If no row is selected than nothing will be deleted
}
}
});
Create.addActionListener(new ActionListener(){
#Override // setting the create buttons function
public void actionPerformed(ActionEvent e) {
row[0] = lastName.getText();
row[1] = firstName.getText();
row[2] = phoneNumber.getText(); // when create is presses get
row[3] = addressLocation.getText(); // the data from the textfields
row[4] = postalCode.getText();
row[5] = emailAddress.getText();
row[6] = noteMemo.getText();
model.addRow(row);
}
});
Save.addActionListener(new ActionListener(){
#Override // setting the Save button function
public void actionPerformed(ActionEvent e){
try{
File file = new File("records.txt");
// if the file records.txt does not exist
// then the program will create one itself
if(!file.exists()){
file.createNewFile();
}
FileWriter read = new FileWriter("records.txt", true); // create new FileWriter
BufferedWriter write1 = new BufferedWriter(read); // create new BufferedWriter
for(int i = 0; i < table.getRowCount(); i++){ // get the amount of rows in JTable
for(int j = 0; j < table.getColumnCount(); j++){
write1.write(table.getModel().getValueAt(i, j)+" "); // write all data from table in records.txt
}
write1.write("\r\n"); // add space between every contact
}
write1.close();
read.close();
JOptionPane.showMessageDialog(null, "All Contacts Saved"); // when contacts successfully transferred show pop up box
}catch(Exception ex){
ex.printStackTrace();
}
}
});
Import.addActionListener(new ActionListener(){
#Override // setting the Import button function
public void actionPerformed(ActionEvent e){
try {
BufferedReader write2 = new BufferedReader(new FileReader("records.txt")); // find the file records.txt
Object[] tableLines = write2.lines().toArray();
for(int i = 0; i < tableLines.length; i++) // add contacts to JTable
{
String line = tableLines[i].toString().trim();
String[] dataRow = line.split("/"); // every space means new column
model.addRow(dataRow);
}
} catch (Exception ex) {
}
}
});
}
}
}

Correct your book class make Book to extend JFrame and then reorganise your code as below.
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
// Importing all necessary packages/extensions
// Created By: Qamar Irfan, Dimitri Kolechi and Ehsan Saleh
// Date: 21/12/2017
// Description: This is the main program of Address Book. You can Create, Delete, Save and import contacts to this book.
public class Book extends JFrame {
// Making the layout of the frame and adding all buttons and labels
JTable table = new JTable(); // Create Table
DefaultTableModel model = new DefaultTableModel();
JTextField lastName = new JTextField();
JTextField firstName = new JTextField();
JTextField phoneNumber = new JTextField();
JTextField addressLocation = new JTextField(); // Create Text Fields
JTextField postalCode = new JTextField();
JTextField emailAddress = new JTextField();
JTextField noteMemo = new JTextField();
Object[] row = new Object[7];
public Book() {
super("Creating Contacts"); // Create frame
init();
}
public void init() {
JLabel name1 = new JLabel("Last Name");
JLabel name2 = new JLabel("First Name");
JLabel phone = new JLabel("Phone Number"); // Create Labels
JLabel address = new JLabel("Address");
JLabel pcode = new JLabel("Postal Code");
JLabel eaddress = new JLabel("Email Address");
JLabel note = new JLabel("Note");
JButton Create = new JButton("Create Contact");
JButton Quit = new JButton("Quit"); // set name of buttons
JButton Delete = new JButton("Delete a Contact");
JButton Save = new JButton("Save Contacts");
JButton Import = new JButton("Import Saved Contacts");
JButton Help = new JButton("Instructions");
setSize(1215, 600); // set size of frame
setVisible(true); // make the frame visible
setLayout(null);
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
getContentPane().add(Create);
getContentPane().add(Quit); // add all buttons to frame
getContentPane().add(Delete);
getContentPane().add(Save);
getContentPane().add(Import);
getContentPane().add(Help);
getContentPane().add(name1);
getContentPane().add(name2);
getContentPane().add(phone);
getContentPane().add(address); // add all Labels
getContentPane().add(pcode);
getContentPane().add(eaddress);
getContentPane().add(note);
getContentPane().add(lastName);
getContentPane().add(firstName);
getContentPane().add(phoneNumber);
getContentPane().add(addressLocation); // add all Text Field
getContentPane().add(postalCode);
getContentPane().add(emailAddress);
getContentPane().add(noteMemo);
Help.setBounds(820, 150, 200, 30);
Create.setBounds(700, 20, 200, 30); // set size of buttons
Delete.setBounds(700, 90, 200, 30);
Save.setBounds(950, 90, 200, 30);
Import.setBounds(950, 20, 200, 30);
Quit.setBounds(820, 200, 200, 30);
name1.setBounds(40, 11, 100, 100);
name2.setBounds(250, 11, 100, 100);
phone.setBounds(460, 11, 100, 100); // set location of all Labels
address.setBounds(40, 75, 100, 100);
pcode.setBounds(250, 75, 100, 100);
eaddress.setBounds(460, 75, 100, 100);
note.setBounds(160, 150, 100, 100);
lastName.setBounds(105, 50, 100, 25);
firstName.setBounds(320, 50, 100, 25);
phoneNumber.setBounds(550, 50, 100, 25);
addressLocation.setBounds(105, 114, 100, 25); // set location of all
// Text Fields
postalCode.setBounds(320, 114, 100, 25);
emailAddress.setBounds(550, 114, 100, 25);
noteMemo.setBounds(200, 180, 300, 50);
// Creating The Table
Object[] columns = { "Last Name", "First Name", "Phone Number",
"Address", "Postal Code", "Email Address", "Note" };
model.setColumnIdentifiers(columns); // making the table
table.setModel(model);
table.setBackground(Color.LIGHT_GRAY);
table.setForeground(Color.black);
Font font = new Font("", 4, 12); // setting the table up
table.setFont(font);
table.setRowHeight(30);
JScrollPane pane = new JScrollPane(table);
pane.setBounds(0, 275, 1200, 700); // setting size and location of
// table
setLayout(null); // adding table to frame
add(pane);
// Setting the functions of all buttons
Quit.addActionListener(new ActionListener() {
#Override
// setting the quit buttons function
public void actionPerformed(ActionEvent e) {
System.exit(0); // When Quit is clicked close frame
}
});
Help.addActionListener(new ActionListener() {
#Override
// setting the Help buttons function
public void actionPerformed(ActionEvent e) {
JOptionPane
.showMessageDialog(
null,
"Type the credentials in the fields, make sure to add '/' at end of every field. after typing, click create, make sure everytime create a contact to save it. once saved delete contact and then save another contact.",
"Instructions", JOptionPane.INFORMATION_MESSAGE);
// When Help is clicked open pop up box with instructions
}
});
Delete.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int i = table.getSelectedRow(); // setting the delete
// buttons function
if (i >= 0) {
model.removeRow(i); // delete the selected row
} else {
System.out.println("Please select a Contact"); // If no
// row
// is
// selected
// than
// nothing
// will
// be
// deleted
}
}
});
Create.addActionListener(new ActionListener() {
#Override
// setting the create buttons function
public void actionPerformed(ActionEvent e) {
row[0] = lastName.getText();
row[1] = firstName.getText();
row[2] = phoneNumber.getText(); // when create is presses
// get
row[3] = addressLocation.getText(); // the data from the
// textfields
row[4] = postalCode.getText();
row[5] = emailAddress.getText();
row[6] = noteMemo.getText();
model.addRow(row);
}
});
Save.addActionListener(new ActionListener() {
#Override
// setting the Save button function
public void actionPerformed(ActionEvent e) {
try {
File file = new File("records.txt");
// if the file records.txt does not exist
// then the program will create one itself
if (!file.exists()) {
file.createNewFile();
}
FileWriter read = new FileWriter("records.txt", true); // create
// new
// FileWriter
BufferedWriter write1 = new BufferedWriter(read); // create
// new
// BufferedWriter
for (int i = 0; i < table.getRowCount(); i++) { // get
// the
// amount
// of
// rows
// in
// JTable
for (int j = 0; j < table.getColumnCount(); j++) {
write1.write(table.getModel().getValueAt(i, j)
+ " "); // write all data from table in
// records.txt
}
write1.write("\r\n"); // add space between every
// contact
}
write1.close();
read.close();
JOptionPane.showMessageDialog(null, "All Contacts Saved"); // when
// contacts
// successfully
// transferred
// show
// pop
// up
// box
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
Import.addActionListener(new ActionListener() {
#Override
// setting the Import button function
public void actionPerformed(ActionEvent e) {
try {
BufferedReader write2 = new BufferedReader(new FileReader(
"records.txt")); // find the file // records.txt
Object[] tableLines = write2.lines().toArray();
for (int i = 0; i < tableLines.length; i++) // add //
// contacts //
// to JTable
{
String line = tableLines[i].toString().trim();
String[] dataRow = line.split("/"); // every space //
// means new //
// column
model.addRow(dataRow);
}
} catch (Exception ex) {
}
}
});
}
}
// END OF PROGRAM

Write after Book c = new Book();
c.setVisible(true);

Related

how do i make a button that sorts my list in an ascending order(java swing)?

I have created a an jtable in java swing which looks like the following
I have added 6 buttons and 3 of them work fine(add,update,delete). im not worried about random match button but i want "Sort By goals" button to sort out all the records entered by the highest number of goals. same goes for points. I have tried many times but i dont seem to be able to figure out.
Here is the code for my table arrays;
// create JFrame and JTable
JFrame frame = new JFrame();
JTable table = new JTable();
Container c = frame.getContentPane();
c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
c.add(table);
// create a table model and set a Column Identifiers to this model
Object[] columns = {"Team name", "Wins", "Losses", "Goals Difference","Points","Matches played"};
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columns);
// set the model to the table
table.setModel(model);
// Change A JTable Background Color, Font Size, Font Color, Row Height
table.setBackground(Color.LIGHT_GRAY);
table.setForeground(Color.black);
Font font = new Font("", 1, 22);
table.setFont(font);
table.setRowHeight(30);
// table.setVisible(true);
Here is my draft for the button;
btnSortPoints.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
Here is my delete button;
btnDelete.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// i = the index of the selected row
int i = table.getSelectedRow();
if(i >= 0){
// remove a row from jtable
model.removeRow(i);
}
else{
System.out.println("Delete Error");
}
}
});
Here is my entire code;
public class table{
public static void main(String[] args) {
// create JFrame and JTable
JFrame frame = new JFrame();
JTable table = new JTable();
Container c = frame.getContentPane();
c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
c.add(table);
// create a table model and set a Column Identifiers to this model
Object[] columns = {"Team name", "Wins", "Losses", "Goals Difference","Points","Matches played"};
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(columns);
// set the model to the table
table.setModel(model);
// Change A JTable Background Color, Font Size, Font Color, Row Height
table.setBackground(Color.LIGHT_GRAY);
table.setForeground(Color.black);
Font font = new Font("", 1, 22);
table.setFont(font);
table.setRowHeight(30);
// table.setVisible(true);
// create JTextFields
JTextField txtTeamName = new JTextField();
JTextField txtWins = new JTextField();
JTextField txtLosses = new JTextField();
JTextField txtGD = new JTextField();
JTextField txtPoints = new JTextField();
JTextField txtMatches = new JTextField();
JLabel lblTeamName = new JLabel("Team name");
JLabel lblWins = new JLabel("Wins");
JLabel lblLosses = new JLabel("Losses");
JLabel lblGD = new JLabel("Goal difference");
JLabel lblPoints = new JLabel("Points");
JLabel lblMatches = new JLabel("Matches");
// create JButtons
JButton btnAdd = new JButton("Add");
JButton btnDelete = new JButton("Delete");
JButton btnUpdate = new JButton("Update");
JButton btnSortPoints = new JButton("Sort by points");
JButton btnSortGoals = new JButton("Sort by goals");
JButton btnRandomMatch = new JButton("Add a random data");
txtTeamName.setBounds(1200, 230, 100, 25);
txtWins.setBounds(1200, 260, 100, 25);
txtLosses.setBounds(1200, 290, 100, 25);
txtGD.setBounds(1200, 320, 100, 25);
txtMatches.setBounds(1200,350,100,25);
txtPoints.setBounds(1200,380,100,25);
lblTeamName.setBounds(1100,230,100,25);
lblWins.setBounds(1100,260,100,25);
lblLosses.setBounds(1100,290,100,25);
lblGD.setBounds(1100,320,100,25);
lblMatches.setBounds(1100,350,100,25);
lblPoints.setBounds(1100,380,100,25);
btnAdd.setBounds(1150, 20, 200, 50);
btnUpdate.setBounds(1150, 80, 200, 50);
btnDelete.setBounds(1150, 140, 200, 50);
btnSortGoals.setBounds(920,20,200,50);
btnSortPoints.setBounds(920,80,200,50);
btnRandomMatch.setBounds(920,140,200,50);
// create JScrollPane
JScrollPane pane = new JScrollPane(table);
pane.setBounds(0, 0, 880, 400);
frame.setLayout(null);
frame.add(pane);
// add JTextFields to the jframe
frame.add(txtTeamName);
frame.add(txtWins);
frame.add(txtLosses);
frame.add(txtGD);
frame.add(txtMatches);
frame.add(txtPoints);
//Adding the labels to the frame
frame.add(lblTeamName);
frame.add(lblWins);
frame.add(lblLosses);
frame.add(lblGD);
frame.add(lblMatches);
frame.add(lblPoints);
// add JButtons to the jframe
frame.add(btnAdd);
frame.add(btnDelete);
frame.add(btnUpdate);
frame.add(btnSortGoals);
frame.add(btnSortPoints);
frame.add(btnRandomMatch);
// create an array of objects to set the row data
Object[] row = new Object[6];
// button add row
btnAdd.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
row[0] = txtTeamName.getText();
row[1] = txtWins.getText();
row[2] = txtLosses.getText();
row[3] = txtGD.getText();
row[4] = txtMatches.getText();
row[5] = txtPoints.getText();
// add row to the model
model.addRow(row);
}
});
// Event listener for button remove row
btnDelete.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// i = the index of the selected row
int i = table.getSelectedRow();
if(i >= 0){
// remove a row from jtable
model.removeRow(i);
}
else{
System.out.println("Delete Error");
}
}
});
// get selected row data From table to textfields
table.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
// i = the index of the selected row
int i = table.getSelectedRow();
txtTeamName.setText(model.getValueAt(i, 0).toString());
txtWins.setText(model.getValueAt(i, 1).toString());
txtLosses.setText(model.getValueAt(i, 2).toString());
txtGD.setText(model.getValueAt(i, 3).toString());
txtMatches.setText(model.getValueAt(i,4).toString());
txtPoints.setText(model.getValueAt(i,5).toString());
}
});
// button update row
btnUpdate.addActionListener(new ActionListener(){
#Override
public void actionPerformed (ActionEvent e) {
// i = the index of the selected row
int i = table.getSelectedRow();
if(i >= 0)
{
model.setValueAt(txtTeamName.getText(), i, 0);
model.setValueAt(txtWins.getText(), i, 1);
model.setValueAt(txtLosses.getText(), i, 2);
model.setValueAt(txtGD.getText(), i, 3);
model.setValueAt(txtMatches.getText(),i,4);
model.setValueAt(txtPoints.getText(),i,5);
}
else{
System.out.println("Update Error");
}
}
});
btnSortPoints.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
frame.setSize(1400, 500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
You first need to add sorting support to your JTable. Read the Sorting and Filtering link from the tutorial for information on how to do that.
Once that is done the user will be able to sort any column by clicking on the column header of the column.
Verify the sorting works by manually clicking on the columns headers.
i want "Sort By goals" button to sort out all the records entered by the highest number of goals and points
Now that your JTable supports sorting you can add add an ActionListener to your buttons to do the specific sorting:
btnSortPoints.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Points column in the model is converted to the view column
int viewColumn = table.convertColumnIndexToView(4);
// Set up the columns you want to sort on
List<RowSorter.SortKey> sortKeys = new ArrayList<>();
sortKeys.add(new RowSorter.SortKey(viewColumn, SortOrder.ASCENDING));
// Do the sorting
TableRowSorter sorter = (TableRowSorter)table.getRowSorter();
sorter.setSortKeys(sortKeys);
}
});
`

Error while trying to add rows to JTable

I'm trying to add rows to my table whenever the user selects yes when they are asked to add the product to the cart or not with the help of JOptionPane Confirm Dialog. My code is as follows:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class Home {
final static int WINDOW_WIDTH = 500;
final static int WINDOW_HEIGHT = 200;
JFrame window;
public Home() {
window = new JFrame();
window.setTitle("Home");
window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel title = new JLabel("Please select a book for more information", JLabel.CENTER);
title.setHorizontalTextPosition(JLabel.CENTER);
Font plainFont = new Font("Serif", 0, 24);
title.setFont(plainFont);
title.setBounds(180, 230, 97, 29);
//====================================================================//
String [] bookStrings = {"[Select a book]", "The Host", "Ruby", "Divergent", "The Secret Garden", "Hunger Games"};
JComboBox bookList = new JComboBox(bookStrings);
//====================================================================//
JLabel bookinfo = new JLabel();
//====================================================================//
JButton search = new JButton("Search");
search.setHorizontalTextPosition(JButton.CENTER);
JButton cart = new JButton("Show Cart");
search.setHorizontalTextPosition(JButton.CENTER);
JButton exit = new JButton("Exit");
search.setHorizontalTextPosition(JButton.CENTER);
JTable cartTable;
String[] columns = {"Book Name","Author", "Quantity", "Price"};
String [][] data = {};
cartTable = new JTable(data, columns);
cartTable.setPreferredScrollableViewportSize(new Dimension(450, 63));
cartTable.setFillsViewportHeight(true);
JScrollPane jps = new JScrollPane(cartTable);
//====================================================================//
search.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (bookList.getSelectedIndex() == 1) {
int reply = JOptionPane.showConfirmDialog(null,
"<html>Title: The Host <br> Author: Stephenie Meyer <br> Price: 110 AED <br> " +
"\n Synopsis: The Host is a romance novel by Stephenie Meyer. The book is about Earth, " +
"\n in a post apocalyptic time, being invaded by a parasitic alien race, known as \"Souls\", and " +
"\n follows one Soul's predicament when the consciousness of her human host refuses to co-operate " +
"\n with the takeover of her body."
+ "\n \n Would you like to add this to cart?", "Book Details", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION){
String [][] data = {{"The Host", "Stephenie Meyer", "2", "110"}};
DefaultTableModel model = (DefaultTableModel)(cartTable.getModel());
model.addRow(data);
}
else {
JOptionPane.showMessageDialog(null, "GOODBYE");
}
}
});
cart.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new Cart();
window.setVisible(false);
}
});
exit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
//====================================================================//
JPanel panel;
panel = new JPanel();
panel.add(title);
panel.add(bookList);
panel.add(search);
panel.add(bookinfo);
panel.add(cart);
panel.add(exit);
panel.add(jps);
window.add(panel);
window.setVisible(true);
}
}
However I'm getting this error:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JTable$1 cannot be cast to javax.swing.table.DefaultTableModel
Can someone help me with where I'm going wrong? Thank You.
cartTable = new JTable(data, columns);
uses an anonymous AbstractTableModel if I remember correctly.
Use instead:
cartTable = new JTable(new DefaultTableModel(data, columns));
DefaultTableModel fires miscellaneous change events and handles dynamic data.

Tried to add data to the JTable Dynamically using DefaultTableModel but it is not working

I tried to add data to the JTable Dynamically using DefaultTableModel, but it isn't working.
I had created two classes: One class (Input.java) represents a popup which allows you to write the data (name, option and constraint) and save it. Another class represents a popup which includes a table (InputMain.java). InputMain will then transform those info (if received) to a row with in the table that list out those all the information in three columns. In Input, I created an instance of InputMain, and set the model of the table to a new DefaultTableModel() (if I don't do this, it will throw an error) (a table is already created in InputMain, so that if I create an instance of InputMain, I am probably calling the table within InputMain). Then, according to actionPerformed(ActionEvent e), after the 'enter' button is clicked within the JPanel, it will create a new array of data with nameText, optionText and constraintText. And finally, the data will be added to the model.
I don't know why I can't add all those data into the table, except that method above sounds logical to me.
Here's the InputMain.java class:
package com.company;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by paull on 14/5/2016.
*/
public class InputMain {
JButton add;
JButton change;
JButton delete;
JTable table;
String[] columns;
String[][] data;
JButton create;
JPanel labelPanel;
JPanel bigPanel;
JPanel centerPanel;
public InputMain() {
int fontSize = 50;
add = new JButton("add");
change = new JButton("change");
delete = new JButton("delete");
create = new JButton("create");
columns = new String[]{"name","option","constraint"};
data = new String[][]{{"","",""}};
table = new JTable(data,columns) {
#Override
public boolean isCellEditable(int row, int column) {
return false; //to avoid it from being changable by double clicking any data
}
};
table.setPreferredScrollableViewportSize(new Dimension(450,63));
table.setFillsViewportHeight(true);
JScrollPane jsp = new JScrollPane(table); // not always can the table be fully shown --> add a scrollbar
add.setFont(new Font(add.getName(),Font.PLAIN,fontSize));
change.setFont(new Font(add.getName(),Font.PLAIN,fontSize));
delete.setFont(new Font(add.getName(),Font.PLAIN,fontSize));
create.setFont(new Font(add.getName(),Font.PLAIN,fontSize));
table.setFont(new Font(table.getName(),Font.PLAIN,fontSize));
//table.getEditorComponent().setFont(new Font(add.getName(),Font.PLAIN,fontSize));
table.getTableHeader().setFont(new Font(table.getName(),Font.PLAIN,fontSize));
labelPanel = new JPanel();
labelPanel.add(add);
labelPanel.add(change);
labelPanel.add(delete);
labelPanel.setLayout(new FlowLayout(10,30,10));
centerPanel = new JPanel();
centerPanel.add(labelPanel);
centerPanel.setLayout(new GridBagLayout());
bigPanel = new JPanel();
bigPanel.setLayout(new GridLayout(3,0));
bigPanel.add(centerPanel);
bigPanel.add(jsp);
bigPanel.add(create);
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
InputFrame s = new InputFrame();
Input i = new Input();
s.add(i.labelPanel);
s.setVisible(true);
}
}); // pressing add button pops up the Input Frame
}
}
And here's the Input.java class:
package com.company;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by paull on 14/5/2016.
*/
public class Input extends JPanel{
JLabel nameLabel;
JLabel optionLabel;
JLabel constraintLabel;
JButton enter;
JPanel labelPanel;
JPanel jp2;
JPanel jp3;
JPanel jp4;
JTextField nameText;
String[] optionStrings;
JComboBox<String> optionText;
JCheckBox wk1;
JCheckBox wk2;
JCheckBox wk3;
JCheckBox wk4;
JCheckBox wk5;
public Input() {
nameLabel = new JLabel("name: ");
optionLabel = new JLabel("option: ");
constraintLabel = new JLabel("constraint:");
enter = new JButton("add");
nameText = new JTextField(10);
Options c = new Options();
optionStrings = new String[]{c.satNight,c.sunEight,c.sunNineThirty,c.sunEleven,c.sunNight};
optionText = new JComboBox<String>(optionStrings);
wk1 = new JCheckBox("1");
wk2 = new JCheckBox("2");
wk3 = new JCheckBox("3");
wk4 = new JCheckBox("4");
wk5 = new JCheckBox("5");
int fontSize = 50;
nameLabel.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
optionLabel.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
constraintLabel.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
enter.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
nameText.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
optionText.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
wk1.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
wk2.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
wk3.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
wk4.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
wk5.setFont(new Font(nameLabel.getName(),Font.PLAIN,fontSize));
labelPanel = new JPanel();
labelPanel.add(nameLabel);
labelPanel.add(nameText);
labelPanel.add(optionLabel);
labelPanel.add(optionText);
labelPanel.add(constraintLabel);
labelPanel.add(wk1);
labelPanel.add(wk2);
labelPanel.add(wk3);
labelPanel.add(wk4);
labelPanel.add(wk5);
labelPanel.add(enter);
labelPanel.setLayout(new FlowLayout(10,30,10));
InputMain i = new InputMain();
i.table.setModel(new DefaultTableModel());
DefaultTableModel model = (DefaultTableModel) i.table.getModel();
enter.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String constraintText = "";
String[] data = new String[]{nameText.getText(),optionText.getSelectedItem().toString(),constraintText};
model.addRow(data);
nameText.setText("");
}
});
}
}
Thanks in advance.
I think the problem lies in the actionPerformed of InputMain.
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
InputFrame s = new InputFrame();
Input i = new Input();
s.add(i.labelPanel);
s.setVisible(true);
}
});
You construct a new instance of Input. That means that you create a new empty DefaultTableModel and attach it to your table each time you click on the add button. Try move the construction of the Input outside of your actionPerformed like this:
Input i = new Input();
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
InputFrame s = new InputFrame();
s.add(i.labelPanel);
s.setVisible(true);
}
UPDATE
Of course the instantiation of InputMain inside of Input should be removed, too. Instead have a member of Type InputMain in Input:
private InputMain inputMain;
and change the constructor of Input to set the value:
public Input (InputMain inputMain) {
this.inputMain = inputMain;
...
And change the instantiation of Input in InputMain to
Input i = new Input(this);

Data in 1 column is getting stored in different row than other columns

I'm Working on a swing project and i have a JDialogbox which contain two textfield and 1 combobox and two button "ok" and "cancel"and a Frame which have a text area which acts like Notepad and all of these Components are connected to Oracle Database whenever I insert data in JDialog and click on Ok the data is stored in database and the frame containing the text area is called and when i save the data written in textarea and click the save button the inserted Data is saved in different row in the Database but not in the same row as the JDialog components
import javax.swing.*;
import java.sql.*;
import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.event.*;
import java.awt.*;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
public class newmenu implements ActionListener {
JDialog jf;
JButton okBtn,CanBtn;
JTextField tf1,tf3;
JComboBox type;
JLabel prName,prType,prWritter;
JFrame frame;
JMenuBar menuBar;
JMenu file;
JMenuItem open, save, exit;
JFileChooser fileChooser;
JTextArea textArea;
public newmenu(){
jf = new JDialog();
jf.setTitle("New Report");
okBtn = new JButton("Ok");
okBtn.setBounds(10, 140, 60, 20);
okBtn.addActionListener(this);
CanBtn = new JButton("Cancel");
CanBtn.addActionListener(this);
CanBtn.setBounds(100, 140, 100, 20);
tf1 = new JTextField();
tf1.setBounds(150, 20, 100, 20);
String r_Type [] = {"Cosmetics","Pharametical","Medical"};
type = new JComboBox(r_Type);
type.setBounds(150, 60, 100, 20);
tf3 = new JTextField();
tf3.setBounds(150, 100, 100, 20);
prName = new JLabel("Report Name");
prName.setBounds(10, 20, 100, 20);
prType = new JLabel("Report type");
prType.setBounds(10,60,100,20);
prWritter = new JLabel("Report Written");
prWritter.setBounds(10,100,100,20);
jf.add(okBtn);
jf.add(CanBtn);
jf.add(tf1);
jf.add(type);
jf.add(tf3);
jf.add(prName);
jf.add(prType);
jf.add(prWritter);
jf.setSize(300, 200);
jf.setResizable(false);
jf.setLayout(null);
jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jf.setVisible(true);
}
public void notepad(){
frame = new JFrame();
frame.setTitle("Notepad");
file = new JMenu("File");
save = new JMenuItem("Save");
save.addActionListener(this);
exit = new JMenuItem("Exit");
exit.addActionListener(this);
textArea = new JTextArea();
fileChooser = new JFileChooser();
menuBar = new JMenuBar();
frame.setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(textArea);
file.add(save);
file.add(exit);
menuBar.add(file);
frame.setJMenuBar(menuBar);
frame.setSize(800, 600);
frame.setVisible(true);
}
public void insert(){
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
Connection con = DriverManager
.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","root");
Statement st = con.createStatement();
st.executeUpdate("insert into report (reportname, reporttype,clientname) VALUES('"
+ tf1.getText() + "','"
+ tf3.getText() + "','" + type.getSelectedItem()+ "')");
}
catch (Exception e1)
{
System.out.println("Exception:" + e1);
}
}
public void notepadinsert(){
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
Connection con = DriverManager
.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","root");
Statement st = con.createStatement();
st.executeUpdate("insert into report (report) VALUES('"
+ textArea.getText() + "')");
}
catch (Exception e1)
{
System.out.println("Exception:" + e1);
}
}
public void actionPerformed(ActionEvent ev){
if(ev.getSource()==okBtn){
if( tf1.getText().trim().equals("")){
okBtn.setEnabled(false);
if(tf1.getText().hashCode() != 0){
okBtn.setEnabled(true);
}
}
else{
okBtn.setEnabled(true);
jf.dispose();
insert();
notepad();
}
}
else if(ev.getSource()==CanBtn){
System.exit(0);
}
else if(ev.getSource()==save){
notepadinsert();
}
else if(ev.getSource()==exit){
System.exit(0);
}
}
public static void main(String args[]){
new newmenu();
}
}
Use a flag to check if it's a first request.
private int flag=0;
...
insert(){
...
if(flag==0){
//insert command
flag=1;
}
else
{
//update here.
}
}
UPDATE:
A better way can be to check if the current user has done the update..You have to create a field (like user_name) because I cannot see that in your insert query .
insert(){
...
//search for the current record with user_name in DB
if(!found){
//insert command
}
else
{
//update here.
}
}
Chnged your code like this... In the insert() method now you have data to be stored... Store that data in database in one go... I have added System.out.println(); because i couldn't create an oracle database and this was only way to check if i am getting all the data needed...
You just write your code for inserting into the DataBase in the insert method and pass the values from the string array which i have used to print the values...
public void insert(String[] Str){ // Write your code for insertion
// of values in database
System.out.println(Str[0]);
System.out.println(Str[1]); // I just used these to check
System.out.println(Str[2]); // If i am getting correct values
System.out.println(Str[3]);
}
#Override
public void actionPerformed(ActionEvent ev){
String[] Data_To_Insert = new String[4];
if(ev.getSource()==okBtn){
if( tf1.getText().trim().equals("")){
okBtn.setEnabled(false);
if(tf1.getText().hashCode() != 0){
okBtn.setEnabled(true);
}
}
else{
okBtn.setEnabled(true);
jf.dispose();
notepad();
}
}
else if(ev.getSource()==CanBtn){
System.exit(0);
}
else if(ev.getSource()==save){
Data_To_Insert[0] = tf1.getText();
Data_To_Insert[1] = tf3.getText();
Data_To_Insert[2] = type.getSelectedItem().toString();
Data_To_Insert[3] = textArea.getText();
insert(Data_To_Insert);
}
else if(ev.getSource()==exit){
System.exit(0);
}
}
Also remember you have to create 4 columns to store the data...
Hoping it helped...

Runtime Error Java app

Hi guys I built this app to show students how a loop works graphically, that was working although not correctly, but I'll address that in a question later. I'm not sure what I did to the applet but now I get this runtime error. How do I fix this? thanks in advanced!
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import javax.swing.JOptionPane;
public class Checkerboard extends Frame implements ActionListener
{
int[] blocksTextField = new int[15];
Panel blocksPanel = new Panel();
TextArea blocksDisplay[] = new TextArea[16];
TextField start = new TextField (3);
TextField stop = new TextField (3);
TextField step = new TextField (3);
//Colors
Color Red = new Color(255, 90, 90);
Color Green = new Color(140, 215, 40);
Color white = new Color(255,255,255);
//textField ints
int inputStart;
int inputStop;
int inputStep;
//Lables
Label custStartLabel = new Label ("Start : ");
Label custStopLabel = new Label ("Stop : ");
Label custStepLabel = new Label ("Step : ");
//Buttons
Button goButton = new Button("Go");
Button clearButton = new Button("Clear");
//panel for input textFields and lables
Panel textInputPanel = new Panel();
//Panel for buttons
Panel buttonPanel = new Panel();
Checkerboard()
{//constructor method
//set the 3 input textFields to 0
inputStart = 0;
inputStop = 0;
inputStep = 0;
//set Layouts for frame and three panels
this.setLayout(new BorderLayout());
//grid layout (row,col,horgap,vertgap)
blocksPanel.setLayout(new GridLayout(4,4,10,10));
textInputPanel.setLayout(new GridLayout(2,3,20,10));
buttonPanel.setLayout(new FlowLayout());
//setEditable()
//setText()
//add components to blocks panel
for (int i = 0; i<16; i++)
{
blocksDisplay[i] = new TextArea(null,3,5,3);
if(i<6)
blocksDisplay[i].setText(" " +i);
else
blocksDisplay[i].setText(" " +i);
blocksDisplay[i].setEditable(false);
// blocksDisplay[i].setBackground(Red);
blocksPanel.add(blocksDisplay[i]);
}
//add componets to panels
//add text fields
textInputPanel.add(start);
textInputPanel.add(stop);
textInputPanel.add(step);
//add lables
textInputPanel.add(custStartLabel);
textInputPanel.add(custStopLabel);
textInputPanel.add(custStepLabel);
//add button to panel
buttonPanel.add(goButton);
buttonPanel.add(clearButton);
//ADD ACTION LISTENRS TO BUTTONS (!IMPORTANT)
goButton.addActionListener(this);
clearButton.addActionListener(this);
add(blocksPanel, BorderLayout.NORTH);
add(textInputPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
//overridding the windowcClosing() method will allow the user to clisk the Close button
addWindowListener(
new WindowAdapter()
{
public void windowCloseing(WindowEvent e)
{
System.exit(0);
}
}
);
}//end of constructor method
public void actionPerformed(ActionEvent e)
{
//if & else if to see what button clicked and pull user input
if(e.getSource() == goButton) //if go clicked ...
{
System.out.println("go clicked");
try{
String inputStart = start.getText();
int varStart = Integer.parseInt(inputStart);
if (varStart<=0 || varStart>=15 )throw new NumberFormatException();
System.out.println("start = " + varStart);
// roomDisplay[available].setBackground(lightRed);
String inputStop = stop.getText();
int varStop = Integer.parseInt(inputStop);
if (varStop<=0 || varStart>=15 )throw new NumberFormatException();
System.out.println("stop = " + varStop);
String inputStep = step.getText();
int varStep = Integer.parseInt(inputStep);
if (varStep<=0 || varStep>=15 )throw new NumberFormatException();
System.out.println("step = " + varStep);
for (int i = varStart; i<varStop; varStep++)//ADD WHILE LOOP
{
blocksDisplay[i].setBackground(Red);
blocksDisplay[i].setText(" " +i);
}
}
catch (NumberFormatException ex)
{
JOptionPane.showMessageDialog(null, "You must enter a Start, Stop and Step value greater than 0 and less than 15",
"Error",JOptionPane.ERROR_MESSAGE);
}
}
else if(e.getSource() == clearButton ) //else if clear clicked ...
{
System.out.println("clear clicked");
}
//int available = room.bookRoom(smoking.getState());
//if (available > 0)//Rooms is available
}//end action performed method
public static void main(String[]args)
{
Checkerboard frame = new Checkerboard ();
frame.setBounds(50, 100, 300, 410);//changed size to make text feilds full charater size
frame.setTitle("Checkerboarder Array");
frame.setVisible(true);
}//end of main method
}
Make the constructor public.
public Checkerboard() {
...
}
The error appears because the constructor is package-private, e.g. you can't instantiate the class outside it's package.

Categories