Adding a hyperlink to a single value of sql in jTable - java

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);
}
}

Related

I can't populate a JComboBox with an ArrayList

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

Overwrite JLabels when different selections are selected in JComboBox?

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();

Previous instance of table appends to the newly invoked table. The page should show only one table

When I click the button called Enrolled Subjects, a table showing enrolled subjects is invoked. The data is loaded from a text file. But when I go to another page of the application and go back to the Enrolled Subjects or when I click the Enrolled Subjects Button again, a new table loads and adds to the previously loaded table. This makes the table grow longer every time I click Enrolled Subjects. I have added a removeAll() method which clears the content of the pane before loading the table again, but the previously loaded table, for some reason, does not go away.
Here's the code of the panel where the table is attached.
public class EnrolledSubjectsPanel extends JPanel
{
public EnrolledSubjectsPanel(String path)
{
setBackground(Color.LIGHT_GRAY);
setBounds(183, 280, 1129, 401);
setLayout(null);
LoadTable table = new LoadTable(path);
table.setBounds(0,60,1129,600);
add(table);
JLabel lblEnrolledSubjects = new JLabel("Enrolled Subjects");
lblEnrolledSubjects.setFont(new Font("Tahoma", Font.PLAIN, 35));
lblEnrolledSubjects.setBounds(446, 0, 292, 43);
add(lblEnrolledSubjects);
setVisible(true);
}
}
The class that creates the table
public class LoadTable extends JPanel
{
private static String path;
private static String header[] = {"Subject", "Schedule", "Room", "Proferssor", "Units"};
private static DefaultTableModel dtm = new DefaultTableModel(null, header);
boolean isLaunched;
public LoadTable(String path)
{
this.path = "subjects" + path;
setBackground(Color.LIGHT_GRAY);
setBounds(183, 280, 1129, 401);
setLayout(null);
JTable table = new JTable(dtm);
JScrollPane jsp = new JScrollPane(table);
jsp.setBounds(0, 0, 1129, 380);
add(jsp);
try
{
TextReaderBasic file = new TextReaderBasic(path);
String data[] = file.openFile();
int i = 0;
for(i = 0; i <= data.length; i++)
{
addRow(i);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
setVisible(true);
}
public static void addRow(int x)
{
try
{
TextReaderBasic file = new TextReaderBasic(path);
String data[] = file.openFile();
int size = data.length;
int i = 0 + x;
int j = 6 + x;
int k = 12 + x;
int l = 18 + x;
int m = 24 + x;
dtm.addRow(new Object[]{data[i], data[j], data[k], data[l], data[m]});
}
catch(Exception e)
{
System.out.println("Action completed :)");
}
}
}
The main class where the panel is attached to
public class LaunchPage extends JFrame
{ public LaunchPage(String path)
{
getContentPane().setBackground(Color.white);
getContentPane().setLayout(null);
StudentBasicInformationPanel studentBasicInfo = new StudentBasicInformationPanel(path);
getContentPane().add(studentBasicInfo);
JLabel universityTitleL = new JLabel("Evil Genuises University");
universityTitleL.setFont(new Font("Edwardian Script ITC", Font.ITALIC, 42));
universityTitleL.setBounds(514, 11, 343, 65);
getContentPane().add(universityTitleL);
JPanel panelToAttach = new JPanel();
panelToAttach.setBounds(173, 280, 1129, 404);
getContentPane().add(panelToAttach);
setSize(1366, 768);
JButton enrollmentButton = new JButton("Enrollment");
enrollmentButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
EnrollmentPanel ep = new EnrollmentPanel();
ep.setBackground(Color.LIGHT_GRAY);
ep.setBounds(0, 0, 1129, 401);
panelToAttach.add(ep);
repaint();
}
});
enrollmentButton.setBounds(10, 280, 157, 58);
getContentPane().add(enrollmentButton);
JButton viewEnrolledSubjectsButton = new JButton("Enrolled Subjects");
viewEnrolledSubjectsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
EnrolledSubjectsPanel es = new EnrolledSubjectsPanel(path);
es.setBackground(Color.LIGHT_GRAY);
es.setBounds(0, 0, 1129, 401);
panelToAttach.add(es);
repaint();
}
});
viewEnrolledSubjectsButton.setBounds(10, 349, 157, 58);
getContentPane().add(viewEnrolledSubjectsButton);
JButton viewGradesButton = new JButton("View Grades");
viewGradesButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
GradesPanel gp = new GradesPanel();
gp.setBackground(Color.LIGHT_GRAY);
gp.setBounds(0, 0, 1129, 401);
panelToAttach.add(gp);
repaint();
}
});
viewGradesButton.setBounds(10, 418, 157, 58);
getContentPane().add(viewGradesButton);
JButton clearanceButton = new JButton("Clearance");
clearanceButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
ClearancePanel cp = new ClearancePanel();
cp.setBackground(Color.LIGHT_GRAY);
cp.setBounds(0, 0, 1129, 401);
panelToAttach.add(cp);
repaint();
}
});
clearanceButton.setBounds(10, 487, 157, 58);
getContentPane().add(clearanceButton);
JButton viewAccountButton = new JButton("View Account");
viewAccountButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
AccountPanel ap = new AccountPanel();
ap.setBackground(Color.LIGHT_GRAY);
ap.setBounds(0, 0, 1129, 401);
panelToAttach.add(ap);
repaint();
}
});
viewAccountButton.setBounds(10, 556, 157, 58);
getContentPane().add(viewAccountButton);
JButton closeButton = new JButton("Close");
closeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
closeButton.setBounds(10, 626, 157, 58);
getContentPane().add(closeButton);
setVisible(true);
}
}
Thanks in advance!
Try using below code in your LoadTable class before you adding the rows to the table. It will clear the rows in the table model.
dtm.setRowCount(0);
So your new LoadTable class should look like this:
public class LoadTable extends JPanel
{
private static String path;
private static String header[] = {"Subject", "Schedule", "Room", "Proferssor", "Units"};
private static DefaultTableModel dtm = new DefaultTableModel(null, header);
dtm.setRowCount(0); //THIS WILL CLEAR THE ROWS IN YOUR STATIC TABLEMODEL
boolean isLaunched;
public LoadTable(String path)
{
this.path = "subjects" + path;
setBackground(Color.LIGHT_GRAY);
setBounds(183, 280, 1129, 401);
setLayout(null);
JTable table = new JTable(dtm);
JScrollPane jsp = new JScrollPane(table);
jsp.setBounds(0, 0, 1129, 380);
add(jsp);
try
{
TextReaderBasic file = new TextReaderBasic(path);
String data[] = file.openFile();
int i = 0;
for(i = 0; i <= data.length; i++)
{
addRow(i);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
setVisible(true);
}
public static void addRow(int x)
{
try
{
TextReaderBasic file = new TextReaderBasic(path);
String data[] = file.openFile();
int size = data.length;
int i = 0 + x;
int j = 6 + x;
int k = 12 + x;
int l = 18 + x;
int m = 24 + x;
dtm.addRow(new Object[]{data[i], data[j], data[k], data[l], data[m]});
}
catch(Exception e)
{
System.out.println("Action completed :)");
}
}
}

Jtable cant load data from database

I cant seems to load data into table despite being able to load column name dynamically. When I try to load data nothing appear despite the fact that Java Icon still showed on the taskbar. It doesn't look like there is anything wrong with GUI itself so I was wondering if opening a connection from constructor will cause logical error.I printed out the locals variables in the second for loop of populateTable method to check if data was passed into local variables and they did, so I don't know exactly what was causing this error.
here is the code for GUI:
public class WeatherFrame extends JFrame {
private JPanel contentPane;
private JTable table;
HealthData health = new HealthData();
private DefaultTableModel model;
String[] columnNames = {"zipcode", "county", "city", "state", "year", "month","ageGroup",
"numOfVisits", "MonthlyMax", "MonthlyMin", "MonthlyNor"};
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WeatherFrame frame = new WeatherFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public WeatherFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 300);
contentPane = new JPanel();
contentPane.setBounds(100, 100,750, 200);
setContentPane(contentPane);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(6, 25, 788, 180);
contentPane.add(scrollPane);
model = new DefaultTableModel();
populateTable();
table = new JTable(model);
scrollPane.setViewportView(table);
JButton btnInsert = new JButton("insert");
btnInsert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnInsert.setBounds(315, 217, 117, 29);
contentPane.add(btnInsert);
JButton btnDelete = new JButton("delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnDelete.setBounds(198, 243, 117, 29);
contentPane.add(btnDelete);
JButton btnSearch = new JButton("search");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnSearch.setBounds(81, 243, 117, 29);
contentPane.add(btnSearch);
JLabel lblWeatherTable = new JLabel("Weather Table");
lblWeatherTable.setBounds(149, 6, 107, 16);
contentPane.add(lblWeatherTable);
JButton btnNext = new JButton("update");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnNext.setBounds(198, 217, 117, 29);
contentPane.add(btnNext);
JButton btnRefresh = new JButton("refresh");
btnRefresh.setBounds(81, 217, 117, 29);
contentPane.add(btnRefresh);
}
public void populateTable() {
for(String name: columnNames)
model.addColumn(name);
ArrayList<Health> healthdata = new ArrayList<Health>();
healthdata = health.showAllData();
model.addRow(healthdata.toArray());
}
}
this is the constructor for the HealthData class
public HealthData(){
try {
/* Connect to database */
connection = DriverManager.getConnection(jdbcURL, MySQLConfig.user, MySQLConfig.password);
statement = connection.createStatement();
data = new ArrayList<Health>();
} catch (Exception e)
{
e.printStackTrace();
}
}
this is the code for showAlldata method
public ArrayList<Health> showAllData(){
ArrayList<Health> list = new ArrayList<Health>();
try {
connection = DriverManager.getConnection(jdbcURL, MySQLConfig.user, MySQLConfig.password);
Statement stmt = connection.createStatement();
ResultSet result = stmt.executeQuery(SELECT_ALL_QUERY);
/* Get and print out data from health table : zipcode, county, city, state, year, month, ageGroup, numberOfVisits, MMax, MMin, MNor */
while(result.next()){
Health data = new Health();
int zipcode = result.getInt(1);
data.setZipCode(zipcode);
String county = result.getString(2);
data.setCounty(county);
String city = result.getString(3);
data.setCity(city);
String state = result.getString(4);
data.setState(state);
int year = result.getInt(5);
data.setYear(year);
int month = result.getInt(6);
data.setMonth(month);
String ageGroup = result.getString(7);
data.setAgeGroup(ageGroup);
int numOfVisits = result.getInt(8);
data.setNumOfVisits(numOfVisits);
float MMax = result.getFloat(9);
data.setMMax(MMax);
float MMin = result.getFloat(10);
data.setMMin(MMin);
float MNor = result.getFloat(11);
data.setMNor(MNor);
list.add(data);
connection.close()
stmt.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
Can someone suggest a solution for solving this problem. Thank you in advance for helping. I already posted a question about this but this question is up to date with required codes.
I edit the code to make only one call to showAlldata and also close connection and statement, however, the same error still persist
public void populateTable() {
model = new DefaultTableModel(){
#Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
};
for(String name: columnNames)
model.addColumn(name);
ArrayList<Health> temp = new ArrayList<Health>();
temp = health.showAllData();
for(int i = 0; i< temp.size(); i++) {
Object[] data = {temp.get(i).getZipCode(), temp.get(i).getCounty(), temp.get(i).getCounty(), temp.get(i).getState(),temp.get(i).getYear(),
temp.get(i).getMonth(), temp.get(i).getAgeGroup(), temp.get(i).getNumOfVisits(), temp.get(i).getMMax(), temp.get(i).getMMin(), temp.get(i).getMNor()};
model.addRow(data);
}
}
thank you very much for helping, I solved this question by modifying my populateTable Method as above.

I cannot insert value in the table using textfield

I need to create a program in which values can be inserted using textfield in Java.
database getting connected ...
bt Cannot insert values using JTextfield ....need help..
shows error ..
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
package youtubetest;
import java.sql.*;
import java.awt.event.*;
import javax.swing.*;
public class YouTubeTest extends JFrame{
private static final String USERNAME = "root";
private static final String PASSWORD = "****";
private static final String CONN_STRING = "jdbc:mysql://localhost:3306/youtube";
Connection conn;
PreparedStatement stmt;
JButton b1,b2;
JTextField t1,t2;
JLabel l1,l2;
String Fname;
String Lname;
public YouTubeTest()
{
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setLayout(null);
add(t1 = new JTextField(30));
t1.setBounds(10,10,200,50);
add(t2 = new JTextField(30));
t2.setBounds(10, 100, 200, 50);
add(l1 = new JLabel("First Name : "));
l1.setBounds(220, 10, 200, 50);
add(l2 = new JLabel("Last Name : "));
l2.setBounds(220, 100, 200, 50);
add(b1 = new JButton("Submit"));
b1.setBounds(10, 400, 60, 60);
add(b2 = new JButton("Clear"));
b2.setBounds(100, 400, 60, 60);
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(CONN_STRING,USERNAME,PASSWORD);
System.out.println("Database Connected Succesfully ..... ");
stmt = conn.prepareStatement("Insert into user(Fname,Lname) values('"+Fname+"','"+Lname+"')");
}catch(Exception e){
e.printStackTrace();
}
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae){
try{
Fname = t1.getText();
Lname = t2.getText();
stmt.setString(1, Fname);
stmt.setString(2, Lname);
stmt.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}}
});
b2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
t1.setText("");
t2.setText("");
}
});
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
try{
stmt.close();
conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
});
setVisible(true);
}
public static void main(String[] args)throws Exception {
new YouTubeTest();
}
};

Categories