jFrame not opening correctly or showing contents - java

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.

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

Adding a hyperlink to a single value of sql in jTable

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

Data submission not working while using Swing application otherwise it works normally

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

generating a unique string on pressing JButton and storing it into database table

I need to generate sequential number between 0-9 and want to display it in the JTextfield combined with the value from JCombobox(i.e.element of jcombobox+count)
as a string after pressing the JButton
When I select the first value from combobox and press the JButton the count should start from 0 and again when the second element from the combobox is selected the count should again start from 0 for second element and this should be the case for all other element of combobox.
For example-- when element 1 is selected and button is pressed the combined output should be 10,11,12,13... but,if in between this element 2 is selected
the output displayed in textfield should again start from 0 i.e.20,21,22...
and for element 3 the count should again start from 0 i.e. 30,31,32...
The combined output should be displayed in textfield
import java.sql.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
class Test extends JFrame implements ActionListener {
JButton b1, b2;
JComboBox jc;
String name;
JTextField t1;
Connection con, conn;
Statement st;
PreparedStatement pst;
ResultSet rs, rs1;
Test() {
setLayout(null);
JLabel l1 = new JLabel("USER SELECTION :");
l1.setBounds(100, 100, 150, 60);
add(l1);
jc = new JComboBox();
jc.setBounds(230, 114, 120, 30);
jc.addItem("SELECT");
jc.addActionListener(this);
add(jc);
JButton b1 = new JButton("GENERATE PART NO. :");
b1.setBounds(70, 340, 170, 30);
b1.addActionListener(this);
add(b1);
t1 = new JTextField(10);
t1.setBounds(270, 340, 200, 30);
add(t1);
JButton b2 = new JButton("BACK");
b2.setBounds(190, 420, 120, 30);
b2.addActionListener(this);
add(b2);
setSize(500, 500);
setResizable(false);
this.setVisible(true);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/d03", "root", "");
st = con.createStatement();
String s = "select Userdata from user1";
rs = st.executeQuery(s);
while (rs.next()) {
String name = rs.getString("Userdata");
jc.addItem(rs.getString("Userdata"));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERROR");
}
finally {
try {
st.close();
rs.close();
con.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "ERROR CLOSE");
}
}
}
public void actionPerformed(ActionEvent ae) {
String str = ae.getActionCommand();
if (str.equals("GENERATE PART NO. :")) {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/d03", "root", "");
st = con.createStatement();
String s = "select value from user1 where Userdata='" + jc.getSelectedItem() + "'";
rs = st.executeQuery(s);
t1.getText();
if (rs.next()) {
String add1 = rs.getString("value");
t1.setEditable(false);
t1.setText("B" + add1);// B is the default value here which
// is also concatenated
}
}
catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "ERROR CLOSE");
}
}
if (str.equals("BACK") == true) {
new categ();
setVisible(false);
}
}
public static void main(String[] args) throws IOException {
Test td = new Test();
}
}

I can't show photo blob more than once

I have a database with photos for each person. I have a class that shows the photos of the people. When the class is running first, it stores the foto locally, and then another method takes it and displays it. The problem is that the class works correctly ONLY the first time! Every other name selection displays the first picture. Please help me to identify where does this happen!
Here is my Class:
public class Profile extends JFrame {
int x;
JLabel label;
Image img;
ImageIcon pic;
JPanel panel;
private JTextPane namepanel = new JTextPane();
private JLabel namelabel = new JLabel();
private JLabel lastnamelabel = new JLabel();
private JTextPane lastnamepanel = new JTextPane();
ResultSet resultSet;
private JButton add = new JButton();
private JButton remove = new JButton();
public Profile() {
try {
//getData(x);
//showImage();
//jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
public void getData(int p_id) throws Exception {
Login login = new Login();
String url = "jdbc:oracle:thin:#localhost:1521:ORCL";
String username = login.getUsername();
String password = login.getPassword();
Connection conn = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, username, password);
System.out.println("At the profile class id = " + p_id);
String sql = "SELECT foto, name, surname FROM criminals WHERE id = " + p_id;
System.out.println(sql);
PreparedStatement stmt = conn.prepareStatement(sql);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
namepanel.setText(resultSet.getString(2));
lastnamepanel.setText(resultSet.getString(3));
File image = new File("java.jpg");
FileOutputStream fos = new FileOutputStream(image);
byte[] buffer = new byte[256];
// Get the binary stream of our BLOB data
InputStream is = resultSet.getBinaryStream(1);
int bytes = 0;
while ((bytes = is.read(buffer)) > 0) {
fos.write(buffer, 0, bytes);
}
showImage();
fos.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null && !conn.isClosed()) {
conn.close();
}
}
}
public void showImage() throws Exception {
this.getContentPane().removeAll();
img = null;
img = new ImageIcon("java.jpg").getImage();
pic = null;
pic = new ImageIcon(img);
label = new JLabel("", pic, JLabel.CENTER);
panel = new JPanel(new BorderLayout());
panel.setBounds(new Rectangle(0, 0, 340, 310));
namepanel.setBounds(new Rectangle(340, 30, 295, 35));
namelabel.setText("Name");
namelabel.setBounds(new Rectangle(340, 0, 295, 30));
lastnamelabel.setText("Surname");
lastnamelabel.setBounds(new Rectangle(340, 65, 295, 30));
lastnamepanel.setBounds(new Rectangle(340, 105, 295, 35));
add.setText("add");
add.setBounds(new Rectangle(440, 175, 255, 40));
remove.setText("remove");
remove.setBounds(new Rectangle(440, 240, 255, 35));
panel.add(label, null);
panel.add(label, BorderLayout.CENTER);
this.getContentPane().setLayout(null);
this.setSize(new Dimension(1148, 336));
this.getContentPane().add(remove, null);
this.getContentPane().add(add, null);
this.getContentPane().add(lastnamepanel, null);
this.getContentPane().add(lastnamelabel, null);
this.getContentPane().add(namelabel, null);
this.getContentPane().add(namepanel, null);
this.getContentPane().add(panel, null);
}
The way you are using is the not way of using preparedstatement. Use this way
String sql = "SELECT foto, name, surname FROM criminals WHERE id = ?" ;
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setInt(1,p_id);
I found the solution! Here it is in case anyone else searches for it!
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, username, password);
System.out.println("At the profile class id = " + p_id);
String sql = "SELECT foto, name, surname FROM criminals WHERE id = " + p_id;
System.out.println(sql);
PreparedStatement stmt = conn.prepareStatement(sql);
resultSet = stmt.executeQuery();
byte[] bytes = null;
while (resultSet.next()) {
namepanel.setText(resultSet.getString(2));
lastnamepanel.setText(resultSet.getString(3));
bytes = resultSet.getBytes(1);
}
resultSet.close();
stmt.close();
conn.close();
if (bytes != null) {
JFrame f = new JFrame();
image = f.getToolkit().createImage(bytes);
}
} catch (Exception e) {
}
jbInit();
}
public void jbInit() throws Exception {
pic = new ImageIcon(image);
label = new JLabel("", pic, JLabel.CENTER);
}

Categories