Can't add a data from ArrayList to a jtable - java

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

Related

After exporting project to jar file, my project is not fully working

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

How to save changes made to an array list in java

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

Java color changing Text with Timer. you can help pls?

I want to write text that changes colors twice a second. Can someone tell me why it doesn't work ? if you could explain to me how to do it I would be very happy.
import java.awt.EventQueue;
import java.awt.Color;
import javax.swing.*;
import java.util.Random;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.border.BevelBorder;
import javax.swing.border.SoftBevelBorder;
public class test {
private JFrame frmTest;
private JTextField textField;
private JLabel lblNewLabel;
private JTextField textField_1;
private JLabel lblNombreUtilisPour;
private JTextField textField_2;
private JLabel lblNombreChiffr;
private JLabel lblNombreDechiffr;
private JTextField textField_3;
private JButton btnDehiffrer;
private JSeparator separator;
private JTextField textField_4;
private JButton button;
private JLabel label;
private JTextField textField_6;
private JLabel label_2;
private JTextField textField_7;
private JLabel label_3;
private JButton button_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
test window = new test();
window.frmTest.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public test() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
Random rand = new Random();
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();
Color randomColor = new Color(r, g, b);
frmTest = new JFrame();
frmTest.setResizable(false);
frmTest.setTitle("TPE");
frmTest.setBounds(100, 100, 450, 450);
frmTest.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTest.getContentPane().setLayout(null);
JLabel label_1 = new JLabel(new ImageIcon("test5.gif"));
label_1.setForeground(randomColor.brighter());
frmTest.setContentPane(label_1);
textField = new JTextField();
textField.setSelectedTextColor(randomColor.brighter());
textField.setOpaque(false);
textField.setForeground(randomColor.brighter());
textField.setName("");
textField.setFont(new Font("Tahoma", Font.PLAIN, 14));
textField.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
textField.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
textField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
if(!(Character.isDigit(evt.getKeyChar()))){
evt.consume();
}
}
});
}
});
textField.setHorizontalAlignment(SwingConstants.CENTER);
textField.setToolTipText("Entrer un nombre ici");
textField.setBounds(215, 32, 219, 20);
frmTest.getContentPane().add(textField);
textField.setColumns(10);
textField.setDocument(new JTextFieldLimit(9));
lblNewLabel = new JLabel("Entrer un nombre:");
lblNewLabel.setForeground(randomColor.brighter());
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblNewLabel.setBounds(10, 30, 141, 20);
frmTest.getContentPane().add(lblNewLabel);
textField_1 = new JTextField();
textField_1.setSelectedTextColor(randomColor.brighter());
textField_1.setForeground(randomColor.brighter());
textField_1.setFont(new Font("Tahoma", Font.PLAIN, 14));
textField_1.setOpaque(false);
textField_1.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
textField_1.setHorizontalAlignment(SwingConstants.CENTER);
textField_1.setToolTipText("Nombre utilisé pour chiffrer: ");
textField_1.setEditable(false);
textField_1.setColumns(10);
textField_1.setBounds(215, 63, 219, 20);
frmTest.getContentPane().add(textField_1);
lblNombreUtilisPour = new JLabel("Nombre utilisé pour chiffrer: ");
lblNombreUtilisPour.setForeground(randomColor.brighter());
lblNombreUtilisPour.setToolTipText("Nombre utilisé pour chiffrer: ");
lblNombreUtilisPour.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblNombreUtilisPour.setBounds(10, 61, 195, 20);
frmTest.getContentPane().add(lblNombreUtilisPour);
textField_2 = new JTextField();
textField_2.setSelectedTextColor(randomColor.brighter());
textField_2.setForeground(randomColor.brighter());
textField_2.setFont(new Font("Tahoma", Font.PLAIN, 14));
textField_2.setOpaque(false);
textField_2.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
textField_2.setEditable(false);
textField_2.setHorizontalAlignment(SwingConstants.CENTER);
textField_2.setToolTipText("Nombre chiffré: ");
textField_2.setColumns(10);
textField_2.setBounds(215, 94, 219, 20);
frmTest.getContentPane().add(textField_2);
lblNombreChiffr = new JLabel("Nombre chiffré: ");
lblNombreChiffr.setForeground(randomColor.brighter());
lblNombreChiffr.setToolTipText("Nombre chiffré: ");
lblNombreChiffr.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblNombreChiffr.setBounds(10, 92, 195, 20);
frmTest.getContentPane().add(lblNombreChiffr);
textField_3 = new JTextField();
textField_3.setSelectedTextColor(randomColor.brighter());
textField_3.setForeground(randomColor.brighter());
textField_3.setFont(new Font("Tahoma", Font.PLAIN, 14));
textField_3.setOpaque(false);
textField_3.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
textField_3.setHorizontalAlignment(SwingConstants.CENTER);
textField_3.setEditable(false);
textField_3.setToolTipText("Nombre dechiffré: ");
textField_3.setColumns(10);
textField_3.setBounds(215, 125, 219, 20);
frmTest.getContentPane().add(textField_3);
lblNombreDechiffr = new JLabel("Nombre dechiffré: ");
lblNombreDechiffr.setForeground(randomColor.brighter());
lblNombreDechiffr.setToolTipText("Nombre dechiffré: ");
lblNombreDechiffr.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblNombreDechiffr.setBounds(10, 125, 151, 20);
frmTest.getContentPane().add(lblNombreDechiffr);
btnDehiffrer = new JButton("Dechiffrer");
btnDehiffrer.setHorizontalTextPosition(SwingConstants.CENTER);
btnDehiffrer.setBorder(null);
btnDehiffrer.setContentAreaFilled(false);
btnDehiffrer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int min = 0;
int max = 250;
Random r = new Random();
//Demande de nombre
int nmb = Integer.parseInt(textField.getText());
//Chifrement
int chif = r.nextInt(max-min) * r.nextInt(max-min) + r.nextInt(max-min) / r.nextInt(max-min);
int chif_nmb = nmb * chif;
int dechif_nmb = chif_nmb / chif;
textField_3.setText(""+dechif_nmb);
}
});
JButton btnButton1 = new JButton("Chiffrer");
btnButton1.setHorizontalTextPosition(SwingConstants.CENTER);
btnButton1.setContentAreaFilled(false);
btnButton1.setBorder(null);
btnButton1.setOpaque(false);
btnButton1.setToolTipText("Chiffrer");
btnButton1.setFont(new Font("Tahoma", Font.PLAIN, 16));
btnButton1.setForeground(randomColor.brighter());
btnButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int min = 0;
int max = 250;
Random r = new Random();
//Demande de nombre
int nmb = Integer.parseInt(textField.getText());
//Chifrement
int chif = r.nextInt(max-min) * r.nextInt(max-min) + r.nextInt(max-min) / r.nextInt(max-min);
textField_1.setText(""+chif);
int chif_nmb = nmb * chif;
textField_2.setText(""+chif_nmb);
}
});
btnButton1.setBounds(0, 156, 450, 23);
frmTest.getContentPane().add(btnButton1);
btnDehiffrer.setToolTipText("Dechiffrer");
btnDehiffrer.setForeground(randomColor.brighter());
btnDehiffrer.setFont(new Font("Tahoma", Font.PLAIN, 16));
btnDehiffrer.setBounds(0, 190, 450, 23);
frmTest.getContentPane().add(btnDehiffrer);
separator = new JSeparator();
separator.setOpaque(true);
separator.setBackground(randomColor.brighter());
separator.setForeground(randomColor.brighter());
separator.setBounds(0, 224, 450, 2);
frmTest.getContentPane().add(separator);
textField_4 = new JTextField();
textField_4.setSelectedTextColor(randomColor.brighter());
textField_4.setForeground(randomColor.brighter());
textField_4.setFont(new Font("Tahoma", Font.PLAIN, 14));
textField_4.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
textField_4.setOpaque(false);
textField_4.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
textField_4.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
if(!(Character.isDigit(evt.getKeyChar()))){
evt.consume();
}
}
});
}
});
textField_4.setToolTipText("Entrer un nombre ici");
textField_4.setHorizontalAlignment(SwingConstants.CENTER);
textField_4.setColumns(10);
textField_4.setBounds(215, 261, 219, 20);
frmTest.getContentPane().add(textField_4);
textField_4.setDocument(new JTextFieldLimit(9));
label = new JLabel("Entrer un nombre:");
label.setForeground(randomColor.brighter());
label.setFont(new Font("Tahoma", Font.PLAIN, 15));
label.setBounds(10, 259, 141, 20);
frmTest.getContentPane().add(label);
textField_6 = new JTextField();
textField_6.setSelectedTextColor(randomColor.brighter());
textField_6.setForeground(randomColor.brighter());
textField_6.setFont(new Font("Tahoma", Font.PLAIN, 14));
textField_6.setOpaque(false);
textField_6.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
textField_6.addKeyListener(new KeyAdapter() {
#Override
public void keyTyped(KeyEvent e) {
textField_6.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
if(!(Character.isDigit(evt.getKeyChar()))){
evt.consume();
}
}
});
}
});
textField_6.setToolTipText("Nombre chiffré: ");
textField_6.setHorizontalAlignment(SwingConstants.CENTER);
textField_6.setColumns(10);
textField_6.setBounds(215, 292, 219, 20);
frmTest.getContentPane().add(textField_6);
textField_6.setDocument(new JTextFieldLimit(9));
label_2 = new JLabel("Nombre chiffré: ");
label_2.setForeground(randomColor.brighter());
label_2.setToolTipText("Nombre chiffré: ");
label_2.setFont(new Font("Tahoma", Font.PLAIN, 15));
label_2.setBounds(10, 290, 195, 20);
frmTest.getContentPane().add(label_2);
textField_7 = new JTextField();
textField_7.setSelectedTextColor(randomColor.brighter());
textField_7.setForeground(randomColor.brighter());
textField_7.setFont(new Font("Tahoma", Font.PLAIN, 14));
textField_7.setOpaque(false);
textField_7.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
textField_7.setEditable(false);
textField_7.setToolTipText("Nombre dechiffré: ");
textField_7.setHorizontalAlignment(SwingConstants.CENTER);
textField_7.setColumns(10);
textField_7.setBounds(215, 323, 219, 20);
frmTest.getContentPane().add(textField_7);
label_3 = new JLabel("Nombre dechiffré: ");
label_3.setForeground(randomColor.brighter());
label_3.setToolTipText("Nombre dechiffré: ");
label_3.setFont(new Font("Tahoma", Font.PLAIN, 15));
label_3.setBounds(10, 321, 151, 20);
frmTest.getContentPane().add(label_3);
button = new JButton("Chiffrer");
button.setHorizontalTextPosition(SwingConstants.CENTER);
button.setContentAreaFilled(false);
button.setBorder(null);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Demande de nombre
int nmb = Integer.parseInt(textField_4.getText());
//Chifrement
int chif_nmb = (510-nmb)+834*nmb;
textField_6.setText(""+chif_nmb);
}
});
button.setToolTipText("Chiffrer");
button.setForeground(randomColor.brighter());
button.setFont(new Font("Tahoma", Font.PLAIN, 16));
button.setBounds(0, 354, 450, 23);
frmTest.getContentPane().add(button);
button_1 = new JButton("Dechiffrer");
button_1.setHorizontalTextPosition(SwingConstants.CENTER);
button_1.setBorder(null);
button_1.setContentAreaFilled(false);
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Demande de nombre
int nmb = Integer.parseInt(textField_6.getText());
//Chifrement
int chif_nmb = (nmb - 510)/833;
textField_7.setText(""+chif_nmb);
}
});
button_1.setToolTipText("Dechiffrer");
button_1.setForeground(randomColor.brighter());
button_1.setFont(new Font("Tahoma", Font.PLAIN, 16));
button_1.setBounds(0, 388, 450, 23);
frmTest.getContentPane().add(button_1);
JLabel lblCh = new JLabel("Chiffrement complexe");
lblCh.setForeground(randomColor.brighter());
lblCh.setFont(new Font("Comic Sans MS", Font.BOLD, 19));
lblCh.setBounds(121, 0, 219, 28);
frmTest.getContentPane().add(lblCh);
JLabel label_4 = new JLabel("Chiffrement normal");
label_4.setForeground(randomColor.brighter());
label_4.setFont(new Font("Comic Sans MS", Font.BOLD, 19));
label_4.setBounds(121, 230, 219, 28);
frmTest.getContentPane().add(label_4);
}
}
You could write a Thread changing the color of your component as needed, eg :
class Effect extends Thread {
public void run() {
try {
while (true) {
yourLabel.setForeground(new Color(aValue, bValue, cValue)); // you can apply coloring logic
Thread.sleep(500); //sleep for 0.5 secs , so your color changes twice every second
}
} catch (InterruptedException e) {
}
}
}

