Related
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
I am trying to come up with a simple tool that takes DB Parameters as input from the user in JTextFields and when the user clicks on connect to DB, it uses the input to connect to DB. The UI part is written in a function in the main class from where it is supposed to call the DBConnector class method and pass the input text parameters via the ActionListener. I cannot seem to make the ActionListener part work at all. Here's the main class code below:
public class ExcelReportGenerator implements DocumentListener{
//MAIN METHOD
public static void main(String[] args) {
try {
createAndShowUI();
} catch (Exception e) {
e.printStackTrace();
}
}
public ExcelReportGenerator(JButton button1, JButton button2)
{
button1=this.button1;
button2=this.button2;
}
private JButton button1 ;
private JButton button2;
private List<JTextField> textFields = new ArrayList<JTextField>();
//public void DBCaller()
public void addTextField(JTextField textField)
{
textFields.add( textField );
textField.getDocument().addDocumentListener( this );
}
public boolean isDataEntered()
{
for (JTextField textField : textFields)
{
if (textField.getText().trim().length() == 0)
return false;
}
return true;
}
#Override
public void insertUpdate(DocumentEvent e)
{
checkData();
}
#Override
public void removeUpdate(DocumentEvent e)
{
checkData();
}
#Override
public void changedUpdate(DocumentEvent e) {}
private void checkData()
{
button1.setEnabled( isDataEntered() );
button2.setEnabled( isDataEntered() );
}
private static void createAndShowUI() throws RowsExceededException, ClassNotFoundException, WriteException, SQLException, IOException
{
//CREATING BUTTONS
JButton submit = new JButton( "Connect To DB" );
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
DBConnector.DBConnection(textField_1.getText(),textField_2.getText(),
textField_3.getText(),textField_4.getText(),textField_5.getText());
//NEED TO ACCESS THE DBCONNECTOR CLASS METHOD HERE
}
});
submit.setEnabled(false);
submit.setBackground(UIManager.getColor("Button.disabledShadow"));
submit.setForeground(new Color(0, 0, 128));
submit.setBounds(282, 77, 192, 36);
JButton btnExportToExcel = new JButton("Export To Excel");
btnExportToExcel.setEnabled(false);
btnExportToExcel.setForeground(new Color(0, 0, 128));
btnExportToExcel.setBackground(UIManager.getColor("Button.background"));
submit.setBackground(UIManager.getColor("Button.disabledShadow"));
btnExportToExcel.setBounds(282, 178, 192, 36);
//DECLARING TEXTFIELDS
JTextField textField_1 = new JTextField();
textField_1.setBackground(new Color(255, 255, 224));
JTextField textField_2 = new JTextField();
textField_2.setBackground(new Color(255, 255, 224));
JTextField textField_3 = new JTextField();
textField_3.setBackground(new Color(255, 255, 224));
JTextField textField_4 = new JTextField();
textField_4.setBackground(new Color(255, 255, 224));
JTextField textField_5 = new JTextField();
textField_5.setBackground(new Color(255, 255, 224));
JTextField textField_6 = new JTextField();
textField_6.setBackground(new Color(255, 255, 224));
JTextField textField_7 = new JTextField();
textField_7.setBackground(new Color(255, 255, 224));
//ADDING TEXTFIELDS TO ARRAY THROUGH CONSTRUCTOR
ExcelReportGenerator de = new ExcelReportGenerator( submit , btnExportToExcel);
de.addTextField( textField_1 );
de.addTextField( textField_2 );
de.addTextField( textField_3 );
de.addTextField( textField_4 );
de.addTextField( textField_5 );
de.addTextField( textField_6 );
de.addTextField( textField_7 );
//CREATING THE FRAME
JFrame frame = new JFrame("Report Maker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(500,335));
frame.getContentPane().setLayout(null);
frame.getContentPane().add(submit);
frame.getContentPane().add(btnExportToExcel);
//ALL TEXTFIELDS
textField_1.setBounds(112, 62, 117, 20);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
textField_2.setBounds(112, 93, 117, 20);
frame.getContentPane().add(textField_2);
textField_2.setColumns(10);
textField_3.setBounds(112, 124, 117, 20);
frame.getContentPane().add(textField_3);
textField_3.setColumns(10);
textField_4.setBounds(112, 155, 117, 20);
frame.getContentPane().add(textField_4);
textField_4.setColumns(10);
textField_5.setBounds(112, 186, 117, 20);
frame.getContentPane().add(textField_5);
textField_5.setColumns(10);
textField_6.setBounds(112, 219, 117, 20);
frame.getContentPane().add(textField_6);
textField_6.setColumns(10);
textField_7.setBounds(112, 250, 117, 20);
frame.getContentPane().add(textField_7);
textField_7.setColumns(10);
//DBConnector.DBConnection(username,password,hostname,port,sid,tablename,filename);
//ALL LABELS
JLabel lblDatabaseToExcel = new JLabel("Database To Excel Tool");
lblDatabaseToExcel.setForeground(new Color(0, 0, 128));
lblDatabaseToExcel.setFont(new Font("Georgia", Font.BOLD, 20));
lblDatabaseToExcel.setBounds(123, -11, 351, 50);
frame.getContentPane().add(lblDatabaseToExcel);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblUsername.setForeground(new Color(0, 0, 128));
lblUsername.setBounds(20, 44, 200, 50);
frame.getContentPane().add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblPassword.setForeground(new Color(0, 0, 128));
lblPassword.setBounds(20, 78, 200, 50);
frame.getContentPane().add(lblPassword);
JLabel lblHostname = new JLabel("Hostname:");
lblHostname.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblHostname.setForeground(new Color(0, 0, 128));
lblHostname.setBounds(20, 109, 200, 50);
frame.getContentPane().add(lblHostname);
JLabel lblPort = new JLabel("Port:");
lblPort.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblPort.setForeground(new Color(0, 0, 128));
lblPort.setBounds(20, 140, 200, 50);
frame.getContentPane().add(lblPort);
JLabel lblSid = new JLabel("SID:");
lblSid.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblSid.setForeground(new Color(0, 0, 128));
lblSid.setBounds(20, 171, 200, 50);
frame.getContentPane().add(lblSid);
JLabel lblEnterDbDetails = new JLabel("DB Details:");
lblEnterDbDetails.setForeground(new Color(0, 0, 128));
lblEnterDbDetails.setFont(new Font("Vrinda", Font.BOLD, 15));
lblEnterDbDetails.setBounds(20, 11, 200, 50);
frame.getContentPane().add(lblEnterDbDetails);
JLabel lblTableviewName = new JLabel("Table/View Name:");
lblTableviewName.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblTableviewName.setForeground(new Color(0, 0, 128));
lblTableviewName.setBackground(new Color(255, 228, 225));
lblTableviewName.setBounds(20, 203, 200, 50);
frame.getContentPane().add(lblTableviewName);
JLabel lblEnterNameOf = new JLabel("Enter Name Of File:");
lblEnterNameOf.setForeground(new Color(0, 0, 128));
lblEnterNameOf.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblEnterNameOf.setBounds(20, 235, 200, 50);
frame.getContentPane().add(lblEnterNameOf);
JLabel lblgeneratedFileLocated = new JLabel("(Generated File Located At C:\\)");
lblgeneratedFileLocated.setFont(new Font("Tahoma", Font.PLAIN, 11));
lblgeneratedFileLocated.setForeground(new Color(205, 92, 92));
lblgeneratedFileLocated.setBounds(305, 204, 200, 50);
frame.getContentPane().add(lblgeneratedFileLocated);
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
}
Here's the DBConnector Class code below:
public class DBConnector implements ActionListener
{
public static void DBConnection(String user,String pword, String host, String portnum, String sidValue, String table, String generatedfile) throws SQLException, ClassNotFoundException, RowsExceededException, WriteException, IOException
{
String username=user;
String password=pword;
String hostname=host;
String port=portnum;
String sid=sidValue;
String tablename=table;
String filename=generatedfile;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is the fricking JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("Oracle JDBC Driver Found!");
Connection con;
try {
Properties props=new Properties();
props.put("user",username);
props.put("password",password);
props.setProperty("hostname",hostname);
props.setProperty("port",port);
props.setProperty("sid",sid);
String jdbcurl="jdbc:oracle:oci:#";
System.out.println();
con = DriverManager
.getConnection(jdbcurl,props);
}
catch (SQLException e)
{
JOptionPane.showMessageDialog(null, " DB Connection Failed,\n Make Sure All Details Entered Are Correct");
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (con != null)
{
JOptionPane.showMessageDialog(null, "Connected to Database\nClick on the Export To Excel Button");
System.out.println("You made it, take control your database now!");
ReportMaker.reportParameters(tablename,filename, con);
}
else
{
JOptionPane.showMessageDialog(null, " DB Connection Failed,\n Make Sure All Details Entered Are Correct");
}
}
}
import java.awt.*;
public class MainWindow {
private JFrame frmMainwindow;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_5;
private JTextField textField_6;
private JTextField textField_7;
private JTextField textField_8;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frmMainwindow.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*
*/
Connection conn = null;
Connection conn1 = null;
public MainWindow() {
initialize();
MainPage mp = new MainPage();
mp.setVisible(true);
}
/**
* Initialize the contents of the frame.
*/
public void Reset(){
textField.setText(null);
textField_1.setText(null);
textField_2.setText(null);
textField_3.setText(null);
textField_4.setText(null);
textField_5.setText(null);
textField_6.setText(null);
textField_7.setText(null);
textField_8.setText(null);
}
public void DBCreation(){
conn = CreatingDb.CreateDb();
String DBName = textField.getText();
try{
String query = "CREATE DATABASE " + DBName ;
PreparedStatement pst = conn.prepareStatement(query);
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "DB Created Successful.....");
pst.close();
}catch(Exception R){
JOptionPane.showMessageDialog(null, R);
}
}
public void Insert(){
String DBName = textField.getText();
conn1 = SqlConnection.InsertDB(DBName);
try{
String Table1 = "CREATE TABLE PERSONALINFO (PersonName VARCHAR(25),DoorNO VARCHAR(10),Street VARCHAR(25),Village VARCHAR(25),PhoneNo LONGINT(10),UserName VARCHAR(15),Password VARCHAR(10),Hint VARCHAR(50))";
String Insert1 = "INSERT INTO PERSONALINFO (PersonName,DoorNO,Street,Village,PhoneNo,UserName,Password,Hint) VALUES (?,?,?,?,?,?,?,?)";
PreparedStatement pstt = conn.prepareStatement(Table1);
PreparedStatement psti = conn.prepareStatement(Insert1);
psti.setString(1, textField_1.getText());
psti.setString(2, textField_2.getText());
psti.setString(3, textField_3.getText());
psti.setString(4, textField_4.getText());
psti.setString(5, textField_5.getText());
psti.setString(6, textField_6.getText());
psti.setString(7, textField_7.getText());
psti.setString(8, textField_8.getText());
pstt.execute();
psti.execute();
JOptionPane.showMessageDialog(null, "Table Created and Data Inserted Successfully....");
psti.close();
pstt.close();
}catch(Exception R){
JOptionPane.showMessageDialog(null, R);
}
}
private void initialize() {
frmMainwindow = new JFrame();
frmMainwindow.getContentPane().setBackground(Color.WHITE);
frmMainwindow.getContentPane().setFont(new Font("Times New Roman", Font.BOLD, 14));
frmMainwindow.setTitle("Create DataBase");
frmMainwindow.setBounds(100, 100, 668, 416);
frmMainwindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int height = screenSize.height;
int width = screenSize.width;
frmMainwindow.setSize(width/2, height/2);
// center the jframe on screen
frmMainwindow.setLocationRelativeTo(null);
frmMainwindow.getContentPane().setLayout(null);
JPanel panel_1 = new JPanel();
panel_1.setBackground(Color.WHITE);
panel_1.setBounds(120, 70, 426, 205);
frmMainwindow.getContentPane().add(panel_1);
panel_1.setLayout(null);
panel_1.setVisible(false);
JLabel lblDatabaseName = new JLabel("DataBase Name");
lblDatabaseName.setBounds(0, 3, 107, 14);
panel_1.add(lblDatabaseName);
lblDatabaseName.setFont(new Font("Times New Roman", Font.BOLD, 14));
JLabel lblPersonName = new JLabel("Person Name");
lblPersonName.setBounds(0, 32, 89, 14);
panel_1.add(lblPersonName);
lblPersonName.setFont(new Font("Times New Roman", Font.BOLD, 14));
JLabel lblDoorNo = new JLabel("Door No");
lblDoorNo.setBounds(0, 57, 79, 14);
panel_1.add(lblDoorNo);
lblDoorNo.setFont(new Font("Times New Roman", Font.BOLD, 14));
JLabel lblStreet = new JLabel("Street");
lblStreet.setBounds(0, 85, 46, 14);
panel_1.add(lblStreet);
lblStreet.setFont(new Font("Times New Roman", Font.BOLD, 14));
JLabel lblVillage = new JLabel("Village");
lblVillage.setBounds(0, 110, 46, 14);
panel_1.add(lblVillage);
lblVillage.setFont(new Font("Times New Roman", Font.BOLD, 14));
JLabel lblPhoneNo = new JLabel("Phone No");
lblPhoneNo.setBounds(0, 135, 58, 14);
panel_1.add(lblPhoneNo);
lblPhoneNo.setFont(new Font("Times New Roman", Font.BOLD, 14));
JLabel lblUserbame = new JLabel("UserName");
lblUserbame.setBounds(232, 3, 79, 14);
panel_1.add(lblUserbame);
lblUserbame.setFont(new Font("Times New Roman", Font.BOLD, 14));
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(232, 32, 68, 14);
panel_1.add(lblPassword);
lblPassword.setFont(new Font("Times New Roman", Font.BOLD, 14));
JLabel lblHint = new JLabel("Hint");
lblHint.setBounds(232, 57, 46, 14);
panel_1.add(lblHint);
lblHint.setFont(new Font("Times New Roman", Font.BOLD, 14));
textField = new JTextField();
textField.setBounds(117, 0, 105, 20);
panel_1.add(textField);
textField.setFont(new Font("Times New Roman", Font.BOLD, 14));
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(117, 29, 105, 20);
panel_1.add(textField_1);
textField_1.setFont(new Font("Times New Roman", Font.BOLD, 14));
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(117, 54, 105, 20);
panel_1.add(textField_2);
textField_2.setFont(new Font("Times New Roman", Font.BOLD, 14));
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(117, 82, 105, 20);
panel_1.add(textField_3);
textField_3.setFont(new Font("Times New Roman", Font.BOLD, 14));
textField_3.setColumns(10);
textField_4 = new JTextField();
textField_4.setBounds(117, 107, 105, 20);
panel_1.add(textField_4);
textField_4.setFont(new Font("Times New Roman", Font.BOLD, 14));
textField_4.setColumns(10);
textField_5 = new JTextField();
textField_5.setBounds(117, 132, 105, 20);
panel_1.add(textField_5);
textField_5.setFont(new Font("Times New Roman", Font.BOLD, 14));
textField_5.setColumns(10);
textField_6 = new JTextField();
textField_6.setBounds(321, 0, 105, 20);
panel_1.add(textField_6);
textField_6.setFont(new Font("Times New Roman", Font.BOLD, 14));
textField_6.setColumns(10);
textField_7 = new JTextField();
textField_7.setBounds(321, 29, 105, 20);
panel_1.add(textField_7);
textField_7.setFont(new Font("Times New Roman", Font.BOLD, 14));
textField_7.setColumns(10);
textField_8 = new JTextField();
textField_8.setBounds(321, 54, 105, 20);
panel_1.add(textField_8);
textField_8.setFont(new Font("Times New Roman", Font.BOLD, 14));
textField_8.setColumns(10);
JButton btnReset = new JButton("Reset");
btnReset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Reset();
}
});
btnReset.setBounds(232, 171, 89, 23);
panel_1.add(btnReset);
JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DBCreation();
Insert();
Reset();
}
});
btnSave.setBounds(327, 171, 89, 23);
panel_1.add(btnSave);
panel_1.setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{lblDatabaseName, textField_1, lblPersonName, lblDoorNo, lblStreet, lblVillage, lblPhoneNo, lblUserbame, lblPassword, lblHint, textField_2, textField_3, textField_4, textField_5, textField_6, textField_7, textField_8, btnSave, btnReset, textField}));
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
panel.setBounds(217, 122, 233, 101);
frmMainwindow.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblCreateDatabase = new JLabel("Create DataBase");
lblCreateDatabase.setBounds(0, 4, 120, 14);
panel.add(lblCreateDatabase);
lblCreateDatabase.setFont(new Font("Times New Roman", Font.BOLD, 14));
JLabel lblOpenDatabase = new JLabel("Open DataBase");
lblOpenDatabase.setBounds(0, 42, 120, 14);
panel.add(lblOpenDatabase);
lblOpenDatabase.setFont(new Font("Times New Roman", Font.BOLD, 14));
JLabel lblNewLabel = new JLabel("Delete DataBase");
lblNewLabel.setBounds(0, 82, 120, 14);
panel.add(lblNewLabel);
lblNewLabel.setFont(new Font("Times New Roman", Font.BOLD, 14));
JButton btnNew = new JButton("New");
btnNew.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
panel.setVisible(false);
panel_1.setVisible(true);
}
});
btnNew.setBounds(144, 0, 89, 23);
panel.add(btnNew);
btnNew.setFont(new Font("Times New Roman", Font.BOLD, 14));
JButton btnSelect = new JButton("Select");
btnSelect.setBounds(144, 38, 89, 23);
panel.add(btnSelect);
btnSelect.setFont(new Font("Times New Roman", Font.BOLD, 14));
JButton btnRemove = new JButton("Remove");
btnRemove.setBounds(144, 78, 89, 23);
panel.add(btnRemove);
btnRemove.setFont(new Font("Times New Roman", Font.BOLD, 14));
}
}
My Second java file
public class SqlConnection {
Connection conn1 = null;
public static Connection InsertDB(String DBName){
String value = DBName;
try{
Class.forName("com.mysql.jdbc.Driver");
String DB = "jdbc:mysql://localhost:3306/";
Connection conn = DriverManager.getConnection(DB+value,"root","");
JOptionPane.showMessageDialog(null,value);
return conn;
}catch(Exception e){
JOptionPane.showMessageDialog(null,e);
return null;
}
}
}
MY Third java File
public class CreatingDb {
Connection conn = null;
public static Connection CreateDb(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/","root","");
return conn;
}catch(Exception e){
JOptionPane.showMessageDialog(null,e);
return null;
}
}
}
MY Forth java File..
public class MainPage extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainPage frame = new MainPage();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainPage() {
setExtendedState(Frame.MAXIMIZED_BOTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmNew = new JMenuItem("New");
mnFile.add(mntmNew);
JMenuItem mntmOpen = new JMenuItem("Open");
mnFile.add(mntmOpen);
JMenuItem mntmSave = new JMenuItem("Save");
mnFile.add(mntmSave);
JMenuItem mntmSaveAs = new JMenuItem("Save As...");
mnFile.add(mntmSaveAs);
JMenuItem mntmExit = new JMenuItem("Exit");
mnFile.add(mntmExit);
JMenu mnEdit = new JMenu("Edit");
menuBar.add(mnEdit);
JMenu mnHelp = new JMenu("Help");
menuBar.add(mnHelp);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
}
}
I Have imported required packages...
In the above code I am creating database using textfield at beginning of application. DataBase is created successfully but i am unable to access the created dataBase . It show java.sql.Exception: Unknown database Selection.
please any one help me ....
String DB = "jdbc:mysql://localhost:3306/";
Connection conn = DriverManager.getConnection(DB+value,"root","");
i think your problem appending. you do not append DB + value. give password.
The MySQL manual says this:
If the database is not specified, the connection is made with no default database. In this case, either call the setCatalog() method on the Connection instance, or fully specify table names using the database name (that is, SELECT dbname.tablename.colname FROM dbname.tablename...) in your SQL. Opening a connection without specifying the database to use is generally only useful when building tools that work with multiple databases, such as GUI database managers.
Note
Always use the Connection.setCatalog() method to specify the desired database in JDBC applications, rather than the USE database statement.
It doesn't specify what happens if you don't call setCatalog() but given your problem I guess "nothing good." You should add a schema to your connect string or call setCatalog().
I am having a problem with my Java GUI application. It for some reason says that it cannot find or load the main class. I have checked all the brackets and don't see a problem. I had originally copied this over from another file as I wanted to start over with some things, maybe that is the problem. Here is the code:
public class GradeAverage extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
JTextField textField;
int numAverage = 0;
double average;
Container c;
JLabel gradelbl;
class AnswerHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
numAverage++;
gradelbl.setText("" + numAverage);
}
}
public GradeAverage() {
super("Final Grades");
c = getContentPane();
JLabel lblNewLabel = new JLabel("Grade: ");
lblNewLabel.setFont(new Font("Times New Roman", Font.BOLD, 14));
lblNewLabel.setBounds(30, 50, 46, 14);
textField = new JTextField();
textField.setBounds(81, 47, 86, 20);
textField.setColumns(10);
JLabel gradeLbl = new JLabel("0");
gradeLbl.setFont(new Font("Times New Roman", Font.BOLD, 14));
gradeLbl.setBounds(91, 92, 15, 14);
JLabel gradeTextLbl = new JLabel("Grades Recorded");
gradeTextLbl.setFont(new Font("Times New Roman", Font.BOLD, 14));
gradeTextLbl.setBounds(106, 92, 123, 14);
JButton recordBtn = new JButton("Record");
AnswerHandler ah = new AnswerHandler();
recordBtn.addActionListener(ah);
recordBtn.setBounds(177, 47, 86, 20);
JButton displayAverageBtn = new JButton("New button");
displayAverageBtn.setBounds(30, 117, 233, 23);
JPanel finalGradePanel = new JPanel();
finalGradePanel.setBorder(new TitledBorder(null, "Enter Your Final Grades", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 128)));
finalGradePanel.setBounds(10, 21, 264, 131);
JPanel avgGradePanel = new JPanel();
avgGradePanel.setFont(new Font("Times New Roman", Font.BOLD, 16));
avgGradePanel.setBounds(10, 178, 264, 61);
avgGradePanel.setBorder(new TitledBorder(null, "Average Grade", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 128)));
c.add(avgGradePanel);c.add(finalGradePanel);c.add(displayAverageBtn);c.add(recordBtn);c.add(gradeTextLbl);c.add(gradeLbl);
}
public static void main(String[] args) {
GradeAverage app = new GradeAverage();
app.setSize(300, 300);
app.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
app.setVisible(true);
}
}
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");
}
}