How do I pass data from jList to database(mySQL) - java

I need some help regarding my program. How do I pass data from JList into database?
In ItemDetails.java, I have passed the checkbox value into a JList in another JForm. Now I want to retrieve the data from JList into my database.
ItemDetails.java
private void jButtonNextActionPerformed(java.awt.event.ActionEvent evt) {
ShoppingCart sc=new ShoppingCart();
if(!jCheckBoxAdele.isSelected()&&!jCheckBox1DPerfect.isSelected()&&!jCheckBoxBieber.isSelected()
&&!jCheckBox1D1Thing.isSelected()&&!jCheckBoxHujan.isSelected()&&!jCheckBoxSamWriting.isSelected()
&&!jCheckBoxAlessiaWil.isSelected()&&!jCheckBoxSamStayWithMe.isSelected()
&&!jCheckBoxFx.isSelected()&&!jCheckBoxSonaone.isSelected()&&!jCheckBoxRabbani.isSelected()
&&!jCheckBoxTroye.isSelected()&&!jCheckBoxMarvinGaye.isSelected())
{
sc.setVisible(false);
JOptionPane.showMessageDialog(null, "Please pick your song !!!");
dispose();
new ItemDetails().setVisible(true);
}
if(jCheckBoxAdele.isSelected())
songsdetails.add("Adele - Hello");
if(jCheckBox1DPerfect.isSelected())
songsdetails.add("One Direction - Perfect");
if(jCheckBoxBieber.isSelected())
songsdetails.add("Justin Bieber - Sorry");
if(jCheckBox1D1Thing.isSelected())
songsdetails.add("One Direction - One Thing");
if(jCheckBoxHujan.isSelected())
songsdetails.add("Hujan - Anging Kencang");
if(jCheckBoxSamWriting.isSelected())
songsdetails.add("Sam Smith - Writing On The Walls");
if(jCheckBoxAlessiaWil.isSelected())
songsdetails.add("Alessia Cara");
if(jCheckBoxSamStayWithMe.isSelected())
songsdetails.add("Sam Smith - Stay With Me");
if(jCheckBoxFx.isSelected())
songsdetails.add("F(x) - 4 Walls");
if(jCheckBoxDemi.isSelected())
songsdetails.add("Demi Lovato - I Really Don't Care");
if(jCheckBoxSonaone.isSelected())
songsdetails.add("Sonaone - Firefly");
if(jCheckBoxRabbani.isSelected())
songsdetails.add("Rabbani - Pergi Tak Kembali");
if(jCheckBoxTroye.isSelected())
songsdetails.add("Troye Sivan - Fools");
if(jCheckBoxMarvinGaye.isSelected())
songsdetails.add("Charlie Puth - Marvin Gaye");
new ShoppingCart(songsdetails).setVisible(true);
dispose();
}
ShoppingCart.java
public class ShoppingCart extends javax.swing.JFrame {
public Connection cn;
public PreparedStatement st;
static ArrayList songsdetails;
/**
* Creates new form ShoppingCart
*/
public ShoppingCart() {
initComponents();
}
public ShoppingCart(ArrayList SONGSDETAILS) {
initComponents();
songsdetails = SONGSDETAILS;
}
private void jButtonEditActionPerformed(java.awt.event.ActionEvent evt) {
this.setVisible(false);
jList1.clearSelection();
new ItemDetails().setVisible(true);
}
private void jButtonNextActionPerformed(java.awt.event.ActionEvent evt) {
try {
Class.forName("com.mysql.jdbc.Driver");
cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/sdmusic","root","");
st=cn.prepareStatement("SELECT `Username`, `SongsSelection` FROM `user` WHERE `Username`=? 'SongsSelection' = ?");
} catch (ClassNotFoundException ex) {
Logger.getLogger(ShoppingCart.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(ShoppingCart.class.getName()).log(Level.SEVERE, null, ex);
}
dispose();
new CalculatePay().setVisible(true);
}
private void formWindowOpened(java.awt.event.WindowEvent evt) {
// TODO add your handling code here:
DefaultListModel list = new DefaultListModel();
System.out.println(""+songsdetails.get(0));
for(int i=0; i <songsdetails.size();i++){
list.addElement(songsdetails.get(i));
}
jList1.setModel(list);
}

Retrieve needed values from your JList, see here
Prepare an INSERT INTO statement, see here
Execute your statement, see here

Related

How to know which row was selected from another Frame?

In the first Jframe I have a JTable filled from database and i need to pass data of the selected jTable to another frame.
So I need to know from another JInternalFrame which row was selected in the First Jframe
public void showTableData() {
try {
Class.forName(driverName);
Connection con = DriverManager.getConnection(url, userName, password);
String sql = "SELECT t.name, t.exam, l.coursename\n"
+ "FROM exam AS t\n"
+ "INNER JOIN Course as l ON (t.LendaID=l.LendaID)";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
int i = 0;
Jtable1.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error",
JOptionPane.ERROR_MESSAGE);
}
}
This is the table I've in the first Jframe
Regardless the number of your components, as a simple solution, you can create a CourseEventDispatcher class to be central point to dispatch course events across the application.
public class CourseEventDispatcher {
private List<CourseEventSubscriber> subscribers;
// ...
public void dispatchEvent(CourseEvent event) {
for(CourseEventSubscriber: subscribers) {
if( event.getSource() != subscriber ) {
subscriber.onCourseEvent(event);
}
}
}
}
And for each relevant view, there is a controller which is a CourseEventSubscriber:
public class SomeFrameController implements CourseEventSubscriber {
private CourseEventDispatcher courseEventDispatcher;
public SomeFrameController(CourseEventDispatcher courseEventDispather) {
this.courseEventDispatcher = courseEventDispatcher;
}
public void addSelectionListener() {
// ...
table.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
doYourOwnStuff();
// then dispatch the event
courseEventDispatcher.dispatch(new CourseEvent(this, event));
}
}
);
}
// from some other view
public void onCourseEvent(CourseEvent event) {
// process the event
// e.g. event.getEvent()
}
}
And CourseEvent is a simple class of
public class CourseEvent {
private CourseEventSubscriber source;
private EventObject event;
public CourseEvent(CourseEventSubscriber source, EventObject event) {
this.source = source;
this.event = event;
}
// getters
}
You can add(register) your controllers after you created a dispatcher.
Hope this gives you another perspective.

