what does java.awt.EventDispatchThread.pumpEvents mean? - java

we have a problem with our GUI code. When we run it several errors occurs and we have no idea what they mean. We are creating an ordersystem from a model and then we have to include an interface that we build in Window builder. Very new to java programming so we need all help we can get:D thanks.
GUI code:
package ISprojekt3;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
public class OrderApplication {
Controller1 controller = new Controller1();
private JFrame frame;
private JTextField name;
private JTextField customerNumber;
private JTextField address;
private JTextField deliveryDate;
private JTextField orderID;
private JTextField number;
private JTextField quantity;
private JTextField nameProduct;
private JTextField category;
private JTextField price;
private JTextField serialNumber;
private JTextArea message;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
OrderApplication window = new OrderApplication();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public OrderApplication() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 672, 482);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblName = new JLabel("Namn:");
lblName.setBounds(23, 45, 61, 16);
frame.getContentPane().add(lblName);
JLabel lblCustomerNumber = new JLabel("Kundnummer:");
lblCustomerNumber.setBounds(23, 73, 106, 16);
frame.getContentPane().add(lblCustomerNumber);
JLabel lblAddress = new JLabel("Adress:");
lblAddress.setBounds(23, 103, 61, 16);
frame.getContentPane().add(lblAddress);
JLabel lblCustomer = new JLabel("Kund");
lblCustomer.setBounds(23, 17, 61, 16);
frame.getContentPane().add(lblCustomer);
name = new JTextField();
name.setBounds(125, 40, 130, 26);
frame.getContentPane().add(name);
name.setColumns(10);
customerNumber = new JTextField();
customerNumber.setBounds(125, 68, 130, 26);
frame.getContentPane().add(customerNumber);
customerNumber.setColumns(10);
address = new JTextField();
address.setBounds(125, 98, 130, 26);
frame.getContentPane().add(address);
address.setColumns(10);
JLabel lblOrder = new JLabel("Order");
lblOrder.setBounds(313, 17, 61, 16);
frame.getContentPane().add(lblOrder);
JLabel lblOrderID = new JLabel("OrderID:");
lblOrderID.setBounds(313, 45, 61, 16);
frame.getContentPane().add(lblOrderID);
JLabel lblDeliveryDate = new JLabel("Leveransdatum:");
lblDeliveryDate.setBounds(313, 73, 106, 16);
frame.getContentPane().add(lblDeliveryDate);
deliveryDate = new JTextField();
deliveryDate.setBounds(412, 68, 130, 26);
frame.getContentPane().add(deliveryDate);
deliveryDate.setColumns(10);
orderID = new JTextField();
orderID.setBounds(412, 40, 130, 26);
frame.getContentPane().add(orderID);
orderID.setColumns(10);
JLabel lblOrderLine = new JLabel("Orderrad");
lblOrderLine.setBounds(313, 159, 61, 16);
frame.getContentPane().add(lblOrderLine);
JLabel lblNumber = new JLabel("Nummer:");
lblNumber.setBounds(313, 187, 61, 16);
frame.getContentPane().add(lblNumber);
JLabel lblQuantity = new JLabel("Antal produkter:");
lblQuantity.setBounds(313, 215, 106, 16);
frame.getContentPane().add(lblQuantity);
number = new JTextField();
number.setBounds(412, 182, 130, 26);
frame.getContentPane().add(number);
number.setColumns(10);
quantity = new JTextField();
quantity.setBounds(412, 210, 130, 26);
frame.getContentPane().add(quantity);
quantity.setColumns(10);
JLabel lblProduct = new JLabel("Produkt");
lblProduct.setBounds(23, 159, 61, 16);
frame.getContentPane().add(lblProduct);
JLabel lblName_2 = new JLabel("Namn:");
lblName_2.setBounds(23, 187, 61, 16);
frame.getContentPane().add(lblName_2);
JLabel lblCategory = new JLabel("Kategori:");
lblCategory.setBounds(23, 215, 61, 16);
frame.getContentPane().add(lblCategory);
nameProduct = new JTextField();
nameProduct.setBounds(125, 187, 130, 26);
frame.getContentPane().add(nameProduct);
nameProduct.setColumns(10);
category = new JTextField();
category.setBounds(125, 215, 130, 26);
frame.getContentPane().add(category);
category.setColumns(10);
price = new JTextField();
price.setBounds(125, 238, 130, 26);
frame.getContentPane().add(price);
price.setColumns(10);
JLabel lblPrice = new JLabel("Pris:");
lblPrice.setBounds(23, 243, 61, 16);
frame.getContentPane().add(lblPrice);
JLabel lblCopy = new JLabel("Exemplar");
lblCopy.setBounds(23, 297, 69, 16);
frame.getContentPane().add(lblCopy);
JLabel lblSerialNumber = new JLabel("Serienummer:");
lblSerialNumber.setBounds(23, 325, 106, 16);
frame.getContentPane().add(lblSerialNumber);
serialNumber = new JTextField();
serialNumber.setBounds(125, 320, 130, 26);
frame.getContentPane().add(serialNumber);
serialNumber.setColumns(10);
JButton btnSearch = new JButton("Sök");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnSearch.setBounds(409, 263, 117, 29);
frame.getContentPane().add(btnSearch);
JButton btnAdd = new JButton("Lägg till");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String customerName = name.getText();
String customerNumber = number.getText();
String customerAddress = address.getText();
if((customerName.length() < 1) || (customerNumber.length() < 1) || (customerAddress.length() < 1)) {
message.setText("Tilläggning misslyckades");
}
else {
controller.addCustomer(customerNumber, customerName, customerAddress);
message.setText("Kunden är tillagd");
}
String order = orderID.getText();
String dDate = deliveryDate.getText();
if((order.length() < 1 ) || (dDate.length() < 1)) {
message.setText("Tilläggning misslyckades");
}
else {
controller.addOrder(order, dDate, customerNumber);
message.setText("Ordern är tillagd till kund " + controller.findCustomer(customerNumber).getCustomerNumber());
}
String productName = nameProduct.getText();
String productCategory = category.getText();
String productPrice = price.getText();
if((productName.length() < 1 ) || (productCategory.length() < 1 ) || (productPrice.length() < 1 )) {
message.setText("Tilläggning misslyckades");
}
else {
controller.addProduct(productName, productCategory, productPrice);
message.setText("Produkten är tillagd");
}
String orderLineNumber = number.getText();
String orderLineQuantity = quantity.getText();
if((orderLineNumber.length() < 1 ) || (orderLineQuantity.length() < 1)) {
message.setText("Tilläggning misslyckades");
}
else {
controller.addOrderLine(orderLineNumber, orderLineQuantity, order);
message.setText("Orderraden är tillagd i order" + controller.findOrder(order).getOrderID());
}
String serialNumberCopy = serialNumber.getText();
if((serialNumberCopy.length() < 1)) {
message.setText("Tilläggningen misslyckades");
}
else {
controller.addCopy(serialNumberCopy, productName);
message.setText("Exemplaret är tillagd i produkt " + controller.findProduct(productName).getName());
}
}
});
btnAdd.setBounds(409, 292, 117, 29);
frame.getContentPane().add(btnAdd);
JButton btnRemove = new JButton("Ta bort");
btnRemove.setBounds(409, 370, 117, 29);
frame.getContentPane().add(btnRemove);
JButton btnChange = new JButton("Ändra");
btnChange.setBounds(409, 345, 117, 29);
frame.getContentPane().add(btnChange);
JTextArea message = new JTextArea();
message.setBounds(23, 375, 231, 50);
frame.getContentPane().add(message);
}
}
And here are the errors:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at ISprojekt3.OrderApplication$3.actionPerformed(OrderApplication.java:198)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6533)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6298)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4889)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2746)
at java.awt.Component.dispatchEvent(Component.java:4711)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Use messed up with variable scopes and the used field private JTextArea message was not initialized.
The created local scoped one JTextArea message = new JTextArea() was never assigned to the field message.

Related

Can't add a data from ArrayList to a jtable

