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);
}
}
Related
My code is a basic file creator and manager. The main way I organise all the files are in a directory text file. I import it into an array so the program can access it. My delete button doesn't remove the string from the ArrayList. How can i fix this?
//This part initialises the code and imports the array
private void startActionPerformed(java.awt.event.ActionEvent evt) {
ArrayList<String> directory = new ArrayList();
String content1;
try {
content1 = new String(Files.readAllBytes(Paths.get("directory.txt")));
output.setText(content1);
directory.add(content1);
refresh();
} catch (IOException ex) {
Logger.getLogger(filemanagerUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
//This allows me to refresh the output text area
private void refresh() {
String content = "";
for (int i = 0; i < directory.size(); i++) {
content = content + directory.get(i) + "\n";
}
try {
Files.write(Paths.get("directory.txt"), directory);
} catch (IOException ex) {
Logger.getLogger(filemanagerUI.class.getName()).log(Level.SEVERE, null, ex);
}
output.setText(content);
System.out.println(directory);
}
//This deletes the file from the directory and the actual file
private void deleteActionPerformed(java.awt.event.ActionEvent evt) {
directory.remove(input.getText());
String fileDelete = input.getText();
directory.remove(input.getText());
Path deletefile = (Paths.get(fileDelete + ".txt"));
try {
Files.delete(deletefile);
} catch (IOException ex) {
Logger.getLogger(filemanagerUI.class.getName()).log(Level.SEVERE, null, ex);
}
try {
Files.write(Paths.get("directory.txt"), directory);
} catch (IOException ex) {
Logger.getLogger(filemanagerUI.class.getName()).log(Level.SEVERE, null, ex);
}
refresh();
}
Maybe you have the file open when you debugging it. Make sure the program can access it
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
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.
I had the following code, which is responsible for assigning roles and groups to users.
private void override(List<Assignment> assignments) {
removeAll();
addMultiple(assignments);
}
protected void removeAll() {
removeAllRoles();
removeAllGroups();
}
private void removeAllGroups() {
Iterator<String> userGroups = user.getParentGroups(false);
while (userGroups.hasNext()) {
UMHelper.removeUserFromGroup(user.getUniqueID(), userGroups.next());
}
}
private void addMultiple(List<Assignment> assignments) {
for (Assignment assignment : assignments) {
add(assignment);
}
}
public static void addUserToGroup(String userId, String groupId) {
try {
SimpleLogger.log(Severity.INFO, Category.APPLICATIONS, loc, null, "Trying to add user " + userId + " to group " + groupId);
groupFactory.addUserToGroup(userId, groupId);
SimpleLogger.log(Severity.INFO, Category.APPLICATIONS, loc, null, "Success");
} catch (UMException e) {
SimpleLogger.traceThrowable(Severity.ERROR, loc, "Addition failed", e);
}
}
I hope the logic is pretty clear. Most of the code is iteration over collections. Adding a user to role or group can cause exception, which I report in log.
Since I find it not good to suppress exceptions and because a client calling override method should know the result of assigment, I rewrote the code adding exception handling. The execution should continue, even if some assignments failed.
private void override(List<Assignment> assignments) {
SimpleLogger.log(Severity.INFO, Category.APPLICATIONS, loc, null, "Override was started with " + assignments.size() + " assignments");
try {
removeAll();
} catch (UMException e) {
SimpleLogger.log(Severity.INFO, Category.APPLICATIONS, loc, null, "Removing all existing elements failed");
}
try {
addMultiple(assignments);
} catch (UMException e) {
SimpleLogger.log(Severity.INFO, Category.APPLICATIONS, loc, null, "Adding new elements failed");
}
}
protected void removeAll() throws UMException {
boolean successfulRemoval = true;
try {
removeAllRoles();
} catch (UMException e) {
successfulRemoval = false;
}
try {
removeAllGroups();
} catch (UMException e) {
successfulRemoval = false;
}
if (!successfulRemoval){
throw new UMException("Not all user elements could be removed");
}
}
private void removeAllGroups() throws UMException {
boolean removeSuccessful = true;
Iterator<String> userGroups = user.getParentGroups(false);
while (userGroups.hasNext()) {
try {
UMHelper.removeUserFromGroup(user.getUniqueID(), userGroups.next());
} catch (UMException e) {
removeSuccessful = false;
}
}
if (!removeSuccessful) {
throw new UMException("Not all user groups could be removed");
}
}
private void addMultiple(List<Assignment> assignments) throws UMException {
boolean additionSuccessful = true;
for (Assignment assignment : assignments) {
try {
add(assignment);
} catch (UMException e) {
additionSuccessful = false;
}
}
if (!additionSuccessful) {
throw new UMException("Addition of new rights failed");
}
}
public static void addUserToGroup(String userId, String groupId) throws UMException {
SimpleLogger.log(Severity.INFO, Category.APPLICATIONS, loc, null, "Trying to add user " + userId + " to group " + groupId);
groupFactory.addUserToGroup(userId, groupId);
SimpleLogger.log(Severity.INFO, Category.APPLICATIONS, loc, null, "Success");
}
Now the code got 3 times bigger and not as clear as it was. If I just had to stop execution after first assignment failed, the code would have been easier, but that's the requirement. Do I handle exceptions wrong or is there a way to improve the code?
In this scenario I would change all these methods from throwing exceptions to
returning a boolean value which indicates if they did their job successfully or not.
If you have control over these methods and can do this change, I think that's better
suited for your scenario.
With a little code reorganization, that is, all removals/additions/etc are in a single transaction, the code can be made clearer, as in, for instance:
String failmsg = null;
// tx is some transaction object
tx.start();
try {
failmsg = "user removal failed";
tx.removeUsers();
failmsg = "group removal failed";
tx.removeGroups();
failmsg = "new additions failed";
tx.addNew();
tx.commit();
} catch (UMException e) {
tx.rollback();
log(failmsg);
} finally {
tx.close();
}
Is there any way to make this piece of code work? The only problem I am having is that when the user clicks cancel, the message dialog shows up.
public static void main(String[] args) {
try {
JOptionPane.showInputDialog("Enter something")
} catch (Exception error) {
JOptionPane.showMessageDialog("Something went wrong.");
}
}
I fixed your code so it compiles:
import javax.swing.JOptionPane;
public class Example {
public static void main(String[] args) {
try {
JOptionPane.showInputDialog("Enter something");
} catch (Exception error) {
error.printStackTrace();
JOptionPane.showMessageDialog(null, "Something went wrong.");
}
}
}
And it works fine when it runs, whether or not I click 'cancel', or 'ok'. No exception is thrown.
I suspect your actual code has something else going on other than what you've posted.
import javax.swing.*;
class GetInput {
public static void getInput() {
String result = JOptionPane.showInputDialog(null, "Enter something");
if (result==null) {
System.out.println("User cancelled action.");
} else {
System.out.println("User entered '" + result + "'.");
}
}
public static void main (String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
getInput();
getInput();
}
});
}
}
Typical output
User entered 'this code runs!'.
User cancelled action.
Press any key to continue . . .
When they press Cancel you get a null back. I suspect you are getting a NPE which is getting caught. Check the return value for null.
try{
//some code ;)
} catch(Exception e) {
System.out.println(e.getMessage());
JOptionPane.showMessageDialog(this, " erreur !!! :" + e.getMessage());
}