how to close a frame inside thread

I have this problem that I can't close current form after receiving message from server, I have implemented a thread class as I need to exchange message from a server, the problem that I am facing now is I cant close the current form after receiving start message from the server, opening new form is working correctly, but when I'm coming to close the current form it not working !! I don't know how to solve this problem so I need help with that
public class StartForm extends javax.swing.JFrame {
// needed info about the current user
public static StartForm form= new StartForm() ;
private String name;
private String currentUsers;
private int id ;
private static int time ;
public static Socket socket;
public boolean firstFlag;
private boolean close=false;
public static PrintWriter printWriter;
public static BufferedReader bufferedReader;
public static Scanner reader;
public static java.lang.Thread thread2;
public void setName (String name){
this.name=name;}
public String getName (){
return this.name;}
public void setCurrentUsers (String currentUsers){
this.currentUsers=currentUsers;}
public String getCurrentUsers (){
return this.currentUsers;}
public void setId (int id){
this.id=id;}
public int getId (){
return this.id;}
public void setTime (int time){
this.time=time;}
public int getTime (){
return this.time;}
public void setSocket (Socket socket){
this.socket=socket;
}
public Socket getSocket (){
return this.socket;}
public void setFirstFlag (boolean firstFlag){
this.firstFlag=firstFlag;}
public boolean getFirstFlag (){
return this.firstFlag;}
/**
* Creates new form StartForm
*/
public StartForm() {
initComponents();
}
// constructor to initialize
private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {
if (testInput(jTextField1.getText())){
// PrintWriter printWriter;
// read the inserted time and falidate it if it number send it to the server to notify the other users
printWriter.println("time:"+jTextField1.getText());
jButton2.setEnabled(false);
jTextField1.setEnabled(false);
jButton1.setEnabled(true);
}
else {
//if time inserted is not number unaccepted
JOptionPane.showMessageDialog(null, "only insert numbers");
jTextField1.setText("");
}
// TODO add your handling code here:
}
private void formWindowActivated(java.awt.event.WindowEvent evt) {
// initiate the needed reader and writer objects
try {
printWriter = new PrintWriter(socket.getOutputStream(),true);
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// starting the thread
Thread thread = new Thread (this.getId(),form);
thread2 = new java.lang.Thread(thread);
thread2.start();
} catch (IOException ex) {
Logger.getLogger(StartForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void formWindowClosed(java.awt.event.WindowEvent evt) {
// close the frame
this.dispose();
System.exit(0); }
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
printWriter.println("ready"+id);
jLabel8.show();
this.disable();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(StartForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(StartForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(StartForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(StartForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
form.setVisible(true);
}
});
}
public class Thread implements Runnable {
private int idd;
private StartForm form3;
public Thread(int id, StartForm form2){
idd=id;
form3=form;
}
public void run()
{
try {
String message="";
while((message=bufferedReader.readLine())!=null){
{
else if (message.substring(0,5).equals("start")){
GameForm gameFrame= new GameForm();
int trunid =Integer.parseInt(message.substring(5));
System.out.println("$$$$$ on the thread "+ trunid);
if (id==trunid)
gameFrame.setTurn(true);
else gameFrame.setTurn(false);
gameFrame.setId(idd);
form3.setVisible(false);
gameFrame.setVisible(true);
}
else {
jTextArea2.append(message); }
}
}
} catch (IOException ex) {
Logger.getLogger(StartForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
// Variables declaration - do not modify
}

Incorrect syntax near inserted value

I wrote this code to edit an existing table of my database called RegisterationForm. I'm using Jframe forms, but after running the program when I press the edit button, an error shows incorrect syntax near 'the word I've entered for sourceName'.
Even if I don't change anything and press edit, the error appears.
I tried debugging but I can't find out what's wrong.
reg is the name of the combobox I wanna choose an existing RegisterationForm id from to edit its records.
My code:
private void editActionPerformed(java.awt.event.ActionEvent evt) {
if(l==0)
{
JOptionPane.showMessageDialog(rootPane,"choose a number", WIDTH);
return;
}
if(id.getText().equalsIgnoreCase(""))
{
JOptionPane.showMessageDialog(rootPane,"retry", WIDTH);
return;
}
String s="update RegisterationForm set id='"+id.getText()+"' , date="+date.getText()+" , sourceName="+sourceName.getText()+" , sourceCode='"+sourceCode.getText()+"' where id='"+reg.getSelectedItem().toString()+"'";
try
{
DBlabprj.stmt.execute(s);
JOptionPane.showMessageDialog(rootPane,"Done.");
this.dispose();
this.setVisible(false);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(rootPane,e.getMessage());
}
}
private void showActionPerformed(java.awt.event.ActionEvent evt) {
reg.setEnabled(false);
l=1;
String s="select * from RegisterationForm where id='"+reg.getSelectedItem().toString()+"'";
try
{
DBlabprj.rs=DBlabprj.stmt.executeQuery(s);
DBlabprj.rs.next();
id.setText(DBlabprj.rs.getString("id"));
date.setText(DBlabprj.rs.getString("date"));
sourceName.setText(DBlabprj.rs.getString("sourceName"));
sourceCode.setText(DBlabprj.rs.getString("sourceCode"));
}
catch (Exception e)
{
JOptionPane.showMessageDialog(rootPane,e.getMessage());
}
}
private void formWindowOpened(java.awt.event.WindowEvent evt) {
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
reg.removeAllItems();
String s="";
s="select id from RegisterationForm order by id";
try {
DBlabprj.rs=DBlabprj.stmt.executeQuery(s);
while(DBlabprj.rs.next())
{
reg.addItem(DBlabprj.rs.getString("id"));
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(rootPane,ex.getMessage());
Logger.getLogger(NewForm.class.getName()).log(Level.SEVERE, null, ex);
}
}

XMPP Group chat java - logic to join users in room inside invitation listener is not working

I am trying to create sample java application to implement the MultiUserChat of XMPP. Some how I can able to create user and make it online in openfire. Can any one suggest how to join all the users to the created chatRoom?
Here is my sample code inside the class SampleMultiUserChat Where I invite all the users to join the group but it is not getting joined. What I am missing?
SampleMultiUserChat(){
oConnectionConfiguration = new ConnectionConfiguration("10.10.1.105",5223);
createChatRoom();
}
/**
* #param args
*/
public static void main(String[] args) {
SampleMultiUserChat oSampleMultiUserChat = new SampleMultiUserChat();
for(int i = 2; i < 4; i++){
oSampleMultiUserChat.openXMPPConnection("user"+i);
oSampleMultiUserChat.createAcceptInvitationListener("user"+i);
oSampleMultiUserChat.inviteToJoinRoom("user"+i);
}
Thread mainThread = Thread.currentThread();
while(true){
try {
mainThread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void openXMPPConnection(String user){
XMPPConnection oXmppConnection = new XMPPConnection(oConnectionConfiguration);
try {
oXmppConnection.connect();
oXmppConnection.login(user, "60474c9c10d7142b7508ce7a50acf414");
userConnection.put(user, oXmppConnection);
} catch (XMPPException e) {
System.out.println("Exception occured in login in user : "+user);
}
}
private void createChatRoom(){
XMPPConnection oXmppConnection = new XMPPConnection(oConnectionConfiguration);
try {
oXmppConnection.connect();
oXmppConnection.login("user1", "60474c9c10d7142b7508ce7a50acf414");
myChattingRoom = new MultiUserChat(oXmppConnection, "mychattingroom#conference.10.10.1.105");
myChattingRoom.create("roomNickName");
myChattingRoom.sendConfigurationForm(new Form(Form.TYPE_SUBMIT));
} catch (XMPPException e) {
e.printStackTrace();
}
}
private void inviteToJoinRoom(String user){
myChattingRoom.invite(user+"#10.10.1.105", "Please join my chatting room");
System.out.println("sent invitation by "+user);
}
private void sendMessage(String msg){
try {
myChattingRoom.sendMessage(msg);
} catch (XMPPException e) {
System.out.println("Exception occured while sending msg to chat room"+e);
}
}
private void createAcceptInvitationListener(String user){
MultiUserChat.addInvitationListener(userConnection.get(user), new InvitationListener() {
public void invitationReceived(Connection connection, String room, String inviter,
String reason, String password, Message msg) {
try {
myChattingRoom.join(connection.getUser().substring(0, connection.getUser().indexOf("#")));
} catch (XMPPException e) {
e.printStackTrace();
}
}
});
}
Thanks in advance.
I solved my above problem by creating new instance of MultiUserChat.
Here is my edited method 'createAcceptInvitationListener'
private void createAcceptInvitationListener(String user){
System.out.println("inside create accept invitation listener");
final XMPPConnection oXmppConnection = userConnection.get(user);
MultiUserChat.addInvitationListener(oXmppConnection, new InvitationListener() {
public void invitationReceived(Connection connection, String room, String inviter,
String reason, String password, Message msg) {
System.out.println("inside invitation received method");
try {
System.out.println(connection.getUser().substring(0, connection.getUser().indexOf("#")));
MultiUserChat myChattingRoom = new MultiUserChat(oXmppConnection, "mychattingroom#conference.10.10.1.105");
myChattingRoom.join(connection.getUser().substring(0, connection.getUser().indexOf("#")));
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception occured while joining the chat room : "+e);
}
}
});
}
private void reservedRoomsCreation(MultiUserChat myChattingRoom) throws XMPPException{
Form form = myChattingRoom.getConfigurationForm();
Form submitForm = form.createAnswerForm();
for(Iterator fields = form.getFields(); fields.hasNext();){
FormField formFields = (FormField) fields.next();
if (!FormField.TYPE_HIDDEN.equals(formFields.getType()) && formFields.getVariable() != null) {
submitForm.setDefaultAnswer(formFields.getVariable());
}
}
submitForm.setAnswer("muc#roomconfig_persistentroom", true);
myChattingRoom.sendConfigurationForm(submitForm);
}

Unhandled exception type URISyntaxException when trying to make links clickable in JTable

The aim is to make the link clickable in jtable so that when user clicks on the link the desired page gets opened in the browser. One of the items fetched from database is link and my attempt is to make it active and clickable. I get the error as
Unhandled exception type URISyntaxException
For the line in my code:
final URI uri = new URI("http://www.roseindia.net");
And even if i put it in try catch block, the error doesn't seem to resolve. Rather on surrounding in a try-catch block, I get the error as
Cannot refer to a non-final variable uri inside an inner class defined in a different method
So what could be the possible solution and fix?
public class JTableButtonMouseListener extends MouseAdapter
{
private final JTable table;
public JTableButtonMouseListener(JTable table)
{
this.table = table;
}
public void mouseClicked(MouseEvent e) {
counter=0;
// System.out.println("***************************************************************");
System.out.println("counter value="+counter++);
//System.out.println("/////////////////////////////////////////////////////////////////////");
int column = table.getColumnModel().getColumnIndexAtX(e.getX());
int row = e.getY()/table.getRowHeight();
if (row < table.getRowCount() && row >= 0 && column < table.getColumnCount() && column >= 0) {
Object value = table.getValueAt(row, column);
// System.out.println("row clicked="+row);
//System.out.println("column clicked="+column);
System.out.println("object value="+value);
System.out.println(".............................................................");
/* public void getsecname(String s)
{
String ss=s;
}*/
if(table.getValueAt(row, 4)!=null)
{
Object ob = table.getValueAt(row, 4);
String link_string=ob.toString();
// final URI uri = null;
// URI uri;
try{
final URI uri = new URI("http://www.roseindia.net");
}
catch (URISyntaxException e1)
{
e1.printStackTrace();
}
System.out.println(".....................");
((AbstractButton) ob).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(uri);
// button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
// desktop.setCursor(new Cursor(Cursor.HAND_CURSOR));
} catch (Exception ex) {
}
} else {
}
}
});
}
// String link_string=ob.toString();
//ob.setClickable(true);
if(value==null)
{
Object v=table.getValueAt(row, 1);
//System.out.println("--------------------------------------------");
s = v.toString();
jmenu_frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
jmenu_frame.setContentPane(new ListModelExample(s));
jmenu_frame.setSize(260, 200);
jmenu_frame.setVisible(true);
jmenu_frame.setLocationRelativeTo(null);
//it ends here
}
if (value instanceof JButton) {
((JButton)value).doClick();
}
}
}
}
You can not use non-final variable inside your inner class. Discussion.
if(table.getValueAt(row, 4)!=null)
{
Object ob = table.getValueAt(row, 4);
String link_string=ob.toString();
try {
final URI uri = new URI("http://www.roseindia.net");
System.out.println(".....................");
((AbstractButton) ob).addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(uri);
//button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
// desktop.setCursor(new Cursor(Cursor.HAND_CURSOR));
} catch (Exception ex) {
}
}
}
});
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
What is telling you is that you need a try catch block to handle a URISyntaxException:
final URI;
try{
uri = new URI("http://www.roseindia.net");
} catch (URISyntaxException e) {
e.printStackTrace();
}
To solve uri cannot be resolved to a variable You could instead of using try catch, add a throws URISyntaxException to the method in which uri is declared. But I do not think that is a good practice. Maybe it works in your case.

Categories

Resources