I just tried to add some data from ArrayList to a JTable using DefaultTableModel function addRow(), I loop it inside to add the data but the data didn't come out in the frame. can anyone help me? here's my code so far (the problem is in action event of the button "bt_htg" and "bt_refresh"
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.*;
public class GuiDataMhs extends JFrame implements ActionListener, ItemListener, DocumentListener{
JLabel lbl_judul;
JLabel lbl_findName;
JLabel lbl_nim;
JLabel lbl_nama;
JLabel lbl_smt;
JLabel lbl_mk;
JLabel lbl_formatif;
JLabel lbl_uts;
JLabel lbl_uas;
JTextField txt_findName;
JTextField txt_nim;
JTextField txt_nama;
JComboBox cb_smt;
JComboBox cb_mk;
DefaultTableModel DftTabMode;
TableRowSorter sorter;
JTable tbl_mhs;
JScrollPane spane;
JSpinner sp_formatif;
JSpinner sp_uts;
JSpinner sp_uas;
JButton bt_htg;
JButton bt_refresh;
GuiDataMhs(){
getContentPane().setLayout(null);
lbl_judul = new JLabel("Form Data Mahasiswa");
lbl_findName = new JLabel("Cari Nama: ");
lbl_nim = new JLabel("NIM: ");
lbl_nama = new JLabel("Nama: ");
lbl_smt = new JLabel("Semester: ");
lbl_mk = new JLabel("MK: ");
lbl_formatif = new JLabel("Formatif: ");
lbl_uts = new JLabel("UTS: ");
lbl_uas = new JLabel("UAS: ");
txt_findName = new JTextField();
txt_nim = new JTextField();
txt_nama = new JTextField();
String columns[]= {"Nama", "NIM", "Semester", "MK", "Formatif", "UTS", "UAS", "Nilai Mutu", "Nilai Huruf"};
DftTabMode = new DefaultTableModel(columns, 0);
sorter = new TableRowSorter<>(DftTabMode);
tbl_mhs = new JTable(DftTabMode);
tbl_mhs.setRowSorter(sorter);
spane = new JScrollPane(tbl_mhs);
cb_smt = new JComboBox();
cb_mk = new JComboBox();
sp_formatif = new JSpinner();
sp_uts = new JSpinner();
sp_uas = new JSpinner();
bt_htg = new JButton("Hitung");
bt_refresh = new JButton("Refresh");
lbl_judul.setFont(new Font("Tahoma", Font.BOLD, 18));
lbl_judul.setBounds(10, 11, 199, 22);
getContentPane().add(lbl_judul);
lbl_findName.setFont(new Font("Tahoma", Font.PLAIN, 12));
lbl_findName.setBounds(10, 41, 61, 22);
getContentPane().add(lbl_findName);
txt_findName.setFont(new Font("Tahoma", Font.PLAIN, 12));
txt_findName.setBounds(81, 41, 154, 22);
txt_findName.setDocument(new onlyLetter().getOnlyLetter());
getContentPane().add(txt_findName);
txt_findName.getDocument().addDocumentListener(this);
spane.setBounds(10, 74, 870, 125);
getContentPane().add(spane);
lbl_nim.setFont(new Font("Tahoma", Font.PLAIN, 12));
lbl_nim.setBounds(10, 225, 84, 22);
getContentPane().add(lbl_nim);
txt_nim.setFont(new Font("Tahoma", Font.PLAIN, 12));
txt_nim.setBounds(94, 225, 310, 22);
txt_nim.setDocument(new onlyDigit().getOnlyDigit());
getContentPane().add(txt_nim);
lbl_nama.setFont(new Font("Tahoma", Font.PLAIN, 12));
lbl_nama.setBounds(10, 258, 84, 22);
getContentPane().add(lbl_nama);
txt_nama.setFont(new Font("Tahoma", Font.PLAIN, 12));
txt_nama.setBounds(94, 258, 310, 22);
txt_nama.setDocument(new onlyLetter().getOnlyLetter());
getContentPane().add(txt_nama);
lbl_smt.setFont(new Font("Tahoma", Font.PLAIN, 12));
lbl_smt.setBounds(10, 291, 84, 22);
getContentPane().add(lbl_smt);
cb_smt.setFont(new Font("Tahoma", Font.PLAIN, 12));
cb_smt.addItem("Semester 1");
cb_smt.addItem("Semester 2");
cb_smt.setSelectedItem(null);
cb_smt.setBounds(94, 291, 310, 22);
getContentPane().add(cb_smt);
cb_smt.addItemListener(this);
lbl_mk.setFont(new Font("Tahoma", Font.PLAIN, 12));
lbl_mk.setBounds(10, 324, 84, 22);
getContentPane().add(lbl_mk);
cb_mk.setFont(new Font("Tahoma", Font.PLAIN, 12));
cb_mk.setSelectedItem(null);
cb_mk.setBounds(94, 324, 310, 22);
getContentPane().add(cb_mk);
lbl_formatif.setFont(new Font("Tahoma", Font.PLAIN, 12));
lbl_formatif.setBounds(498, 225, 90, 22);
getContentPane().add(lbl_formatif);
sp_formatif.setBounds(592, 225, 115, 22);
getContentPane().add(sp_formatif);
lbl_uts.setFont(new Font("Tahoma", Font.PLAIN, 12));
lbl_uts.setBounds(498, 258, 90, 22);
getContentPane().add(lbl_uts);
sp_uts.setBounds(592, 258, 115, 22);
getContentPane().add(sp_uts);
lbl_uas.setFont(new Font("Tahoma", Font.PLAIN, 12));
lbl_uas.setBounds(498, 291, 90, 22);
getContentPane().add(lbl_uas);
sp_uas.setBounds(592, 291, 115, 22);
getContentPane().add(sp_uas);
bt_htg.setFont(new Font("Tahoma", Font.BOLD, 12));
bt_htg.setBounds(592, 324, 85, 22);
getContentPane().add(bt_htg);
bt_htg.addActionListener(this);
bt_refresh.setFont(new Font("Tahoma", Font.BOLD, 12));
bt_refresh.setBounds(695, 324, 85, 22);
getContentPane().add(bt_refresh);
bt_refresh.addActionListener(this);
}
public String checkIfEmpty() {
String result = "";
if(txt_nim.getText().trim().equals("")) {
result = "NIM mahasiswa harus diisi!";
}else if(txt_nama.getText().trim().equals("")) {
result = "Nama mahasiswa harus diisi!";
}else if(cb_smt.getSelectedIndex() == -1) {
result = "Semester mahasiswa harus dipilih!";
}else if(cb_mk.getSelectedIndex() == -1) {
result = "Mata kuliah mahasiswa harus dipilih!";
}else if((Integer)sp_formatif.getValue() == 0) {
result = "Nilai formatif harus diisi!";
}else if((Integer)sp_uts.getValue() == 0) {
result = "Nilai UTS harus diisi!";
}else if((Integer)sp_uas.getValue() == 0) {
result = "Nilai UAS harus diisi!";
}else {
result = "valid";
}
return result;
}
#Override
public void actionPerformed(ActionEvent ev) {
ArrayList<String> list = new ArrayList<String>();
if(ev.getSource().equals(bt_htg)) {
String check = checkIfEmpty();
if(check.equals("valid")) {
String formatif, uts, uas, mutu, nama, nim, semester, matkul, huruf;
HitungNilaiMhs htg = new HitungNilaiMhs();
nama = txt_nama.getText().trim();
nim = txt_nim.getText().trim();
semester = (String) cb_smt.getSelectedItem();
matkul = (String) cb_mk.getSelectedItem();
formatif = String.valueOf(sp_formatif.getValue());
uts = String.valueOf(sp_uts.getValue());
uas = String.valueOf(sp_uas.getValue());
mutu = htg.htg_nilaiMutu(formatif, uts, uas);
huruf = htg.nl_huruf();
String item[] = {nama, nim, semester, matkul, formatif, uts, uas, mutu, huruf};
// DftTabMode.addRow(item);
for(int i=0;i<9;i++) {
list.add(item[i]);
}
txt_nama.setText("");
txt_nim.setText("");
cb_smt.setSelectedItem(null);
cb_mk.setSelectedItem(null);
sp_formatif.setValue(0);
sp_uts.setValue(0);
sp_uas.setValue(0);
JOptionPane.showMessageDialog(null, "Data berhasil diproses");
}else {
JOptionPane.showMessageDialog(null, check);
}
}else if(ev.getSource().equals(bt_refresh)) {
// DftTabMode.setRowCount(0);
for(int i=0;i<list.size()/9;i++) {
DftTabMode.addRow(new Object[] {list.get(i*9),
list.get(i*9+1),
list.get(i*9+2),
list.get(i*9+3),
list.get(i*9+3),
list.get(i*9+4),
list.get(i*9+5),
list.get(i*9+6),
list.get(i*9+7),
list.get(i*9+8)
});
}
list.clear();
JOptionPane.showMessageDialog(null, "Data berhasil direfresh");
}
}
public void itemStateChanged(ItemEvent ev) {
try {
if(cb_smt.getSelectedItem().equals("Semester 1")) {
cb_mk.removeAllItems();
cb_mk.addItem("Kalkulus 1");
cb_mk.addItem("Elektronika Dasar");
cb_mk.addItem("Studi Islam");
cb_mk.addItem("Matematika Diskrit");
cb_mk.addItem("Pendidikan Pancasila dan Kewarnegaraan");
cb_mk.addItem("Dasar-dasar Pemrograman");
cb_mk.addItem("Pengantar Teknologi Informasi dan Komunikasi");
cb_mk.setSelectedItem(null);
}else if (cb_smt.getSelectedItem().equals("Semester 2")){
cb_mk.removeAllItems();
cb_mk.addItem("Statistika Elementer");
cb_mk.addItem("Sistem Digital");
cb_mk.addItem("Praktikum Qiroah dan Ibadah");
cb_mk.addItem("Pemrograman Lanjut");
cb_mk.addItem("Kalkulus 2");
cb_mk.addItem("Islam dan Ilmu Pengetahuan");
cb_mk.addItem("Bahasa Indonesia");
cb_mk.addItem("Aljabar Linier");
cb_mk.setSelectedItem(null);
}
}catch(Exception ex) {
ex.getMessage();
}
}
public void search(String str) {
if(str.length()==0) {
sorter.setRowFilter(null);
}else {
sorter.setRowFilter(RowFilter.regexFilter(str));
}
}
#Override
public void insertUpdate(DocumentEvent e) {
search(txt_findName.getText());
}
#Override
public void removeUpdate(DocumentEvent e) {
search(txt_findName.getText());
}
#Override
public void changedUpdate(DocumentEvent e) {
search(txt_findName.getText());
}
public static void main(String[] args) {
GuiDataMhs frame = new GuiDataMhs();
frame.setTitle("Aplikasi Daftar Mahasiswa");
frame.setSize(900, 450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
above is the code, as you can see on the action event I put my data to an Array List the data will be stored until the button refresh is clicked, if it's not the data will still inside the Array List and not adding the row. the problem is after I clicked the refresh button, the data wouldn't show up. please help

how to read from text file to labels

so i have program that need save to file and then read from it, i already have read from text file that works but i cant get read from the file working, i had it static before but teacher does not like it and make me to change it to read from file. i never used gui before and the only stuff what he show us in gui is how to place a button and text field.
private DefaultListModel<String> populateFlights() { // populate avalible flights to the list
DefaultListModel<String> list = new DefaultListModel<String>();
ArrayList<Flight> FlightList = MainMenu.getAirlineMgr().getFlightList();
// loop to get flight list
for (int i = 0; i < FlightList.size(); i++) {
list.addElement(FlightList.get(i).getFlightNumber());
}
return list;
}
private void PopulateAvailableSeats(Flight flight, JComboBox<String> cb) {
Seat lSeat;
cb.removeAllItems();
for (int i = 0; i < flight.getSeats().size(); i++) {
lSeat = flight.getSeats().get(i);
if (lSeat.getSeatstatus() == Seat.Status.AVAILABLE) {
cb.addItem(lSeat.getSeatNo());
}
}
}
private Double CalculateTotalCost(Flight flight, int discount, Boolean suitCase) {
Double total;
total = flight.getCost() - ((discount * flight.getCost()) / 100); // discount
if (suitCase) { // if statement to add suitcase if applyed
total = total + 50;
}
return total;
}
private void ConfirmBooking(Flight flight, Passenger passenger, String seatNumber, Boolean suitCase) {
Double totalCost = CalculateTotalCost(flight, passenger.getDiscount(), suitCase);
Seat lSeat = flight.getSeatByNumber(seatNumber);
// Assign the Passenger to Seat and change StatusSeat to RESERVED/booked
passenger.setSeatNo(lSeat.getSeatNo());
lSeat.setPassenger(passenger);
lSeat.setSeatstatus(Seat.Status.RESERVED);
// Create a booking
Book booking = new Book(passenger);
booking.setFlightToBook(flight);
booking.setSeat(lSeat);
booking.setSuitCase(suitCase);
booking.setTotalCost(totalCost);
// Assign booking to the passenger
passenger.setReservation(booking);
// Displays save dialog
try {
booking.SaveTicket();
} catch (IOException ioe) {
JOptionPane.showMessageDialog(null, "File Error");
}
}
private Boolean ValidateBooking(Flight flight) {
return (flight.getFlightStatus() == Flight.Status.AVAILABLE)
|| (flight.getFlightStatus() == Flight.Status.CHECKING);
}
public BookPanel() {
setBackground(new Color(176, 224, 230));
setLayout(null);
JLabel label = new JLabel("Departure Date:");
label.setBounds(10, 58, 112, 14);
add(label);
JLabel lblSelectAFlight = new JLabel("Select a flight:");
lblSelectAFlight.setFont(new Font("Tahoma", Font.BOLD, 11));
lblSelectAFlight.setBounds(10, 306, 121, 14);
add(lblSelectAFlight);
JLabel label_2 = new JLabel("Departure Airport:");
label_2.setBounds(10, 9, 112, 14);
add(label_2);
JLabel label_3 = new JLabel("Arrival Airport:");
label_3.setBounds(218, 9, 112, 14);
add(label_3);
JLabel label_4 = new JLabel("Arrival Date:");
label_4.setBounds(218, 58, 112, 14);
add(label_4);
JLabel lblFlightStatus1 = new JLabel("Flight Status:");
lblFlightStatus1.setBounds(10, 108, 99, 14);
add(lblFlightStatus1);
JLabel lbDepartureAirport = new JLabel("");
lbDepartureAirport.setForeground(Color.GREEN);
lbDepartureAirport.setBackground(Color.ORANGE);
lbDepartureAirport.setBounds(10, 33, 121, 14);
add(lbDepartureAirport);
JLabel lbDepartureDate = new JLabel("");
lbDepartureDate.setForeground(Color.GREEN);
lbDepartureDate.setBackground(Color.ORANGE);
lbDepartureDate.setBounds(10, 83, 183, 14);
add(lbDepartureDate);
JLabel lbArrivalAirport = new JLabel("");
lbArrivalAirport.setForeground(Color.MAGENTA);
lbArrivalAirport.setBackground(Color.ORANGE);
lbArrivalAirport.setBounds(218, 34, 121, 13);
add(lbArrivalAirport);
JLabel lbArrivalDate = new JLabel("");
lbArrivalDate.setForeground(Color.MAGENTA);
lbArrivalDate.setBackground(Color.ORANGE);
lbArrivalDate.setBounds(218, 83, 183, 14);
add(lbArrivalDate);
JLabel lblFlightStatus = new JLabel("");
lblFlightStatus
.setFont(lblFlightStatus.getFont().deriveFont(lblFlightStatus.getFont().getStyle() | Font.BOLD, 13f));
lblFlightStatus.setForeground(Color.BLACK);
lblFlightStatus.setBackground(Color.ORANGE);
lblFlightStatus.setBounds(10, 133, 99, 23);
add(lblFlightStatus);
JLabel lblPassengerInfo = new JLabel("Passenger info:");
lblPassengerInfo.setFont(new Font("Tahoma", Font.BOLD, 11));
lblPassengerInfo.setBounds(10, 167, 99, 14);
add(lblPassengerInfo);
JLabel lblName = new JLabel("Name:");
lblName.setBounds(10, 192, 69, 14);
add(lblName);
JLabel lbPassengerName = new JLabel("");
lbPassengerName.setFont(new Font("Tahoma", Font.BOLD, 12));
lbPassengerName.setBackground(Color.WHITE);
lbPassengerName.setBounds(99, 192, 187, 14);
add(lbPassengerName);
JLabel lbSureName = new JLabel("");
lbSureName.setFont(new Font("Tahoma", Font.BOLD, 12));
lbSureName.setBackground(Color.WHITE);
lbSureName.setBounds(99, 212, 187, 14);
add(lbSureName);
JLabel lblSureName = new JLabel("Sure Name:");
lblSureName.setBounds(10, 212, 73, 14);
add(lblSureName);
JLabel lblDiscount1 = new JLabel("Discount:");
lblDiscount1.setBounds(342, 182, 59, 14);
add(lblDiscount1);
JLabel lblDiscount = new JLabel("");
lblDiscount.setFont(new Font("Tahoma", Font.BOLD, 12));
lblDiscount.setBounds(342, 212, 59, 14);
add(lblDiscount);
JLabel lblCost = new JLabel("Cost:");
lblCost.setBounds(342, 133, 37, 14);
add(lblCost);
JSeparator separator = new JSeparator();
separator.setBounds(449, 144, 1, 2);
add(separator);
JSeparator separator_1 = new JSeparator();
separator_1.setOrientation(SwingConstants.VERTICAL);
separator_1.setBounds(412, 9, 13, 393);
add(separator_1);
JLabel lblType = new JLabel("Type:");
lblType.setBounds(10, 233, 73, 14);
add(lblType);
JLabel lbType = new JLabel("");
lbType.setFont(new Font("Tahoma", Font.BOLD, 12));
lbType.setBounds(103, 233, 187, 14);
add(lbType);
JComboBox<String> cbSeats = new JComboBox<String>();
cbSeats.setBounds(289, 313, 112, 20);
add(cbSeats);
JLabel lblAvailableSeats = new JLabel("Available seats:");
lblAvailableSeats.setBounds(196, 316, 112, 14);
add(lblAvailableSeats);
JLabel lbCost = new JLabel("");
lbCost.setFont(new Font("Tahoma", Font.BOLD, 12));
lbCost.setBounds(342, 157, 59, 14);
add(lbCost);
JLabel lblTotalCost1 = new JLabel("Total Cost:");
lblTotalCost1.setBounds(342, 233, 69, 14);
add(lblTotalCost1);
JLabel lblTotalCost = new JLabel("");
lblTotalCost.setFont(new Font("Tahoma", Font.BOLD, 14));
lblTotalCost.setBounds(328, 258, 73, 23);
add(lblTotalCost);
// Action for CheckBox
JCheckBox chckbxNewCheckBox = new JCheckBox("Suite case (+$50)");
chckbxNewCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
lblTotalCost.setText(Double.toString(
CalculateTotalCost(flightSelected, passenger.getDiscount(), chckbxNewCheckBox.isSelected()))
+ "$");
}
});
chckbxNewCheckBox.setBounds(180, 272, 142, 23);
add(chckbxNewCheckBox);
// Action for button cancel
JButton button = new JButton("Cancel");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
MainMenu.hideBook();
}
});
button.setBounds(10, 379, 89, 23);
add(button);
// Action for button confirm
JButton btnPay = new JButton("Confirm");
btnPay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (ValidateBooking(flightSelected)) {
ConfirmBooking(flightSelected, passenger, cbSeats.getSelectedItem().toString(),
chckbxNewCheckBox.isSelected());
// JOptionPane.showMessageDialog(null,
// directory.getAbsolutePath()));
MainMenu.hideBook();
} else {
JOptionPane.showMessageDialog(null, "The flight is not available");
}
}
});
btnPay.setBounds(312, 379, 89, 23);
add(btnPay);
// passenger info
passenger = MainMenu.getAirlineMgr().getPassenger();
if (passenger != null) {
lbPassengerName.setText(passenger.getFname());
lbSureName.setText(passenger.getSname());
lblDiscount.setText(Integer.toString(passenger.getDiscount()) + "%");
if (passenger.getClass() == Business.class) {
lbType.setText("BUSINESS");
} else {
if (passenger.getClass() == Ordinary.class) {
lbType.setText("ORDINARY");
} else {
if (passenger.getClass() == Island.class) {
lbType.setText("ISLAND");
}
}
}
}
// flight info
JList list = new JList(populateFlights());
list.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
flightSelected = MainMenu.getAirlineMgr().getFlightByNumber(list.getSelectedValue().toString());
lbDepartureAirport.setText(flightSelected.getDepartureAirport());
lbArrivalAirport.setText(flightSelected.getArrivalAirport());
lbDepartureDate.setText(flightSelected.getDepartureDate().toString());
lbArrivalDate.setText(flightSelected.getArrivalDate().toString());
lbCost.setText(Double.toString(flightSelected.getCost()) + "£");
PopulateAvailableSeats(flightSelected, cbSeats);
lblTotalCost.setText(Double.toString(
CalculateTotalCost(flightSelected, passenger.getDiscount(), chckbxNewCheckBox.isSelected()))
+ "£");
// if statement for STATUS
if (flightSelected.getFlightStatus() == Flight.Status.AVAILABLE) {
lblFlightStatus.setText("AVAILABLE");
} else {
if (flightSelected.getFlightStatus() == Flight.Status.BOARDING) {
lblFlightStatus.setText("BOARDING");
} else {
if (flightSelected.getFlightStatus() == Flight.Status.CHECKING) {
lblFlightStatus.setText("CHECKING");
} else {
if (flightSelected.getFlightStatus() == Flight.Status.CLOSED) {
lblFlightStatus.setText("CLOSED");
}
}
}
}
}
});
list.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
list.setBounds(104, 314, 89, 88);
add(list);
JLabel lblBookAFlight = new JLabel("Book a Flight");
lblBookAFlight.setFont(new Font("Tele-Marines", Font.PLAIN, 12));
lblBookAFlight.setBounds(140, 142, 81, 14);
add(lblBookAFlight);
}
}
oh yeah if this help here is save to the file code:pic of save to file