add dynamic checkbox in java windowbuilder

I want to add a dynamic checkbox after selecting an item in combo box.
I am working on eclipse and design my frame on window builder.
final JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String typeName = comboBox.getSelectedItem().toString();
for (int i = 0; i < SqlQuery.getCoursesName(typeName).size(); i++) {
JCheckBox c = new JCheckBox(SqlQuery.getCoursesName(typeName).get(i));
c.setVisible(true);
coursePanel.add(c);
frame.repaint();
frame.validate();
System.out.println(c.getText());
}
}
});
comboBox.setBounds(208, 221, 91, 20);
frame.getContentPane().add(comboBox);
edit: thats my full code.
public class registerForm {
private JFrame frame;
private JTextField txtFirstName;
private JTextField txtLastName;
private JTextField txtPassword;
private JTextField txtEmail;
List<Integer> coursesId; // ן¿½ן¿½ן¿½ן¿½ן¿½ ן¿½ן¿½ ן¿½ן¿½ן¿½ן¿½ן¿½ ן¿½ן¿½ ן¿½ן¿½ן¿½ן¿½ן¿½ן¿½
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
registerForm window = new registerForm();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public registerForm() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 442);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("\u05D4\u05E8\u05E9\u05DE\u05D4");
lblNewLabel.setBounds(165, 11, 91, 29);
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 24));
frame.getContentPane().add(lblNewLabel);
JLabel label = new JLabel("\u05E9\u05DD \u05E4\u05E8\u05D8\u05D9:");
label.setBounds(363, 55, 61, 14);
label.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label);
txtFirstName = new JTextField();
txtFirstName.setBounds(75, 51, 221, 20);
frame.getContentPane().add(txtFirstName);
txtFirstName.setColumns(10);
JLabel label_1 = new JLabel("\u05E9\u05DD \u05DE\u05E9\u05E4\u05D7\u05D4:");
label_1.setBounds(344, 80, 80, 14);
label_1.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_1);
txtLastName = new JTextField();
txtLastName.setBounds(75, 82, 221, 20);
txtLastName.setColumns(10);
frame.getContentPane().add(txtLastName);
txtPassword = new JTextField();
txtPassword.setBounds(75, 140, 221, 20);
txtPassword.setColumns(10);
frame.getContentPane().add(txtPassword);
JLabel label_2 = new JLabel("\u05DE\u05D9\u05D9\u05DC:");
label_2.setBounds(392, 110, 32, 14);
label_2.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_2);
txtEmail = new JTextField();
txtEmail.setBounds(75, 109, 221, 20);
txtEmail.setColumns(10);
frame.getContentPane().add(txtEmail);
JLabel label_3 = new JLabel("\u05E1\u05D9\u05E1\u05DE\u05D0:");
label_3.setBounds(373, 141, 51, 14);
label_3.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_3);
final JDateChooser dateChooser = new JDateChooser();
dateChooser.setBounds(75, 171, 221, 39);
frame.getContentPane().add(dateChooser);
JLabel label_4 = new JLabel("\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4:");
label_4.setBounds(344, 167, 90, 14);
label_4.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_4);
JButton btnSend = new JButton("\u05E9\u05DC\u05D7");
btnSend.setBounds(258, 334, 61, 58);
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// date
Date date = new Date(dateChooser.getDate().getTime());
}
});
frame.getContentPane().add(btnSend);
JButton button = new JButton("\u05E0\u05E7\u05D4");
button.setBounds(175, 334, 61, 58);
frame.getContentPane().add(button);
JLabel label_5 = new JLabel("\u05DE\u05D2\u05DE\u05D4:");
label_5.setFont(new Font("Tahoma", Font.PLAIN, 14));
label_5.setBounds(382, 218, 42, 14);
frame.getContentPane().add(label_5);
final JPanel coursePanel = new JPanel();
coursePanel.setBounds(10, 249, 286, 74);
frame.getContentPane().add(coursePanel);
coursePanel.setLayout(null);
final JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String typeName = comboBox.getSelectedItem().toString();
for (int i = 0; i < SqlQuery.getCoursesName(typeName).size(); i++) {
JCheckBox c = new JCheckBox(SqlQuery.getCoursesName(typeName).get(i));
int selectedIndex = comboBox.getSelectedIndex();
boolean isInPanel = c.getParent() == coursePanel;
if (selectedIndex == 1 && !isInPanel) {
coursePanel.add(c);
coursePanel.repaint(); //Repaint the proper panel that has this component.
coursePanel.revalidate();
} else if (isInPanel && selectedIndex != 1) {
coursePanel.remove(c);
coursePanel.repaint(); //Repaint the proper panel that has this component.
coursePanel.revalidate();
}
coursePanel.repaint();
coursePanel.validate();
System.out.println(c.getText());
}
}
});
comboBox.setBounds(208, 221, 91, 20);
frame.getContentPane().add(comboBox);
// fill comboBox
List<String> lst = SqlQuery.getTypes();
for (int i = 0; i < lst.size(); i++)
comboBox.addItem(lst.get(i));
JLabel label_6 = new JLabel("\u05E9\u05DC\u05D9\u05D8\u05D4 \u05D1\u05E7\u05D5\u05E8\u05E1\u05D9\u05DD");
label_6.setFont(new Font("Tahoma", Font.PLAIN, 14));
label_6.setBounds(321, 245, 103, 14);
frame.getContentPane().add(label_6);
}
}
Hope you understand what I wrote. I want to show a list of coursesName after click on the comboBox.
Why the frame does'nt show the checkbox?
Thank you.
First and foremost. The comboBox.setBounds() is a very bad practice. Take some time and see Layout Managers. Also add 'swing' tag in your post since you are referring to Swing library.
The frame doesn't show the component because you repaint the wrong one. You add the checkbox in coursePanel, which means you have to repaint() & revalidate() coursePanel. So coursePanel.repaint() instead of frame.repaint() will help you.
Also checkBox.setVisible(true)is not required, since checkBox is visible by default.
Finally i have added the way of how i would do it.
package test;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
private JFrame frame;
private JCheckBox checkBox;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test window = new Test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test() {
frame = new JFrame();
frame.setPreferredSize(new Dimension(300, 300));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(createPanel());
frame.pack();
}
private JPanel createPanel() {
JPanel p = new JPanel(new FlowLayout());
checkBox = new JCheckBox("I am a checkbox"); //Create the checkbox
JComboBox<String> combo = new JComboBox<>();
combo.addItem("Hello");
combo.addItem("Stack");
combo.addItem("OverFlow");
combo.addActionListener(e -> {
//Its better to handle indices when there is not dynmic data to your combobox
int selectedIndex = combo.getSelectedIndex();
boolean isInPanel = checkBox.getParent() == p;
if (selectedIndex == 1 && !isInPanel) {
p.add(checkBox);
p.repaint(); //Repaint the proper panel that has this component.
p.revalidate();
} else if (isInPanel && selectedIndex != 1) {
p.remove(checkBox);
p.repaint(); //Repaint the proper panel that has this component.
p.revalidate();
}
});
p.add(combo);
return p;
}
}
The answer to your problem (make the checkbox visible) after comments:
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class registerForm {
private JFrame frame;
private JTextField txtFirstName;
private JTextField txtLastName;
private JTextField txtPassword;
private JTextField txtEmail;
private JCheckBox checkBox;
List<Integer> coursesId; // ן¿½ן¿½ן¿½ן¿½ן¿½ ן¿½ן¿½ ן¿½ן¿½ן¿½ן¿½ן¿½ ן¿½ן¿½ ן¿½ן¿½ן¿½ן¿½ן¿½ן¿½
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
registerForm window = new registerForm();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public registerForm() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 442);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("\u05D4\u05E8\u05E9\u05DE\u05D4");
lblNewLabel.setBounds(165, 11, 91, 29);
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 24));
frame.getContentPane().add(lblNewLabel);
JLabel label = new JLabel("\u05E9\u05DD \u05E4\u05E8\u05D8\u05D9:");
label.setBounds(363, 55, 61, 14);
label.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label);
txtFirstName = new JTextField();
txtFirstName.setBounds(75, 51, 221, 20);
frame.getContentPane().add(txtFirstName);
txtFirstName.setColumns(10);
JLabel label_1 = new JLabel("\u05E9\u05DD \u05DE\u05E9\u05E4\u05D7\u05D4:");
label_1.setBounds(344, 80, 80, 14);
label_1.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_1);
txtLastName = new JTextField();
txtLastName.setBounds(75, 82, 221, 20);
txtLastName.setColumns(10);
frame.getContentPane().add(txtLastName);
txtPassword = new JTextField();
txtPassword.setBounds(75, 140, 221, 20);
txtPassword.setColumns(10);
frame.getContentPane().add(txtPassword);
JLabel label_2 = new JLabel("\u05DE\u05D9\u05D9\u05DC:");
label_2.setBounds(392, 110, 32, 14);
label_2.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_2);
txtEmail = new JTextField();
txtEmail.setBounds(75, 109, 221, 20);
txtEmail.setColumns(10);
frame.getContentPane().add(txtEmail);
JLabel label_3 = new JLabel("\u05E1\u05D9\u05E1\u05DE\u05D0:");
label_3.setBounds(373, 141, 51, 14);
label_3.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_3);
JLabel label_4 = new JLabel("\u05EA\u05D0\u05E8\u05D9\u05DA \u05DC\u05D9\u05D3\u05D4:");
label_4.setBounds(344, 167, 90, 14);
label_4.setFont(new Font("Tahoma", Font.PLAIN, 14));
frame.getContentPane().add(label_4);
JButton button = new JButton("\u05E0\u05E7\u05D4");
button.setBounds(175, 334, 61, 58);
frame.getContentPane().add(button);
JLabel label_5 = new JLabel("\u05DE\u05D2\u05DE\u05D4:");
label_5.setFont(new Font("Tahoma", Font.PLAIN, 14));
label_5.setBounds(382, 218, 42, 14);
frame.getContentPane().add(label_5);
final JPanel coursePanel = new JPanel();
coursePanel.setBounds(10, 249, 286, 74);
frame.getContentPane().add(coursePanel);
coursePanel.setLayout(null);
List<String> lst = new ArrayList<>();
lst.add("Hello");
lst.add("Stack");
lst.add("Over");
lst.add("Flow");
//Prepare the checkBox
checkBox = new JCheckBox("nothing");
final JComboBox<String> comboBox = new JComboBox<String>();
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String typeName = comboBox.getSelectedItem().toString();
for (int i = 0; i < lst.size(); i++) {
checkBox.setText(typeName);
//set the same bounds as comboBox but reduce its X by 80.
//Compare checkBoxbounds and combobox bounds
//Remind: setBounds is baaaaad practice.
checkBox.setBounds(128, 221, 91, 20);
//if you want to add it in coursePanel, change all frame.getContentPane() to coursePanel
int selectedIndex = comboBox.getSelectedIndex();
boolean isInPanel = checkBox.getParent() == frame.getContentPane();
if (selectedIndex == 1 && !isInPanel) {
frame.getContentPane().add(checkBox);
} else if (isInPanel && selectedIndex != 1) {
frame.getContentPane().remove(checkBox);
}
frame.getContentPane().repaint();
frame.getContentPane().validate();
System.out.println(checkBox.getText());
}
}
});
comboBox.setBounds(208, 221, 91, 20);
frame.getContentPane().add(comboBox);
// fill comboBox
for (int i = 0; i < lst.size(); i++)
comboBox.addItem(lst.get(i));
JLabel label_6 = new JLabel("\u05E9\u05DC\u05D9\u05D8\u05D4 \u05D1\u05E7\u05D5\u05E8\u05E1\u05D9\u05DD");
label_6.setFont(new Font("Tahoma", Font.PLAIN, 14));
label_6.setBounds(321, 245, 103, 14);
frame.getContentPane().add(label_6);
}
}
Another option is to create the checkbox as a field outside of the actionlistener (like i did) and set its bounds with window builder and use setVisible(false). Then on your listener, setVisible(true)

how to read from text file to labels

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

Categories