Related
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
i have a problem that in Eclipse when i run my project everything is working fine but when i exporting it last class don't want to open by clicking the button. I'm using database in every class as well as i have referenced library(jcalendar-1.4) if it will help you to solve the problem.
login and registration class are working fine and after logged in and transfer to addActivity class most thing are working like adding everything to database but that one button is unable to open that last class that should show all activities added.
code for AddActivity class and button that is not working in jar file is called txtAddActivity
AddActivity.java
package timeManager;
public class AddActivity {
protected JFrame frmAddActiviti;
private Login loginScreen = null;
private Database database = null;
private ShowActivities showActivities = null;
private JTextField textActivityName;
private JTextField txtLogoff;
private JLabel lblNewLabel_1;
private JLabel lblActivityDescription;
private JTextField txtAddActivity;
private JTextField txtShowActivitis;
private JTextArea textArea;
private JDateChooser dateChooser;
private String login = "";
private String password = "";
private String deadline = "";
private Date date;
private JLabel lblErrorMessage;
private JLabel lblErrorMessage2;
private JLabel lblErrorMessage3;
/**
* Create the application.
*/
public AddActivity() {
gui();
}
public AddActivity(String login, String password) {
this.login = login;
this.password = password;
gui();
}
/**
* Initialize the contents of the frame.
*/
private void gui() {
frmAddActiviti = new JFrame();
frmAddActiviti.setTitle("Add Activity");
frmAddActiviti.setSize(450, 300);
frmAddActiviti.setResizable(false);
frmAddActiviti.setLocationRelativeTo(null);
frmAddActiviti.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmAddActiviti.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBackground(new Color(128, 128, 128));
panel.setBounds(0, 0, 434, 261);
frmAddActiviti.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblNewLabel = new JLabel("Welcome, " + login);
lblNewLabel.setBorder(new LineBorder(new Color(255, 255, 255), 3, true));
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 14));
lblNewLabel.setForeground(new Color(255, 255, 255));
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setBounds(26, 11, 224, 25);
panel.add(lblNewLabel);
textActivityName = new JTextField();
textActivityName.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
textActivityName.setBounds(26, 64, 224, 20);
panel.add(textActivityName);
textActivityName.setColumns(10);
textArea = new JTextArea();
textArea.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
textArea.setBounds(26, 112, 224, 57);
panel.add(textArea);
txtLogoff = new JTextField();
txtLogoff.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
logoff();
}
});
txtLogoff.setEditable(false);
txtLogoff.setFont(new Font("Tahoma", Font.BOLD, 14));
txtLogoff.setForeground(new Color(255, 255, 255));
txtLogoff.setHorizontalAlignment(SwingConstants.CENTER);
txtLogoff.setText("Sign out");
txtLogoff.setBorder(new EtchedBorder(EtchedBorder.RAISED, null, null));
txtLogoff.setBackground(new Color(128, 128, 128));
txtLogoff.setBounds(273, 11, 92, 25);
panel.add(txtLogoff);
txtLogoff.setColumns(10);
lblNewLabel_1 = new JLabel("Activity Name*");
lblNewLabel_1.setFont(new Font("Tahoma", Font.BOLD, 12));
lblNewLabel_1.setForeground(new Color(255, 255, 255));
lblNewLabel_1.setHorizontalAlignment(SwingConstants.LEFT);
lblNewLabel_1.setBounds(26, 47, 104, 14);
panel.add(lblNewLabel_1);
lblActivityDescription = new JLabel("Activity Description");
lblActivityDescription.setHorizontalAlignment(SwingConstants.LEFT);
lblActivityDescription.setForeground(Color.WHITE);
lblActivityDescription.setFont(new Font("Tahoma", Font.BOLD, 12));
lblActivityDescription.setBounds(26, 95, 138, 14);
panel.add(lblActivityDescription);
dateChooser = new JDateChooser();
dateChooser.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
dateChooser.setBounds(260, 64, 119, 20);
panel.add(dateChooser);
txtAddActivity = new JTextField();
txtAddActivity.setEditable(false);
txtAddActivity.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseMoved(MouseEvent arg0) {
txtAddActivity.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
}
});
txtAddActivity.addMouseListener(new MouseAdapter() {
#Override
public void mouseExited(MouseEvent e) {
txtAddActivity.setBorder(new BevelBorder(BevelBorder.RAISED, null, null, null, null));
}
#Override
public void mouseClicked(MouseEvent e) {
add();
}
});
txtAddActivity.setFont(new Font("Tahoma", Font.BOLD, 12));
txtAddActivity.setHorizontalAlignment(SwingConstants.CENTER);
txtAddActivity.setText("Add activity");
txtAddActivity.setBorder(new BevelBorder(BevelBorder.RAISED, null, null, null, null));
txtAddActivity.setForeground(new Color(255, 255, 255));
txtAddActivity.setBackground(new Color(128, 128, 128));
txtAddActivity.setBounds(26, 192, 104, 25);
panel.add(txtAddActivity);
txtAddActivity.setColumns(10);
JLabel lblDeadline = new JLabel("Deadline*");
lblDeadline.setHorizontalAlignment(SwingConstants.LEFT);
lblDeadline.setForeground(Color.WHITE);
lblDeadline.setFont(new Font("Tahoma", Font.BOLD, 12));
lblDeadline.setBounds(260, 47, 104, 14);
panel.add(lblDeadline);
txtShowActivitis = new JTextField();
txtShowActivitis.setEditable(false);
txtShowActivitis.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseMoved(MouseEvent arg0) {
txtShowActivitis.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
}
});
txtShowActivitis.addMouseListener(new MouseAdapter() {
#Override
public void mouseExited(MouseEvent e) {
txtShowActivitis.setBorder(new BevelBorder(BevelBorder.RAISED, null, null, null, null));
}
#Override
public void mouseClicked(MouseEvent e) {
show();
}
});
txtShowActivitis.setText("Show activities");
txtShowActivitis.setHorizontalAlignment(SwingConstants.CENTER);
txtShowActivitis.setForeground(Color.WHITE);
txtShowActivitis.setFont(new Font("Tahoma", Font.BOLD, 12));
txtShowActivitis.setColumns(10);
txtShowActivitis.setBorder(new BevelBorder(BevelBorder.RAISED, null, null, null, null));
txtShowActivitis.setBackground(Color.GRAY);
txtShowActivitis.setBounds(146, 192, 104, 25);
panel.add(txtShowActivitis);
lblErrorMessage = new JLabel("");
lblErrorMessage.setFont(new Font("Tahoma", Font.PLAIN, 11));
lblErrorMessage.setForeground(new Color(128, 0, 0));
lblErrorMessage.setBounds(26, 72, 398, 36);
panel.add(lblErrorMessage);
lblErrorMessage2 = new JLabel("");
lblErrorMessage2.setForeground(new Color(128, 0, 0));
lblErrorMessage2.setFont(new Font("Tahoma", Font.PLAIN, 11));
lblErrorMessage2.setBounds(26, 161, 398, 36);
panel.add(lblErrorMessage2);
lblErrorMessage3 = new JLabel("");
lblErrorMessage3.setForeground(Color.GREEN);
lblErrorMessage3.setFont(new Font("Tahoma", Font.PLAIN, 11));
lblErrorMessage3.setBounds(26, 208, 398, 36);
panel.add(lblErrorMessage3);
}
private void logoff() {
loginScreen = new Login();
loginScreen.frmLogin.setVisible(true);
frmAddActiviti.setVisible(false);
}
private void add() {
String activityName = "";
String activityDescription = "";
boolean activityNameCorrect = true;
boolean descriptionCorrect = true;
boolean dateAccepted = true;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
lblErrorMessage3.setText("");
activityName = textActivityName.getText();
activityDescription = textArea.getText();
try {
if (!(Character.isUpperCase(activityName.charAt(0)) && activityName.length() > 1)) {
activityNameCorrect = false;
lblErrorMessage
.setText("Activity name need to start with capital letter and have at least 2 characters");
} else {
lblErrorMessage.setText("");
}
} catch (Exception ex) {
activityNameCorrect = false;
lblErrorMessage.setText("Activity name need to start with capital letter and have at least 2 characters");
System.out.println(ex);
}
try {
int counterWords = 0;
for (int i = 0; i < activityDescription.length(); i++) {
if (activityDescription.charAt(i) == ' ') {
counterWords++;
}
}
if (counterWords > 20) {
descriptionCorrect = false;
lblErrorMessage2.setText("you cant have more than 20 words in description");
}
} catch (Exception ex) {
System.out.println(ex);
}
if (activityNameCorrect == true) {
// gettign today's date
date = new Date();
String todayDate = dateFormat.format(date);
try {
// checking if chosen date is earlier than today's one
deadline = dateFormat.format(dateChooser.getDate());
if (todayDate.compareTo(deadline) > 0) {
lblErrorMessage.setText("You cant choose date earlier than today's date");
dateAccepted = false;
}
} catch (Exception ex) {
dateAccepted = false;
lblErrorMessage.setText("You need to pick the date");
System.out.println(ex);
}
}
if (activityNameCorrect == true && dateAccepted == true && descriptionCorrect == true) {
boolean originalActivityName = false;
database = new Database(activityName, login, 0);
originalActivityName = database.getOriginalName();
if (originalActivityName == true) {
try {
date = dateFormat.parse(deadline);
} catch (Exception ex) {
System.out.println(ex);
}
database = new Database(activityName, activityDescription, date, login, password);
lblErrorMessage3.setText("Activity added!");
} else {
lblErrorMessage3.setText("");
lblErrorMessage2.setText("This activity name already exist");
}
}
}
private void show() {
showActivities = new ShowActivities(login, password);
showActivities.frmShowActivities.setVisible(true);
frmAddActiviti.setVisible(false);
}
}
code for ShowActivities that is not displaying in jar file
ShowActivities.java
package timeManager;
public class ShowActivities {
protected JFrame frmShowActivities;
private Login loginScreen = null;
private AddActivity addActivity = null;
private Database database = null;
private String login, password;
private String[] activityNames = new String[100];
private String[] activityDescriptions = new String[100];
private String[] deadlines = new String[100];
private int[] counters = { 0, 1 };
private int activitiesCount;
private JTextField txtLogoff, txtAddNewActivity;
private JLabel lblActivityName, lblActivityDeadline, lblActivityName2, lblActivityDeadline2;
private JTextArea textArea, textArea2;
/**
* Create the application.
*/
public ShowActivities() {
initialize();
}
public ShowActivities(String login, String password) {
this.login = login;
this.password = password;
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmShowActivities = new JFrame();
frmShowActivities.setResizable(false);
frmShowActivities.setTitle("Show Activities");
frmShowActivities.setSize(536, 345);
frmShowActivities.setLocationRelativeTo(null);
frmShowActivities.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmShowActivities.getContentPane().setLayout(null);
getAllUserActivity();
JPanel panel = new JPanel();
panel.setBackground(new Color(128, 128, 128));
panel.setBounds(0, 0, 546, 342);
frmShowActivities.getContentPane().add(panel);
panel.setLayout(null);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(105, 105, 105));
panel_1.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
panel_1.setBounds(187, 11, 308, 143);
panel.add(panel_1);
panel_1.setLayout(null);
JLabel lblNewLabel_1 = new JLabel("Activity Name:");
lblNewLabel_1.setHorizontalAlignment(SwingConstants.RIGHT);
lblNewLabel_1.setFont(new Font("Tahoma", Font.BOLD, 11));
lblNewLabel_1.setForeground(new Color(255, 255, 255));
lblNewLabel_1.setBounds(5, 5, 114, 14);
panel_1.add(lblNewLabel_1);
lblActivityName = new JLabel("");
lblActivityName.setText(activityNames[counters[0]]);
lblActivityName.setForeground(new Color(255, 255, 255));
lblActivityName.setFont(new Font("Tahoma", Font.BOLD, 11));
lblActivityName.setBounds(123, 5, 175, 14);
panel_1.add(lblActivityName);
JLabel lblNewLabel_3 = new JLabel("Activity Description:");
lblNewLabel_3.setHorizontalAlignment(SwingConstants.RIGHT);
lblNewLabel_3.setFont(new Font("Tahoma", Font.BOLD, 11));
lblNewLabel_3.setForeground(new Color(255, 255, 255));
lblNewLabel_3.setBounds(5, 47, 114, 14);
panel_1.add(lblNewLabel_3);
textArea = new JTextArea();
textArea.setText(activityDescriptions[counters[0]]);
textArea.setEditable(false);
textArea.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
textArea.setBounds(123, 45, 175, 90);
panel_1.add(textArea);
JLabel lblDeadline = new JLabel("Deadline:");
lblDeadline.setHorizontalAlignment(SwingConstants.RIGHT);
lblDeadline.setForeground(Color.WHITE);
lblDeadline.setFont(new Font("Tahoma", Font.BOLD, 11));
lblDeadline.setBounds(5, 25, 114, 14);
panel_1.add(lblDeadline);
lblActivityDeadline = new JLabel("");
lblActivityDeadline.setText(deadlines[counters[0]]);
lblActivityDeadline.setForeground(Color.WHITE);
lblActivityDeadline.setFont(new Font("Tahoma", Font.BOLD, 11));
lblActivityDeadline.setBounds(123, 25, 175, 14);
panel_1.add(lblActivityDeadline);
JLabel lblComplete = new JLabel("");
lblComplete.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
removeActivity(0);
}
});
lblComplete.setIcon(new ImageIcon("C:\\Users\\jakub\\OneDrive\\Desktop\\Done.png"));
lblComplete.setBounds(40, 85, 50, 50);
panel_1.add(lblComplete);
JLabel lblNewLabel_2 = new JLabel("Activity Completed?");
lblNewLabel_2.setFont(new Font("Tahoma", Font.BOLD, 11));
lblNewLabel_2.setForeground(new Color(255, 255, 255));
lblNewLabel_2.setBounds(5, 69, 114, 14);
panel_1.add(lblNewLabel_2);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setBounds(-175, 30, 161, 212);
panel_1.add(lblNewLabel);
lblNewLabel.setIcon(new ImageIcon("C:\\Users\\jakub\\OneDrive\\Desktop\\stock-going-up-png.png"));
JLabel lblUP = new JLabel("");
lblUP.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
moveUP();
}
});
lblUP.setIcon(new ImageIcon(ShowActivities.class
.getResource("/com/sun/javafx/scene/control/skin/caspian/dialog-fewer-details.png")));
lblUP.setBounds(502, 11, 21, 21);
panel.add(lblUP);
JLabel lblDOWN = new JLabel("");
lblDOWN.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
moveDown();
}
});
lblDOWN.setIcon(new ImageIcon(ShowActivities.class
.getResource("/com/sun/javafx/scene/control/skin/caspian/dialog-more-details.png")));
lblDOWN.setBounds(502, 275, 21, 21);
panel.add(lblDOWN);
JPanel panel_2 = new JPanel();
panel_2.setLayout(null);
panel_2.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
panel_2.setBackground(SystemColor.controlDkShadow);
panel_2.setBounds(187, 155, 308, 143);
panel.add(panel_2);
JLabel label = new JLabel("Activity Name:");
label.setHorizontalAlignment(SwingConstants.RIGHT);
label.setForeground(Color.WHITE);
label.setFont(new Font("Tahoma", Font.BOLD, 11));
label.setBounds(5, 5, 114, 14);
panel_2.add(label);
lblActivityName2 = new JLabel("");
lblActivityName2.setText(activityNames[counters[1]]);
lblActivityName2.setForeground(Color.WHITE);
lblActivityName2.setFont(new Font("Tahoma", Font.BOLD, 11));
lblActivityName2.setBounds(123, 5, 175, 14);
panel_2.add(lblActivityName2);
JLabel label_2 = new JLabel("Activity Description:");
label_2.setHorizontalAlignment(SwingConstants.RIGHT);
label_2.setForeground(Color.WHITE);
label_2.setFont(new Font("Tahoma", Font.BOLD, 11));
label_2.setBounds(5, 47, 114, 14);
panel_2.add(label_2);
textArea2 = new JTextArea();
textArea2.setText(activityDescriptions[counters[1]]);
textArea2.setEditable(false);
textArea2.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
textArea2.setBounds(123, 45, 175, 90);
panel_2.add(textArea2);
JLabel label_3 = new JLabel("Deadline:");
label_3.setHorizontalAlignment(SwingConstants.RIGHT);
label_3.setForeground(Color.WHITE);
label_3.setFont(new Font("Tahoma", Font.BOLD, 11));
label_3.setBounds(5, 25, 114, 14);
panel_2.add(label_3);
lblActivityDeadline2 = new JLabel("");
lblActivityDeadline2.setText(deadlines[counters[1]]);
lblActivityDeadline2.setForeground(Color.WHITE);
lblActivityDeadline2.setFont(new Font("Tahoma", Font.BOLD, 11));
lblActivityDeadline2.setBounds(123, 25, 175, 14);
panel_2.add(lblActivityDeadline2);
JLabel lblComplete2 = new JLabel("");
lblComplete2.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
removeActivity(1);
}
});
lblComplete2.setIcon(new ImageIcon("C:\\Users\\jakub\\OneDrive\\Desktop\\Done.png"));
lblComplete2.setBounds(40, 85, 50, 50);
panel_2.add(lblComplete2);
JLabel label_6 = new JLabel("Activity Completed?");
label_6.setForeground(Color.WHITE);
label_6.setFont(new Font("Tahoma", Font.BOLD, 11));
label_6.setBounds(5, 69, 114, 14);
panel_2.add(label_6);
txtLogoff = new JTextField();
txtLogoff.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
logoff();
}
});
txtLogoff.setText("Sign out");
txtLogoff.setHorizontalAlignment(SwingConstants.CENTER);
txtLogoff.setForeground(Color.WHITE);
txtLogoff.setFont(new Font("Tahoma", Font.BOLD, 14));
txtLogoff.setEditable(false);
txtLogoff.setColumns(10);
txtLogoff.setBorder(new EtchedBorder(EtchedBorder.RAISED, null, null));
txtLogoff.setBackground(Color.GRAY);
txtLogoff.setBounds(40, 11, 92, 25);
panel.add(txtLogoff);
txtAddNewActivity = new JTextField();
txtAddNewActivity.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseMoved(MouseEvent arg0) {
txtAddNewActivity.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
}
});
txtAddNewActivity.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
callAddActivity();
}
#Override
public void mouseExited(MouseEvent e) {
txtAddNewActivity.setBorder(new BevelBorder(BevelBorder.RAISED, null, null, null, null));
}
});
txtAddNewActivity.setText("Add new activity");
txtAddNewActivity.setHorizontalAlignment(SwingConstants.CENTER);
txtAddNewActivity.setForeground(Color.WHITE);
txtAddNewActivity.setFont(new Font("Tahoma", Font.BOLD, 12));
txtAddNewActivity.setEditable(false);
txtAddNewActivity.setColumns(10);
txtAddNewActivity.setBorder(new BevelBorder(BevelBorder.RAISED, null, null, null, null));
txtAddNewActivity.setBackground(Color.GRAY);
txtAddNewActivity.setBounds(30, 270, 120, 25);
panel.add(txtAddNewActivity);
JLabel lblNewLabel_4 = new JLabel("");
lblNewLabel_4.setIcon(new ImageIcon("C:\\Users\\jakub\\OneDrive\\Desktop\\graphs.png"));
lblNewLabel_4.setBounds(10, 47, 167, 212);
panel.add(lblNewLabel_4);
}
private void callAddActivity() {
addActivity = new AddActivity(login, password);
addActivity.frmAddActiviti.setVisible(true);
frmShowActivities.setVisible(false);
}
private void logoff() {
loginScreen = new Login();
loginScreen.frmLogin.setVisible(true);
frmShowActivities.setVisible(false);
}
/**
* sort from smallest date to biggest
*/
private void sortActivitiesInOrder() {
String[] temp = new String[3];
for (int i = 0; i < (activitiesCount - 1); i++) {
for (int j = 0; j < (activitiesCount - 1); j++) {
if (deadlines[j].compareTo(deadlines[j + 1]) > 0) {
temp[0] = deadlines[j];
temp[1] = activityNames[j];
temp[2] = activityDescriptions[j];
deadlines[j] = deadlines[j + 1];
activityNames[j] = activityNames[j + 1];
activityDescriptions[j] = activityDescriptions[j + 1];
deadlines[j + 1] = temp[0];
activityNames[j + 1] = temp[1];
activityDescriptions[j + 1] = temp[2];
}
}
}
}
/**
* getting all activities for a user
*/
private void getAllUserActivity() {
database = new Database(login, activityNames, activityDescriptions, deadlines);
activityNames = database.getActivityNames();
activityDescriptions = database.getActivityDescriptions();
deadlines = database.getDeadlines();
activitiesCount = database.getCounter();
sortActivitiesInOrder();
}
private void removeActivity(int i) {
database = new Database(login, password, activityNames[counters[i]], activityDescriptions[counters[i]],
deadlines[counters[i]]);
activityNames = new String[100];
activityDescriptions = new String[100];
deadlines = new String[100];
getAllUserActivity();
setActivitiesTexts();
}
private void moveDown() {
activitiesCount = database.getCounter();
if (counters[1] < (activitiesCount - 1)) {
counters[0]++;
counters[1]++;
setActivitiesTexts();
}
}
private void moveUP() {
if (counters[0] > 0) {
counters[0]--;
counters[1]--;
setActivitiesTexts();
}
}
private void setActivitiesTexts() {
lblActivityName.setText(activityNames[counters[0]]);
lblActivityName2.setText(activityNames[counters[1]]);
textArea.setText(activityDescriptions[counters[0]]);
textArea2.setText(activityDescriptions[counters[1]]);
lblActivityDeadline.setText(deadlines[counters[0]]);
lblActivityDeadline2.setText(deadlines[counters[1]]);
}
}
Changing from Eclipse to NetBeans fixed the issue as jar file exported from netBeans worked perfectly fine
I am just a beginner in java coding and I want to know how I can save changes made to an array list through a GUI i have created. This code allows to store data, remove, add, update student information. However it is only temporarily since it is not connected to the hard disk to permanently store this information. I am wondering how I can make this code save the modified information made to it after i close it. I thank you for your time and consideration. The main class code is:
public class StudentDataStorage {
private JFrame frame;
private JTextField textStudentName;
private JTextField textStudentId;
private JTextField textCourseId;
private JTextField textCourseSubject;
void clearFields() {
textStudentName.setText("");
textStudentId.setText("");
textCourseId.setText("");
textCourseSubject.setText("");
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
StudentDataStorage window = new StudentDataStorage();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
private ArrayList<Student> arrayList;
private ListIterator<Student> listIterator;
int size;
public StudentDataStorage() {
initialize();
arrayList = new ArrayList<>();
size = 0;
arrayList.add(new Student("Jon Rugova", 340007862, "ISTE.121.500", "CompProblemSolvingInfoDomainII"));
arrayList.add(new Student("Sindi Rryta", 125172286, "ACCT.210.501", "Management Accounting"));
arrayList.add(new Student("Arianit Sylafeta", 545919686, "MTSC.231..501", "Contemporary Science: Biology"));
arrayList.add(new Student("Enxo Muçaj", 223375558, "POLS.110.500", "American Politics"));
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 991, 656);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(6, 0, 979, 65);
frame.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblNewLabel = new JLabel("Student Data Storage");
lblNewLabel.setBounds(287, 6, 393, 44);
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 36));
panel.add(lblNewLabel);
JPanel panel_1 = new JPanel();
panel_1.setBounds(6, 64, 979, 315);
frame.getContentPane().add(panel_1);
panel_1.setLayout(null);
JLabel lblStudentName = new JLabel("Student Name");
lblStudentName.setFont(new Font("Tahoma", Font.BOLD, 20));
lblStudentName.setBounds(164, 57, 196, 23);
lblStudentName.setHorizontalAlignment(SwingConstants.LEFT);
panel_1.add(lblStudentName);
textStudentName = new JTextField();
textStudentName.setFont(new Font("Tahoma", Font.BOLD, 20));
textStudentName.setBounds(372, 55, 421, 26);
panel_1.add(textStudentName);
textStudentName.setColumns(10);
JLabel lblIdNumber = new JLabel("Student ID");
lblIdNumber.setHorizontalAlignment(SwingConstants.LEFT);
lblIdNumber.setFont(new Font("Tahoma", Font.BOLD, 20));
lblIdNumber.setBounds(164, 101, 196, 23);
panel_1.add(lblIdNumber);
textStudentId = new JTextField();
textStudentId.setFont(new Font("Tahoma", Font.BOLD, 20));
textStudentId.setColumns(10);
textStudentId.setBounds(372, 99, 421, 26);
panel_1.add(textStudentId);
JLabel lblCourseId = new JLabel("Course ID");
lblCourseId.setHorizontalAlignment(SwingConstants.LEFT);
lblCourseId.setFont(new Font("Tahoma", Font.BOLD, 20));
lblCourseId.setBounds(164, 145, 196, 23);
panel_1.add(lblCourseId);
textCourseId = new JTextField();
textCourseId.setFont(new Font("Tahoma", Font.BOLD, 20));
textCourseId.setColumns(10);
textCourseId.setBounds(372, 143, 421, 26);
panel_1.add(textCourseId);
JLabel lblCourseSubject = new JLabel("Course Subject");
lblCourseSubject.setHorizontalAlignment(SwingConstants.LEFT);
lblCourseSubject.setFont(new Font("Tahoma", Font.BOLD, 20));
lblCourseSubject.setBounds(164, 186, 196, 23);
panel_1.add(lblCourseSubject);
textCourseSubject = new JTextField();
textCourseSubject.setFont(new Font("Tahoma", Font.BOLD, 20));
textCourseSubject.setColumns(10);
textCourseSubject.setBounds(372, 184, 421, 26);
panel_1.add(textCourseSubject);
JPanel panel_2 = new JPanel();
panel_2.setBounds(6, 378, 979, 250);
frame.getContentPane().add(panel_2);
panel_2.setLayout(null);
JButton btnFirst = new JButton("First");
btnFirst.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
size = arrayList.size();
listIterator = arrayList.listIterator();
Student ss;
ss = listIterator.next();
textStudentName.setText(ss.getName());
textStudentId.setText(""+ss.getStudentId());
textCourseId.setText(ss.getCourseId());
textCourseSubject.setText(ss.getCourseSubject());
}
});
btnFirst.setFont(new Font("Tahoma", Font.BOLD, 18));
btnFirst.setBounds(151, 56, 139, 68);
panel_2.add(btnFirst);
JButton btnNext = new JButton("Next");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(textStudentName.getText().contentEquals("")||textStudentId.getText().contentEquals("")||textCourseId.getText().contentEquals("")||textCourseSubject.getText().contentEquals("")) {
JOptionPane.showMessageDialog(null, "Error: Some Fields Are Empty!");
}else {
if(listIterator.hasNext()) {
Student ss;
ss = listIterator.next();
textStudentName.setText(ss.getName());;
textStudentId.setText(""+ss.getStudentId());
textCourseId.setText(ss.getCourseId());
textCourseSubject.setText(ss.getCourseSubject());
}else {
JOptionPane.showMessageDialog(null, "You Have Reached the Last Student.");
}
}
}
});
btnNext.setFont(new Font("Tahoma", Font.BOLD, 18));
btnNext.setBounds(317, 56, 139, 68);
panel_2.add(btnNext);
JButton btnAdd = new JButton("Add Data");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(textStudentName.getText().contentEquals("")||textStudentId.getText().contentEquals("")||textCourseId.getText().contentEquals("")||textCourseSubject.getText().contentEquals("")) {
JOptionPane.showMessageDialog(null, "Error: Some Fields Are Empty!");
}else {
String name = textStudentName.getText();
int studentid = Integer.parseInt(textStudentId.getText());
String courseid = textCourseId.getText();
String coursesubject = textCourseSubject.getText();
arrayList.add(new Student(name, studentid, courseid, coursesubject));
size = arrayList.size();
clearFields();
JOptionPane.showMessageDialog(null, "Student Data Added Successfully!");
}
}
});
btnAdd.setFont(new Font("Tahoma", Font.BOLD, 18));
btnAdd.setBounds(483, 56, 139, 68);
panel_2.add(btnAdd);
JButton btnRemove = new JButton("Remove");
btnRemove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(textStudentName.getText().contentEquals("")||textStudentId.getText().contentEquals("")||textCourseId.getText().contentEquals("")||textCourseSubject.getText().contentEquals("")) {
JOptionPane.showMessageDialog(null, "Error: Some Fields Are Empty!");
}else {
String name = textStudentName.getText();
int studentid = Integer.parseInt(textStudentId.getText());
String courseid = textCourseId.getText();
String coursesubject = textCourseSubject.getText();
for(Student s:arrayList) {
if(studentid == s.getStudentId()) {
arrayList.remove(s);
listIterator = arrayList.listIterator();
clearFields();
JOptionPane.showMessageDialog(null, "Student Data Removed Successfully!");
break;
}
}
}
}
});
btnRemove.setFont(new Font("Tahoma", Font.BOLD, 18));
btnRemove.setBounds(649, 56, 139, 68);
panel_2.add(btnRemove);
JButton btnLast = new JButton("Last");
btnLast.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
size = arrayList.size();
listIterator = arrayList.listIterator(arrayList.size());
if(listIterator.hasPrevious()) {
Student ss;
ss = listIterator.previous();
textStudentName.setText(ss.getName());;
textStudentId.setText(""+ss.getStudentId());
textCourseId.setText(ss.getCourseId());
textCourseSubject.setText(ss.getCourseSubject());
}
}
});
btnLast.setFont(new Font("Tahoma", Font.BOLD, 18));
btnLast.setBounds(151, 144, 139, 68);
panel_2.add(btnLast);
JButton btnPrevious = new JButton("Previous");
btnPrevious.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(textStudentName.getText().contentEquals("")||textStudentId.getText().contentEquals("")||textCourseId.getText().contentEquals("")||textCourseSubject.getText().contentEquals("")) {
JOptionPane.showMessageDialog(null, "Error: Some Fields Are Empty!");
}else {
if(listIterator.hasPrevious()) {
Student ss;
ss = listIterator.previous();
textStudentName.setText(ss.getName());;
textStudentId.setText(""+ss.getStudentId());
textCourseId.setText(ss.getCourseId());
textCourseSubject.setText(ss.getCourseSubject());
}else {
JOptionPane.showMessageDialog(null, "You Have Reached the First Student.");
}
}
}
});
btnPrevious.setFont(new Font("Tahoma", Font.BOLD, 18));
btnPrevious.setBounds(317, 144, 139, 68);
panel_2.add(btnPrevious);
JButton btnUpdate = new JButton("Update Data");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(textStudentName.getText().contentEquals("")||textStudentId.getText().contentEquals("")||textCourseId.getText().contentEquals("")||textCourseSubject.getText().contentEquals("")) {
JOptionPane.showMessageDialog(null, "Error: Some Fields Are Empty!");
}else {
String name = textStudentName.getText();
int studentid = Integer.parseInt(textStudentId.getText());
String courseid = textCourseId.getText();
String coursesubject = textCourseSubject.getText();
for(Student s:arrayList) {
if(studentid == s.getStudentId()) {
s.setName(name);
s.setCourseId(courseid);
s.setCourseSubject(coursesubject);
JOptionPane.showMessageDialog(null, "Changes Have Been Made Successfully!");
break;
}
}
}
}
});
btnUpdate.setFont(new Font("Tahoma", Font.BOLD, 18));
btnUpdate.setBounds(483, 144, 139, 68);
panel_2.add(btnUpdate);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnExit.setFont(new Font("Tahoma", Font.BOLD, 18));
btnExit.setBounds(649, 144, 139, 68);
panel_2.add(btnExit);
}
}
-jon
I am having a problem with opening a new window. If I comment out the if(e.getsource() == btnAddBook) the action performed opens the window. As soon as I add the if statement in and try to open the window, nothing happens.
/* this is the code that adds the button and the action listner
JButton btnAddBook = new JButton("Add Book");
btnAddBook.setFont(new Font("Tahoma", Font.BOLD, 8));
btnAddBook.setBounds(10, 327, 86, 23);
btnAddBook.addActionListener(this);
getContentPane().add(btnAddBook);
*/
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == btnAddBook){
ChildWindowAdd child = new ChildWindowAdd(this);
this.setVisible(true);
child.setVisible(true);
child.setSize(450,400);
child.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
}
}
class ChildWindowAdd extends JFrame implements ActionListener {
LibraryDatabase parent;
Container c;
JLabel lblTitle, lblaName, lblISBN, lblDate,lbl1,lbl5,lbl10;
JTextField txtTitle, txtaName, txtISBN, txtDate;
JButton btnSave;
JSlider sRating;
JCheckBox chkSci, chkFant, chkRomance, chkAction, chkThriller, chkHorror;
public ChildWindowAdd(LibraryDatabase parent){
this.parent = parent;
getContentPane().setLayout(null);
txtTitle = new JTextField();
txtTitle.setBounds(46, 29, 146, 20);
getContentPane().add(txtTitle);
txtTitle.setColumns(10);
JLabel lblTitle = new JLabel("Book Title");
lblTitle.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblTitle.setBounds(36, 11, 72, 14);
getContentPane().add(lblTitle);
JLabel lblaName = new JLabel("Author Name");
lblaName.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblaName.setBounds(36, 60, 89, 14);
getContentPane().add(lblaName);
txtaName = new JTextField();
txtaName.setBounds(46, 85, 146, 20);
getContentPane().add(txtaName);
txtaName.setColumns(10);
JLabel lblIsbnNumber = new JLabel("ISBN Number");
lblIsbnNumber.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblIsbnNumber.setBounds(36, 116, 86, 14);
getContentPane().add(lblIsbnNumber);
txtISBN = new JTextField();
txtISBN .setBounds(46, 143, 146, 20);
getContentPane().add(txtISBN );
txtISBN .setColumns(10);
JLabel lblDate = new JLabel("Date Added yyyy/mm/dd");
lblDate.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblDate.setBounds(36, 174, 177, 20);
getContentPane().add(lblDate);
txtDate = new JTextField();
txtDate.setBounds(46, 199, 146, 20);
getContentPane().add(txtDate);
txtDate.setColumns(10);
JPanel genreP = new JPanel();
genreP.setBounds(239, 29, 158, 194);
genreP.setBorder(new TitledBorder(null, "Genre's", TitledBorder.LEADING, TitledBorder.TOP, null, null));
getContentPane().add(genreP);
genreP.setLayout(null);
final JCheckBox chkSci = new JCheckBox("Sci - Fi");
chkSci.setBounds(23, 22, 97, 23);
genreP.add(chkSci);
final JCheckBox chkFant = new JCheckBox("Fantasy");
chkFant.setBounds(23, 48, 97, 23);
genreP.add(chkFant);
final JCheckBox chkRomance = new JCheckBox("Romance");
chkRomance.setBounds(23, 74, 97, 23);
genreP.add(chkRomance);
final JCheckBox chkAction = new JCheckBox("Action");
chkAction.setBounds(23, 100, 97, 23);
genreP.add(chkAction);
final JCheckBox chkThriller = new JCheckBox("Thriller");
chkThriller.setBounds(23, 126, 97, 23);
genreP.add(chkThriller);
final JCheckBox chkHorror = new JCheckBox("Horror");
chkHorror.setBounds(23, 152, 97, 23);
genreP.add(chkHorror);
final JSlider sRating = new JSlider();
sRating.setBounds(118, 280, 200, 26);
getContentPane().add(sRating);
JLabel lbl1 = new JLabel("1");
lbl1.setBounds(118, 257, 7, 14);
getContentPane().add(lbl1);
JLabel lbl10 = new JLabel("10");
lbl10.setBounds(301, 257, 17, 14);
getContentPane().add(lbl10);
JLabel lbl5 = new JLabel("5");
lbl5.setBounds(214, 257, 7, 14);
getContentPane().add(lbl5);
JButton btnSave = new JButton("Save Book");
btnSave.addActionListener(this);
btnSave.setBounds(164, 317, 110, 23);
getContentPane().add(btnSave);
JLabel lblRating = new JLabel("Rate the book");
lblRating.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblRating.setBounds(118, 226, 95, 20);
getContentPane().add(lblRating);
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
PrintWriter fileWriter = null;
try {
fileWriter = new PrintWriter(new BufferedWriter(new FileWriter("c:\\temp\\database.dat", true)));
} catch (IOException e) {
e.printStackTrace();
}
fileWriter.println( txtTitle.getText()+" , "+txtaName.getText()+" , "+txtISBN.getText()+" , "+txtDate.getText()+" , "+String.valueOf(chkSci.isSelected())+" , "+String.valueOf(chkFant.isSelected())+" , "+String.valueOf(chkRomance.isSelected())+" , "+String.valueOf(chkAction.isSelected())+" , "+String.valueOf(chkThriller.isSelected())+" , "+String.valueOf(chkHorror.isSelected())+" , "+sRating.getValue());
fileWriter.close();
}
});
}
#Override
public void actionPerformed(ActionEvent arg0) {
parent.setVisible(true);
this.dispose();
}
public void actionPerformed1(ActionEvent e) {
// TODO Auto-generated method stub
}
}
Check on the basis of button text
((JButton)source).getText().equals("Add Book")
here is complete code
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source instanceof JButton && ((JButton) source).getText().equals("Add Book")) {
...
}
}
This worked for me. I had to match the String as the e.getsource was not working.
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
String test = ((JButton)source).getText();
if(test == "Add Book"){
ChildWindowAdd child = new ChildWindowAdd(this);
this.setVisible(true);
child.setVisible(true);
child.setSize(450,400);
child.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
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");
}
}