java.sql.SQLSyntaxErrorException: Table/View 'CUSTOMER' does not exist

I have a prog that takes input from jframe and tries to store that data into a derby embedded database. I have tried to run a simple insert statement to test the database and it gives me the "java.sql.SQLSyntaxErrorException: Table/View 'CUSTOMER' does not exist." Error. What am I doing wrong?`
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Label;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTabbedPane;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.ButtonGroup;
import javax.swing.JComboBox;
import javax.swing.JRadioButton;
import java.awt.Button;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JList;
import java.awt.List;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSetMetaData;
public class Auto extends javax.swing.JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = -5777093322764526515L;
private JPanel contentPane;
private JTextField f_name;
private JTextField l_name;
private JTextField f_name2;
private JTextField l_name2;
private JTextField Age;
private JTextField issuing;
private JTextField liscense_num;
private JTextField rental;
private JTextField return_d;
private JTextField total;
private JTextField Age2;
private JTextField issuing2;
private JTextField liscense_num2;
private JTextField rental2;
private JTextField return_d2;
private JTextField total2;
private JTextField agreement_id;
private Button Submit_button;
private Button Clear_button;
private JButton load_button;
private Button Update_button;
private Button return_car;
private JComboBox<?> car_select, car_select2;
private JRadioButton cc_button;
private JRadioButton cc_button2;
private JRadioButton debit_button;
private JRadioButton debit_button2;
private static String url;
private static Connection myConnection;
private static Statement myStatement;
/**
* Launch the application.
*/
public static void main(String[] args) throws SQLException, ClassNotFoundException {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
url = "jdbc:derby:MyDB;create=true";
myConnection = DriverManager.getConnection(url);
myStatement = myConnection.createStatement( );
Auto frame = new Auto();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Auto() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 694, 497);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JTabbedPane Auto_Pane = new JTabbedPane(JTabbedPane.TOP);
Auto_Pane.setBounds(5, 5, 422, 432);
contentPane.add(Auto_Pane);
JPanel New_rent = new JPanel();
Auto_Pane.addTab("New Rental", null, New_rent, null);
New_rent.setLayout(null);
JLabel first_name = new JLabel("First Name: ");
first_name.setBounds(12, 8, 84, 16);
New_rent.add(first_name);
f_name = new JTextField(15);
f_name.setBounds(97, 5, 116, 22);
New_rent.add(f_name);
f_name.setColumns(10);
l_name = new JTextField(15);
l_name.setBounds(97, 40, 116, 22);
l_name.setColumns(10);
New_rent.add(l_name);
JLabel last_name = new JLabel("Last Name: ");
last_name.setBounds(12, 43, 84, 16);
New_rent.add(last_name);
JLabel age = new JLabel("Age: ");
age.setBounds(12, 76, 84, 16);
New_rent.add(age);
Age = new JTextField(2);
Age.setBounds(97, 75, 35, 22);
Age.setColumns(10);
New_rent.add(Age);
JLabel liscense = new JLabel("License #: ");
liscense.setBounds(12, 113, 84, 16);
New_rent.add(liscense);
JLabel issuing_st = new JLabel("Issuing State: ");
issuing_st.setBounds(12, 146, 84, 16);
New_rent.add(issuing_st);
issuing = new JTextField(2);
issuing.setBounds(97, 143, 116, 22);
issuing.setColumns(10);
New_rent.add(issuing);
liscense_num = new JTextField(13);
liscense_num.setBounds(97, 110, 116, 22);
liscense_num.setColumns(10);
New_rent.add(liscense_num);
String[] carStrings = { "Compact", "Midsized", "Standard", "Full Size", "SUV", "Mini Van" };
car_select = new JComboBox<Object>(carStrings);
car_select.setBounds(97, 178, 112, 22);
New_rent.add(car_select);
JLabel car_type = new JLabel("Car Type:");
car_type.setBounds(12, 181, 84, 16);
New_rent.add(car_type);
JLabel rent_date = new JLabel("Rental Date:");
rent_date.setBounds(12, 216, 84, 16);
New_rent.add(rent_date);
rental = new JTextField(10);
rental.setBounds(97, 213, 116, 22);
rental.setColumns(10);
New_rent.add(rental);
JLabel return_date = new JLabel("Return Date:");
return_date.setBounds(12, 251, 84, 16);
New_rent.add(return_date);
return_d = new JTextField(10);
return_d.setBounds(97, 248, 116, 22);
return_d.setColumns(10);
New_rent.add(return_d);
JLabel total_num = new JLabel("Total:");
total_num.setBounds(12, 283, 84, 16);
New_rent.add(total_num);
total = new JTextField(7);
total.setBounds(97, 280, 116, 22);
total.setColumns(10);
New_rent.add(total);
JLabel payment_type = new JLabel("Payment Type:");
payment_type.setBounds(12, 317, 100, 16);
New_rent.add(payment_type);
cc_button = new JRadioButton("Credit Card");
cc_button.setBounds(128, 313, 127, 25);
New_rent.add(cc_button);
debit_button = new JRadioButton("Debit");
debit_button.setBounds(259, 313, 127, 25);
New_rent.add(debit_button);
ButtonGroup group = new ButtonGroup();
group.add(debit_button);
group.add(cc_button);
Submit_button = new Button("Submit");
Submit_button.setBounds(12, 356, 99, 24);
Submit_button.addActionListener(this);
New_rent.add(Submit_button);
Clear_button = new Button("Clear Form");
Clear_button.setBounds(128, 356, 99, 24);
Clear_button.addActionListener(this);
New_rent.add(Clear_button);
JPanel Current_rent = new JPanel();
Auto_Pane.addTab("Current Rental", null, Current_rent, null);
Current_rent.setLayout(null);
load_button = new JButton("Load Current Rental Agreements");
load_button.addActionListener(this);
load_button.setBounds(12, 13, 393, 25);
Current_rent.add(load_button);
List load_list = new List();
load_list.setBounds(12, 54, 393, 229);
Current_rent.add(load_list);
JPanel Rental_ret = new JPanel();
Auto_Pane.addTab("Rental Details", null, Rental_ret, null);
Rental_ret.setLayout(null);
JLabel first_name2 = new JLabel("First Name: ");
first_name2.setBounds(15, 48, 71, 16);
Rental_ret.add(first_name2);
f_name2 = new JTextField(15);
f_name2.setBounds(109, 45, 116, 22);
Rental_ret.add(f_name2);
f_name2.setColumns(10);
l_name2 = new JTextField(15);
l_name2.setBounds(109, 74, 116, 22);
l_name2.setColumns(10);
Rental_ret.add(l_name2);
JLabel last_name2 = new JLabel("Last Name: ");
last_name2.setBounds(15, 77, 69, 16);
Rental_ret.add(last_name2);
Age2 = new JTextField(2);
Age2.setBounds(109, 109, 116, 22);
Age2.setColumns(10);
Rental_ret.add(Age2);
JLabel liscense2 = new JLabel("License #: ");
liscense2.setBounds(15, 141, 64, 16);
Rental_ret.add(liscense2);
JLabel issuing_st2 = new JLabel("Issuing State: ");
issuing_st2.setBounds(15, 170, 83, 16);
Rental_ret.add(issuing_st2);
issuing2 = new JTextField(2);
issuing2.setBounds(109, 167, 116, 22);
issuing2.setColumns(10);
Rental_ret.add(issuing2);
liscense_num2 = new JTextField(13);
liscense_num2.setBounds(109, 138, 116, 22);
liscense_num2.setColumns(10);
Rental_ret.add(liscense_num2);
car_select2 = new JComboBox<Object>(carStrings);
car_select2.setBounds(109, 197, 116, 22);
Rental_ret.add(car_select2);
JLabel car_type2 = new JLabel("Car Type:");
car_type2.setBounds(15, 199, 57, 16);
Rental_ret.add(car_type2);
JLabel rent_date2 = new JLabel("Rental Date:");
rent_date2.setBounds(15, 234, 71, 16);
Rental_ret.add(rent_date2);
JTextField rental2 = new JTextField(10);
rental2.setBounds(109, 231, 116, 22);
rental2.setColumns(10);
Rental_ret.add(rental2);
JLabel return_date2 = new JLabel("Return Date:");
return_date2.setBounds(15, 269, 73, 16);
Rental_ret.add(return_date2);
JTextField return_d2 = new JTextField(10);
return_d2.setColumns(10);
return_d2.setBounds(109, 266, 116, 22);
Rental_ret.add(return_d2);
JLabel total_num2 = new JLabel("Total:");
total_num2.setBounds(15, 298, 34, 16);
Rental_ret.add(total_num2);
JTextField total2 = new JTextField(7);
total2.setColumns(10);
total2.setBounds(109, 295, 116, 22);
Rental_ret.add(total2);
JLabel payment_type2 = new JLabel("Payment Type:");
payment_type2.setBounds(15, 332, 86, 16);
Rental_ret.add(payment_type2);
cc_button2 = new JRadioButton("Credit Card");
cc_button2.setBounds(109, 328, 93, 25);
Rental_ret.add(cc_button2);
debit_button2 = new JRadioButton("Debit");
debit_button2.setBounds(220, 326, 57, 25);
Rental_ret.add(debit_button2);
ButtonGroup group2 = new ButtonGroup();
group2.add(debit_button);
group2.add(cc_button);
JLabel age2 = new JLabel("Age: ");
age2.setBounds(15, 112, 31, 16);
Rental_ret.add(age2);
Update_button = new Button("Update");
Update_button.setBounds(15, 368, 83, 24);
Rental_ret.add(Update_button);
Update_button.addActionListener(this);
JLabel Agreement = new JLabel("Agreement ID: ");
Agreement.setBounds(15, 13, 93, 16);
Rental_ret.add(Agreement);
agreement_id = new JTextField();
agreement_id.setColumns(10);
agreement_id.setBounds(109, 10, 116, 22);
Rental_ret.add(agreement_id);
return_car = new Button("Return Car");
return_car.setBounds(109, 368, 83, 24);
Rental_ret.add(return_car);
return_car.addActionListener(this);
}
public void actionPerformed(ActionEvent action) {
if(action.getSource() == Submit_button){
try {
myStatement.executeUpdate("INSERT INTO Customer (FNAME, LNAME, AGE, LICNUM, STATE, CAR_TYPE, RENTDATE, RETURNDATE, TOTAL, PAYTYPE, RETURNED) VALUES('chen','lee', 40,'S633-433-83-400-0', 'FL', 'C', '2016-04-07', '2016-04-10', 213.47, 'Credit', true)");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(action.getSource() == load_button);
if(action.getSource() == Clear_button);
if(action.getSource() == return_car);
if(action.getSource() == Update_button);
}
}
You need to have the Customers table on your database. Your code insert but don't create the table.
Is necessary to create the table by your code or directly in your DBMS.
Example:
try {
c = DriverManager.getConnection("jdbc...", "user", "pass");
String com = "CREATE TABLE Customers(col1 VARCHAR(20) PRIMARY KEY, coln VARCHAR(50) NOT NULL);";
PreparedStatement st = c.prepareStatement(com);
st.execute();
st.close();
System.out.println("OK!");
}
catch (Exception e) {
e.printStackTrace();
}
Where c is a Connection.
OK I have the Table created under APP. But My INSERT statement does not work, even though the format is correct and query for create table worked from program. The Submit button has action listener so that's not the problem. Why is this statement not working?
try {
myStatement.execute("create table Customer (AgreementID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY(START WITH 1000, INCREMENT BY 1), "
+ "FNAME VARCHAR(25) NOT NULL, LNAME VARCHAR(25) NOT NULL, AGE INTEGER NOT NULL, "
+ "LICNUM VARCHAR(20) NOT NULL, STATE VARCHAR(2) NOT NULL, "
+ "CAR_TYPE VARCHAR(12) NOT NULL, RENTDATE VARCHAR(25) NOT NULL, RETURNDATE VARCHAR(25) NOT NULL, TOTAL DECIMAL(7,2) NOT NULL, "
+ "PAYTYPE VARCHAR(20) NOT NULL, RETURNED BOOLEAN, constraint customer_id_pk primary key (AgreementID))");
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
myStatement.execute("create table Customer (AgreementID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY(START WITH 1000, INCREMENT BY 1), "
+ "FNAME VARCHAR(25) NOT NULL, LNAME VARCHAR(25) NOT NULL, AGE INTEGER NOT NULL, "
+ "LICNUM VARCHAR(20) NOT NULL, STATE VARCHAR(2) NOT NULL, "
+ "CAR_TYPE VARCHAR(12) NOT NULL, RENTDATE VARCHAR(25) NOT NULL, RETURNDATE VARCHAR(25) NOT NULL, TOTAL DECIMAL(7,2) NOT NULL, "
+ "PAYTYPE VARCHAR(20) NOT NULL, RETURNED BOOLEAN, constraint customer_id_pk primary key (AgreementID))");
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

Inheriting from a JFrame class to another class and using the variables

I'm new in java, and I'm working on a program using GUI. My problem is that I'm reaching 1000 Line and this is stressful because all my code are in one file. I'm not liking this. So I research the internet about Inheritance. However, I'm not sure how this can help me in my problem because all what I know about Inheritance that Inherit everything in the parent class. However, when I try to use a variables in the child class I can't for example let say that I have in the parent class something like this:
JButton getButton = new JButton("Enter");
now when I go to the child class. I want to Inherit and use this variable so I can use the ActionListener it's not working.
So could any tell me what I'm I doing wrong here, or this not the right way to do it ?
Thank you everyone before and after.
Here is some of my code:
public class H_Store extends JFrame {
private JCheckBox groundMeatCheckBox;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
H_Store frame = new H_Store();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public H_Store() {
super("Hussin Store");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1378, 657);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenu mnHelp = new JMenu("Help");
menuBar.add(mnHelp);
mainPane = new JPanel();
mainPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(mainPane);
mainPane.setLayout(new GridLayout(0, 2, 0, 0));
JPanel meetPanel = new JPanel();
meetPanel.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
mainPane.add(meetPanel);
JLabel meatLabel = new JLabel("*Meat*");
meatLabel.setBounds(546, 101, 79, 77);
meatLabel.setHorizontalAlignment(SwingConstants.LEFT);
meatLabel.setFont(new Font("Times New Roman", Font.PLAIN, 25));
///////////////////
JCheckBox groundMeatCheckBox = new JCheckBox("Ground ");
groundMeatCheckBox.setBounds(8, 71, 113, 25);
groundMeatCheckBox.setVerticalAlignment(SwingConstants.BOTTOM);
groundMeatCheckBox.setHorizontalAlignment(SwingConstants.LEFT);
meetPanel.setLayout(null);
meetPanel.add(meatLabel);
meetPanel.add(groundMeatCheckBox);
JCheckBox chuckMeatCheckBox = new JCheckBox("Chuck");
chuckMeatCheckBox.setBounds(8, 126, 113, 25);
meetPanel.add(chuckMeatCheckBox);
JCheckBox ribMeatCheckBox = new JCheckBox("Rib");
ribMeatCheckBox.setBounds(8, 101, 113, 25);
meetPanel.add(ribMeatCheckBox);
JCheckBox steakMeatCheckBox = new JCheckBox("Steak");
steakMeatCheckBox.setBounds(8, 153, 120, 25);
meetPanel.add(steakMeatCheckBox);
JCheckBox flankMeatCheckBox = new JCheckBox("Flank");
flankMeatCheckBox.setBounds(8, 183, 113, 25);
meetPanel.add(flankMeatCheckBox);
JCheckBox roundMeatCheckBox = new JCheckBox("Round");
roundMeatCheckBox.setBounds(8, 213, 113, 25);
meetPanel.add(roundMeatCheckBox);
ground_M_QTextField = new JTextField(10);
ground_M_QTextField.setText("0");
ground_M_QTextField.setBounds(155, 76, 18, 16);
meetPanel.add(ground_M_QTextField);
ground_M_QTextField.setColumns(10);
chuck_M_QTextField = new JTextField();
chuck_M_QTextField.setText("0");
chuck_M_QTextField.setColumns(10);
chuck_M_QTextField.setBounds(155, 105, 18, 16);
meetPanel.add(chuck_M_QTextField);
rib_M_QTextField = new JTextField();
rib_M_QTextField.setText("0");
rib_M_QTextField.setColumns(10);
rib_M_QTextField.setBounds(155, 130, 18, 16);
meetPanel.add(rib_M_QTextField);
steak_M_QTextField = new JTextField();
steak_M_QTextField.setText("0");
steak_M_QTextField.setColumns(10);
steak_M_QTextField.setBounds(155, 157, 18, 16);
meetPanel.add(steak_M_QTextField);
flank_M_QTextField = new JTextField();
flank_M_QTextField.setText("0");
flank_M_QTextField.setColumns(10);
flank_M_QTextField.setBounds(155, 187, 18, 16);
meetPanel.add(flank_M_QTextField);
round_M_QTextField = new JTextField();
round_M_QTextField.setText("0");
round_M_QTextField.setColumns(10);
round_M_QTextField.setBounds(155, 217, 18, 16);
meetPanel.add(round_M_QTextField);
JLabel lblType = new JLabel("Type:");
lblType.setFont(new Font("Tahoma", Font.BOLD, 13));
lblType.setBounds(8, 46, 44, 16);
meetPanel.add(lblType);
JLabel lblNewLabel = new JLabel("Quantity:");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 13));
lblNewLabel.setBounds(155, 46, 61, 16);
meetPanel.add(lblNewLabel);
ground_M_WTextField = new JTextField();
ground_M_WTextField.setText("0.00");
ground_M_WTextField.setColumns(10);
ground_M_WTextField.setBounds(291, 73, 36, 16);
meetPanel.add(ground_M_WTextField);
chuck_M_WTextField = new JTextField();
chuck_M_WTextField.setText("0.00");
chuck_M_WTextField.setColumns(10);
chuck_M_WTextField.setBounds(291, 105, 36, 16);
meetPanel.add(chuck_M_WTextField);
rib_M_WTextField = new JTextField();
rib_M_WTextField.setText("0.00");
rib_M_WTextField.setColumns(10);
rib_M_WTextField.setBounds(291, 130, 36, 16);
meetPanel.add(rib_M_WTextField);
steak_M_WTextField = new JTextField();
steak_M_WTextField.setText("0.00");
steak_M_WTextField.setColumns(10);
steak_M_WTextField.setBounds(291, 157, 36, 16);
meetPanel.add(steak_M_WTextField);
flank_M_WTextField = new JTextField();
flank_M_WTextField.setText("0.00");
flank_M_WTextField.setColumns(10);
flank_M_WTextField.setBounds(291, 187, 36, 16);
meetPanel.add(flank_M_WTextField);
round_M_WTextField = new JTextField();
round_M_WTextField.setText("0.00");
round_M_WTextField.setColumns(10);
round_M_WTextField.setBounds(291, 217, 36, 16);
meetPanel.add(round_M_WTextField);
JLabel lblWeightlp = new JLabel("(LP) Weight: ");
lblWeightlp.setFont(new Font("Tahoma", Font.BOLD, 13));
lblWeightlp.setBounds(291, 46, 86, 16);
meetPanel.add(lblWeightlp);
at_M_QTextField = new JTextField();
at_M_QTextField.setText("0");
at_M_QTextField.setColumns(10);
at_M_QTextField.setBounds(155, 251, 18, 16);
meetPanel.add(at_M_QTextField);
at_M_WTextField = new JTextField();
at_M_WTextField.setText("0.00");
at_M_WTextField.setColumns(10);
at_M_WTextField.setBounds(291, 251, 36, 16);
meetPanel.add(at_M_WTextField);
at_meat_TextField = new JTextField();
at_meat_TextField.setText("Another Type..");
at_meat_TextField.setColumns(10);
at_meat_TextField.setBounds(8, 250, 98, 24);
meetPanel.add(at_meat_TextField);
lblPrice = new JLabel("(LP)Price:");
lblPrice.setFont(new Font("Tahoma", Font.BOLD, 13));
lblPrice.setBounds(446, 46, 73, 16);
meetPanel.add(lblPrice);
ground_M_PTextField = new JTextField();
ground_M_PTextField.setText("0.00");
ground_M_PTextField.setColumns(10);
ground_M_PTextField.setBounds(445, 71, 36, 16);
meetPanel.add(ground_M_PTextField);
rib_M_PTextField = new JTextField();
rib_M_PTextField.setText("0.00");
rib_M_PTextField.setColumns(10);
rib_M_PTextField.setBounds(445, 103, 36, 16);
meetPanel.add(rib_M_PTextField);
chuck_M_PTextField = new JTextField();
chuck_M_PTextField.setText("0.00");
chuck_M_PTextField.setColumns(10);
chuck_M_PTextField.setBounds(445, 128, 36, 16);
meetPanel.add(chuck_M_PTextField);
steak_M_PTextField = new JTextField();
steak_M_PTextField.setText("0.00");
steak_M_PTextField.setColumns(10);
steak_M_PTextField.setBounds(445, 155, 36, 16);
meetPanel.add(steak_M_PTextField);
flank_M_PTextField = new JTextField();
flank_M_PTextField.setText("0.00");
flank_M_PTextField.setColumns(10);
flank_M_PTextField.setBounds(445, 185, 36, 16);
meetPanel.add(flank_M_PTextField);
round_M_PTextField = new JTextField();
round_M_PTextField.setText("0.00");
round_M_PTextField.setColumns(10);
round_M_PTextField.setBounds(445, 215, 36, 16);
meetPanel.add(round_M_PTextField);
at_M_PTextField = new JTextField();
at_M_PTextField.setText("0.00");
at_M_PTextField.setColumns(10);
at_M_PTextField.setBounds(445, 249, 36, 16);
meetPanel.add(at_M_PTextField);
JPanel chikenPanel = new JPanel();
chikenPanel.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, Color.BLUE, null, null));
mainPane.add(chikenPanel);
chikenPanel.setLayout(null);
JLabel lblChiken = new JLabel("*Chiken*");
lblChiken.setBounds(543, 104, 120, 77);
lblChiken.setFont(new Font("Times New Roman", Font.PLAIN, 25));
chikenPanel.add(lblChiken);
JCheckBox whole_C_CheckBox = new JCheckBox("Whole");
whole_C_CheckBox.setVerticalAlignment(SwingConstants.BOTTOM);
whole_C_CheckBox.setHorizontalAlignment(SwingConstants.LEFT);
whole_C_CheckBox.setBounds(12, 66, 113, 25);
chikenPanel.add(whole_C_CheckBox);
JCheckBox half_C_CheckBox = new JCheckBox("Half");
half_C_CheckBox.setBounds(12, 96, 113, 25);
chikenPanel.add(half_C_CheckBox);
JCheckBox breast_C_CheckBox = new JCheckBox("Breast");
breast_C_CheckBox.setBounds(12, 126, 113, 25);
chikenPanel.add(breast_C_CheckBox);
JCheckBox wings_C_CheckBox = new JCheckBox("Wings");
wings_C_CheckBox.setBounds(12, 156, 120, 25);
chikenPanel.add(wings_C_CheckBox);
JCheckBox liver_C_CheckBox = new JCheckBox("Liver");
liver_C_CheckBox.setBounds(12, 186, 113, 25);
chikenPanel.add(liver_C_CheckBox);
JCheckBox heart_C_CheckBox = new JCheckBox("Heart");
heart_C_CheckBox.setBounds(12, 216, 113, 25);
chikenPanel.add(heart_C_CheckBox);
textField_13 = new JTextField();
textField_13.setText("0");
textField_13.setColumns(10);
textField_13.setBounds(170, 71, 25, 16);
chikenPanel.add(textField_13);
textField_14 = new JTextField();
textField_14.setText("0");
textField_14.setColumns(10);
textField_14.setBounds(170, 97, 25, 16);
chikenPanel.add(textField_14);
textField_15 = new JTextField();
textField_15.setText("0");
textField_15.setColumns(10);
textField_15.setBounds(170, 130, 25, 16);
chikenPanel.add(textField_15);
textField_16 = new JTextField();
textField_16.setText("0");
textField_16.setColumns(10);
textField_16.setBounds(170, 160, 25, 16);
chikenPanel.add(textField_16);
textField_17 = new JTextField();
textField_17.setText("0");
textField_17.setColumns(10);
textField_17.setBounds(170, 190, 25, 16);
chikenPanel.add(textField_17);
textField_18 = new JTextField();
textField_18.setText("0");
textField_18.setColumns(10);
textField_18.setBounds(170, 220, 25, 16);
chikenPanel.add(textField_18);
textField_19 = new JTextField();
textField_19.setText("0.00");
textField_19.setColumns(10);
textField_19.setBounds(320, 220, 38, 16);
chikenPanel.add(textField_19);
textField_20 = new JTextField();
textField_20.setText("0.00");
textField_20.setColumns(10);
textField_20.setBounds(320, 190, 38, 16);
chikenPanel.add(textField_20);
textField_21 = new JTextField();
textField_21.setText("0.00");
textField_21.setColumns(10);
textField_21.setBounds(320, 157, 38, 16);
chikenPanel.add(textField_21);
textField_22 = new JTextField();
textField_22.setText("0.00");
textField_22.setColumns(10);
textField_22.setBounds(320, 130, 38, 16);
chikenPanel.add(textField_22);
textField_23 = new JTextField();
textField_23.setText("0.00");
textField_23.setColumns(10);
textField_23.setBounds(320, 100, 38, 16);
chikenPanel.add(textField_23);
textField_24 = new JTextField();
textField_24.setText("0.00");
textField_24.setColumns(10);
textField_24.setBounds(320, 71, 38, 16);
chikenPanel.add(textField_24);
JLabel label = new JLabel("Type:");
label.setFont(new Font("Tahoma", Font.BOLD, 13));
label.setBounds(12, 41, 56, 16);
chikenPanel.add(label);
JLabel label_1 = new JLabel("Quantity:");
label_1.setFont(new Font("Tahoma", Font.BOLD, 13));
label_1.setBounds(170, 41, 75, 16);
chikenPanel.add(label_1);
JLabel label_2 = new JLabel("(LP) Weight: ");
label_2.setFont(new Font("Tahoma", Font.BOLD, 13));
label_2.setBounds(320, 41, 92, 16);
chikenPanel.add(label_2);
textField_12 = new JTextField();
textField_12.setText("Another Type..");
textField_12.setColumns(10);
textField_12.setBounds(12, 250, 99, 24);
chikenPanel.add(textField_12);
textField_34 = new JTextField();
textField_34.setText("0");
textField_34.setColumns(10);
textField_34.setBounds(170, 251, 25, 16);
chikenPanel.add(textField_34);
textField_35 = new JTextField();
textField_35.setText("0.00");
textField_35.setColumns(10);
textField_35.setBounds(320, 251, 38, 16);
chikenPanel.add(textField_35);
label_5 = new JLabel("Price:");
label_5.setFont(new Font("Tahoma", Font.BOLD, 13));
label_5.setBounds(477, 41, 43, 16);
chikenPanel.add(label_5);
textField_7 = new JTextField();
textField_7.setText("0.00");
textField_7.setColumns(10);
textField_7.setBounds(477, 71, 36, 16);
chikenPanel.add(textField_7);
textField_8 = new JTextField();
textField_8.setText("0.00");
textField_8.setColumns(10);
textField_8.setBounds(477, 100, 36, 16);
chikenPanel.add(textField_8);
textField_9 = new JTextField();
textField_9.setText("0.00");
textField_9.setColumns(10);
textField_9.setBounds(476, 130, 36, 16);
chikenPanel.add(textField_9);
textField_10 = new JTextField();
textField_10.setText("0.00");
textField_10.setColumns(10);
textField_10.setBounds(476, 160, 36, 16);
chikenPanel.add(textField_10);
textField_11 = new JTextField();
textField_11.setText("0.00");
textField_11.setColumns(10);
textField_11.setBounds(477, 190, 36, 16);
chikenPanel.add(textField_11);
textField_25 = new JTextField();
textField_25.setText("0.00");
textField_25.setColumns(10);
textField_25.setBounds(477, 220, 36, 16);
chikenPanel.add(textField_25);
textField_32 = new JTextField();
textField_32.setText("0.00");
textField_32.setColumns(10);
textField_32.setBounds(477, 254, 36, 16);
chikenPanel.add(textField_32);
JPanel otherThingsPanel = new JPanel();
otherThingsPanel.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
mainPane.add(otherThingsPanel);
otherThingsPanel.setLayout(null);
JLabel lblOtherThings = new JLabel("*Other Things*");
lblOtherThings.setBounds(421, 117, 176, 42);
lblOtherThings.setFont(new Font("Tahoma", Font.PLAIN, 25));
otherThingsPanel.add(lblOtherThings);
JLabel label_3 = new JLabel("Type:");
label_3.setFont(new Font("Tahoma", Font.BOLD, 13));
label_3.setBounds(16, 46, 65, 16);
otherThingsPanel.add(label_3);
JCheckBox chckbxCheese = new JCheckBox("Cheese");
chckbxCheese.setVerticalAlignment(SwingConstants.BOTTOM);
chckbxCheese.setHorizontalAlignment(SwingConstants.LEFT);
chckbxCheese.setBounds(12, 71, 113, 25);
otherThingsPanel.add(chckbxCheese);
JCheckBox chckbxBread = new JCheckBox("Bread");
chckbxBread.setBounds(12, 101, 113, 25);
otherThingsPanel.add(chckbxBread);
JCheckBox chckbxRice = new JCheckBox("Rice");
chckbxRice.setBounds(12, 131, 113, 25);
otherThingsPanel.add(chckbxRice);
JCheckBox chckbxBeefBurger = new JCheckBox("Burger ");
chckbxBeefBurger.setBounds(12, 161, 120, 25);
otherThingsPanel.add(chckbxBeefBurger);
JCheckBox chckbxChickenBurger = new JCheckBox("Kebab");
chckbxChickenBurger.setBounds(12, 191, 113, 25);
otherThingsPanel.add(chckbxChickenBurger);
JCheckBox chckbxFalafel = new JCheckBox("Falafel");
chckbxFalafel.setBounds(12, 221, 113, 25);
otherThingsPanel.add(chckbxFalafel);
textField_26 = new JTextField();
textField_26.setText("0");
textField_26.setColumns(10);
textField_26.setBounds(165, 225, 25, 16);
otherThingsPanel.add(textField_26);
textField_27 = new JTextField();
textField_27.setText("0");
textField_27.setColumns(10);
textField_27.setBounds(165, 195, 25, 16);
otherThingsPanel.add(textField_27);
textField_28 = new JTextField();
textField_28.setText("0");
textField_28.setColumns(10);
textField_28.setBounds(165, 162, 25, 16);
otherThingsPanel.add(textField_28);
textField_29 = new JTextField();
textField_29.setText("0");
textField_29.setColumns(10);
textField_29.setBounds(165, 132, 25, 16);
otherThingsPanel.add(textField_29);
textField_30 = new JTextField();
textField_30.setText("0");
textField_30.setColumns(10);
textField_30.setBounds(165, 102, 25, 16);
otherThingsPanel.add(textField_30);
textField_31 = new JTextField();
textField_31.setText("0");
textField_31.setColumns(10);
textField_31.setBounds(165, 76, 25, 16);
otherThingsPanel.add(textField_31);
JLabel label_4 = new JLabel("Quantity:");
label_4.setFont(new Font("Tahoma", Font.BOLD, 13));
label_4.setBounds(165, 46, 65, 16);
otherThingsPanel.add(label_4);
otherThings_AnotherTypeTextField = new JTextField();
otherThings_AnotherTypeTextField.setText("Another Type..");
otherThings_AnotherTypeTextField.setColumns(10);
otherThings_AnotherTypeTextField.setBounds(16, 250, 93, 24);
otherThingsPanel.add(otherThings_AnotherTypeTextField);
textField_36 = new JTextField();
textField_36.setText("0");
textField_36.setColumns(10);
textField_36.setBounds(165, 254, 25, 16);
otherThingsPanel.add(textField_36);
label_6 = new JLabel("Price:");
label_6.setFont(new Font("Tahoma", Font.BOLD, 13));
label_6.setBounds(310, 46, 56, 16);
otherThingsPanel.add(label_6);
textField_33 = new JTextField();
textField_33.setText("0.00");
textField_33.setColumns(10);
textField_33.setBounds(309, 71, 36, 16);
otherThingsPanel.add(textField_33);
textField_37 = new JTextField();
textField_37.setText("0.00");
textField_37.setColumns(10);
textField_37.setBounds(309, 103, 36, 16);
otherThingsPanel.add(textField_37);
textField_38 = new JTextField();
textField_38.setText("0.00");
textField_38.setColumns(10);
textField_38.setBounds(309, 128, 36, 16);
otherThingsPanel.add(textField_38);
textField_39 = new JTextField();
textField_39.setText("0.00");
textField_39.setColumns(10);
textField_39.setBounds(309, 155, 36, 16);
otherThingsPanel.add(textField_39);
textField_40 = new JTextField();
textField_40.setText("0.00");
textField_40.setColumns(10);
textField_40.setBounds(309, 185, 36, 16);
otherThingsPanel.add(textField_40);
textField_41 = new JTextField();
textField_41.setText("0.00");
textField_41.setColumns(10);
textField_41.setBounds(309, 215, 36, 16);
otherThingsPanel.add(textField_41);
textField_42 = new JTextField();
textField_42.setText("0.00");
textField_42.setColumns(10);
textField_42.setBounds(309, 249, 36, 16);
otherThingsPanel.add(textField_42);
JPanel calculationPanel = new JPanel();
calculationPanel.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
mainPane.add(calculationPanel);
calculationPanel.setLayout(null);
JLabel lblCalculation = new JLabel("*Calculation*");
lblCalculation.setBounds(212, 12, 148, 29);
lblCalculation.setFont(new Font("Times New Roman", Font.PLAIN, 25));
calculationPanel.add(lblCalculation);
// Calculation everything
JButton calculateButton = new JButton("Calculate");
calculateButton.addActionListener(new CalcButtonListener());
calculateButton.setFont(new Font("Tahoma", Font.PLAIN, 25));
calculateButton.setBounds(340, 177, 313, 97);
calculationPanel.add(calculateButton);
txtrWriteYourComment = new JTextArea();
txtrWriteYourComment.setRows(1);
txtrWriteYourComment.setFont(new Font("Courier New", Font.PLAIN, 12));
txtrWriteYourComment.setText("Write Your Comment here.....");
txtrWriteYourComment.setBounds(12, 54, 641, 111);
calculationPanel.add(txtrWriteYourComment);
getProfitJButton = new JButton("Get Profit");
getProfitJButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFrame frame2 = new JFrame("Profit");
frame2.setVisible(true);
frame2.setSize(350,200);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
profitPanel = new JPanel();
profitPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(profitPanel);
profitPanel.setLayout(new GridLayout(0, 2, 0, 0));
frame2.getContentPane().add(profitPanel);
profitFileButton = new JButton("Porfit File");
profitFileTextField = new JTextField();
getProfitJButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
profitJFileChooser = new JFileChooser();
profitJFileChooser.showOpenDialog(null);
File f = profitJFileChooser.getSelectedFile();
String fileName = f.getAbsolutePath();
profitFileTextField.setText(fileName);
}
});
profitPanel.add(profitFileButton);
profitPanel.add(profitFileTextField);
sellFileButtton = new JButton("Sell File");
profitPanel.add(sellFileButtton);
}
});
getProfitJButton.setFont(new Font("Tahoma", Font.PLAIN, 25));
getProfitJButton.setBounds(12, 177, 316, 97);
calculationPanel.add(getProfitJButton);
///////////////////////////////////////////
theholder holder = new theholder();
groundMeatCheckBox.addItemListener(holder);
}
private class CalcButtonListener implements ActionListener{
// vairbles for the ground Meat check box
private double total_GM;
private double weightPrice_1;
private String stringQ;
private String stringW;
private String stringP;
private int meat_Q1;
private double meat_W1;
private double meat_P1;
public void actionPerformed(ActionEvent e){
total_GM = 0;
// The ground Meat check box calculation
stringQ = ground_M_QTextField.getText();
meat_Q1 = Integer.parseInt(stringQ);
stringW = ground_M_WTextField.getText();
meat_W1 = Double.parseDouble(stringW);
stringP = ground_M_PTextField.getText();
meat_P1 = Double.parseDouble(stringP);
weightPrice_1 = meat_W1 * meat_P1;
total_GM += weightPrice_1 * meat_Q1;
JOptionPane.showMessageDialog(null, total_GM + "\n" + s);
}
}
}
What I want to do exactly is to take the last code into another class or do something with so I can use it in the Parent class, in other word any math I want outside the Parent class.
Note: I mean this code
private class CalcButtonListener implements ActionListener{
// vairbles for the ground Meat check box
private double total_GM;
private double weightPrice_1;
private String stringQ;
private String stringW;
private String stringP;
private int meat_Q1;
private double meat_W1;
private double meat_P1;
public void actionPerformed(ActionEvent e){
total_GM = 0;
// The ground Meat check box calculation
stringQ = ground_M_QTextField.getText();
meat_Q1 = Integer.parseInt(stringQ);
stringW = ground_M_WTextField.getText();
meat_W1 = Double.parseDouble(stringW);
stringP = ground_M_PTextField.getText();
meat_P1 = Double.parseDouble(stringP);
weightPrice_1 = meat_W1 * meat_P1;
total_GM += weightPrice_1 * meat_Q1;
JOptionPane.showMessageDialog(null, total_GM + "\n" + s);
}
}
You state:
My problem is that I'm reaching 1000 Line and this is stressful because all my code are in one file. I'm not liking this.
You are quite right to not like this and to try to improve this set up as this type of program will be a monster to maintain, debug and enhance..
You then state:
Inheriting from a JFrame class to another class and using the variables
This is not what inheritance is for as objects of the child class will be a completely distinct entities from objects of the parent class, so you will not want to do this.
Instead
Remember to strive to enhance by composition rather than inheritance, meaning have classes contain fields of other classes.
Avoid using the static modifier to make global-like variables as this will hog-tie your code.
try to break out logical parts of your program from the visual, the GUI parts,
And split up each specific logical part and each major GUI part into its own class.
make sure all classes have decent setter and getter methods,
and that the classes are written so that they communicate well with each other.
A Swing specific recommendation is for you to avoid extending JFrame.
Instead gear your Swing GUI's towards creating JPanels, panels which can be placed anywhere you want them, including in JFrames, JApplets, JDialogs, JOptionPanes, inside of other JPanels, in JTabbedPanes, as "cards" in a CardLayout-using JPanel,....
This will greatly improve the flexibility and enhance-ability of your program.
For more specific help, please feel free to provide more details about your program and its code.
Edit
Sorry to be blunt, but you've come for advice on your code, and I have to inform you that it has some significant problems including:
it contains more quite a bit of unnecessary redundency that makes it hard to follow and debug.
You have grids of JTextFields, all of which can and should be replaced by three JTables, one for Meat, one for Chicken, and one for "other things".
You use null layouts and absolute positioning, something that seems to a newbie an easier way to create complex GUI's, but in the long run is the most difficult way to create, maintain and upgrade these. You're far better off learning about and using the layout managers, including nesting JPanels each with its own layout.
Any time I see variables named something12, something13, something14, something15, something16, something17, something18, ... I think that most of this can be replaced by an array or a collection such as an ArrayList, or in your case (as noted above), a JTable whose model is based in a collection.
Each one of your table entries should likely be in its own class.
I stand by my original recommendation that you should not have any of your classes inherit from the main GUI as this will lead to non-workable code.
Also, your JFrame should not launch another JFrame, but rather the getProfitButton should launch a modal JDialog.
Edit
For example:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
public class TableEg extends JPanel {
private static final String[] ROW_TITLES = { "Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday" };
MyTableModel tableModel = new MyTableModel(ROW_TITLES);
private JTable table;
public TableEg() {
table = new JTable(tableModel) {
#Override
public TableCellRenderer getCellRenderer(int row, int column) {
JComponent renderer = (JComponent) super.getCellRenderer(row,
column);
boolean enabled = (Boolean) table.getValueAt(row, 0);
renderer.setEnabled(enabled);
return super.getCellRenderer(row, column);
}
};
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
super.mouseReleased(e);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
table.repaint();
}
});
}
});
JScrollPane scrollpane = new JScrollPane(table);
scrollpane.getViewport().setPreferredSize(table.getPreferredSize());
JButton getSumButton = new JButton(new GetSumAction("Get Sum", tableModel));
JPanel southPanel = new JPanel();
southPanel.add(getSumButton);
setLayout(new BorderLayout());
add(scrollpane, BorderLayout.CENTER);
add(southPanel, BorderLayout.SOUTH);
}
private static void createAndShowGui() {
TableEg mainPanel = new TableEg();
JFrame frame = new JFrame("TableEg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class MyTableModel extends DefaultTableModel {
private static final String[] COLUMN_NAMES = { "Selected", "Name", "Number" };
public MyTableModel(String[] rowTitles) {
super(COLUMN_NAMES, 0);
for (int i = 0; i < rowTitles.length; i++) {
Object[] rowData = { Boolean.FALSE, rowTitles[i], Integer.valueOf(0) };
addRow(rowData);
}
Object[] rowData = { Boolean.FALSE, "", Integer.valueOf(0) };
addRow(rowData);
}
#Override
public boolean isCellEditable(int row, int column) {
if (column == 0) {
return true;
}
if (column == 1) {
return row >= getRowCount() - 1;
}
if (column > 1) {
return ((Boolean) getValueAt(row, 0)).booleanValue();
}
return super.isCellEditable(row, column);
}
#Override
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0:
return Boolean.class;
case 1:
return String.class;
case 2:
return Integer.class;
}
return super.getColumnClass(columnIndex);
}
}
class GetSumAction extends AbstractAction {
private MyTableModel tableModel;
public GetSumAction(String name, MyTableModel tableModel) {
super(name);
this.tableModel = tableModel;
}
#Override
public void actionPerformed(ActionEvent evt) {
int sum = 0;
for (int i = 0; i < tableModel.getRowCount(); i++) {
Object value = tableModel.getValueAt(i, 2);
if (value != null) {
sum += ((Integer) value).intValue();
}
}
String text = "Number of days: " + sum;
String title = "Number of Days";
JOptionPane.showMessageDialog((JButton) evt.getSource(), text, title,
JOptionPane.INFORMATION_MESSAGE);
}
}
First of all try to divide your code into methods, that would make your code more clear.
As for inheritance, you can only modify variables that are in the parent class from the child class if those variable are :
.Data members
.Their visibility is set to protected
Here is an example
public class Parent{
protected JButton button;
protected int something;
protected String whatever;
//^Those are the data members
public Parent(){//Constructor
//some code here
}
//more code
}//end of parent class
public class Child extends Parent{
private int randomstuff;
private String morerandomDatamembers;
public Child(){
super();
}
public void modify(){
something=3;
whatever="yayyy it worked";
}
}
protected data members can only be accessed by the children of some class.
EDIT- Inheritance can be used in specific cases. You can still modify data members of some class from a different class. Every method should have getters and setters.
Example:
public class Car{
private int ModelNumber;
private String CarName;
public Car(int ModelNum,String name){
ModelNumber=ModelNum;
CarName=name;
}
public int getModelNum(){//First getter
return ModelNumber;
}
public void setModelNum(int ModelNum){//First setter
ModelNumber=ModelNum;
}
public String getCarName(){//Second getter;
return CarName;
}
public void setCarName(String Car){
CarName=Car;
}
}
public class Company{
private Car car;
public Company(Car c){
car=c;
}
public void modify(){
car.setModelNum(123);
car.setCarName("Ferrari");
System.out.println("Being so awesome,Roudy will let me try his Ferrari");
}
}

java app querying database returning nullpointerexception

I'm having a problem with my code in java. It is supposed to insert data into a database but it's returning a nullpointerexception. Here is my code.
package client;
import java.sql.*;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class AddCon {
private Connection conn;
private JFrame frmAddContract;
private JTextField ContractNo;
private JTextField EngagerName;
private JTextField contNo;
private JTextField month;
private JTextField day;
private JTextField year;
private JTextField tme;
private JTextField cladd;
private JTextField eventadd;
private JTextField textField_fp;
private JTextField refer;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddCon window = new AddCon();
window.frmAddContract.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public AddCon() {
try{
//Load database driver and connect
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/KusinaNiKambal","root","1234");
Statement stmt = null;
stmt = conn.createStatement();}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);}
/**
* Initialize the contents of the frame.
*/
initialize();
}
private void initialize() {
frmAddContract = new JFrame();
frmAddContract.setResizable(false);
frmAddContract.setTitle("Add Contract");
frmAddContract.setBounds(100, 100, 450, 640);
frmAddContract.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmAddContract.getContentPane().setLayout(null);
ContractNo = new JTextField();
ContractNo.setBounds(38, 32, 152, 20);
frmAddContract.getContentPane().add(ContractNo);
ContractNo.setColumns(10);
JLabel lblContract = new JLabel("Contract #");
lblContract.setBounds(38, 18, 76, 14);
frmAddContract.getContentPane().add(lblContract);
JLabel lblEngager = new JLabel("Engager");
lblEngager.setBounds(38, 63, 48, 14);
frmAddContract.getContentPane().add(lblEngager);
EngagerName = new JTextField();
EngagerName.setBounds(38, 78, 152, 20);
frmAddContract.getContentPane().add(EngagerName);
EngagerName.setColumns(10);
contNo = new JTextField();
contNo.setBounds(38, 128, 152, 20);
frmAddContract.getContentPane().add(contNo);
contNo.setColumns(10);
JLabel lblNewLabel = new JLabel("Contact #");
lblNewLabel.setBounds(38, 109, 86, 14);
frmAddContract.getContentPane().add(lblNewLabel);
month = new JTextField();
month.setBounds(38, 255, 116, 20);
frmAddContract.getContentPane().add(month);
day = new JTextField();
day.setBounds(181, 255, 81, 20);
frmAddContract.getContentPane().add(day);
year = new JTextField();
year.setBounds(294, 255, 86, 20);
frmAddContract.getContentPane().add(year);
year.setColumns(10);
JLabel lblMonth = new JLabel("Month in number format");
lblMonth.setBounds(38, 236, 100, 14);
frmAddContract.getContentPane().add(lblMonth);
JLabel lblDay = new JLabel("Day");
lblDay.setBounds(181, 236, 48, 14);
frmAddContract.getContentPane().add(lblDay);
JLabel lblYear = new JLabel("Year");
lblYear.setBounds(294, 236, 48, 14);
frmAddContract.getContentPane().add(lblYear);
JLabel lblEventDate = new JLabel("Event Date");
lblEventDate.setBounds(38, 222, 76, 14);
frmAddContract.getContentPane().add(lblEventDate);
tme = new JTextField();
tme.setBounds(38, 307, 59, 20);
frmAddContract.getContentPane().add(tme);
tme.setColumns(10);
cladd = new JTextField();
cladd.setBounds(38, 180, 363, 31);
frmAddContract.getContentPane().add(cladd);
cladd.setColumns(10);
JLabel lblAddress = new JLabel("Client Address");
lblAddress.setBounds(38, 159, 98, 14);
frmAddContract.getContentPane().add(lblAddress);
JLabel lblTime = new JLabel("Time");
lblTime.setBounds(38, 286, 60, 14);
frmAddContract.getContentPane().add(lblTime);
eventadd = new JTextField();
eventadd.setBounds(38, 358, 373, 50);
frmAddContract.getContentPane().add(eventadd);
eventadd.setColumns(10);
JLabel lblEventAddress = new JLabel("Event Address");
lblEventAddress.setBounds(38, 338, 116, 14);
frmAddContract.getContentPane().add(lblEventAddress);
textField_fp = new JTextField();
textField_fp.setBounds(38, 454, 276, 20);
frmAddContract.getContentPane().add(textField_fp);
textField_fp.setColumns(10);
JLabel lblFilepathOfContract = new JLabel("Filepath of Contract - the PDF file");
lblFilepathOfContract.setBounds(38, 431, 116, 14);
frmAddContract.getContentPane().add(lblFilepathOfContract);
JButton btnBrowse = new JButton("Browse...");
btnBrowse.setBounds(324, 453, 89, 23);
frmAddContract.getContentPane().add(btnBrowse);
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
final JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
String filepath = fc.getSelectedFile().getAbsolutePath();
textField_fp.setText(filepath);
}
});
refer = new JTextField();
refer.setBounds(38, 510, 276, 20);
frmAddContract.getContentPane().add(refer);
refer.setColumns(10);
JLabel lblEncodedBy = new JLabel("Referred By");
lblEncodedBy.setBounds(38, 485, 116, 14);
frmAddContract.getContentPane().add(lblEncodedBy);
JButton btnAdd = new JButton("Add");
btnAdd.setBounds(101, 560, 89, 23);
frmAddContract.getContentPane().add(btnAdd);
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try{
String cntr = ContractNo.getText();
String en = EngagerName.getText();
String cont = contNo.getText();
String mo = month.getText();
String d = day.getText();
String yr = year.getText();
String dte = yr + "-" + mo + "-" + d;
String cla = cladd.getText();
String tm = tme.getText() + ":00";
String evadd = eventadd.getText();
String filepath = textField_fp.getText();
String ref = refer.getText();
String SQL = "insert into cis "+
"values ('"+cntr+"','"+en+"','"+
cont+"','"+cla+"' '"+dte+"','"+tm+"','"+
evadd+"','"+filepath+"','"+ref+")";
PreparedStatement stmt = conn.prepareStatement(SQL);
ResultSet rs = stmt.executeQuery();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
});
JButton btnCancel = new JButton("Cancel");
btnCancel.setBounds(225, 560, 89, 23);
frmAddContract.getContentPane().add(btnCancel);
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
frmAddContract.setVisible(false);
}
});
}
}
Sorry, i'm not really that experienced in java programming and this is my first time making a code for querying databases.
You do never initialize your conn instance variable. This will lead to a NullPointerException (at least) in this line:
PreparedStatement stmt = conn.prepareStatement(SQL);
^------------ NEVER INITIALIZED
public class AddCon {
private Connection conn;
...
// constructor
public AddCon() {
try{
//Load database driver and connect
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(<your parameters>);
^----------- MISTAKE
...
In the above code you create a connection, but instead of assigning it to the instance variable you just use a local variable. Replace that line with:
this.conn = DriverManager.getConnection(<your parameters>);
Edit: Please always post the stacktrace in case of exceptions!

Categories