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.
Related
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);
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);
Perhaps this was already asked once but I am kinda stuck and cant find a solution by myself.
I got text from first button using text fields. And now i need to get this text into second button OR text file.
Code below and i know that this one gives error.
System.out.println("Author's name: " + newauthor());
System.out.println("Book name: " + newbook());
import java.awt.GridLayout;
import java.awt.event.*;
import java.io.FileNotFoundException;
import javax.swing.*;
public class library extends JFrame
{
private JPanel pnl;
public library() throws FileNotFoundException {
pnl = (JPanel) getContentPane();
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(null);
JButton addbutton = new JButton("Add new book");
addbutton.setBounds(75, 30, 150, 30);
addbutton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
JTextField authorfield = new JTextField(15);
JTextField bookField = new JTextField(15);
JPanel mypanel = new JPanel(new GridLayout(0, 1));
mypanel.add(new JLabel("Type Author's Name and Book name:"));
mypanel.add(new JLabel("Author's Name:"));
mypanel.add(authorfield);
mypanel.add(new JLabel("Book name:"));
mypanel.add(bookField);
int result = JOptionPane.showConfirmDialog(null, mypanel,
"Add a new book", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION)
{
String newauthor = authorfield.getText();
String newbook = bookField.getText();
if (!newauthor.isEmpty() && !newbook.isEmpty())
{
JOptionPane.showMessageDialog(pnl, "Book "+bookField.getText()+"\nAuthor "+authorfield.getText()+"\nSuccessfully added to the list.",
"Book was added.", JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(pnl, "Both must be filled!",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
});
panel.add(addbutton);
JButton listbutton = new JButton("List");
listbutton.setBounds(75, 60, 150, 30);
panel.add(listbutton);
addbutton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
System.out.println("Author's name: " + newauthor());
System.out.println("Book name: " + newbook());
}
});
JButton deletebutton = new JButton("Delete");
deletebutton.setBounds(75, 90, 150, 30);
panel.add(deletebutton);
setTitle("Library Menu");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) throws FileNotFoundException {
library ex = new library();
ex.setVisible(true);
}
}
Your code is having many issues.
1.Both should be declared inside of your class but outside of your any method.
String newauthor = "";
String newbook = "";
Now in the if condition
if (result == JOptionPane.OK_OPTION)
{
newauthor = authorfield.getText();
newbook = bookField.getText();
..............................
2.
JButton listbutton = new JButton("List");
listbutton.setBounds(75, 60, 150, 30);
panel.add(listbutton);
listbutton.addActionListener(new ActionListener()// its listbutton not addbutton
{
public void actionPerformed(ActionEvent event)
{
System.out.println("Author's name: " + newauthor);
System.out.println("Book name: " + newbook);
}
});
Both newauthor and newbook are variables. But not methods.
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...
I have this code in Java Swings which creates 2 frames.The first frame contains 4 text fields(roll no,name,class,section) leaving the text fields blank I click on the search button in the 1st frame,another frame opens with all my table records in the database.Once I select a record(or the row) all the details of it appear in the 1st frame,i.e roll no,class,name and section get populated.
Right now I am using the search button to go to the next frame.What should I do so that the action is performed once I click on the roll no. text field instead of the search button?
This is the code:
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;
import java.util.Vector;
import java.awt.event.*;
public class barcoder1 implements ActionListener{
JFrame frame,frame1;
JTextField textbox,textbox1,textbox2,textbox3,textbox4,textbox5,textbox6,textbox7,textbox8;
JLabel label,label1,label2,label3,label4,label5,label6,label7,label8;
JButton button;
JPanel panel;
static JTable table;
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mydb";
String userName = "root";
String password = "root";
String[] columnNames = {"Roll No", "Name", "Class", "Section"};
public void createUI()
{
frame = new JFrame("Database Search Result");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
textbox = new JTextField();
textbox.setBounds(120,30,150,20);
label=new JLabel("Roll No.");
label.setBounds(10, 30, 100, 20);
textbox1 = new JTextField();
textbox1.setBounds(120,50,150,20);
label1=new JLabel("Name");
label1.setBounds(10, 50, 100, 20);
textbox2 = new JTextField();
textbox2.setBounds(120,70,150,20);
label2=new JLabel("Class");
label2.setBounds(10, 70, 100, 20);
textbox3 = new JTextField();
textbox3.setBounds(120,90,150,20);
label3=new JLabel("Section");
label3.setBounds(10, 90, 100, 20);
button = new JButton("search");
button.setBounds(120,230,150,20);
button.addActionListener(this);
frame.add(textbox);
frame.add(label);
frame.add(textbox1);
frame.add(label1);
frame.add(textbox2);
frame.add(label2);
frame.add(textbox3);
frame.add(label3);
frame.add(button);
frame.setVisible(true);
frame.setSize(500, 400);
}
public void actionPerformed(ActionEvent ae)
{
button = (JButton)ae.getSource();
System.out.println("Showing Table Data.......");
showTableData();
}
public void showTableData()
{
frame1 = new JFrame("Database Search Result");
//frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setLayout(new BorderLayout());
//TableModel tm = new TableModel();
DefaultTableModel model = new DefaultTableModel(){
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
model.setColumnIdentifiers(columnNames);
//DefaultTableModel model = new DefaultTableModel(tm.getData1(), tm.getColumnNames());
//table = new JTable(model);
final JTable table = new JTable(model);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
int row = table.getSelectedRow();
System.out.println("Selecte table row = " + row);
if (row != -1) {
int modelRow = table.convertRowIndexToModel(row);
System.out.println("Selecte model row = " + row);
Vector data = (Vector) ((DefaultTableModel) table.getModel()).getDataVector().get(modelRow);
textbox.setText(data.get(0).toString());
textbox1.setText(data.get(1).toString());
textbox2.setText(data.get(2).toString());
textbox3.setText(data.get(3).toString());
}
}
});
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2) {
if (table.getSelectedRow() != -1) {
SwingUtilities.getWindowAncestor(table).dispose();
}
}
}
});
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
JScrollPane scroll = new JScrollPane(table);
scroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
String textvalue = textbox.getText();
String roll= "";
String name= "";
String cl = "";
String sec = "";
try
{
Class.forName(driverName);
Connection con = DriverManager.getConnection(url, userName, password);
//String sql = "select * from student where rollno = "+textvalue;
String sql="select * from student";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
int i =0;
while(rs.next())
{
roll = rs.getString("rollno");
name = rs.getString("name");
cl = rs.getString("class");
sec = rs.getString("section");
model.addRow(new Object[]{roll, name, cl, sec});
}
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage(),"Error",
JOptionPane.ERROR_MESSAGE);
}
frame1.add(scroll);
frame1.setVisible(true);
frame1.setSize(400,300);
}
public static void main(String args[])
{
barcoder1 sr = new barcoder1();
sr.createUI();
}
}