I have a JComboBox that retrieves it's data from a database (Ahmed, Mahmoud, Ali).
when I select the first option, it displays the information of Ahmed that I retrieved from the database and shown in a JFrame as text of a JLabels
The problem is that when I choose the second option, it overwrites the informations of Ahmed with Mahmoud's and display it above.
JPanel calendarPanel = new JPanel();
calendarPanel.setToolTipText("");
calendarPanel.setBorder(new TitledBorder(null, "Calendar Panel", TitledBorder.LEADING, TitledBorder.TOP, null, null));
calendarPanel.setBounds(12, 13, 878, 254);
frameDetails.getContentPane().add(calendarPanel);
calendarPanel.setLayout(null);
JLabel lblSat = new JLabel("Saturday");
lblSat.setBounds(12, 70, 56, 16);
calendarPanel.add(lblSat);
JLabel lblSun = new JLabel("Sunday");
lblSun.setBounds(12, 99, 56, 16);
calendarPanel.add(lblSun);
JLabel lblMon = new JLabel("Monday");
lblMon.setBounds(12, 128, 56, 16);
calendarPanel.add(lblMon);
JLabel lblTus = new JLabel("Tuesday");
lblTus.setBounds(12, 157, 56, 16);
calendarPanel.add(lblTus);
JLabel lblWes = new JLabel("Wednesday");
lblWes.setBounds(12, 187, 77, 16);
calendarPanel.add(lblWes);
JLabel lblThur = new JLabel("Thursday");
lblThur.setBounds(12, 217, 56, 16);
calendarPanel.add(lblThur);
JPanel panel_12 = new JPanel();
String statment12 = "select f310t410 from calendar where days='saturday'";
panelColorChanger(panel_12, statment12);
panel_12.setForeground(Color.LIGHT_GRAY);
panel_12.setBounds(144, 64, 90, 21);
calendarPanel.add(panel_12);
JPanel panel_14 = new JPanel();
String statment14 = "select f420t520 from calendar where days='saturday'";
panelColorChanger(panel_14, statment14);
panel_14.setForeground(Color.LIGHT_GRAY);
panel_14.setBounds(300, 64, 90, 21);
calendarPanel.add(panel_14);
String statment16 = "select f530t630 from calendar where days='saturday'";
String statment18 = "select f640t740 from calendar where days='saturday'";
String statment110 = "select f750t850 from calendar where days='saturday'";
JPanel panel_22 = new JPanel();
panel_22.setForeground(Color.LIGHT_GRAY);
String statment22 = "select f310t410 from calendar where days='sunday'";
panelColorChanger(panel_22, statment22);
panel_22.setBounds(145, 92, 90, 24);
calendarPanel.add(panel_22);
JPanel panel_24 = new JPanel();
panel_24.setForeground(Color.LIGHT_GRAY);
String statment24 = "select f420t520 from calendar where days='sunday'";
panelColorChanger(panel_24, statment24);
panel_24.setBounds(301, 92, 90, 24);
calendarPanel.add(panel_24);
String statment26 = "select f530t630 from calendar where days='sunday'";
String statment28 = "select f640t740 from calendar where days='sunday'";
String statment210 = "select f750t850 from calendar where days='sunday'";
JPanel panel_32 = new JPanel();
panel_32.setForeground(Color.LIGHT_GRAY);
String statment32 = "select f310t410 from calendar where days='monday'";
panelColorChanger(panel_32, statment32);
panel_32.setBounds(145, 122, 90, 22);
calendarPanel.add(panel_32);
JPanel panel_34 = new JPanel();
panel_34.setForeground(Color.LIGHT_GRAY);
String statment34 = "select f420t520 from calendar where days='monday'";
panelColorChanger(panel_34, statment34);
panel_34.setBounds(301, 122, 90, 22);
calendarPanel.add(panel_34);
String statment36 = "select f530t630 from calendar where days='monday'";
String statment38 = "select f640t740 from calendar where days='monday'";
String statment310 = "select f750t850 from calendar where days='monday'";
JPanel panel_42 = new JPanel();
panel_42.setForeground(Color.LIGHT_GRAY);
String statment42 = "select f310t410 from calendar where days='tuesday'";
panelColorChanger(panel_42, statment42);
panel_42.setBounds(145, 149, 90, 23);
calendarPanel.add(panel_42);
JPanel panel_44 = new JPanel();
panel_44.setForeground(Color.LIGHT_GRAY);
String statment44 = "select f420t520 from calendar where days='tuesday'";
panelColorChanger(panel_44, statment44);
panel_44.setBounds(301, 149, 90, 23);
calendarPanel.add(panel_44);
String statment46 = "select f530t630 from calendar where days='tuesday'";
String statment48 = "select f640t740 from calendar where days='tuesday'";
String statment410 = "select f750t850 from calendar where days='tuesday'";
JPanel panel_52 = new JPanel();
panel_52.setForeground(Color.LIGHT_GRAY);
String statment52 = "select f310t410 from calendar where days='wednesday'";
panelColorChanger(panel_52, statment52);
panel_52.setBounds(145, 179, 90, 25);
calendarPanel.add(panel_52);
JPanel panel_54 = new JPanel();
panel_54.setForeground(Color.LIGHT_GRAY);
String statment54 = "select f420t520 from calendar where days='wednesday'";
panelColorChanger(panel_54, statment54);
panel_54.setBounds(301, 179, 90, 25);
calendarPanel.add(panel_54);
String statment56 = "select f530t630 from calendar where days='wednesday'";
String statment58 = "select f640t740 from calendar where days='wednesday'";
String statment510 = "select f750t850 from calendar where days='wednesday'";
JPanel panel_62 = new JPanel();
panel_62.setForeground(Color.LIGHT_GRAY);
String statment62 = "select f310t410 from calendar where days='thursday'";
panelColorChanger(panel_62, statment62);
panel_62.setBounds(145, 209, 90, 24);
calendarPanel.add(panel_62);
JPanel panel_64 = new JPanel();
panel_64.setForeground(Color.LIGHT_GRAY);
String statment64 = "select f420t520 from calendar where days='thursday'";
panelColorChanger(panel_64, statment64);
panel_64.setBounds(301, 209, 90, 24);
calendarPanel.add(panel_64);
String statment66 = "select f530t630 from calendar where days='thursday'";
String statment68 = "select f640t740 from calendar where days='thursday'";
String statment610 = "select f750t850 from calendar where days='thursday'";
////////////////////////////////////////////////////////////////////////////////Calendar Table
////////////////////////////////////////////////////////////////////////////////Add Patient
patientPanel = new JPanel();
patientPanel.setLayout(null);
patientPanel.setBorder(new TitledBorder(null, "Add New Patient", TitledBorder.LEADING, TitledBorder.TOP, null, null));
patientPanel.setBounds(12, 280, 1304, 163);
frameDetails.getContentPane().add(patientPanel);
lblName = new JLabel("Name");
lblName.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblName.setBounds(31, 24, 56, 16);
patientPanel.add(lblName);
txtName = new JTextField();
txtName.setBounds(120, 24, 240, 22);
patientPanel.add(txtName);
txtName.setColumns(10);
lblAge = new JLabel("Age");
lblAge.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblAge.setBounds(31, 59, 56, 23);
patientPanel.add(lblAge);
lblMobile = new JLabel("Mobile");
lblMobile.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblMobile.setBounds(31, 95, 56, 16);
patientPanel.add(lblMobile);
txtAge = new JTextField();
txtAge.setColumns(10);
txtAge.setBounds(120, 59, 240, 22);
patientPanel.add(txtAge);
txtMobile = new JTextField();
txtMobile.setColumns(10);
txtMobile.setBounds(120, 95, 240, 22);
patientPanel.add(txtMobile);
JComboBox comboBoxDays = new JComboBox();
List<String> arrDays = new ArrayList<String>();
//arrDays.add("44444444");
//comboBoxDays.setModel(new DefaultComboBoxModel(arrDays.toArray()));
comboBoxDays.setBounds(474, 24, 127, 22);
patientPanel.add(comboBoxDays);
JComboBox comboBoxTime = new JComboBox();
List<String> arrTime = new ArrayList<String>();
arrTime.add("");
comboBoxTime.setModel(new DefaultComboBoxModel(arrTime.toArray()));
// add time available to list of times when select a day
comboBoxDays.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
});
comboBoxTime.setBounds(474, 61, 127, 22);
patientPanel.add(comboBoxTime);
JLabel lblDay = new JLabel("Day");
lblDay.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblDay.setBounds(389, 27, 56, 16);
patientPanel.add(lblDay);
JLabel lblTime = new JLabel("Time");
lblTime.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblTime.setBounds(389, 64, 56, 16);
patientPanel.add(lblTime);
JLabel lblDescription = new JLabel("Description");
lblDescription.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblDescription.setBounds(31, 132, 77, 22);
patientPanel.add(lblDescription);
txtDescription = new JTextField();
txtDescription.setColumns(10);
txtDescription.setBounds(120, 132, 240, 22);
patientPanel.add(txtDescription);
JButton btnAddNewPatient = new JButton("Add New Patient");
btnAddNewPatient.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String radioText = "Not Confirmed";
try {
if (txtName.getText().isEmpty() || txtAge.getText().isEmpty() || txtMobile.getText().isEmpty() || txtDescription.getText().isEmpty() || comboBoxDays.getSelectedItem().toString().isEmpty() || comboBoxTime.getSelectedItem().toString().isEmpty())
{
JOptionPane.showMessageDialog(null, "Please fill empty fields!");
}
else {
//to insert the patient name with his time into table patientCalender
String statInsertPatient = "insert into patientCalendar values ('"+txtName.getText()+"','"+comboBoxDays.getSelectedItem().toString()+"','"+comboBoxTime.getSelectedItem().toString()+"')";
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnAddNewPatient.setBounds(630, 24, 194, 58);
patientPanel.add(btnAddNewPatient);
////////////////////////////////////////////////////////////////////////////////Add Patient
////////////////////////////////////////////////////////////////////////////////Details table
detailsPanel = new JPanel();
detailsPanel.setLayout(null);
detailsPanel.setToolTipText("");
detailsPanel.setBorder(new TitledBorder(null, "Details", TitledBorder.LEADING, TitledBorder.TOP, null, null));
detailsPanel.setBounds(12, 456, 1304, 252);
frameDetails.getContentPane().add(detailsPanel);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(12, 32, 940, 207);
detailsPanel.add(scrollPane);
detailsTable = new JTable();
scrollPane.setViewportView(detailsTable);
detailsTable.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
}
));
detailsTable.setBorder(new LineBorder(new Color(0, 0, 0)));
textFieldSearch = new JTextField();
textFieldSearch.setToolTipText("Enter Patient Name");
textFieldSearch.setBounds(1034, 45, 179, 29);
detailsPanel.add(textFieldSearch);
textFieldSearch.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent arg0) {
}
}
);
textFieldSearch.setColumns(10);
JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "delete from patient where name='"+textFieldSearch.getText() +"' ";
PreparedStatement pst= connection.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null , "Deleted ");
pst.close();
} catch(Exception e1) {
e1.printStackTrace();
}
}
}
);
btnDelete.setBounds(1065, 133, 116, 40);
detailsPanel.add(btnDelete);
JButton btnShow = new JButton("Show All");
btnShow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "select * from patient ";
PreparedStatement pst= connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
detailsTable.setModel(DbUtils.resultSetToTableModel(rs));
} catch(Exception el) {
el.printStackTrace();
}
}
});
btnShow.setBounds(1065, 178, 116, 42);
detailsPanel.add(btnShow);
JButton btnSearch = new JButton("Search");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "select * from patient where name=?";
PreparedStatement pst= connection.prepareStatement(query);
pst.setString(1, textFieldSearch.getText() );
ResultSet rs = pst.executeQuery();
detailsTable.setModel(DbUtils.resultSetToTableModel(rs));
pst.close();
} catch(Exception e1) {
e1.printStackTrace();
}
}
});
btnSearch.setBounds(1065, 87, 116, 40);
detailsPanel.add(btnSearch);
////////////////////////////////////////////////////////////////////////////////Details table
////////////////////////////////////////////////////////////////////////////////Set Calendar
JPanel setCalendarPanel = new JPanel();
setCalendarPanel.setBorder(new TitledBorder(null, "Set Calender Days", TitledBorder.LEADING, TitledBorder.TOP, null, null));
setCalendarPanel.setBounds(902, 24, 260, 243);
frameDetails.getContentPane().add(setCalendarPanel);
setCalendarPanel.setLayout(null);
chckbxSaturday = new JCheckBox("Saturday");
chckbxSaturday.setBounds(8, 54, 160, 25);
setCalendarPanel.add(chckbxSaturday);
chckbxSunday = new JCheckBox("Sunday");
chckbxSunday.setBounds(8, 84, 160, 25);
setCalendarPanel.add(chckbxSunday);
chckbxMonday = new JCheckBox("Monday");
chckbxMonday.setBounds(8, 116, 160, 25);
setCalendarPanel.add(chckbxMonday);
chckbxTuesday = new JCheckBox("Tuesday");
chckbxTuesday.setBounds(8, 146, 160, 25);
setCalendarPanel.add(chckbxTuesday);
chckbxWednesday = new JCheckBox("Wednesday");
chckbxWednesday.setBounds(8, 178, 160, 25);
setCalendarPanel.add(chckbxWednesday);
chckbxThursday = new JCheckBox("Thursday");
chckbxThursday.setBounds(8, 209, 87, 25);
setCalendarPanel.add(chckbxThursday);
JLabel lblPleaseSelectAvailable = new JLabel("Please select available days: ");
lblPleaseSelectAvailable.setFont(new Font("Tahoma", Font.BOLD, 16));
lblPleaseSelectAvailable.setBounds(8, 19, 239, 37);
setCalendarPanel.add(lblPleaseSelectAvailable);
//////////////////////////////////
//Set selected days on launch to add the selected days to comboBoxDays
String sqlquery11 = "select f310t410 from calendar WHERE calendar.days='saturday'";
String panelColor11= connect2databaseWithexecuteQuery(sqlquery11);
if (panelColor11.contentEquals("white") || panelColor11.contentEquals("green") || panelColor11.contentEquals("red")){
chckbxSaturday.setSelected(true);
}
String sqlquery22 = "select f310t410 from calendar WHERE calendar.days='sunday'";
String panelColor22= connect2databaseWithexecuteQuery(sqlquery22);
if (panelColor22.contentEquals("white") || panelColor22.contentEquals("green") || panelColor22.contentEquals("red"))
{
chckbxSunday.setSelected(true);
}
String sqlquery33 = "select f310t410 from calendar WHERE calendar.days='monday'";
String panelColor33= connect2databaseWithexecuteQuery(sqlquery33);
if (panelColor33.contentEquals("white") || panelColor33.contentEquals("green") || panelColor33.contentEquals("red"))
{
chckbxMonday.setSelected(true);
}
String sqlquery44 = "select f310t410 from calendar WHERE calendar.days='tuesday'";
String panelColor44= connect2databaseWithexecuteQuery(sqlquery44);
if (panelColor44.contentEquals("white") || panelColor44.contentEquals("green") || panelColor44.contentEquals("red"))
{
chckbxTuesday.setSelected(true);
}
String sqlquery55 = "select f310t410 from calendar WHERE calendar.days='wednesday'";
String panelColor55= connect2databaseWithexecuteQuery(sqlquery55);
if (panelColor55.contentEquals("white") || panelColor55.contentEquals("green") || panelColor55.contentEquals("red"))
{
chckbxWednesday.setSelected(true);
}
String sqlquery66 = "select f310t410 from calendar WHERE calendar.days='thursday'";
String panelColor66= connect2databaseWithexecuteQuery(sqlquery66);
if (panelColor66.contentEquals("white") || panelColor66.contentEquals("green") || panelColor66.contentEquals("red")){
chckbxThursday.setSelected(true);
}
///***************
//check if checkboxes selected to add their text to comboBoxDays
arrDays.add("");
if (chckbxSaturday.isSelected()){
arrDays.add("Saturday");
}
if (chckbxSunday.isSelected()){
arrDays.add("Sunday");
}
if (chckbxMonday.isSelected()){
arrDays.add("Monday");
}
if (chckbxTuesday.isSelected()){
arrDays.add("Tuesday");
}
if (chckbxWednesday.isSelected()){
arrDays.add("Wednesday");
}
if (chckbxThursday.isSelected()){
arrDays.add("Thursday");
}
comboBoxDays.setModel(new DefaultComboBoxModel(arrDays.toArray()));
JButton btnUpdatePatientStatus = new JButton("Update Patient Status");
btnUpdatePatientStatus.setBounds(843, 21, 194, 58);
patientPanel.add(btnUpdatePatientStatus);
////////////////////////////////
JButton btnSetCalender = new JButton("Set Calender"); // Button Set Calendar
btnSetCalender.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (chckbxSaturday.isSelected()){
//access database
//make colms of Saturday all white
if(arrDays.contains("Saturday") == false){
arrDays.add("Saturday");
}
}
else
{
//access database
//make colms of Saturday all gray
if(arrDays.contains("Saturday") == true){
arrDays.remove("Saturday");
}
}
if (chckbxSunday.isSelected()){
//access database
//make colms of Sunday all white
if(arrDays.contains("Sunday") == false){
arrDays.add("Sunday");
}
}
else
{
//access database
//make colms of Sunday all gray
if(arrDays.contains("Sunday") == true){
arrDays.remove("Sunday");
}
}
if (chckbxMonday.isSelected()){
//access database
//make colms of Monday all white
if(arrDays.contains("Monday") == false){
arrDays.add("Monday");
}
}
else
{
//access database
//make colms of Monday all gray
if(arrDays.contains("Monday") == true){
arrDays.remove("Monday");
}
}
if (chckbxTuesday.isSelected()){
//access database
//make colms of Tuesday all white
if(arrDays.contains("Tuesday") == false){
arrDays.add("Tuesday");
}
}
else
{
//access database
//make colms of Tuesday all gray
if(arrDays.contains("Tuesday") == true){
arrDays.remove("Tuesday");
}
}
if (chckbxWednesday.isSelected()){
//access database
//make colms of Wednesday all white
if(arrDays.contains("Wednesday") == false){
arrDays.add("Wednesday");
}
}
else
{
//access database
//make colms of Wednesday all gray
if(arrDays.contains("Wednesday") == true){
arrDays.remove("Wednesday");
}
}
if (chckbxThursday.isSelected()){
//access database
//make colms of Thursday all white
if(arrDays.contains("Thursday") == false){
arrDays.add("Thursday");
}
}
else
{
//access database
//make colms of Thursday all gray
if(arrDays.contains("Thursday") == true){
arrDays.remove("Thursday");
}
}
comboBoxDays.setModel(new DefaultComboBoxModel(arrDays.toArray())); //Days ComboBox
JOptionPane.showMessageDialog(null, "Calendar Set Successfully!","Calender Set",JOptionPane.DEFAULT_OPTION);
}
});
btnSetCalender.setBounds(104, 203, 146, 37);
setCalendarPanel.add(btnSetCalender);
///////////////////////////////////////////////////////////////////////////////////////////Add Doctor
JPanel panel = new JPanel();
panel.setBorder(new TitledBorder(null, "Add/Choose Doctor", TitledBorder.LEADING, TitledBorder.TOP, null, null));
panel.setBounds(1174, 24, 162, 241);
frameDetails.getContentPane().add(panel);
panel.setLayout(null);
comboBoxDoctorsNames = new JComboBox();
arrDoctors = new ArrayList<String>();
arrDoctors.add("");
arrDoctors.addAll(getMultiDocsNames());
System.out.println(getMultiDocsNames());
comboBoxDoctorsNames.setModel(new DefaultComboBoxModel(arrDoctors.toArray()));
comboBoxDoctorsNames.setBounds(12, 49, 138, 22);
panel.add(comboBoxDoctorsNames);
comboBoxDoctorsNames.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String selectedDoctor = comboBoxDoctorsNames.getSelectedItem().toString();
String query = "select * from '"+selectedDoctor+"'";
List<String> arrColms = new ArrayList<String>();
List<JLabel> arrLbls = new ArrayList<JLabel>();
int boundTimelbl = 162;
try {
//access the table and get colms names
Connection con = DriverManager.getConnection("jdbc:sqlite:DoctorProject.db");
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
// The column count starts from 1
for (int i = 2; i <= columnCount; i++ ) {
String name = rsmd.getColumnName(i);
// Do stuff with name
if(arrColms.contains(name) == false){
arrColms.add(name);
}
}
for (String colm : arrColms) {
mTimelbl = new JLabel();
mTimelbl.setText(colm);
mTimelbl.setBounds(boundTimelbl, 35, 56, 16);
boundTimelbl = boundTimelbl + 156;
arrLbls.add(mTimelbl);
}
Component[] components = calendarPanel.getComponents();
for (Component component : components) {
if (component instanceof JLabel) {
jPanel1.remove(component);
}
}
for (JLabel mLbl : arrLbls) {
calendarPanel.add(mLbl);
}
calendarPanel.revalidate();
calendarPanel.repaint();
System.out.println(arrColms);
con.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
try to use calendarPanel.removeAll(); before to remove all components
for (JLabel mLbl : arrLbls) {
calendarPanel.add(mLbl);
}
or use before the loop that I mentioned to remove labels only
Component[] components = calendarPanel.getComponents();
for (Component component : components) {
if (component instanceof JLabel) {
calendarPanel.remove(component);
}
}
for (JLabel mLbl : arrLbls) {
calendarPanel.add(mLbl);
}
but to remove our last added Labels we should first store them somewhere so first we create a List of JLabels
private final List<JLabel> myPreviousAddedLabels = new ArrayList<JLabel>();
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String selectedDoctor = comboBoxDoctorsNames.getSelectedItem().toString();
then you should use this
for (JLabel component : myPreviousAddedLabels) {
calendarPanel.remove(component);
}
myPreviousAddedLabels.clear();
for (JLabel mLbl : arrLbls) {
myPreviousAddedLabels.add(mLbl);
calendarPanel.add(mLbl);
}
calendarPanel.revalidate();
calendarPanel.repaint();
Related
I have two classes, one has an ArrayList called "clanovi" which is populated by data from SQL database and I want to display that data in the "clanComboBox" in another class. I have been trying for two days but I can't figure it out.
Class with the list:
String cnnString;
String user;
String password;
public ArrayList<String> clanovi = new ArrayList<String>();
public ArrayList<String> getList(){
return clanovi;
}
public void Connect(String cnnString, String user, String password){
this.cnnString = cnnString;
this.user = user;
this.password = password;
ResultSet res = null;
try {
Connection connection = DriverManager.getConnection(cnnString, user, password);
System.out.println("Connection successful");
Statement stm = connection.createStatement();
String sql = "select Ime, Prezime from Clanovi";
res = stm.executeQuery(sql);
while(res.next()) {
clanovi.add(res.getString("Ime") + " " + res.getString("Prezime"));
}
System.out.println(clanovi);
} catch (SQLException e) {
System.out.println("An unexpected error occurred.");
e.printStackTrace();
}
}
The GUI class with the combobox:
public class PosuditiFilmFrame implements ActionListener{
SQLConnection con = new SQLConnection();
JFrame posuditiFilmFrame = new JFrame();
JButton posuditiFilmButton = new JButton();
JComboBox clanoviComboBox = new JComboBox();
JComboBox filmoviComboBox = new JComboBox();
JLabel clanLabel = new JLabel("Clan:");
JLabel filmLabel = new JLabel("Film:");
ArrayList<String> cBox = con.getList();
PosuditiFilmFrame(){
posuditiFilmButton = new JButton();
posuditiFilmButton.setBounds(200, 270, 200, 50);
posuditiFilmButton.addActionListener(this);;
posuditiFilmButton.setText("Posuditi Film");
posuditiFilmButton.setFocusable(false);
clanLabel.setBounds(50, 50, 70, 50);
clanLabel.setFont(new Font("Arial", Font.PLAIN, 25));
filmLabel.setBounds(50, 125, 70, 50);
filmLabel.setFont(new Font("Arial", Font.PLAIN, 25));
clanoviComboBox.setBounds(150, 50, 300, 50);
filmoviComboBox.setBounds(150, 125, 300, 50);
posuditiFilmFrame.setTitle("Posuditi Film");
posuditiFilmFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
posuditiFilmFrame.setLayout(null);
posuditiFilmFrame.setSize(600, 400);
posuditiFilmFrame.setVisible(true);
posuditiFilmFrame.add(posuditiFilmButton);
posuditiFilmFrame.add(clanoviComboBox);
posuditiFilmFrame.add(filmoviComboBox);
posuditiFilmFrame.add(clanLabel);
posuditiFilmFrame.add(filmLabel);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==posuditiFilmButton) {
JOptionPane.showMessageDialog(null, "Film je posuden");
}
}
Of course, I also want the data to be displayed in that combobox
I am implementing a search interface in eclipse with the help of mysql. My search interface yields the results I want, but I want to be able to have the "video_url" column clickable and bring up a hyperlink. Is there a way to do this for a single column? Right now the Jtable is "editable", so the user can click on it, but no changes are made to it. The link can be copied and then pasted later, but I'm really trying to have the link be opened from the interface.
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
VIdeo_search_test window = new VIdeo_search_test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public VIdeo_search_test() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setFont(new Font("Tahoma", Font.PLAIN, 17));
frame.setBounds(400, 400, 1050, 1000);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblVideoSearch = new JLabel("Video Search");
lblVideoSearch.setFont(new Font("Tahoma", Font.PLAIN, 19));
lblVideoSearch.setBounds(241, 11, 230, 27);
frame.getContentPane().add(lblVideoSearch);
JButton btnSearchCity = new JButton("Search City");
btnSearchCity.setBounds(216, 80, 165, 25);
btnSearchCity.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel model = new DefaultTableModel(new String[]{"video_url", "video name", "video description", "video_city", "video_subject", "video_tags", "reviewed_by", "star"}, 0);
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/userdatabase", "root", "pass1234");
Statement stmt= con.createStatement();
String sql = "Select * from video where video_city = '" +txtCity.getText()+"'";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
String a = rs.getString("video_url");
String d = rs.getString("video_name");
String e = rs.getString("video_description");
String f = rs.getString("video_city");
String g = rs.getString("video_subject");
String h = rs.getString("video_tags");
String k = rs.getString("reviewed_by");
String i = rs.getString("star");
model.addRow(new Object[]{a, d, e, f, g, h, k, i});
table.setModel(model);
}
{
con.close();}
} catch(Exception e) {System.out.print (e);}
}
});
frame.getContentPane().add(btnSearchCity);
JButton btnSearchTag = new JButton("Search Tag");
btnSearchTag.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel model = new DefaultTableModel(new String[]{"video_url", "video name", "video description", "video_city", "video_subject", "video_tags", "reviewed_by", "star"}, 0);
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/userdatabase", "root", "pass1234");
Statement stmt= con.createStatement();
String sql = "Select * from video where video_tags LIKE '"+txtTag.getText()+"%'";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
String a = rs.getString("video_url");
String d = rs.getString("video_name");
String e = rs.getString("video_description");
String f = rs.getString("video_city");
String g = rs.getString("video_subject");
String h = rs.getString("video_tags");
String k = rs.getString("reviewed_by");
String i = rs.getString("star");
model.addRow(new Object[]{a, d, e, f, g, h, k, i});
table_1.setModel(model);
}
{
con.close();}
} catch(Exception e) {System.out.print (e);}
}
});
btnSearchTag.setBounds(216, 303, 165, 25);
frame.getContentPane().add(btnSearchTag);
txtCity = new JTextField();
txtCity.setBounds(216, 49, 165, 20);
frame.getContentPane().add(txtCity);
txtCity.setColumns(10);
table = new JTable();
table.setBounds(10, 116, 867, 135);
frame.getContentPane().add(table);
txtTag = new JTextField();
txtTag.setColumns(10);
txtTag.setBounds(216, 272, 165, 20);
frame.getContentPane().add(txtTag);
table_1 = new JTable();
table_1.setBounds(10, 341, 601, 135);
frame.getContentPane().add(table_1);
JButton btnViewVideo = new JButton("View Video");
btnViewVideo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
registered_video_interface info = new registered_video_interface();
registered_video_interface.main(null); }
});
btnViewVideo.setBounds(251, 509, 89, 23);
frame.getContentPane().add(btnViewVideo);
}
}
When the user selects the multiple check boxes I need to execute the following with the same name. How to use the for loop condition for this?
I tried to use the if-else if but only one selection gets executed. Is there any way to implement for loop to reduce the code length?
I am using JFrame absolute layout so the checkbox variables already get pre-defined. I can't able to use an array.
public first() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 512, 263);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("Checkout Suite:");
lblNewLabel.setBounds(10, 11, 104, 20);
contentPane.add(lblNewLabel);
JComboBox comboBox = new JComboBox();
comboBox.addItem("Platform - Desktop");
comboBox.addItem("Platform - Mobile");
comboBox.setBounds(124, 11, 331, 20);
contentPane.add(comboBox);
JLabel lblNewLabel_1 = new JLabel("Locales:");
lblNewLabel_1.setBounds(10, 53, 79, 34);
contentPane.add(lblNewLabel_1);
JCheckBox chckbxNewCheckBox = new JCheckBox("A");
chckbxNewCheckBox.setBounds(17, 94, 63, 23);
contentPane.add(chckbxNewCheckBox);
JCheckBox chckbxNewCheckBox_1 = new JCheckBox("B");
chckbxNewCheckBox_1.setBounds(104, 94, 63, 23);
contentPane.add(chckbxNewCheckBox_1);
JCheckBox chckbxNewCheckBox_2 = new JCheckBox("C");
chckbxNewCheckBox_2.setBounds(177, 94, 72, 23);
contentPane.add(chckbxNewCheckBox_2);
JCheckBox chckbxNewCheckBox_3 = new JCheckBox("D");
chckbxNewCheckBox_3.setBounds(17, 133, 63, 23);
contentPane.add(chckbxNewCheckBox_3);
JCheckBox chckbxNewCheckBox_4 = new JCheckBox("E");
chckbxNewCheckBox_4.setBounds(104, 133, 63, 23);
contentPane.add(chckbxNewCheckBox_4);
JCheckBox chckbxNewCheckBox_5 = new JCheckBox("F");
chckbxNewCheckBox_5.setBounds(177, 133, 72, 23);
contentPane.add(chckbxNewCheckBox_5);
JCheckBox chckbxNewCheckBox_6 = new JCheckBox("G");
chckbxNewCheckBox_6.setBounds(17, 174, 63, 23);
contentPane.add(chckbxNewCheckBox_6);
JCheckBox chckbxNewCheckBox_7 = new JCheckBox("H");
chckbxNewCheckBox_7.setBounds(104, 174, 63, 23);
contentPane.add(chckbxNewCheckBox_7);
JCheckBox chckbxNewCheckBox_8 = new JCheckBox("I");
chckbxNewCheckBox_8.setBounds(177, 174, 72, 23);
contentPane.add(chckbxNewCheckBox_8);
JButton btnNewButton = new JButton("Create Test Run");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(comboBox.getSelectedItem().equals("PLatform - Desktop"))
{
System.setProperty("webdriver.chrome.driver","\\chromedriver_win32\\chromedriver.exe");
WebDriver aru=new ChromeDriver();
aru.manage().window().maximize();
aru.get("https://google.com");
//Testrail Login
aru.findElement(By.id("name")).sendKeys("gmail#gmail.com");
aru.findElement(By.id("password")).sendKeys("xyz");
aru.findElement(By.id("button_primary")).click(); //Login
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
aru.findElement(By.xpath("//*[#id=\"suite-22496\"]/div[2]/div[1]/a")).click();
aru.findElement(By.xpath("//*[#id=\"content-header\"]/div/div[2]/a[1]")).click();
aru.findElement(By.xpath("//*[#id=\"includeSpecific\"]")).click();
aru.findElement(By.xpath("//*[#id=\"includeSpecificInfo\"]/a")).click();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
aru.findElement(By.xpath("//*[#id=\"selectCasesNode-744350\"]/input")).click();
aru.findElement(By.id("selectCasesSubmit")).click();
//Suite Name
aru.findElement(By.id("name")).clear();
DateFormat today = new SimpleDateFormat("MM/dd/yyyy ");
Date palani = new Date();
String content= today.format(palani);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(chckbxNewCheckBox.isSelected())
{
aru.findElement(By.id("name")).sendKeys("Platform - Desktop - A - "+content);
//aru.findElement(By.className("button button-left button-positive button-ok")).click();
}
else if(chckbxNewCheckBox_1.isSelected())
{
aru.findElement(By.id("name")).sendKeys("Platform - Desktop - B - "+content);
//aru.findElement(By.className("button button-left button-positive button-ok")).click();
}
else if(chckbxNewCheckBox_2.isSelected())
{
aru.findElement(By.id("name")).sendKeys("Platform - Desktop - C - "+content);
//aru.findElement(By.className("button button-left button-positive button-ok")).click();
}
else if(chckbxNewCheckBox_3.isSelected())
{
aru.findElement(By.id("name")).sendKeys("Platform - Desktop - D - "+content);
//aru.findElement(By.className("button button-left button-positive button-ok")).click();
}
else if(chckbxNewCheckBox_4.isSelected())
{
aru.findElement(By.id("name")).sendKeys("Platform - Desktop - E - "+content);
//aru.findElement(By.className("button button-left button-positive button-ok")).click();
}
else if(chckbxNewCheckBox_5.isSelected())
{
aru.findElement(By.id("name")).sendKeys("Platform - Desktop - F - "+content);
//aru.findElement(By.className("button button-left button-positive button-ok")).click();
}
else if(chckbxNewCheckBox_6.isSelected())
{
aru.findElement(By.id("name")).sendKeys("Platform - Desktop - G - "+content);
//aru.findElement(By.className("button button-left button-positive button-ok")).click();
}
else if(chckbxNewCheckBox_7.isSelected())
{
aru.findElement(By.id("name")).sendKeys("Platform - Desktop - H - "+content);
//aru.findElement(By.className("button button-left button-positive button-ok")).click();
}
else if(chckbxNewCheckBox_8.isSelected())
{
aru.findElement(By.id("name")).sendKeys("Platform - Desktop - I - "+content);
//aru.findElement(By.className("button button-left button-positive button-ok")).click();
}
else
{
JOptionPane.showMessageDialog(null, "Please select from list");
}
}
}
});
btnNewButton.setBounds(285, 122, 169, 34);
contentPane.add(btnNewButton);
}
}
If you use else if it will stop executing further cases as soon as one if returns true. One way to maybe reduce your code a bit would be by adding all the Checkboxes to an ArrayList and then loop through that.
List<JCheckBox> cbList = new ArrayList<>();
JCheckBox chckbxNewCheckBox = new JCheckBox("US");
chckbxNewCheckBox.setBounds(17, 94, 63, 23);
contentPane.add(chckbxNewCheckBox);
cbList.add(chckbxNewCheckBox);
JCheckBox chckbxNewCheckBox_1 = new JCheckBox("UK");
chckbxNewCheckBox_1.setBounds(104, 94, 63, 23);
contentPane.add(chckbxNewCheckBox_1);
cbList.add(chckbxNewCheckBox_1);
JCheckBox chckbxNewCheckBox_2 = new JCheckBox("IN");
chckbxNewCheckBox_2.setBounds(177, 94, 72, 23);
contentPane.add(chckbxNewCheckBox_2);
cbList.add(chckbxNewCheckBox_2);
JCheckBox chckbxNewCheckBox_3 = new JCheckBox("JP");
chckbxNewCheckBox_3.setBounds(17, 133, 63, 23);
contentPane.add(chckbxNewCheckBox_3);
cbList.add(chckbxNewCheckBox_3);
JCheckBox chckbxNewCheckBox_4 = new JCheckBox("FR");
chckbxNewCheckBox_4.setBounds(104, 133, 63, 23);
contentPane.add(chckbxNewCheckBox_4);
cbList.add(chckbxNewCheckBox_4);
JCheckBox chckbxNewCheckBox_5 = new JCheckBox("DE");
chckbxNewCheckBox_5.setBounds(177, 133, 72, 23);
contentPane.add(chckbxNewCheckBox_5);
cbList.add(chckbxNewCheckBox_5);
JCheckBox chckbxNewCheckBox_6 = new JCheckBox("ES");
chckbxNewCheckBox_6.setBounds(17, 174, 63, 23);
contentPane.add(chckbxNewCheckBox_6);
cbList.add(chckbxNewCheckBox_6);
JCheckBox chckbxNewCheckBox_7 = new JCheckBox("IT");
chckbxNewCheckBox_7.setBounds(104, 174, 63, 23);
contentPane.add(chckbxNewCheckBox_7);
cbList.add(chckbxNewCheckBox_7);
JCheckBox chckbxNewCheckBox_8 = new JCheckBox("CA");
chckbxNewCheckBox_8.setBounds(177, 174, 72, 23);
contentPane.add(chckbxNewCheckBox_8);
cbList.add(chckbxNewCheckBox_8);
Alexeys comment got me thinking about checking wether or not any Checkboxes were selected, which might be useful to check at first.
private boolean selectionWasMade()
{
int selectedCounter = 0;
for(JCheckBox checkbox : cbList)
{
if(checkbox.isSelected())
{
selectedCounter++;
}
}
if(selectedCounter != 0)
{
return true;
}
return false;
}
Now you simply check if this returns true and execute this loop:
if(selectionWasMade())
{
for(JCheckBox checkbox : cbList)
{
if(checkbox.isSelected())
{
aru.findElement(By.id("name")).sendKeys("SNS - Checkout Preflight - Desktop - " + checkbox.getText() + " - "+content);
}
}
}
else
{
JOptionPane.showMessageDialog(null, "Please select from list");
}
Hope I could help, my answer should be all cleaned up and correct now after several edits!
When i write PreparedStatement in main function, it works perfectly and submits the data but when i write in in actionPerformed function it doesn't work, why??
I don't think I'm doing anything wrong.
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
public class EnterData {
static void insertData(int rn, String fn, String ln) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentinfo","root","12345")) {
String query = "insert into student (rollno, fname, lname)" + " values (?, ?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt (1, rn);
preparedStmt.setString (2, fn);
preparedStmt.setString (3, ln);
preparedStmt.execute();
}
}
public static void main(String[] args) {
JFrame mainFrame = new JFrame("Submit Information");
mainFrame.setSize(400, 300);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setLocationRelativeTo(null);
mainFrame.setLayout(null);
JLabel heading = new JLabel("Enter Data");
heading.setBounds(150, 10, 100, 20);
mainFrame.add(heading);
JLabel rollnoLabel = new JLabel("Roll Number");
rollnoLabel.setBounds(70, 60, 100, 20);
mainFrame.add(rollnoLabel);
JTextField rollno = new JTextField();
rollno.setBounds(220, 60, 100, 20);
mainFrame.add(rollno);
// Taking First Name
JLabel name1 = new JLabel("First Name");
name1.setBounds(70, 110, 100, 20);
mainFrame.add(name1);
JTextField fname = new JTextField();
fname.setBounds(220, 110, 100, 20);
mainFrame.add(fname);
// Taking Last Name
JLabel name2 = new JLabel("Last Name");
name2.setBounds(70, 160, 100, 20);
mainFrame.add(name2);
JTextField lname = new JTextField();
lname.setBounds(220, 160, 100, 20);
mainFrame.add(lname);
// Submit and Reset Button
JButton submit = new JButton("Submit");
submit.setBounds(70, 220, 100, 20);
mainFrame.add(submit);
JButton reset = new JButton("Reset");
reset.setBounds(220, 220, 100, 20);
mainFrame.add(reset);
// Frame Visibility
mainFrame.setVisible(true);
submit.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
try {
int rn = Integer.parseInt(rollno.getText());
String fn = fname.getText();
String ln = lname.getText();
insertData(rn, fn, ln);
JOptionPane.showMessageDialog(null, "Submitted Successfully...!!!", "Submission Prompt", JOptionPane.PLAIN_MESSAGE);
} catch (Exception ex) {
System.err.println("Got an exception!");
System.err.println(ex.getMessage());
}
}
});
}
}
I've tried this and it works perfectly but when i put those statements in actionPerformed function they don't work.
import java.sql.*;
public class DatabaseTest {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studentinfo","root","12345");
String query = "insert into student (rollno, fname, lname)" + " values (?, ?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt (1, 6505);
preparedStmt.setString (2, "Prince");
preparedStmt.setString (3, "Saini");
preparedStmt.execute();
conn.close();
} catch (Exception e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
}
}
so I have a school project I need help on!
So I am doing a 'task force schedule' app as my major project for this year (Grade 11, south africa) and I am stuck. I have an login system that logs into the database fine, then I have a "check in station" class called CheckIn which has a button that should open a table showing all the people working in a given station at that time if they are checked in.
So far the table only pulls data from the database of everyone that is in the station, regardless of whether they are here or not, but that is not the issue.
The issue is that if I start the class Welcome (the station called 'Welcome') it runs fine showing the following image:
but when I try to open the welcome class from within the program (so I click on the quick link in the CheckIn class, it does this:
The code for the Welcome class works fine, I got it through a tutorial I copied from youtube, but it works 100%.
Is there something I am doing wrong???
Any advice would be greatly appreciated.
Thanks Josh
Here is the code, by the way :P :
CheckIn class:
package co.za.gecko.inked.crm;
import java.awt.EventQueue;
public class CheckIn extends JFrame {
String u = (String) Login.cbxUsername.getSelectedItem();
static ArrayList<String> firstNames = new ArrayList<>();
JLabel lblHello = new JLabel("Hello, "+u.toString());
JLabel lblClock = new JLabel("");
static JComboBox cbxCIFirstName = new JComboBox();
static JComboBox cbxCILastName = new JComboBox();
// to add checked in people to pCI stands for personCheckedIn
static ArrayList<String> pCI = new ArrayList<>();
// all jLabels for the stations
JLabel lblWelcome = new JLabel("Welcome: 0");
JLabel lblScanning = new JLabel("Scanning: 0");
JLabel lblChecking = new JLabel("Checking: 0");
JLabel lblRunners = new JLabel("Runners: 0");
JLabel lblWrapping = new JLabel("Wrapping: 0");
JLabel lblFirstAid = new JLabel("First Aid: 0");
JLabel lblVolunteers = new JLabel("Volunteers: 0");
// all counters for the stations
int cWelcome = 0;
int cScanning = 0;
int cChecking = 0;
int cRunners = 0;
int cWrapping = 0;
int cFirstAid = 0;
int cVolunteers = 0;
// all stations with volunteer id in station
static ArrayList<String> inWelcomeStation = new ArrayList<>();
ArrayList<String> inScanningStation = new ArrayList<>();
ArrayList<String> inCheckingStation = new ArrayList<>();
ArrayList<String> inRunnersStation = new ArrayList<>();
ArrayList<String> inWrappingStation = new ArrayList<>();
ArrayList<String> inFirstAidStation = new ArrayList<>();
ArrayList<String> inVolunteersStation = new ArrayList<>();
JLabel lblCIStation = new JLabel("Welcome");
JLabel lblCITime = new JLabel("10:00");
/**
* Launch the application.
*/
public static void main(String[] args) throws Exception{
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CheckIn frame = new CheckIn();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #throws Exception
*/
public CheckIn() throws Exception{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1024, 768);
getContentPane().setLayout(null);
lblHello.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblHello.setBounds(10, 11, 182, 25);
getContentPane().add(lblHello);
lblClock.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblClock.setBounds(941, 11, 57, 25);
getContentPane().add(lblClock);
JLabel lblDay = new JLabel("Day 1");
lblDay.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblDay.setBounds(863, 11, 57, 25);
getContentPane().add(lblDay);
cbxCIFirstName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
cbxCILastName.removeAllItems();
getLastNames();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
cbxCIFirstName.addInputMethodListener(new InputMethodListener() {
public void caretPositionChanged(InputMethodEvent arg0) {
}
public void inputMethodTextChanged(InputMethodEvent arg0) {
}
});
cbxCIFirstName.setEditable(true);
cbxCIFirstName.setBounds(307, 106, 330, 20);
getContentPane().add(cbxCIFirstName);
cbxCILastName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
updateCheckInData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
cbxCILastName.setBounds(307, 163, 330, 20);
getContentPane().add(cbxCILastName);
JLabel lblFirstName = new JLabel("First Name");
lblFirstName.setBounds(307, 93, 73, 14);
getContentPane().add(lblFirstName);
JLabel lblLastName = new JLabel("Last Name");
lblLastName.setBounds(307, 149, 73, 14);
getContentPane().add(lblLastName);
JLabel lblStation = new JLabel("Station");
lblStation.setBounds(647, 93, 73, 14);
getContentPane().add(lblStation);
JLabel lblTime = new JLabel("Time");
lblTime.setBounds(647, 149, 73, 14);
getContentPane().add(lblTime);
lblCIStation.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblCIStation.setBounds(647, 102, 136, 25);
getContentPane().add(lblCIStation);
lblCITime.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblCITime.setBounds(647, 159, 136, 25);
getContentPane().add(lblCITime);
JButton btnCheckIn = new JButton("Check In");
btnCheckIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
checkedIn();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnCheckIn.setBounds(759, 117, 110, 55);
getContentPane().add(btnCheckIn);
JSeparator separator = new JSeparator();
separator.setBounds(52, 220, 900, 2);
getContentPane().add(separator);
lblWelcome.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblWelcome.setBounds(85, 254, 161, 25);
getContentPane().add(lblWelcome);
lblScanning.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblScanning.setBounds(85, 290, 161, 25);
getContentPane().add(lblScanning);
lblChecking.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblChecking.setBounds(85, 326, 161, 25);
getContentPane().add(lblChecking);
lblRunners.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblRunners.setBounds(452, 326, 161, 25);
getContentPane().add(lblRunners);
lblWrapping.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblWrapping.setBounds(452, 290, 161, 25);
getContentPane().add(lblWrapping);
lblFirstAid.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblFirstAid.setBounds(452, 254, 161, 25);
getContentPane().add(lblFirstAid);
lblVolunteers.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblVolunteers.setBounds(724, 254, 161, 25);
getContentPane().add(lblVolunteers);
JSeparator separator_1 = new JSeparator();
separator_1.setBounds(52, 383, 900, 2);
getContentPane().add(separator_1);
JLabel lblQuickLinks = new JLabel("Quick Links");
lblQuickLinks.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblQuickLinks.setBounds(85, 413, 161, 25);
getContentPane().add(lblQuickLinks);
JButton btnOster = new JButton("Roster");
btnOster.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnOster.setBounds(85, 451, 116, 55);
getContentPane().add(btnOster);
JButton btnVolunteerInfo = new JButton("Volunteer Info");
btnVolunteerInfo.setBounds(211, 451, 116, 55);
getContentPane().add(btnVolunteerInfo);
JButton btnSearch = new JButton("Search");
btnSearch.setBounds(337, 451, 116, 55);
getContentPane().add(btnSearch);
JButton btnWelcome = new JButton("Welcome");
btnWelcome.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnWelcome.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
checkStation("Welcome");
Welcome openWelcome = new Welcome();
openWelcome.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
btnWelcome.setBounds(85, 526, 116, 55);
getContentPane().add(btnWelcome);
JButton btnScanning = new JButton("Scanning");
btnScanning.setBounds(211, 526, 116, 55);
getContentPane().add(btnScanning);
JButton btnChecking = new JButton("Checking");
btnChecking.setBounds(337, 526, 116, 55);
getContentPane().add(btnChecking);
JButton btnFirstAid = new JButton("First Aid");
btnFirstAid.setBounds(463, 526, 116, 55);
getContentPane().add(btnFirstAid);
JButton btnWrapping = new JButton("Wrapping");
btnWrapping.setBounds(589, 526, 116, 55);
getContentPane().add(btnWrapping);
JButton btnRunners = new JButton("Runners");
btnRunners.setBounds(715, 526, 116, 55);
getContentPane().add(btnRunners);
JButton btnVolunteers = new JButton("Volunteers");
btnVolunteers.setBounds(842, 526, 116, 55);
getContentPane().add(btnVolunteers);
JButton btnCheckOut = new JButton("Check Out");
btnCheckOut.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
try {
checkOut();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnCheckOut.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent arg0) {
try {
checkOut();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnCheckOut.setBounds(124, 117, 110, 55);
getContentPane().add(btnCheckOut);
getFirstNames();
}
public static void getFirstNames() throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/crm", "root", "t00rt00r");
PreparedStatement statement = (PreparedStatement) con.prepareStatement("SELECT `first_name` FROM volunteers");
ResultSet result = statement.executeQuery();
cbxCIFirstName.setToolTipText("Select a first name");
cbxCIFirstName.setEditable(true);
cbxCIFirstName.addItem("Please select a first name");
while(result.next()){
if(firstNames.contains(result.getString(1)) != true){
firstNames.add(result.getString(1));
}
}
for(int i=0; i<firstNames.size(); i++){
cbxCIFirstName.addItem(firstNames.get(i));
}
}
public static void getLastNames() throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/crm", "root", "t00rt00r");
PreparedStatement statement = (PreparedStatement) con.prepareStatement("SELECT `last_name` FROM volunteers WHERE `first_name` = '" + cbxCIFirstName.getSelectedItem() + "'");
ResultSet result = statement.executeQuery();
cbxCILastName.setToolTipText("Select a last name");
cbxCILastName.setEditable(true);
int rowcount = 0;
if (result.last()) {
rowcount = result.getRow();
result.beforeFirst(); // not rs.first() because the rs.next() below will move on, missing the first element
}
if(rowcount > 1){
cbxCILastName.addItem("Please select a last name");
}
while(result.next()){
cbxCILastName.addItem(result.getString(1));
}
}
public void checkedIn() throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/crm", "root", "t00rt00r");
PreparedStatement statement = (PreparedStatement) con.prepareStatement("SELECT `volunteer_id` FROM volunteers WHERE `first_name` = '" + cbxCIFirstName.getSelectedItem() + "' AND `last_name` = '" + cbxCILastName.getSelectedItem() + "'");
ResultSet result = statement.executeQuery();
while(result.next()){
// checks if volunteer id is already in the array, ie: already checked in
if(pCI.contains(result.getString(1))){
JOptionPane.showMessageDialog(null, "Sorry, this volunteer is already logged in!");
} else {
// add volunteer id to array list
pCI.add(result.getString(1));
System.out.println(pCI);
addToLabel(result.getString(1));
getStationInfo(result.getString(1));
}
}
}
public void addToLabel(String user_id) throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/crm", "root", "t00rt00r");
PreparedStatement statement = (PreparedStatement) con.prepareStatement("SELECT `station` FROM volunteers WHERE `volunteer_id` = '" + user_id + "'");
ResultSet result = statement.executeQuery();
while(result.next()){
String stat = result.getString(1);
switch (stat) {
case "welcome":
case "Welcome":
cWelcome++;
lblWelcome.setText("Welcome: " + cWelcome);
break;
case "scanning":
case "Scanning":
cScanning++;
lblScanning.setText("Scanning: " + cScanning);
break;
case "checking":
case "Checking":
cChecking++;
lblChecking.setText("Checking: " + cChecking);
break;
case "runners":
case "Runners":
cRunners++;
lblRunners.setText("Runners: " + cRunners);
break;
case "wrapping":
case "Wrapping":
cWrapping++;
lblWrapping.setText("Wrapping: " + cWrapping);
break;
case "firstaid":
case "Firstaid":
case "firstAid":
case "FirstAid":
cFirstAid++;
lblFirstAid.setText("First Aid: " + cFirstAid);
break;
case "volunteers":
case "Volunteers":
cVolunteers++;
lblVolunteers.setText("Volunteers: " + cVolunteers);
break;
default:
break;
}
}
}
public void updateCheckInData() throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/crm", "root", "t00rt00r");
PreparedStatement statement = (PreparedStatement) con.prepareStatement("SELECT `station`, `time` FROM volunteers WHERE `first_name` = '" + cbxCIFirstName.getSelectedItem() + "' AND `last_name` = '" + cbxCILastName.getSelectedItem() + "'");
ResultSet result = statement.executeQuery();
while(result.next()){
lblCIStation.setText(result.getString(1));
String station = lblCIStation.getText();
station = station.substring(0, 1).toUpperCase() + station.substring(1);
lblCIStation.setText(station);
lblCITime.setText(result.getString(2));
}
}
public void checkOut() throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/crm", "root", "t00rt00r");
PreparedStatement statement = (PreparedStatement) con.prepareStatement("SELECT `volunteer_id` FROM volunteers WHERE `first_name` = '" + cbxCIFirstName.getSelectedItem() + "' AND `last_name` = '" + cbxCILastName.getSelectedItem() + "'");
ResultSet result = statement.executeQuery();
while(result.next()){
pCI.remove(result.getString(1));
System.out.println(pCI);
removeFromLabel(result.getString(1));
}
}
public void removeFromLabel(String user_id) throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/crm", "root", "t00rt00r");
PreparedStatement statement = (PreparedStatement) con.prepareStatement("SELECT `station` FROM volunteers WHERE `volunteer_id` = '" + user_id + "'");
ResultSet result = statement.executeQuery();
while(result.next()){
String stat = result.getString(1);
switch (stat) {
case "welcome":
case "Welcome":
cWelcome--;
lblWelcome.setText("Welcome: " + cWelcome);
break;
case "scanning":
case "Scanning":
cScanning--;
lblScanning.setText("Scanning: " + cScanning);
break;
case "checking":
case "Checking":
cChecking--;
lblChecking.setText("Checking: " + cChecking);
break;
case "runners":
case "Runners":
cRunners--;
lblRunners.setText("Runners: " + cRunners);
break;
case "wrapping":
case "Wrapping":
cWrapping--;
lblWrapping.setText("Wrapping: " + cWrapping);
break;
case "firstaid":
case "Firstaid":
case "firstAid":
case "FirstAid":
cFirstAid--;
lblFirstAid.setText("First Aid: " + cFirstAid);
break;
case "volunteers":
case "Volunteers":
cVolunteers--;
lblVolunteers.setText("Volunteers: " + cVolunteers);
break;
default:
break;
}
}
}
public void checkStation(String station) throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/crm", "root", "t00rt00r");
PreparedStatement statement = (PreparedStatement) con.prepareStatement("SELECT `volunteer_id` FROM volunteers WHERE `station` = '" + station + "'");
ResultSet result = statement.executeQuery();
while(result.next()){
switch (station) {
case "Welcome":
case "welcome":
break;
case "Scanning":
case "scanning":
break;
case "Checking":
case "checking":
break;
case "Runners":
case "runners":
break;
case "Wrapping":
case "wrapping":
break;
case "FirstAid":
case "Firstaid":
case "firstAid":
case "firstaid":
break;
case "Volunteers":
case "volunteers":
break;
default:
break;
}
}
}
public void getStationInfo(String id) throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/crm", "root", "t00rt00r");
PreparedStatement statement = (PreparedStatement) con.prepareStatement("SELECT `first_name`, `last_name`, `time`, `station` FROM volunteers WHERE `volunteer_id` = '" + id + "'");
ResultSet result = statement.executeQuery();
String vid = id;
List vidd = new ArrayList<>(Arrays.asList(vid));
while(result.next()){
switch (result.getString(4)) {
case "Welcome":
case "welcome":
inWelcomeStation = (ArrayList<String>) vidd;
break;
case "Scanning":
case "scanning":
inScanningStation = (ArrayList<String>) vidd;
break;
case "Checking":
case "checking":
inCheckingStation = (ArrayList<String>) vidd;
break;
case "Runners":
case "runners":
inRunnersStation = (ArrayList<String>) vidd;
break;
case "Wrapping":
case "wrapping":
inWrappingStation = (ArrayList<String>) vidd;
break;
case "FirstAid":
case "Firstaid":
case "firstAid":
case "firstaid":
inFirstAidStation = (ArrayList<String>) vidd;
break;
case "Volunteers":
case "volunteers":
inVolunteersStation = (ArrayList<String>) vidd;
break;
default:
break;
}
}
}
}
and the Welcome class:
package co.za.gecko.inked.crm;
import java.awt.BorderLayout;
public class Welcome extends JFrame {
static Object[][] databaseInfo;
static Object[] columns = {"first name", "last name", "cellphone", "time", "station"};
static ResultSet rows;
static ResultSetMetaData metaData;
static DefaultTableModel dTableModel = new DefaultTableModel(databaseInfo, columns) {
// public Class getColumnClass(int column){
// Class returnValue;
// if((column >= 0) && (column < getColumnCount())){
// returnValue = getValueAt(0, column).getClass();
// } else {
// returnValue = Object.class;
// }
// return returnValue;
// }
};
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setBounds(0, 0, 1024, 768);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/crm", "root", "t00rt00r");
Statement sqlState = conn.createStatement();
String selectStuff = "SELECT `first_name`, `last_name`, `cellphone`, `time` FROM volunteers";
rows = sqlState.executeQuery(selectStuff);
Object[] tempRow;
while(rows.next()){
tempRow = new Object[]{rows.getString(1), rows.getString(2), rows.getString(3), rows.getString(4)};
dTableModel.addRow(tempRow);
}
// get column name ?
// metaData = rows.getMetaData();
// int numOfCol = metaData.getColumnCount();
//
// columns = new String[numOfCol];
//
// for(int i=1; i<= numOfCol; i++){
// columns[i] = metaData.getColumnName(i);
// }
} catch (ClassNotFoundException ex) {
// TODO Auto-generated catch block
System.out.println(ex.getMessage());
} catch (SQLException ex) {
// TODO Auto-generated catch block
System.out.println(ex.getMessage());
}
JTable table = new JTable(dTableModel);
table.setRowHeight(table.getRowHeight() + 10); // change row height
table.setFont(new Font("Serif", Font.PLAIN, 20)); // change font
table.setAutoCreateRowSorter(true); // sort table
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // change column resize
TableColumn col1 = table.getColumnModel().getColumn(0); // change column width
col1.setPreferredWidth(100);
TableColumn tc = table.getColumn("cellphone");
CenterTableCellRenderer centerRenderer = new CenterTableCellRenderer();
tc.setCellRenderer(centerRenderer);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(800, 500);
frame.setVisible(true);
}
}
(so I click on the quick link in the CheckIn class,
You should be using an ActionListener (not a MouseListener) to listen for a click on a button.
The basic structure for your code should be:
JFrame frame = new JFrame();
...
frame.add(scrollPane...);
frame.pack() //or frame.setSize(...)
frame.pack()
frame.setVisible(true);
That is you should only display the frame AFTER you have added all the component to the frame. Right now your code makes the frame visible before you add any components.
Also, you should not be using static variables. Those variables should be instance variables in your welcome class.
The above comments are general in nature and not the cause of your real problem.
The problem is that your Welcome class doesn't have a constructor.
When you execute the Welcome class through the JVM then the main() method is invoked which is where you create the frame and all the components.
When you invoke the Welcome class through your other program the empty constructor for your Welcome class is executed. This code does nothing. Since your class extends JFrame all you see is an empty frame.
So to solve your problem you basically need to move all the code related to build a frame into the constructor of your Welcome class.