ActionPerformed exception

I am trying to create a gui that uses a seperate class that accesses a database. The gui works fine, but when I try to write the code for the actionPerformed method, I keep getting errors for exceptions that the database class handles itself. I am unsure as to exactly what is going on here. Can anyone shed some light on the subject? the code for the actionPerformed method and the database class is as follows:
public class loginAction implements ActionListener {
     public void actionPerformed(ActionEvent action){               
               DBConnection loginConnection = new DBConnection();
               loginConnection.checkLogin(uName.getText(), pWord.getText());
import javax.swing.JOptionPane;
import java.sql.*;
public class DBConnection {
     private final String url = "jdbc:mysql://localhost:3306/vendor_proposal";
     private final String user = "newb@localhost";
     private final String password = "1234";
     Connection connect = null;
     //Default constructor that creates the connection to the database.
     public DBConnection() throws IllegalAccessException, InstantiationException, SQLException {
          try {
               Class.forName("com.mysql.jdbc.Driver").newInstance();
               connect = DriverManager.getConnection(url, user, password);
          }catch(SQLException e){
               JOptionPane.showMessageDialog(null, "Could not connect to the database.",
                         "Error!", JOptionPane.ERROR_MESSAGE);
               System.exit(0);
          }catch(Exception e){
               JOptionPane.showMessageDialog(null, "Error Occured while running the program.",
                         "Error!", JOptionPane.ERROR_MESSAGE);
     public void closeConnection() throws SQLException{
          try {
               connect.close();
          }catch(SQLException e){
               JOptionPane.showMessageDialog(null, "Error occured while accessing the database.",
                         "Error!", JOptionPane.ERROR_MESSAGE);
     public void checkLogin(String user, String password) throws SQLException{
          boolean passwordCheck = false;
          try{
               Statement stmt = connect.createStatement();
               String query = "select * from user_Accounts where username = '" + user +
               ResultSet rs = stmt.executeQuery(query);
               while (rs.next()){
                    int test;
                    test = password.compareTo(rs.getString("password"));
                    if (test == 0)
                         passwordCheck = true;
                    rs.close();
                    stmt.close();
          }catch(SQLException e){
               JOptionPane.showMessageDialog(null, "Error occured while accessing the " +
                         "database.", "Error!", JOptionPane.ERROR_MESSAGE);
          if (passwordCheck == true) {
               JOptionPane.showMessageDialog(null, "You have successfully logged into the " +
                         "system", "Login Successful!", JOptionPane.INFORMATION_MESSAGE);
          } else {
               JOptionPane.showMessageDialog(null, "Your login information was incorrect, " +
                         "please try again.", "Error!", JOptionPane.ERROR_MESSAGE);
Edited by: aserothbw on Aug 5, 2009 9:27 PM

public *class *loginAction *implements *ActionListener {
*public* *void* actionPerformed(ActionEvent action) *throws* SQLException{
//these two lines throw the unhandled exception error.
_DBConnection loginConnection = *new *DBConnection();_
_loginConnection.checkLogin(uName.getText(), pWord.getText());_
//this code compiles with no errors, and seems to run fine atm.
import javax.swing.JOptionPane;
import java.sql.*;
public *class *DBConnection {
*private* *final* String url = "jdbc:mysql://localhost:3306/vendor_proposal";
*private* *final* String user = "newb@localhost";
*private* *final* String password = "1234";
Connection connect = *null*;
//Default constructor that creates the connection to the database.
*public* DBConnection() *throws* IllegalAccessException, InstantiationException, SQLException {
*try* {
Class.+forName+("com.mysql.jdbc.Driver").newInstance();
connect = DriverManager.+getConnection+(url, user, password);
}*catch*(SQLException e){
JOptionPane.+showMessageDialog+(*null*, "Could not connect to the database.",
"Error!", JOptionPane.+ERROR_MESSAGE+);
System.+exit+(0);
}*catch*(Exception e){
JOptionPane.+showMessageDialog+(*null*, "Error Occured while running the program.",
"Error!", JOptionPane.+ERROR_MESSAGE+);
*public* *void* closeConnection() *throws* SQLException{
*try* {
connect.close();
}*catch*(SQLException e){
JOptionPane.+showMessageDialog+(*null*, "Error occured while accessing the database.",
"Error!", JOptionPane.+ERROR_MESSAGE+);
*public* *void* checkLogin(String user, String password) *throws* SQLException{
*boolean* passwordCheck = *false*;
*try*{
Statement stmt = connect.createStatement();
String query = "select * from user_Accounts where username = '" + user +
ResultSet rs = stmt.executeQuery(query);
*while* (rs.next()){
*int* test;
test = password.compareTo(rs.getString("password"));
*if* (test == 0)
passwordCheck = *true*;
rs.close();
stmt.close();
}*catch*(SQLException e){
JOptionPane.+showMessageDialog+(*null*, "Error occured while accessing the " +
"database.", "Error!", JOptionPane.+ERROR_MESSAGE+);
*if* (passwordCheck == *true*) {
JOptionPane.+showMessageDialog+(*null*, "You have successfully logged into the " +
"system", "Login Successful!", JOptionPane.+INFORMATION_MESSAGE+);
} *else* {
JOptionPane.+showMessageDialog+(*null*, "Your login information was incorrect, " +
"please try again.", "Error!", JOptionPane.+ERROR_MESSAGE+);

Similar Messages

  • Adding button events stops core functonality!

    This should be an easy one; here is a piece of code that i have adapted from the Java website!
    The problem occured when i added the code for the buttons in Public void actionPerformed.
    Instead of animating; the picture is static and will only advance by 1 frame if i press either the play or stop buttons! if u remove the code for the buttons the animation works fine!
    what am i doing wrong?
    (T1 to T10 can be any random gif pictures)
    I was wondering if i need a new actionPerformed class or something????
    hope you can help me
    kind regards
    RSH
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ImageSequenceTimer extends JFrame
                                    implements ActionListener {
        ImageSQPanel imageSQPanel;
        static int frameNumber = -1;
        int delay;
        Thread animatorThread;
        static boolean frozen = false;
        Timer timer;
         //Invoked only when this is run as an application.
        public static void main(String[] args) {
            Image[] waving = new Image[10];
            for (int i = 1; i <= 10; i++) {
                waving[i-1] =
                    Toolkit.getDefaultToolkit().getImage("images/T"+i+".gif");
            JFrame f = new JFrame("ImageSequenceTimer");
            f.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            ImageSequenceTimer controller = new ImageSequenceTimer();
            controller.buildUI(f.getContentPane(), waving);
            controller.startAnimation();
            f.setSize(new Dimension(350, 350));
            f.setVisible(true);
        //Note: Container must use BorderLayout, which is the
        //default layout manager for content panes.
        void buildUI(Container container, Image[] dukes) {
            int fps = 10;
            //How many milliseconds between frames?
            delay = (fps > 0) ? (1000 / fps) : 100;
            //Set up a timer that calls this object's action handler
            timer = new Timer(delay, this);
            timer.setInitialDelay(0);
            timer.setCoalesce(true);
            JPanel buttonPanel = new JPanel();
            JButton play = new JButton("PLAY");
            play.addActionListener(this);
            JButton stop = new JButton("STOP");
            stop.addActionListener(this);
            JButton restart = new JButton("RESTART");
            JButton back = new JButton("Back");
            imageSQPanel = new ImageSQPanel(dukes);
            container.add(imageSQPanel, BorderLayout.CENTER);
            imageSQPanel.addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    if (frozen) {
                        frozen = false;
                        startAnimation();
                    } else {
                        frozen = true;
                        stopAnimation();
           container.add(buttonPanel, BorderLayout.SOUTH);
           buttonPanel.add(play);
           buttonPanel.add(stop);
           buttonPanel.add(restart);
           buttonPanel.add(back);
        public void start() {
            startAnimation();
        public void stop() {
            stopAnimation();
        public synchronized void startAnimation() {
            if (frozen) {
                //Do nothing.  The user has requested that we
                //stop changing the image.
            } else {
                //Start animating!
                if (!timer.isRunning()) {
                    timer.start();
        public synchronized void stopAnimation() {
            //Stop the animating thread.
            if (timer.isRunning()) {
                timer.stop();
        public void actionPerformed(ActionEvent e) {
            //Advance the animation frame.
            frameNumber++;
            //Display it.
            imageSQPanel.repaint();
            {JButton button = (JButton) e.getSource();
             String label = button.getText();
             if("PLAY".equals(label))
             { start();
             else if("STOP".equals(label))
             { stop();
        class ImageSQPanel extends JPanel{
            Image dukesWave[];
            public ImageSQPanel(Image[] dukesWave) {
                this.dukesWave = dukesWave;
            //Draw the current frame of animation.
            public void paintComponent(Graphics g) {
                super.paintComponent(g); //paint background
                //Paint the frame into the image.
                try {
                    g.drawImage(dukesWave[ImageSequenceTimer.frameNumber%10],
                                0, 0, this);
                } catch (ArrayIndexOutOfBoundsException e) {
                    //On rare occasions, this method can be called
                    //when frameNumber is still -1.  Do nothing.
                    return;
    }

    You get ClassCastException at JButton button = (JButton) e.getSource(); therefore
    1. Always look if there are any exceptions thrown
    2. In this case e.getSource() does not always return JButton object reference, actionPerformed is also called by Timer. This is a source of your exception: you cast correctly only once - when button is pressed; then Timer calls actionPerformed, exception is thrown and animation stops.
    Here s corrected code
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test extends JFrame
                                    implements ActionListener {
        ImageSQPanel imageSQPanel;
        static int frameNumber = -1;
        int delay;
        Thread animatorThread;
        static boolean frozen = false;
        Timer timer;
        JButton play, stop; // <------------------------------------
         //Invoked only when this is run as an application.
        public static void main(String[] args) {
            Image[] waving = new Image[10];
            for (int i = 1; i <= 10; i++) {
                waving[i-1] =
                    Toolkit.getDefaultToolkit().getImage("images/T"+i+".gif");
            JFrame f = new JFrame("ImageSequenceTimer");
            f.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            Test controller = new Test();
            controller.buildUI(f.getContentPane(), waving);
            controller.startAnimation();
            f.setSize(new Dimension(350, 350));
            f.setVisible(true);
        //Note: Container must use BorderLayout, which is the
        //default layout manager for content panes.
        void buildUI(Container container, Image[] dukes) {
            int fps = 10;
            //How many milliseconds between frames?
            delay = (fps > 0) ? (1000 / fps) : 100;
            //Set up a timer that calls this object's action handler
            timer = new Timer(delay, this);
            timer.setInitialDelay(0);
            timer.setCoalesce(true);
            JPanel buttonPanel = new JPanel();
            play = new JButton("PLAY"); // <------------------------------------
            play.addActionListener(this);
            stop = new JButton("STOP"); // <------------------------------------
            stop.addActionListener(this);
            JButton restart = new JButton("RESTART");
            JButton back = new JButton("Back");
            imageSQPanel = new ImageSQPanel(dukes);
            container.add(imageSQPanel, BorderLayout.CENTER);
            imageSQPanel.addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    if (frozen) {
                        frozen = false;
                        startAnimation();
                    } else {
                        frozen = true;
                        stopAnimation();
           container.add(buttonPanel, BorderLayout.SOUTH);
           buttonPanel.add(play);
           buttonPanel.add(stop);
           buttonPanel.add(restart);
           buttonPanel.add(back);
        public void start() {
            startAnimation();
        public void stop() {
            stopAnimation();
        public synchronized void startAnimation() {
            if (frozen) {
                //Do nothing.  The user has requested that we
                //stop changing the image.
            } else {
                //Start animating!
                if (!timer.isRunning()) {
                    timer.start();
        public synchronized void stopAnimation() {
            //Stop the animating thread.
            if (timer.isRunning()) {
                timer.stop();
        public void actionPerformed(ActionEvent e) {
            //Advance the animation frame.
            frameNumber++;
            //Display it.
            imageSQPanel.repaint();
             if(e.getSource() == play) // <------------------------------------
             { start();
             else if(e.getSource() == stop) // <------------------------------------
             { stop();
        class ImageSQPanel extends JPanel{
            Image dukesWave[];
            public ImageSQPanel(Image[] dukesWave) {
                this.dukesWave = dukesWave;
            //Draw the current frame of animation.
            public void paintComponent(Graphics g) {
                super.paintComponent(g); //paint background
                //Paint the frame into the image.
                try {
                    g.drawImage(dukesWave[Test.frameNumber%10],
                                0, 0, this);
                } catch (ArrayIndexOutOfBoundsException e) {
                    //On rare occasions, this method can be called
                    //when frameNumber is still -1.  Do nothing.
                    return;
    }

  • WebCenter Satellite Server installation failing

    Hi all.
    Anyone experience issues with WebCenter Sites Satellite Server 11.1.1.6.1 bp1 installer? ssInstall.sh
    In the step where configuring which application server is (Websphere, WebLogic or Tomcat) the combo appears empty and the install_log is getting an ArrayIndexOutOfBounds:
    [2013-03-04 11:39:16.873][CS.INSTALL][ERROR] ftJDialog.actionPerformed: Exception caught:
    java.lang.ArrayIndexOutOfBoundsException
            at java.util.Vector.elementAt(Vector.java:430)
            at COM.FutureTense.Apps.Install.ftJDialog$ftJDialogComboBox.setToHash(ftJDialog.java:2070)
            at COM.FutureTense.Apps.Install.ftJDialog.setToHash(ftJDialog.java:1199)
            at COM.FutureTense.Apps.Install.ftJDialog.actionPerformed(ftJDialog.java:1573)
            at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
            at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
            at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
            at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
            at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
            at java.awt.Component.processMouseEvent(Component.java:6297)
            at javax.swing.JComponent.processMouseEvent(JComponent.java:3275)
            at java.awt.Component.processEvent(Component.java:6062)
            at java.awt.Container.processEvent(Container.java:2039)
            at java.awt.Component.dispatchEventImpl(Component.java:4660)
            at java.awt.Container.dispatchEventImpl(Container.java:2097)
            at java.awt.Component.dispatchEvent(Component.java:4488)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4575)
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4236)
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4166)
            at java.awt.Container.dispatchEventImpl(Container.java:2083)
            at java.awt.Window.dispatchEventImpl(Window.java:2489)
            at java.awt.Component.dispatchEvent(Component.java:4488)
            at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:668)
            at java.awt.EventQueue.access$400(EventQueue.java:81)
            at java.awt.EventQueue$2.run(EventQueue.java:627)
            at java.awt.EventQueue$2.run(EventQueue.java:625)
            at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
            at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
            at java.awt.EventQueue$3.run(EventQueue.java:641)
            at java.awt.EventQueue$3.run(EventQueue.java:639)
            at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:638)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:178)
            at java.awt.Dialog$1.run(Dialog.java:1044)
            at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
            at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:666)
            at java.awt.EventQueue.access$400(EventQueue.java:81)
            at java.awt.EventQueue$2.run(EventQueue.java:627)
            at java.awt.EventQueue$2.run(EventQueue.java:625)How can I fix this issue to continue with the wizard installer?.
    I will verify SatelliteServer.xml file (inside it are the combo values).
    Regards.

    Changing JDK used to launch installer solved the problem :).

  • How to add exception to actionPerformed?

    I have code that looks like this, with the main panel using an action listener in a different class in the same file:
    public class MyPanel
        public MyPanel()
        //Panel code
        button.addActionListener(new MyButton());
    private class MyButton implements ActionListener
        public void actionPerformed(ActionEvent e)
        //I want to throw a FileNotFoundException here, but when
        //I compile it, I get:
        //actionPerformed in Panel.java cannot implement actionPerformed in
        //java.awt.event.ActionListener; overridden method does not throw FileNotFoundException
            Scanner scan = new Scanner(new File("Items.txt"));
        }Any help would be appreciated. Thanks

    I know how to catch an exception once it is thrown, I am having trouble declaring the method will throw an exception. When I put
    public void actionPerformed(ActionEvent e) throws Exceptionand try to compile, it gives me a compiler error (the one in my first post.) I have tried declaring the exception in all other actionPerformed methods in my file, but have had no luck as they will all have a compiler error. I have no clue what to do to fix it.

  • Trouble with CardLayout and actionPerformed; null exception thrown

    Hello. I'm writing my first GUI, and I am using the CardLayout class to do so. I have two panels, and a button on each that "should" navigate to the other. However, when the button is pushed on the first card, I get this exception:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
         at emerensi_BMI.actionPerformed(emerensi_BMI.java:149)
    There are many lines after that, but I figured I would start with the first??
    Here is the code associated with that line:
    public void actionPerformed(ActionEvent e){
         if (e.getSource() == btnReCalculate){
              ((CardLayout)cardPanel.getLayout()).show(cardPanel, "one");
         } else if (e.getSource() == btnCalculate){
              ((CardLayout)cardPanel.getLayout()).show(cardPanel, "two");The last line is the actual line referenced. I am wondering if the "two" is what is null? Here is the code that it's associated with:
    String one = new String();
    String two = new String();
    JPanel cardPanel = new JPanel();
    cardPanel.setLayout(new CardLayout());
    cardPanel.add(one, Page1);
    cardPanel.add(two, Page2);
    contentPane.add(cardPanel, BorderLayout.CENTER);If I understand it correctly, the string in the (string, container) is supposed to reference its container, right?
    I'm not sure if this will make a difference, but also when the "calculate" button is pressed, I have it so that there will be calculations done with text that is entered on the first page, and the second page will display these calculations. Here is the code for that:
    } else if (e.getSource() == btnCalculate){
              ((CardLayout)cardPanel.getLayout()).show(cardPanel, "two");
         String feet = txtFeet.getText();
         String inches =     txtInches.getText();
         String pounds =     txtPounds.getText();
         float f = Float.valueOf(feet);
         float i = Float.valueOf(inches);
         float p = Float.valueOf(pounds);
         float height = (f * 12 + i);
         float math = (p * 703) / (height * height);
         String BMI = String.valueOf(math);
         lblBMI.setText(BMI);
         if (math <= 18.5){
              lblHealthEval.setText("Underweight");
         } else if (math <= 24.9){
              lblHealthEval.setText("Normal");
         } else if (math <= 29.9){
              lblHealthEval.setText("Overweight");
         } else if (30 <= math){
              lblHealthEval.setText("Obese");
         } // end else ifI have labels defined for the second panel that should get the set strings. But since the null exception is thrown right before it regarding the card layout stuff, this probably isn't an issue (yet).
    Sorry if this is verbose; just wanted to be thorough. Thanks for any and all help...

    Well... I took out as much code as I could. Here's my simplified program:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    @SuppressWarnings("serial")
    public class emerensi_BMI extends JFrame implements ActionListener{
         JLabel lblHeading1;
         JLabel lblHeading2;
         JButton btnCalculate;
         JButton btnReCalculate;
         JPanel Page1;
         JPanel Page2;
         String one;
         String two;
         JPanel cardPanel;
    public static void main(String args[]){
              new emerensi_BMI();
         public emerensi_BMI(){
              super("Body Mass Index Calculator");
              setupGUI();
              registerListeners();
         } // end constructor
         public void setupGUI(){
              Container contentPane = getContentPane();
              JPanel pnlHeading1 = new JPanel();
              lblHeading1 = new JLabel("Page 1");
              pnlHeading1.setLayout(new FlowLayout());
              pnlHeading1.add(lblHeading1);
              // north panel for page1
              JPanel pnlCalculate = new JPanel();
              btnCalculate = new JButton("Calculate");
              pnlCalculate.setLayout(new FlowLayout());
              pnlCalculate.add(btnCalculate);
              // south panel for page1
              JPanel Page1 = new JPanel();
              Page1.setLayout(new BorderLayout());
              Page1.add(pnlHeading1, BorderLayout.NORTH);
              Page1.add(pnlCalculate, BorderLayout.SOUTH);
              // page1 panel
              JPanel pnlHeading2 = new JPanel();
              lblHeading2 = new JLabel("Page 2");
              pnlHeading2.setLayout(new FlowLayout());
              pnlHeading2.add(lblHeading2);
              // north panel for page2
              JPanel pnlReCalculate = new JPanel();
              btnReCalculate = new JButton("<-- Recalculate with different data");
              pnlReCalculate.setLayout(new FlowLayout());
              pnlReCalculate.add(btnReCalculate);
              // south panel for page2
              JPanel Page2 = new JPanel();
              Page2.setLayout(new BorderLayout());
              Page2.add(pnlHeading2, BorderLayout.NORTH);
              Page2.add(pnlReCalculate, BorderLayout.SOUTH);
              // page2 panel
              String one = new String();
              String two = new String();
              JPanel cardPanel = new JPanel();
              cardPanel.setLayout(new CardLayout());
              cardPanel.add(Page1, one);
              cardPanel.add(Page2, two);
              contentPane.add(cardPanel, BorderLayout.CENTER);
              // card panel with page1 and page2
              this.setSize(500, 350);
              this.setVisible(true);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         public void itemStateChanged(ItemEvent evt) {
                 CardLayout cl = (CardLayout)(cardPanel.getLayout());
                 cl.show(cardPanel, (String)evt.getItem());
         public void registerListeners() {
              btnCalculate.addActionListener(this);
              btnReCalculate.addActionListener(this);
              // registered actions
         public void actionPerformed(ActionEvent e){
              if (e.getSource() == btnReCalculate){
                   ((CardLayout)cardPanel.getLayout()).show(Page1, one);
              } else if (e.getSource() == btnCalculate){
                   ((CardLayout)cardPanel.getLayout()).show(Page2, two);
              } // end else if else if
              // handling action events
         public void textValueChanged(TextEvent e) {
              // TODO Auto-generated method stub
    }// end main

  • Throwing exceptions in an actionPerformed method

    it tells me I can't do it
    is there a way to get around this?
    I'm reading a file inside the method so thats the exception in case it matters

    It's not in swing.. i'm making it on eclipse
    public void actionPerformed(ActionEvent e) {
    read();
    //do some stuff
    private void read() throws Exception{
    BufferedReader reader = new BufferedReader(new FileReader(file));
    //read some stuff
    thats the lines that are causing me trouble, the only thing i've learned to do is throw exceptions in read() though I know there are better ways such as try{ and catching specific exception I don't know how to use them.
    when I try to make actionPerformed throw Exceptions like I did to read() it says:
    Exception Exception is not compatible with throws clause in ActionListener.actionPerformed(Action Event)
    So... I don't know what to do and this is the final step in a program i've been making for a while now.

  • Exception in thread

    Hello,
    The problem is inside the method "chamaConversor".
    " conversor.pdfToText(arquivoPdf,arquivoTxt);" make a file.txt from one file.pdf. After that it don?t return the control to "ConstrutorDeTemplate2.java", and show the following error message:
    Exception in thread "AWT-EventQueue-O" java.lang.NoClassDefFoundError : org/fontbox/afm/FontMetric
    at org.pdfbox.pdmodel.font.PDFont.getAFM (PDFont.java:334)
    I am using the NetBeans IDE 5.5.
    I have added all of these libraries below to my project from c:\Program Files\netbeans-5.5\PDFBox-0.7.3\external:
    * FontBox-0.1.0-dev.jar
    * ant.jar
    * bcmail-jdk14-132.jar
    * junit.jar
    * bcprov-jdk14-132.jar
    * lucene-core-2.0.0.jar
    * checkstyle-all-4.2.jar
    * lucene-demos-2.0.0.jar
    and PDFBox-0.7.3.jar from c:\Program Files\netbeans-5.5\PDFBox-0.7.3\lib.
    There are no more jar from PDFBox-0.7.3 directory.
    All of these libraries are in "Compile-time Libraries" option in Project Properties. Should I add they to "Run-time Libraries" option?
    What is going on?
    Thank you!
      * ConstrutorDeTemplate2.java
      * Created on 11 de Agosto de 2007, 14:54
      * @author
    package br.unifacs.dis2007.template2;
    // Java core packages
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.text.*;
    import java.util.*;
    // Java extension packages
    import javax.swing.*;
    import org.pdfbox.*;
    public class ConstrutorDeTemplate2 extends JFrame
        implements ActionListener {
        private JTextField enterField;
        private JTextArea outputArea;
        private BufferedWriter out;
        private String word;
        private PdfToText conversor = new PdfToText();
        // ajusta a interface do usu?rio
        public ConstrutorDeTemplate2()
           super( "Testing class File" );
           enterField = new JTextField("Digite aqui o nome do arquivo :" );
           enterField.addActionListener( this );
           outputArea = new JTextArea();
           ScrollPane scrollPane = new ScrollPane();
           scrollPane.add( outputArea );
           Container container = getContentPane();
           container.add( enterField, BorderLayout.NORTH );
           container.add( scrollPane, BorderLayout.CENTER );
           setSize( 400, 400 );
           show();
        // Exibe as informa??es sobre o arquivo especificado pelo usu?rio
        public void actionPerformed( ActionEvent actionEvent )
           File name = new File( actionEvent.getActionCommand() );
           // Se o arquivo existe, envia para a sa?da as informa??es sobre ele
           if ( name.exists() ) {
              outputArea.setText(
                 name.getName() + " exists\n" +
                 ( name.isFile () ?
                    "is a file\n" : "is not a file\n" ) +
                 ( name.isDirectory() ?
                    "is a directory\n" : "is not a directory\n" ) +
                 ( name.isAbsolute() ? "is absolute path\n" :
                    "is not absolute path\n" ) +
                 "Last modified: " + name.lastModified() +
                 "\nLength: " + name.length () +
                 "\nPath: " + name.getPath() +
                 "\nAbsolute path: " + name.getAbsolutePath() +
                 "\nParent: " + name.getParent() );
              // informa??o de sa?da se "name" ? um arquivo
              if ( name.isFile() ) {
                 String nameString = String.valueOf(name.getPath());
                 String nameTeste = new String(nameString);
                 if (nameString.endsWith(".pdf"))
                     nameTeste = chamaConversor(nameString);
                 else
                     if (nameString.endsWith(".doc"))
                         nameTeste = chamaConversorDoc(nameString); // chama conversor de arquivos DOC
                     else
                         if (nameString.endsWith(".txt"))
                             nameTeste = nameString;
                 // se o arquivo termina com ".txt"           
                 if (nameTeste.endsWith(".txt"))
                     // acrescenta conte?do do arquivo ? ?rea de sa?da
                     try {
                         // Create the tokenizer to read from a file
                         FileReader rd = new FileReader(nameTeste);
                         StreamTokenizer st = new StreamTokenizer(rd);
                         // Prepare the tokenizer for Java-style tokenizing rules
                         st.parseNumbers();
                         st.wordChars('_', '_');
                         st.eolIsSignificant (true);
                         // If whitespace is not to be discarded, make this call
                         st.ordinaryChars(0, ' ');
                         // These calls caused comments to be discarded
                         st.slashSlashComments(true);
                         st.slashStarComments(true);
                         // Parse the file
                         int token = st.nextToken();
                         String word_ant = "";
                         outputArea.append( " \n" );
                         out = new BufferedWriter(new FileWriter(nameTeste, true));
                         while (token != StreamTokenizer.TT_EOF) {
                             token = st.nextToken();
                             if (token == StreamTokenizer.TT_EOL){
                                 //out.write(word);
                                 out.flush();
                                 out = new BufferedWriter(new FileWriter(nameTeste, true));
                                 //outputArea.append( word + "\n" );
                                 // out.append ( "\n" );
                             switch (token) {
                             case StreamTokenizer.TT_NUMBER:
                                 // A number was found; the value is in nval
                                 double num = st.nval;
                                 break;
                             case StreamTokenizer.TT_WORD:
                                 // A word was found; the value is in sval
                                 word = st.sval;
                                 //   if (word_ant.equals("a") || word_ant.equals("an") || word_ant.equals("the") || word_ant.equals("The") || word_ant.equals("An"))
                                 outputArea.append( word.toString() + " \n " );
                                // out.append( word + "   " );
                                 //     word_ant = word;
                                 break;
                             case '"':
                                 // A double-quoted string was found; sval contains the contents
                                 String dquoteVal = st.sval;
                                 break;
                             case '\'':
                                 // A single-quoted string was found; sval contains the contents
                                 String squoteVal = st.sval;
                                 break;
                             case StreamTokenizer.TT_EOL:
                                 // End of line character found
                                 break;
                             case StreamTokenizer.TT_EOF:
                                 // End of file has been reached
                                 break;
                             default:
                                 // A regular character was found; the value is the token itself
                                 char ch = (char)st.ttype;
                                 break;
                             } // fim do switch
                         } // fim do while
                         rd.close();
                         out.close();
                     } // fim do try
                     // process file processing problems
                     catch( IOException ioException ) {
                         JOptionPane.showMessageDialog( this,
                         "FILE ERROR",
                         "FILE ERROR", JOptionPane.ERROR_MESSAGE );
                 } // fim do if da linha 92 - testa se o arquivo ? do tipo texto
              } // fim do if da linha 78 - testa se ? um arquivo
              // output directory listing
              else if ( name.isDirectory() ) {
                     String directory[] = name.list();
                 outputArea.append( "\n\nDirectory contents:\n");
                 for ( int i = 0; i < directory.length; i++ )
                    outputArea.append( directory[ i ] + "\n" );
              } // fim do else if da linha 184 - testa se ? um diret?rio
           } // fim do if da linha 62 - testa se o arquivo existe
           // not file or directory, output error message
           else {
              JOptionPane.showMessageDialog( this,
                 actionEvent.getActionCommand() + " Does Not Exist",
                 "ERROR", JOptionPane.ERROR_MESSAGE );
        }  // fim do m?todo actionPerformed
        // m?todo que chama o conversor
        public String chamaConversor(String arquivoPdf){
            String arquivoTxt = new String(arquivoPdf);
            arquivoTxt = arquivoPdf.replace(".pdf", ".txt");
            try {
                conversor.pdfToText(arquivoPdf,arquivoTxt);
            catch (Exception ex) {
                ex.printStackTrace();
            return (arquivoTxt);
        // executa a aplica??o
        public static void main( String args[] )
           ConstrutorDeTemplate2 application = new ConstrutorDeTemplate2();
           application.setDefaultCloseOperation (
              JFrame.EXIT_ON_CLOSE );
        } // fim do m?todo main
    }  // fim da classe ExtratorDeSubstantivos2
      * PdfToText.java
      * Created on 11 de Agosto de 2007, 10:57
      * To change this template, choose Tools | Template Manager
      * and open the template in the editor.
    //package br.unifacs.dis2007.template2;
      * @author www
    package br.unifacs.dis2007.template2;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    import java.net.MalformedURLException;
    import java.net.URL ;
    import org.pdfbox.pdmodel.PDDocument;
    import org.pdfbox.pdmodel.encryption.AccessPermission;
    import org.pdfbox.pdmodel.encryption.StandardDecryptionMaterial;
    import org.pdfbox.util.PDFText2HTML;
    import org.pdfbox.pdmodel.font.PDFont.* ;
    import org.pdfbox.util.PDFTextStripper;
    import org.pdfbox.util.*;
    import org.pdfbox.pdmodel.*;
    public class PdfToText
        public void pdfToText( String pdfFile, String textFile) throws Exception
                Writer output = null;
                PDDocument document = null;
                try
                    try
                        //basically try to load it from a url first and if the URL
                        //is not recognized then try to load it from the file system.
                        URL url = new URL( pdfFile );
                        document = PDDocument.load( url );
                        String fileName = url.getFile();
                        if( textFile == null && fileName.length () >4 )
                            File outputFile =
                                new File( fileName.substring( 0,fileName.length() -4 ) + ".txt" );
                            textFile = outputFile.getName();
                    catch( MalformedURLException e )
                        document = PDDocument.load( pdfFile );
                        if( textFile == null && pdfFile.length() >4 )
                            textFile = pdfFile.substring( 0,pdfFile.length() -4 ) + ".txt";
                       //use default encoding
                      output = new OutputStreamWriter( new FileOutputStream( textFile ) );
                    PDFTextStripper stripper = null;
                    stripper = new PDFTextStripper();
                    stripper.writeText( document, output );
                finally
                    if( output != null )
                        output.close();
                    if( document != null )
                        document.close();
                }//finally
            }//end funcao
     

    You might have to modify you weblogic.policy to grant access rights for
    WLAS.
    Cheers - Wei
    Nyman <[email protected]> wrote in message
    news:[email protected]..
    Hi everyone,
    When running WLS in RedHat 6.2 with the command - ./startWebLogic.sh,an
    error saying "Exception in thread mainjava.security.AccessControlException
    : access denied (java.lang.RuntimePermission createSecurityManager) is
    displayed.
    Could anyone suggestion an solution?
    Best Regardsm

  • Why am I receiving Null pointer Exception Error.

    why am I receiving Null pointer Exception Error.
    Hi I am developing a code for login screen. There is no syntex error as such ut I am receving the aove mentioned error. Can some one please help me ??
    ------------ Main.java------------------
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    public class Main implements ActionListener
    Frame mainf;
    MenuBar mb;
    MenuItem List,admitform,inquiry,exit,helpn;
    Menu newm,update,help;
    Inquiry iq;
    Admit ad;
    // HosHelp hp;
    Howuse hu;
    Register reg;
    Main()
    mainf=new Frame(" Engg College V/S Mumbai University ");
         mb=new MenuBar();
         newm=new Menu(" New ");
         update=new Menu(" Update ");
         help=new Menu(" Help ");
         List=new MenuItem("List");
         admitform=new MenuItem("Admit");
         inquiry=new MenuItem("Inquiry");
         exit=new MenuItem("Exit");
         helpn=new MenuItem("How to Use?");
    newm.add(List);
                   newm.add(admitform);
    newm.add(inquiry);
                   newm.add(exit);
         help.add(helpn);
              mb.add(newm);
              mb.add(update);
              mb.add(help);
    mainf.setMenuBar(mb);
                   exit.addActionListener(this);
                   List.addActionListener(this);
         inquiry.addActionListener(this);
         admitform.addActionListener(this);
    helpn.addActionListener(this);
         mainf.setSize(400,300);
         mainf.setVisible(true);
    public void actionPerformed(ActionEvent ae)
    if (ae.getSource()==List)
              reg=new Register();
         if(ae.getSource()==inquiry)
         iq=new Inquiry();
    if(ae.getSource()==admitform)
         ad=new Admit();
              if(ae.getSource()==helpn)
              hu=new Howuse();
              if(ae.getSource()==exit)
         mainf.setVisible(false);
    public static void main(String args[])
              new Main();
    -------------Register.java---------------------------
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    public class Register implements ActionListener//,ItemListener
    Label id,name,login,pass,repass;
    Button ok,newu,cancel,check;
    Button vok,iok,lok,mok,sok; //buttons for dialog boxes
    TextField idf,namef,loginf,passf,repassf;
    Dialog valid,invlog,less,mismat,acucreat;
    Frame regis;
    Checkbox admin,limit;
    CheckboxGroup type;
    DBconnect db;
    Register()
         db=new DBconnect();
    regis=new Frame("Registeration Form");
              type=new CheckboxGroup();
              admin=new Checkbox("Administrator",type,true);
              limit=new Checkbox("Limited",type,false);
              id=new Label("ID :");
    name=new Label("Name :");
         login=new Label("Login :");
         pass=new Label("Password :");
         repass=new Label("Retype :");
    idf =new TextField(20); idf.setEnabled(false);
         namef=new TextField(30); namef.setEnabled(false);
    loginf=new TextField(30); loginf.setEnabled(false);
         passf=new TextField(30); passf.setEnabled(false);
         repassf=new TextField(30); repassf.setEnabled(false);
    ok=new Button("OK"); ok.setEnabled(false);
         newu=new Button("NEW");
    cancel=new Button("Cancel");
         check=new Button("Check Login"); check.setEnabled(false);
    vok=new Button("OK");
         iok=new Button("OK");
              lok=new Button("OK");
              mok=new Button("OK");
              sok=new Button("OK");
    valid=new Dialog(regis,"Login name is valid !");
         invlog=new Dialog(regis,"Login name already exist!");
         less=new Dialog(regis,"Password is less than six characters !");
    mismat=new Dialog(regis,"password & retyped are not matching !");
    acucreat=new Dialog(regis,"You have registered successfully !");
         regis.setLayout(null);
    //     regis.setBackground(Color.orange);
    valid.setLayout(new FlowLayout());
         invlog.setLayout(new FlowLayout());
         less.setLayout(new FlowLayout());
         mismat.setLayout(new FlowLayout());
    acucreat.setLayout(new FlowLayout());
    id.setBounds(35,50,80,25); //(left,top,width,hight)
    idf.setBounds(125,50,40,25);
    name.setBounds(35,85,70,25);
    namef.setBounds(125,85,150,25);
    login.setBounds(35,120,80,25);
    loginf.setBounds(125,120,80,25);
    check.setBounds(215,120,85,25);
         pass.setBounds(35,155,80,25);
    passf.setBounds(125,155,80,25);
    repass.setBounds(35,190,80,25);
    repassf.setBounds(125,190,80,25);
    admin.setBounds(35,225,100,25);
    limit.setBounds(145,225,100,25);
              ok.setBounds(45,265,70,25);
         newu.setBounds(135,265,70,25);
    cancel.setBounds(225,265,70,25);
         passf.setEchoChar('*');
    repassf.setEchoChar('*');
         regis.add(id);
         regis.add(idf);
    regis.add(name);
         regis.add(namef);
         regis.add(login);
         regis.add(loginf);
         regis.add(check);
    regis.add(pass);
         regis.add(passf);
    regis.add(repass);
         regis.add(repassf);
         regis.add(ok);
         regis.add(newu);
         regis.add(cancel);
    regis.add(admin);
         regis.add(limit);
    valid.add(vok);
         invlog.add(iok);     
         less.add(lok);
         mismat.add(mok);
    acucreat.add(sok);
    ok.addActionListener(this);
         newu.addActionListener(this);
    check.addActionListener(this);
    cancel.addActionListener(this);
         // limit.addItemListener(this);
         //admin.addItemListener(this);
              vok.addActionListener(this);
              iok.addActionListener(this);
         lok.addActionListener(this);
         mok.addActionListener(this);
         sok.addActionListener(this);
    regis.setLocation(250,150);
    regis.setSize(310,300);
    regis.setVisible(true);
         public void actionPerformed(ActionEvent ae)
         if(ae.getSource()==check)
              try{
                   String s2=loginf.getText();
    ResultSet rs=db.s.executeQuery("select* from List");
                        while(rs.next())
                   if(s2.equals(rs.getString(2).trim()))
    //                    invlog.setBackground(Color.orange);
                             invlog.setLocation(250,150);
                             invlog.setSize(300,100);
                   cancel.setEnabled(false);
    ok.setEnabled(false);
    check.setEnabled(false);
                        invlog.setVisible(true);
                             break;
                        else
                        //     valid.setBackground(Color.orange);
                             valid.setLocation(250,150);
                             valid.setSize(300,100);
                   cancel.setEnabled(false);
    ok.setEnabled(false);
    check.setEnabled(false);
                   valid.setVisible(true);
                        }catch(Exception e)
                   e.printStackTrace();
    if(ae.getSource()==newu)
         try{
              ResultSet rs=db.s.executeQuery("select max(ID) from List");
         while(rs.next())
    String s1=rs.getString(1).trim();
                   int i=Integer.parseInt(s1);
    i++;
                   String s2=""+i;
    idf.setText(s2);
                   newu.setEnabled(false);
                   namef.setText(""); namef.setEnabled(true);
              loginf.setText(""); loginf.setEnabled(true);
              passf.setText(""); passf.setEnabled(true);
              repassf.setText(""); repassf.setEnabled(true);
              ok.setEnabled(true);
                   check.setEnabled(true);
                   }catch(Exception e)
              e.printStackTrace();
         if(ae.getSource()==ok)
              try
              String s1=idf.getText();
              String s2=loginf.getText();
              String s3=passf.getText();
         String s4=repassf.getText();
         int x=Integer.parseInt(s1);
         int t;
         if(type.getSelectedCheckbox()==admin)
              t=1;
              else
              t=0;
    ResultSet rs=db.s1.executeQuery("select* from List");
                   while(rs.next())
                   if(s2.equals(rs.getString(2).trim()))
                        invlog.setBackground(Color.orange);
                        invlog.setLocation(250,150);
                        invlog.setSize(300,100);
                   cancel.setEnabled(false);
    ok.setEnabled(false);
    check.setEnabled(false);
                        invlog.setVisible(true);
                        break;
                   else
                        if (s3.length()<6)
                        less.setBackground(Color.orange);
                             less.setLocation(250,150);
                             less.setSize(300,100);
                   ok.setEnabled(false);
                        cancel.setEnabled(false);
                        check.setEnabled(false);
                        less.setVisible(true);
    else if(!(s3.equals(s4)))
                        mismat.setBackground(Color.orange);
                        mismat.setLocation(250,150);
                        mismat.setSize(300,100);
                        ok.setEnabled(false);
                        cancel.setEnabled(false);
                        check.setEnabled(false);
                        mismat.setVisible(true);
                        else
    db.s1.execute("insert into User values("+x+",'"+s2+"','"+s3+"',"+t+")");
                        acucreat.setBackground(Color.orange);
                        acucreat.setLocation(250,150);
                        acucreat.setSize(300,100);
                        regis.setVisible(false);
                        acucreat.setVisible(true);
                   }//else
              }//while
                   } //try
              catch(Exception e1)
              // e1.printStackTrace();
              if (ae.getSource()==cancel)
              regis.setVisible(false);
              if (ae.getSource()==vok)
              ok.setEnabled(true);
                   cancel.setEnabled(true);
    check.setEnabled(true);
                   valid.setVisible(false);
              if (ae.getSource()==iok)
              ok.setEnabled(true);
                   cancel.setEnabled(true);
    check.setEnabled(true);
                   invlog.setVisible(false);
              if (ae.getSource()==lok)
              less.setVisible(false);
                   cancel.setEnabled(true);
    ok.setEnabled(true);
    check.setEnabled(true);
              if (ae.getSource()==mok)
              mismat.setVisible(false);
                   cancel.setEnabled(true);
    ok.setEnabled(true);
    check.setEnabled(true);
    if (ae.getSource()==sok)
              acucreat.setVisible(false);
              ok.setEnabled(false);
                   newu.setEnabled(true);
                   regis.setVisible(true);
         public static void main(String args[])
         new Register();
    -----------DBConnect.java------------------------------------
    import java.sql.*;
    public class DBconnect
    Statement s,s1;
    Connection c;
    public DBconnect()
    try
         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
              c=DriverManager.getConnection("jdbc:odbc:Sonal");
              s=c.createStatement();
    s1=c.createStatement();
         catch(Exception e)
         e.printStackTrace();
    ----------Login.java----------------
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    public class Login implements ActionListener
    Frame log;
    Label login,pass;
    TextField loginf,passf;
    Button ok,cancel;
    Dialog invalid;
    Button iok;
    Register reg;
    DBconnect db;
    Main m;
    Login()
    db=new DBconnect();
         log=new Frame();
         log.setLocation(250,210);
         login=new Label("Login :");
    pass=new Label("Password :");
         loginf=new TextField(20);
         passf=new TextField(20);
         passf.setEchoChar('*');
         ok=new Button("OK");
         // newu=new Button("New User");
         cancel=new Button("CANCEL");
         iok=new Button(" OK ");
    invalid=new Dialog(log,"Invalid User!");
    //log.setBackground(Color.cyan);
    //log.setForeground(Color.black);
         log.setLayout(null);
         // iok.setBackground(Color.gray);
         invalid.setLayout(new FlowLayout());
         login.setBounds(35,50,70,25); //(left,top,width,hight)
         loginf.setBounds(105,50,100,25);
         pass.setBounds(35,85,70,25);
         passf.setBounds(105,85,70,25);
         ok.setBounds(55,130,70,25);
    // newu.setBounds(85,120,80,25);
    cancel.setBounds(145,130,70,25);
    log.add(login);
    log.add(loginf);
    log.add(pass);
    log.add(passf);
    log.add(ok);
    // log.add(newu);
    log.add(cancel);
         invalid.add(iok);//,BorderLayout.CENTER);
    ok.addActionListener(this);
    // newu.addActionListener(this);
    cancel.addActionListener(this);
         iok.addActionListener(this);
    log.setSize(300,170);
    log.setVisible(true);
    public void actionPerformed(ActionEvent a)
    if(a.getSource()==ok)
         try{
              String l=loginf.getText();
              String p=passf.getText();
              ResultSet rs=db.s.executeQuery("select * from List");
              while(rs.next())
              if(l.equals(rs.getString(2).trim())&& p.equals(rs.getString(3).trim()))
                        String tp=rs.getString(4).trim();
                             int tp1=Integer.parseInt(tp);
    log.setVisible(false);
    if(tp1==1)
                             m=new Main();
                        // m.List.setEnabled(true);
                             else
                             m=new Main();
                             m.List.setEnabled(false);
                        break;
    else
                   invalid.setBackground(Color.orange);
                   invalid.setSize(300,100);
                   invalid.setLocation(250,210);
                   cancel.setEnabled(false);
              ok.setEnabled(false);
                   invalid.setVisible(true);
                   }catch(Exception e1)
                   e1.printStackTrace();
         if (a.getSource()==cancel)
         log.setVisible(false);
         if (a.getSource()==iok)
         invalid.setVisible(false);
         loginf.setText("");
         passf.setText("");
         cancel.setEnabled(true);
    ok.setEnabled(true);
         public static void main(String[] args)
         new Login();
    -------------inquiry.java---------------------------------
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.util.Date;
    import java.text.*;
    import java.sql.*;
    public class Inquiry implements ActionListener
    Frame inqry;
    Label name,addr;
    TextField namef,addrf;
    Button ok,cancel,dok;
    Dialog invalid;
    Frame result; //Result of the inquiry....
    Label lrname,lraddr,lward,lrdate,lcdate;
    TextField rname,raddr,ward,rdate,cdate;
    Date d;
    DateFormat df;
    Button rok,rcancel;
    Dialog success;
    Button rdok;
    DBconnect db;
    Inquiry()
              db=new DBconnect();
              inqry=new Frame("Inquiry Form");
              inqry.setLayout(null);
    inqry.setBackground(Color.cyan);
              name=new Label(" NAME ");
              addr=new Label("ADDRESS");
              namef=new TextField(20);
              addrf=new TextField(20);
              ok=new Button("OK");
              cancel=new Button("CANCEL");
              dok=new Button("OK");
              invalid=new Dialog(inqry,"Invalid Name or Address !");
              invalid.setSize(300,100);
         invalid.setLocation(300,180);
              invalid.setBackground(Color.orange);
              invalid.setLayout(new FlowLayout());
    result=new Frame(" INQUIRY RESULT "); //Result Window......
    result.setLayout(null);
    result.setBackground(Color.cyan);
    lcdate=new Label(" DATE ");
         lrname=new Label(" NAME ");
    lraddr=new Label(" ADDRESS ");
         lward=new Label(" WARD ");
         lrdate=new Label(" ADMIT-DATE ");
    cdate=new TextField(10);
         rname=new TextField(20);
    rname.setEnabled(false);
         raddr=new TextField(20);
         raddr.setEnabled(false);
         ward=new TextField(20);
         ward.setEnabled(false);
         rdate=new TextField(10);
         rdate.setEnabled(false);
         cdate=new TextField(20);
         d=new Date();
         df=DateFormat.getDateInstance(DateFormat.MEDIUM,Locale.KOREA);
         cdate.setText(df.format(d));
         cdate.setEnabled(false);
    rok=new Button(" OK ");
         rcancel=new Button("CANCEL");
              name.setBounds(40,50,50,25);
    namef.setBounds(120,50,130,25);
    addr.setBounds(40,100,60,25);
    addrf.setBounds(120,100,80,25);
    ok.setBounds(60,145,70,25);
              cancel.setBounds(140,145,70,25);
              lcdate.setBounds(200,50,60,25); //Result Window......
    cdate.setBounds(270,50,80,25);      
    lrname.setBounds(35,85,70,25);
    rname.setBounds(140,85,180,25);
    lraddr.setBounds(35,120,80,25);
         raddr.setBounds(140,120,100,25);
    lward.setBounds(35,155,80,25);
    ward.setBounds(140,155,100,25);
    lrdate.setBounds(30,190,80,25);
    rdate.setBounds(140,190,80,25);
    rok.setBounds(70,240,70,25);
    rcancel.setBounds(170,240,70,25);
              inqry.add(name);
              inqry.add(namef);
              inqry.add(addr);
              inqry.add(addrf);
              inqry.add(ok);
              inqry.add(cancel);
    invalid.add(dok);
         result.add(lcdate); //Result Window......
         result.add(cdate);
              result.add(lrname);
              result.add(rname);
              result.add(lraddr);
              result.add(raddr);
              result.add(lward);
              result.add(ward);
              result.add(lrdate);
              result.add(rdate);
              result.add(rok);
              result.add(rcancel);
         ok.addActionListener(this);
         cancel.addActionListener(this);
         dok.addActionListener(this);
    rok.addActionListener(this); //Result Window......
         rcancel.addActionListener(this);
         inqry.setSize(280,180);
         inqry.setLocation(300,180);
         inqry.setVisible(true);
              result.setSize(400,280); //Result Window......
         result.setLocation(200,150);
         result.setVisible(false);
              public void actionPerformed(ActionEvent ae)
                   if(ae.getSource()==ok)
                   try
                             String nm=namef.getText();
                             String ad=addrf.getText();
                             inqry.setVisible(false);
                             ResultSet rs=db.s.executeQuery("select * from Billinformation");
                             while(rs.next())
                                  String nm1=rs.getString(2).trim();
                                  String ad1=rs.getString(3).trim();
                                  int k=0;
                                  if((nm1.equals(nm))&&(ad1.equals(ad)))
                             String adm=rs.getString(5).trim();
                             String wr=rs.getString(6).trim();
                             String bd=rs.getString(8).trim();
                                  String wrb=wr+"-"+bd;
    result.setVisible(true);
                                  rname.setText(nm1);
                             raddr.setText(ad1);
                             ward.setText(wrb);
                             rdate.setText(adm);
    k=1;
                                  break;
                                  }//if
                             else if(k==1)
                             invalid.setVisible(true);
                             }//while
    }//try
                             catch(Exception e)
                             e.printStackTrace();
                        } //getsource ==ok
                   if(ae.getSource()==cancel)
    inqry.setVisible(false);
                        if(ae.getSource()==rok) //Result Window......
                        namef.setText("");
                             addrf.setText("");
                             result.setVisible(false);
                        inqry.setVisible(true);
    if(ae.getSource()==rcancel)
    result.setVisible(false);
                        if(ae.getSource()==dok)
                        namef.setText("");
                             addrf.setText("");
                             invalid.setVisible(false);
                             inqry.setVisible(true);
         public static void main(String args[])
              new Inquiry();
    PLease Help me !!
    I need this urgently.

    can you explain what your program tries to do... and
    at where it went wrong..Sir,
    We are trying to make an project where we can make a person register in our data base & after which he/she can search for other user.
    The logged in user can modify his/her own data but can view other ppl's data.
    We are in a phase of registering the user & that's where we are stuck. The problem is that after the login screen when we hit register (OK- button) the data are not getting entered in the data base.
    Can u please help me??
    I am using "jdk1.3' - studnet's edition.
    I am waiting for your reply.
    Thanks in advance & yr interest.

  • Null Pointer exception returned when object is not null!

    I've isolated the problem and cut down the code to the minimum. Why do I get a null pointer exception when the start method is called, when the object objJTextField is not null at this point???? I'm really stuck here, HELP!
    (two small java files, save as BasePage.java and ExtendedPage.java and then run ExtendedPage)
    first file
    ~~~~~~~
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public abstract class BasePage extends JFrame implements ActionListener
    private JPanel objJPanel = null;
    public BasePage()
    setSize(300,200);
    Container objContentPane = getContentPane();
    objJPanel = new JPanel();
    createObjects();
    createPage();
    // Add panels to content pane
    objContentPane.add(objJPanel);
    public void addComponentToPage(JComponent objJComponent)
    objJPanel.add(objJComponent);
    public void addButtonToPage(JButton objJButton)
    objJButton.addActionListener(this);
    objJPanel.add(objJButton);
    public void actionPerformed(ActionEvent objActionEvent)
    System.out.println("Action performed");
    userDefinedButtonClicked(objActionEvent.getActionCommand());
    // overide
    public abstract void createObjects();
    public abstract void createPage();
    public abstract void userDefinedButtonClicked(String sActionCommand);
    file 2
    ~~~~
    import javax.swing.*;
    public class ExtendedPage extends BasePage
    private JTextField objJTextField = null;
    private JButton objJButtonBrowse = null;
    public ExtendedPage()
    super();
    public void createObjects()
    objJTextField = new JTextField(20);
    objJButtonBrowse = new JButton("Start");
    objJButtonBrowse.setActionCommand("START");
    public void createPage()
    addComponentToPage(objJTextField);
    addButtonToPage(objJButtonBrowse);
    public void userDefinedButtonClicked(String sActionCommand)
    if ((sActionCommand != null) && (sActionCommand.equals("START")) )
    start();
    private void start()
    objJTextField.setText("Doesn't work");
    public static void main(String[] args)
    ExtendedPage objEP = new ExtendedPage();
    objEP.show();

    Hello ppaulf,
    Your problem is in your ExtendedPage.java file. You can fix this by changing the line
    private JTextField objJTextField = null;to:
    private JTextField objJTextField = new JTextField();This creates a proper instance.
    Good luck,
    Ming
    Developer Technical Support
    http://www.sun.com/developers/support

  • Exception Error   =/

    Hello, java newb here.
    I have been working on one of my assignments for school. Where as we haven't gotten into GUI yet ... the many required output options of the assignment make it seem almost crazy not to have an interface to navigate with. I have probably bitten off a lot more than I can chew by trying to use tools I'm not ready for yet. I'm trying to learn to create an interface at this time on my own, and when I can get that to work I will begin trying to integrate the actual inputs and outputs of the assignment.
    Anyways, I am getting the following error:
    Exception in thread "main" java.lang.NoClassDefFoundError: IntroTest3/java
    What I don't understand is the code compiles without errors. Its when I try to run the program that the message is displayed. Can anybody advise me as to perhaps what could be happening between compile time and run time? I don't expect anybody to give me any answers or fix my lousy code. Just trying to learn what to look for when it comes to identifying errors.I will paste the code below. By the way, yes I did insert/modify a lot of pieces from some of the tutorial codes or my textbook codes because I don't know enough to fill in the gaps on my own.
    import javax.swing.JInternalFrame;
    import javax.swing.JDesktopPane;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JMenuBar;
    import javax.swing.JFrame;
    import javax.swing.KeyStroke;
    import java.awt.event.*;
    import java.awt.*;
    public class IntroTest3 extends JFrame implements ActionListener
    {//BEGIN INTROTEST3 CLASS
    private JDesktopPane desktop;               // Declare a new desktop frame (Instance variable)
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    public IntroTest3()               // Constructor for IntroTest3 class
         {//BEGIN INTROTEST3 CONSTRUCTOR
         super( "Grade Calculator v1.3" );     // Title bar text
         int inset = 50; // This indents the window?
         Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
         setBounds(inset, inset,
    screenSize.width - inset*2,
    screenSize.height - inset*2);
         desktop = new JDesktopPane();          // Make a new desktop frame
         getContentPane().add( desktop );     // Create the content pane for the desktop frame
         setJMenuBar(createMenuBar());          // Menu bar will be made in createMenuBar()
    desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE); // Faster dragging???
         }//END INTROTEST3 CONSTRUCTOR
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    protected JMenuBar createMenuBar()                
         {//BEGIN CREATEMENUBAR
    //- "menuBar" is the menu bar -
         JMenuBar menuBar = new JMenuBar();          // Create new menu BAR
    *     FIRST MENU - " ADD GRADES ". INCLUDES ITEMS: "REGISTER A NEW CLASS",     *
    *     AND "INSERT GRADES".                                   *
    //- "add_menu" is first option on menu bar -
         JMenu add_menu = new JMenu(" Add Grades ");     // Create the first menu on the bar
    add_menu.setMnemonic(KeyEvent.VK_A);          // Set mnemonic to keystroke A?
         menuBar.add( add_menu );               // Add the menu to the menu bar
    //- "reg_class" is first item under menu -
    //- option "add_menu"               -
         JMenuItem reg_class = new JMenuItem(" Register A New Class "); //New option under Add Grades menu
    reg_class.setMnemonic(KeyEvent.VK_R); // Set mnemonic to keystroke R
    reg_class.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_R, ActionEvent.ALT_MASK));     // Uh, whatever that is ;O
    reg_class.setActionCommand("reg"); // Assign command "reg" to initiate
    reg_class.addActionListener(this); // and add it to ActionListener
    add_menu.add(reg_class);
    //- "insert_g" is next item under menu -
    //- option "add_menu"               -
         JMenuItem insert_g = new JMenuItem(" Insert New Grades "); //2nd option under Add Grades menu
    insert_g.setMnemonic(KeyEvent.VK_I); // Set mnemonic to keystroke I
    insert_g.setAccelerator(KeyStroke.getKeyStroke(
    KeyEvent.VK_I, ActionEvent.ALT_MASK));     // ....
    insert_g.setActionCommand("ins"); // Assign command "ins" to initiate
    insert_g.addActionListener(this); // and add it to ActionListener
    add_menu.add(insert_g);
    return (menuBar);
         }//END CREATEMENUBAR
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // React to menu selection          -
    public void actionPerformed(ActionEvent e)
         {//BEGIN ACTIONPERFORMED
    if ("reg".equals(e.getActionCommand()))
              { //new
         createFrame1();
         else if ("ins".equals(e.getActionCommand()))
              { //new
         createFrame2();
         else
         quit();
         }//END ACTIONPERFORMED
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // Create frame for registering a new class          -
    protected void createFrame1()
    {//BEGIN CREATEFRAME1
    RegFrame frame = new RegFrame();          // New frame RegFrame
    frame.setVisible(true);
    desktop.add(frame);                    // Add new frame to desktop
    try
         {                              // What the fuck is THIS shit?
    frame.setSelected(true);
    } catch (java.beans.PropertyVetoException e) {}
    }//END CREATEFRAME1
    // Create frame for inserting new grades          -
    protected void createFrame2()
    {//BEGIN CREATEFRAME2
    InsFrame frame = new InsFrame();          // New frame InsFrame
    frame.setVisible(true);
    desktop.add(frame);                    // Add new frame to desktop
    try
         {                              // What the fuck is THIS shit too?
    frame.setSelected(true);
    } catch (java.beans.PropertyVetoException e) {}
    }//END CREATEFRAME2
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //Quit the application.
    protected void quit()
    System.exit(0);
    *     COPIED CREATE AND SHOW GUI PIECE FOR TESTING
    private static void createAndShowGUI()
         {//BEGIN CREATEANDSHOW
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    IntroTest3 frame = new IntroTest3();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Display the window.
    frame.setVisible(true);     
         }//END CREATEANDSHOW
    public static void main(String[] args)
         {//BEGIN MAIN
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable()
              {//BEGIN SOME SHIT
         public void run()
         createAndShowGUI();
    });//END SOME SHIT
    }//END MAIN
    // TEST TEST TEST
    class InsFrame extends JInternalFrame
    static final int xOffset = 40, yOffset = 40;
    public InsFrame() {       
         super(" Insert New Grades ",
    true, //resizable
    true, //closable
    true, //maximizable
    true);//iconifiable
    //...Create the GUI and put it in the window...
    //...Then set the window size or call pack...
    setSize(300,300); //Set the window's location.
    setLocation(xOffset, yOffset);
    // TEST TEST TEST
    class RegFrame extends JInternalFrame
    static final int xOffset = 30, yOffset = 30;
    public RegFrame() {       
    super(" Register a New Class ",
    true, //resizable
    true, //closable
    true, //maximizable
    true);//iconifiable
    //...Create the GUI and put it in the window...
    //...Then set the window size or call pack...
    setSize(300,300); //Set the window's location.
    setLocation(xOffset, yOffset);
    Something else that I don't really understand is when I had the classes RegFrame and InsFrame to create the frames, located in different files, I had problems. The end of the main file, IntroTest3 kept giving me errors saying " 'class' or 'interface' expected."
    My teacher gave us this command the other day: javac -classpath . <filename>.java
    He said that this tells the file that the public classes it is looking for will be at the same location (in the same directory). I tried this on some sample code in the lab and it worked with what I had, but I guess not here....
    However, when I was messing around trying different things, I pasted RegFrame and InsFrame into the same file at the bottom as it is in the above code. After removing "public", it compiled.
    So I'm not sure why it occured the way it did.
    Anyways if anybody has any advice I would really be grateful, and I promise I'm not one of those obnoxious people who expects somebody on a forum to do their homework for them! Thank you and I'm sorry if I ramble. =(

    Exception in thread "main" java.lang.NoClassDefFoundError: IntroTest3/javaYou're invoking it like this, aren't you:
    java IntroTest3.java
    That's wrong. The argument to java should be a class name, not the name of the source file or even the filename of the class.
    So what's happening is that the JVM thinks that you're telling it to execute the class called "java" in a package called "IntroTest3".
    You should be doing:
    java IntroTest3

  • ActionPerformed method not working when applet is loaded in browser window.

    Hey there guys. I need urgent help from anybody who has experience in deploying websites whose code is in java.
    I am having two problems as mentioned below...
    first, I have made a simple login screen using java swing and JApplet. there is a single button to login. the action performed for this button accesses a private method to check the username and password which are there in atext file. the applet is working perfectly in appletviewer but when i load the applet in a Internet Explorer window using HTML's Applet tag, the button is giving no response at all even when i enter the correct username and password.
    I guess it is either not calling the private function that is checking the username and password from the tes=xt file or it can not access the file. Please help as soon as possible as this is related to my college project.
    I am attaching the code herewith. Suggestions to improve the coding are also welcome.
    the second problem is that while writing my second program for generating a form which registers a user the html is not at all loading the applet into the browser and also if im trying to access a file to write all the details into the console is showing numerous amount of error after i press the button which i can't not understand. the only thing i can understand is that it is related to file access permissions. If anybody could put some light on the working of worker threads and thread safe activities of SwingUtilities.invokeandWait method it would be really appreciable.
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.plaf.*;
    <applet code = "UserLogin" width = 300 height = 150>
    </applet>
    public class UserLogin extends JApplet implements ActionListener, KeyListener {
         private JLabel lTitle;
         private JLabel lUsername, lPassword;
         private JTextField tUsername;
         private JPasswordField tPassword;
         private JButton bLogin;
         private JLabel lLinkRegister, lLinkForgot;
         private JLabel lEmpty = new JLabel(" ", JLabel.CENTER);
         private JPanel panel1, panel2;
         public void init() {
              try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                   SwingUtilities.invokeAndWait(new Runnable() {
                        public void run() {
                             LoginGUI();
              catch(Exception e) {
                   e.printStackTrace();
         public void start() {
              setVisible(true);
         public void stop() {
              setVisible(false);
         private void LoginGUI() {
              super.setSize(300, 150);
              super.setBackground(Color.white);
              lTitle = new JLabel("<HTML><BODY><FONT FACE = \"COURIER NEW\" SIZE = 6 COLOR = BLUE>Login</FONT></BODY></HTML>", JLabel.CENTER);
              lUsername = new JLabel("Username : ", JLabel.CENTER);
              lPassword = new JLabel("Password : ", JLabel.CENTER);
              tUsername = new JTextField(15);
              tPassword = new JPasswordField(15);
              bLogin = new JButton("LOGIN");
    //          bLogin.setEnabled(false);
              bLogin.addActionListener(this);
              bLogin.addKeyListener(this);
              panel2 = new JPanel();
              GridBagLayout gbag = new GridBagLayout();
              GridBagConstraints gbc = new GridBagConstraints();
              panel2.setLayout(gbag);
              panel2.addKeyListener(this);
              gbc.anchor = GridBagConstraints.CENTER;
              panel2.setMinimumSize(new Dimension(300, 200));
              panel2.setMaximumSize(panel2.getMinimumSize());
              panel2.setPreferredSize(panel2.getMinimumSize());
              gbc.gridx = 1;
              gbc.gridy = 1;
              gbag.setConstraints(lUsername,gbc);
              panel2.add(lUsername);
              gbc.gridx = 2;
              gbc.gridy = 1;
              gbag.setConstraints(tUsername,gbc);
              panel2.add(tUsername);
              gbc.gridx = 1;
              gbc.gridy = 2;
              gbag.setConstraints(lPassword,gbc);
              panel2.add(lPassword);
              gbc.gridx = 2;
              gbc.gridy = 2;
              gbag.setConstraints(tPassword,gbc);
              panel2.add(tPassword);
              gbc.gridx = 2;
              gbc.gridy = 3;
              gbag.setConstraints(lEmpty,gbc);
              panel2.add(lEmpty);
              gbc.gridx = 2;
              gbc.gridy = 4;
              gbag.setConstraints(bLogin,gbc);
              panel2.add(bLogin);
              panel1 = new JPanel(new BorderLayout());
              panel1.add(lTitle, BorderLayout.NORTH);
              panel1.add(panel2, BorderLayout.CENTER);
              add(panel1);
              setVisible(true);
         public void keyReleased(KeyEvent ke) {}
         public void keyTyped(KeyEvent ke) {}
         public void keyPressed(KeyEvent ke) {
              if(ke.getKeyCode() == KeyEvent.VK_ENTER){
                   String username = tUsername.getText();
                   String password = new String(tPassword.getPassword());
                   if(username.length() == 0 || password.length() == 0) {
                        JOptionPane.showMessageDialog(new JFrame(),"You must enter a username and password to login", "Error", JOptionPane.ERROR_MESSAGE);
                   else {
                        boolean flag = checkUsernamePassword(username, password);
                        if(flag)
                             JOptionPane.showMessageDialog(new JFrame(),"Username and Password Accepted", "Access Granted", JOptionPane.INFORMATION_MESSAGE);
                        else
                             JOptionPane.showMessageDialog(new JFrame(),"Username or password Incorrect", "Access Denied", JOptionPane.INFORMATION_MESSAGE);
         public void actionPerformed(ActionEvent ae) {
              String gotCommand = ae.getActionCommand();
              if(gotCommand.equals("LOGIN")) {
                   String username = tUsername.getText();
                   String password = new String(tPassword.getPassword());
                   if(username.length() == 0 || password.length() == 0) {
                        JOptionPane.showMessageDialog(new JFrame(),"You must enter a username and password to login", "Error", JOptionPane.ERROR_MESSAGE);
                   else {
                        boolean flag = checkUsernamePassword(username, password);
                        if(flag)
                             JOptionPane.showMessageDialog(new JFrame(),"Username and Password Accepted", "Access Granted", JOptionPane.INFORMATION_MESSAGE);
                        else
                             JOptionPane.showMessageDialog(new JFrame(),"Username or password Incorrect", "Access Denied", JOptionPane.INFORMATION_MESSAGE);
         private boolean checkUsernamePassword(String username, String password) {
              String user = null, pswd = null;
              try {
                   FileInputStream fin = new FileInputStream("@data\\userpass.txt");
                   DataInputStream din = new DataInputStream(fin);
                   BufferedReader brin = new BufferedReader(new InputStreamReader(din));
                   user = (String) brin.readLine();
                   pswd = (String) brin.readLine();
              catch(IOException ioe) {
                   ioe.printStackTrace();
              if(username.equals(user) && password.equals(pswd))
                   return true;
              else
                   return false;
    }PLEASE HELP ME GUYS......

    RockAsh wrote:
    Hey Andrew, first of all sorry for that shout, it was un-intentional as i am new to posting topics on forums and didn't new that this kind of writing is meant as shouting. Cool.
    Secondly thank you for taking interest in my concern.No worries.
    Thirdly, as i mentioned before, I am reading i file for checking of username and password. the file is named as "userpass.txt" and is saved in the directory named "@data" which is kept in the same directory in which my class file resides.OK - server-side. That makes some sense, and makes things easier. The problem with your current code is that the applet will be looking for that directory on the end user's local file system. Of course the file does not exist there, so the applet will fail unless the the end user is using the same machine as the server is coming from.
    To get access to a resource on the server - the place the applet lives - requires an URL. In applets, URLs are relatively easy to form. It might be something along the lines of
    URL urlToPswrd = new URL(getCodeBase(), "@data/userpass.txt");
    InputStream is = urlToPswrd.openStream();
    DataInputStream din = new DataInputStream(is);
    So the problem is that it is reading the file and showing the specific output dialog box when i run it through appletviewer.. Huhh. What version of the SDK are you using? More recent applet viewers should report security exceptions if the File exists.
    ..but the same is not happening when i launch the applet in my browser window using the code as written belowHave you discovered how to open the Java Console in the browser yet? It is important.
    Also the answer to your second question
    Also, the entire approach to storing/restoring the password is potentially wrong. For instance, where is it supposed to be stored, on the server, or on the client?is that, as of now it is just my college project so all the data files and the username and password wiles will be stored on my laptop only i.e. on the client only. no server involved.OK, but understand that an applet ultimately does not make much sense unless deployed through a server. And the entire server/client distinction becomes very important, since that code would be searching for a non-existent file on the computer of the end user.

  • Exception error !Please help me!

    Exception in thread "AWT-EventQueue-0" java.lang.ArithmeticException: / by zero
    at rational.<init>(rational.java:32)
    at rationalnumber$ButtonHandler.actionPerformed(rationalnumber.java:86)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Sour
    ce)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    Source Code: Class rationalnumber
    import java.awt.FlowLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.JFrame;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    public class rationalnumber extends JFrame {
         private JLabel numerator1;
         private JLabel denominator1;
         private JLabel numerator2;
         private JLabel denominator2;
         private JLabel precision;
         private JTextField numerator_value1;
         private JTextField denominator_value1;
         private JTextField numerator_value2;
         private JTextField denominator_value2;
         private JTextField precision_value;
         private JButton add_value;
         private JButton subtract_value;
         private JButton multiply_value;
         private JButton divide_value;
         int number1;
         int number2;
         int number3;
         int number4;
         int number5;
              public rationalnumber() {
         super("Applet Viewer:Rational Number's Calculation");
         setLayout(new FlowLayout());
         numerator1=new JLabel("Enter numerator 1:");
         add(numerator1);
         numerator_value1=new JTextField("Enter Number");
         add(numerator_value1);
         denominator1=new JLabel("Enter denominator 1:");
         add(denominator1);
         denominator_value1=new JTextField("Enter Number");
         add(denominator_value1);
         numerator2=new JLabel("Enter numerator 2:");
         add(numerator2);
         numerator_value2=new JTextField("Enter Number");
         add(numerator_value2);
         denominator2=new JLabel("Enter denominator 2:");
         add(denominator2);
         denominator_value2=new JTextField("Enter Number");
         add(denominator_value2);
         precision=new JLabel("Enter precision:");
         add(precision);
         precision_value=new JTextField("Enter number");
         add(precision_value);
         add_value=new JButton("Add");
         add(add_value);
         subtract_value=new JButton("Subtract");
         add(subtract_value);
         multiply_value=new JButton("Multiply");
         add(multiply_value);
         divide_value=new JButton("Divide");
         add(divide_value);
         ButtonHandler handler=new ButtonHandler();
         numerator_value1.addActionListener(handler);
         denominator_value1.addActionListener(handler);
         numerator_value2.addActionListener(handler);
         denominator_value2.addActionListener(handler);
         add_value.addActionListener(handler);
         subtract_value.addActionListener(handler);
         multiply_value.addActionListener(handler);
         divide_value.addActionListener(handler);
         private class ButtonHandler implements ActionListener {
    public void actionPerformed(ActionEvent event) {
         if(event.getSource()==numerator_value1) {
         number1=Integer.parseInt(event.getActionCommand());
         else if(event.getSource()==denominator_value1) {
         number2=Integer.parseInt(event.getActionCommand());
         else if(event.getSource()==numerator_value2) {
         number3=Integer.parseInt(event.getActionCommand());
         else if(event.getSource()==denominator_value2) {
         number4=Integer.parseInt(event.getActionCommand());
         else if(event.getSource()==add_value) {
    rational calculation=new rational(number1,number2,number3,number4);
    JOptionPane.showMessageDialog(rationalnumber.this,String.format("a+b= %d",calculation.getAddResult()));
    else if(event.getSource()==subtract_value) {
    rational calculation=new rational(number1,number2,number3,number4);
    JOptionPane.showMessageDialog(rationalnumber.this,String.format("a-b= %f",calculation.getSubtractResult()));
    else if(event.getSource()==multiply_value) {
    rational calculation=new rational(number1,number2,number3,number4);
    JOptionPane.showMessageDialog(rationalnumber.this,String.format("a*b= %f",calculation.getMultiplyResult()));
    else if(event.getSource()==divide_value) {
    ational calculation=new rational(number1,number2,number3,number4);
    JOptionPane.showMessageDialog(rationalnumber.this,String.format("a/b= %f",calculation.getDivideResult()));
    Related source code: class rational
    class rational {
    private int numerator;
    private int denominator;
    private int numerator3;
    private int denominator3;
    float rationalnum1;
    float rationalnum2;
    private int number[]={2,3,4,5,6,7,8,9,11,13,17,19,21,23,27,29,31,33,37,39,41,43,47,49,51,53,57,59,61,63,67,69,71,73,77,79,81,83,87,89,91,93,97,99};
    public rational(int numerator1,int denominator1,int numerator2,int denominator2) {
         if(numerator1%denominator1==0) {
              rationalnum1=numerator1/denominator1;
         else if(numerator1%denominator1!=0) {
              for(int i=0;i<number.length;i++) {
                   for(;(numerator1%number==0)&&(denominator1%number[i]==0);) {
                        numerator=numerator1/number[i];
                        denominator=denominator1/number[i];
         rationalnum1=numerator/denominator;
         if(numerator2%denominator2==0) {
              rationalnum2=numerator2/denominator2;
         else if(numerator2%denominator2!=0) {
              for(int i=0;i<number.length;i++) {
                   for(;(numerator2%number[i]==0)&&(denominator2%number[i]==0);) {
                        numerator3=numerator2/number[i];
                        denominator3=denominator2/number[i];
         rationalnum2=numerator3/denominator3;
    public rational() {
         numerator=12;
         denominator=3;
         rationalnum1=numerator/denominator;
         numerator3=34;
         denominator3=5;
         rationalnum2=numerator3/denominator3;
    public float getAddResult() {
         return rationalnum1+rationalnum2;
    public float getSubtractResult() {
         return rationalnum1-rationalnum2;
    public float getMultiplyResult() {
         return rationalnum1*rationalnum2;
    public float getDivideResult() {
         return rationalnum1/rationalnum2;
    Related Source Code: class ButtonTest
    import javax.swing.JFrame;
    public class ButtonTest {
         public static void main(String args[]) {
              rationalnumber buttonframe=new rationalnumber();
              buttonframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              buttonframe.setSize(120,320);
              buttonframe.setVisible(true);

    Please use [co[/b]de] and [co[/b]de] tags when pasting code. There's a code button when you enter your message. Also, It will make it easier for you to get help if you follow Java conventions for naming classes. Class names should start with a captial letter.
    Exception in thread "AWT-EventQueue-0"
    java.lang.ArithmeticException: / by zero at rational.<init>(rational.java:32)This part of the error tells you that the error is divide by zero, that the error occurred in the rational class constructor (that's what <init> means) and that the error occurred on line number 32 of the rational.java file.
    So your task is to find line number 32 and see why there is a divide by zero. I am guessing that line number 32 is rationalnum2=numerator3/denominator3;Here's a hint. In almost any computer language, if you divide an int by an int, the result is an int and the fractional part of the result is thrown away. So dividing 8 by 3 results in the number 2.

  • Invalid Class Exception problem

    Hi whenever i try to run this method from a different class to the one it is declared in it throws invalid class exception, (in its error it says the class this method is written in is the problem) yet when i run it from its own class in a temporary main it works fine, perhaps someone can see the problem in the method code. All its doing is reading from a few different txt files, deserializing the objects and putting them into arraylists for future access.
    public void readCourseData()
              CourseArrayLengths cal;
              try
                   FileInputStream fis = new FileInputStream("arraylengths.txt");
                   ObjectInputStream ois = new ObjectInputStream(fis);
                   cal = ((CourseArrayLengths) ois.readObject());     
                   ois.close();
                   FileInputStream fis1 = new FileInputStream("units.txt");
                   ObjectInputStream ois1 = new ObjectInputStream(fis1);
                   for(int i=0;i<cal.getUnitArrayLength();i++)
                        units.add((Unit) ois1.readObject());
                   ois1.close();
                   FileInputStream fis2 = new FileInputStream("sections.txt");
                   ObjectInputStream ois2 = new ObjectInputStream(fis2);
                   for(int i=0;i<cal.getSectionArrayLength();i++)
                        sections.add((Section) ois2.readObject());
                   ois2.close();
                   FileInputStream fis3 = new FileInputStream("files.txt");
                   ObjectInputStream ois3 = new ObjectInputStream(fis3);
                   for(int i=0;i<cal.getFileArrayLength();i++)
                        files.add((Filetype) ois3.readObject());
                   ois3.close();
              catch(FileNotFoundException exception)
              System.out.println("The File was not found");
              catch(IOException exception)
              System.out.println(exception);
              catch(ClassNotFoundException exception)
              System.out.println(exception);
         }

    import java.util.ArrayList;
    import java.io.*;
    import javax.swing.*;
    public class Unit implements Serializable
    ArrayList units = new ArrayList();
    ArrayList sections = new ArrayList();
    ArrayList files = new ArrayList();
    String unitName;
    int sStart=0,sEnd=0,sIndex=0,fIndex=0,subIndex=0;
         public Unit(String unitNamec,int sStartc,int sEndc)
              unitName = unitNamec;
              sStart = sStartc;
              sEnd = sEndc;
         public Unit()
         public String getUnitName()
              return unitName;
         public Unit getUnit(int i)
              return (Unit)units.get(i);
         public Section getSection(int i)
              return (Section)sections.get(i);
         public ArrayList getUnitArray()
              return units;
         public int getSectionStart()
              return sStart;
         public int getSectionEnd()
              return sEnd;
         public void setSectionStart(int i)
              sStart = i;
         public void setSectionEnd(int i)
              sEnd = i;
         public void addUnit(String uName)
              units.add(new Unit(uName,sections.size(),sIndex));
              sIndex++;
         public void addSection(String sName,Unit u)
              //problem lies with files.size()
              sections.add(new Section(sName,files.size(),files.size()));
              u.setSectionEnd(u.getSectionEnd()+1);
              //fIndex++;
         public void addFile(String fName,File fPath,Section s)
              files.add(new Filetype(fName,fPath));
              s.setFileEnd(s.getFileEnd()+1);
         public void display(Unit u)
              System.out.println(u.getUnitName());
              for(int i=u.getSectionStart();i<u.getSectionEnd();i++)
                   System.out.println(((Section)sections.get(i)).getSectName());
                   for(int j=((Section)(sections.get(i))).getFileStart();j<((Section)(sections.get(i))).getFileEnd();j++)
                        System.out.println(((Filetype)files.get(j)).getFileName());
         public void writeCourseData()
         //writes 3 arrays to 3 different files
    try
    FileOutputStream fos = new FileOutputStream("units.txt");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
         for(int i=0;i<units.size();i++)
         oos.writeObject((Unit)units.get(i));
         oos.close();
    catch (Exception e)
    System.err.println ("Error writing to file");
    try
    FileOutputStream fos = new FileOutputStream("sections.txt");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
         for(int i=0;i<sections.size();i++)
         oos.writeObject((Section)sections.get(i));
         oos.close();
    catch (Exception e)
    System.err.println ("Error writing to file");
    try
    FileOutputStream fos = new FileOutputStream("files.txt");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
         for(int i=0;i<files.size();i++)
         oos.writeObject((Filetype)files.get(i));
         oos.close();
    catch (Exception e)
    System.err.println ("Error writing to file");
    try
    FileOutputStream fos = new FileOutputStream("arraylengths.txt");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
         oos.writeObject(new CourseArrayLengths(units.size(),sections.size(),files.size()));
         oos.close();
    catch (Exception e)
    System.err.println ("Error writing to file");
         public void readCourseData()
              CourseArrayLengths cal;
              try
                   FileInputStream fis = new FileInputStream("arraylengths.txt");
                   ObjectInputStream ois = new ObjectInputStream(fis);
                   cal = ((CourseArrayLengths) ois.readObject());     
                   ois.close();
                   FileInputStream fis1 = new FileInputStream("units.txt");
                   ObjectInputStream ois1 = new ObjectInputStream(fis1);
                   for(int i=0;i<cal.getUnitArrayLength();i++)
                        units.add((Unit) ois1.readObject());
                   ois1.close();
                   FileInputStream fis2 = new FileInputStream("sections.txt");
                   ObjectInputStream ois2 = new ObjectInputStream(fis2);
                   for(int i=0;i<cal.getSectionArrayLength();i++)
                        sections.add((Section) ois2.readObject());
                   ois2.close();
                   FileInputStream fis3 = new FileInputStream("files.txt");
                   ObjectInputStream ois3 = new ObjectInputStream(fis3);
                   for(int i=0;i<cal.getFileArrayLength();i++)
                        files.add((Filetype) ois3.readObject());
                   ois3.close();
              catch(FileNotFoundException exception)
              System.out.println("The File was not found");
              catch(IOException exception)
              System.out.println(exception);
              catch(ClassNotFoundException exception)
              System.out.println(exception);
         /*public static void main(String args[])
              Unit u1 = new Unit();
              u1.addUnit("Cmps2a22");
              u1.addSection("Section1",u1.getUnit(0));
              //u1.addSubSection("Subsect1",u1.getSection(0));
              u1.addFile("File1",null,u1.getSection(0));
              u1.addFile("File2",null,u1.getSection(0));
              u1.addSection("Section2",u1.getUnit(0));
              u1.addFile("NF",null,u1.getSection(1));
              u1.addFile("NF2",null,u1.getSection(1));
              u1.addFile("NF3",null,u1.getSection(1));
              u1.addSection("Section3",u1.getUnit(0));
              u1.addFile("NF",null,u1.getSection(2));
              u1.addFile("NF2",null,u1.getSection(2));
              u1.addFile("NF4",null,u1.getSection(2));
              u1.display(u1.getUnit(0));
              u1.writeCourseData();
              u1.readCourseData();
              u1.display(u1.getUnit(0));
    import java.util.ArrayList;
    import java.io.*;
    public class Section implements Serializable
    private String sectName,subSectName;
    private int fpStart=0,fpEnd=0,subSectStart=0,subSectEnd=0;
    private Section s;
    private boolean sub;
         public Section(String sectNamec,int fpStartc,int fpEndc,int subSectStartc,int subSectEndc,Section sc,boolean subc)
              sectName = sectNamec;
              fpStart = fpStartc;
              fpEnd = fpEndc;
              subSectStart = subSectStartc;
              subSectEnd = subSectEndc;
              s = sc;
              sub = subc;
         public Section(String sectNamec,int fpStartc,int fpEndc)
              sectName = sectNamec;
              fpStart = fpStartc;
              fpEnd = fpEndc;
         public Section getParent()
              return s;
         public boolean isSub()
              return sub;
         public String getSubName()
              return subSectName;
         public int getSubStart()
              return subSectStart;
         public int getSubEnd()
              return subSectEnd;
         public void setSubStart(int i)
              subSectStart = i;
         public void setSubEnd(int i)
              subSectEnd = i;
         public int getFileStart()
              return fpStart;
         public int getFileEnd()
              return fpEnd;
         public String getSectName()
              return sectName;
         public void setFileStart(int i)
              fpStart = i;
         public void setFileEnd(int i)
              fpEnd = i;
         public void addSection(String sectName)
         /*public static void main(String args[])
    import java.io.*;
    public class Filetype implements Serializable
         private String name;
         private File filepath;
         public Filetype(String namec, File filepathc)
              name = namec;
              filepath = filepathc;
         public String getFileName()
              return name;
         public File getFilepath()
              return filepath;
    import java.io.*;
    public class CourseArrayLengths implements Serializable
    private int ul,sl,fl;
         public CourseArrayLengths(int ulc,int slc,int flc)
              ul = ulc;
              sl = slc;
              fl = flc;
         public int getUnitArrayLength()
              return ul;
         public int getSectionArrayLength()
              return sl;
         public int getFileArrayLength()
              return fl;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.ArrayList;
    import java.io.*;
    public class OrganiserGui implements ActionListener
    int width,height;
    JFrame frame;
         public OrganiserGui()
              width = 600;
              height = 500;
         public void runGui()
              //Frame sizes and location
              frame = new JFrame("StudentOrganiser V1.0");
    frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
              frame.setSize(width,height);
              frame.setLocation(60,60);
              JMenuBar menuBar = new JMenuBar();
              //File menu
              JMenu fileMenu = new JMenu("File");
              menuBar.add(fileMenu);
              fileMenu.addSeparator();
              JMenu addSubMenu = new JMenu("Add");
              fileMenu.add(addSubMenu);
              JMenuItem cwk = new JMenuItem("Coursework assignment");
              addSubMenu.add(cwk);
              JMenuItem lecture = new JMenuItem("Lecture");
              lecture.addActionListener(this);
              addSubMenu.add(lecture);
              JMenuItem seminar = new JMenuItem("Seminar sheet");
              addSubMenu.add(seminar);
              //Calendar menu
              JMenu calendarMenu = new JMenu("Calendar");
              menuBar.add(calendarMenu);
              calendarMenu.addSeparator();
              JMenu calendarSubMenu = new JMenu("Edit Calendar");
              calendarMenu.add(calendarSubMenu);
              JMenuItem eventa = new JMenuItem("Add/Remove Event");
              eventa.addActionListener(this);
              calendarSubMenu.add(eventa);
              JMenuItem calClear = new JMenuItem("Clear Calendar");
              calClear.addActionListener(this);
              calendarSubMenu.add(calClear);
              JMenu calendarSubMenuView = new JMenu("View");
              calendarMenu.add(calendarSubMenuView);
              JMenuItem year = new JMenuItem("By Year");
              year.addActionListener(this);
              calendarSubMenuView.add(year);
              JMenuItem month = new JMenuItem("By Month");
              month.addActionListener(this);          
              calendarSubMenuView.add(month);
              JMenuItem week = new JMenuItem("By Week");
              week.addActionListener(this);
              calendarSubMenuView.add(week);
              //Timetable menu
              JMenu timetableMenu = new JMenu("Timetable");
              menuBar.add(timetableMenu);
              timetableMenu.addSeparator();
              JMenu stimetableSubMenu = new JMenu("Social Timetable");
              timetableMenu.add(stimetableSubMenu);
              JMenu ltimetableSubMenu = new JMenu("Lecture Timetable");
              timetableMenu.add(ltimetableSubMenu);
              frame.setJMenuBar(menuBar);
    frame.setVisible(true);
         public void actionPerformed(ActionEvent e)
              JMenuItem source = (JMenuItem)(e.getSource());
              System.out.println(source.getText());     
              Calendar c = new Calendar();
              if(source.getText().equalsIgnoreCase("By Year"))
                   System.out.println("INSIDE");
                   c.buildArray();
                   c.calendarByYear(Calendar.calendarArray);     
              if(source.getText().equalsIgnoreCase("Add/Remove Event"))
                   c.eventInput();
              if(source.getText().equalsIgnoreCase("clear calendar"))
                   c.buildYear();
                   c.writeEvent(Calendar.calendarArray);
                   c.buildArray();
              if(source.getText().equalsIgnoreCase("lecture"))
                   System.out.println("Nearly working");
                   //JFileChooser jf = new JFileChooser();
                   //jf.showOpenDialog(frame);
                   FileManager fm = new FileManager();
                   //choose unit to add file to
                   JOptionPane unitOption = new JOptionPane();
                   Unit u = new Unit();
                   u.readCourseData();
                   //u.display(u.getUnit(0));
                   System.out.println((u.getUnit(0)).getUnitName());
                   String[] unitNames = new String[u.getUnitArray().size()];
                   for(int i=0;i<unitNames.length;i++)
                        //unitNames[i] = (((Unit)u.getUnitArray().get(i)).getUnitName());
                        //System.out.println(unitNames);
                        System.out.println((u.getUnit(i)).getUnitName());
                   //unitOption.showInputDialog("Select Unit to add lecture to",unitNames);
                   //needs to select where to store it
                   //fm.openFile(jf.getSelectedFile());
         public static void main(String args[])
              OrganiserGui gui = new OrganiserGui();
              gui.runGui();
    java.io.invalidclassexception: Unit; local class incompatible: stream classdesc serialversionUID = 3355176005651395533, local class serialversionUID = 307309993874795880

  • Where can I find information about exceptions and errors?

    I'm new to Java and sometimes run into errors that I don't understand. Is there a list of common errors somewhere that I could look at to at least get a general idea of what's causing my problem?
    for instance:
    I'm writing a little program where the user inputs a number and depending on their input a message is displayed. I'm using java.awt.*, java.awt.event.*, & javax.swing.* for my events, buttons, and other goodies. My program compiles & I can execute my main but when I click on the button that grabs the input I get the following errors.
    java.lang.NullPointerException
         at Horoscope$ButtonHandler.actionPerformed(Horoscope.java:44)
         at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1786)
         at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(AbstractButton.java:1839)
         at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
         at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
         at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:245)
         at java.awt.Component.processMouseEvent(Component.java:5100)
         at java.awt.Component.processEvent(Component.java:4897)
         at java.awt.Container.processEvent(Container.java:1569)
         at java.awt.Component.dispatchEventImpl(Component.java:3615)
         at java.awt.Container.dispatchEventImpl(Container.java:1627)
         at java.awt.Component.dispatchEvent(Component.java:3477)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3483)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3198)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3128)
         at java.awt.Container.dispatchEventImpl(Container.java:1613)
         at java.awt.Window.dispatchEventImpl(Window.java:1606)
         at java.awt.Component.dispatchEvent(Component.java:3477)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:456)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)
    I'm not asking for anyone to solve this for me. It's critical that I learn how to troubleshoot and figure out a solution. I was just wondering if there was a site or link on the web that generally discusses what these (and other) errors mean. Or if anybody could tell me what they mean?

    The Java API documentation is the first place to look. Each exception or error is a class. For instance, information on java.lang.NullPointerException is in the API for the java.lang package, toward the bottom.
    For more than that, just search the internet for the name of the exception/error.

  • How to catch ALL Exception in ONE TIME

    I'm explain my issue:
    I'm making a program with Class, Swing, Thread ...
    Then all action I do on my graphical application, I use a new thread, well
    I want to capture in my Startup programs, all unknow exception and then, I display it with a JOptionPane for example
    In fact, I want to do something like Eclipse, when it crash, I capture the error
    Could you help me ? Tell me the best way to do that ?
    This is an exemple
    FILE: Startup.java
    class Startup{
    public static main (String args[]){
    try{
    new Main();
    }catch(Throwable e){
    //Message d'erreur fenetre
    FILE: Main.java
    class Main{
    Main(){
    init_action();
    void init_action(){
    mybutton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
    Thread th=new Thread(){
    public void run(){
    int a = 1 / 0;
    th.start();
    Well, in this example I want to capture the Divide By 0, I use the Throwable Exeption, in order to be sure I catch all unknow exeption
    Then, a good job, is to put throws Throwable in all function
    but Thread, and ActionPerformed ... could not implement it
    How to put this exception and jump it to Startup Program ?

    I already do that, what can I do for improving capture ?
    That's impossible ... It will be a great idea to make a Redirection of Error to a Exception class in futur version
    For example, when an unknow error arrive, don't show it on console and crash ... but run a class redirector exception, and magic, it show you a beautiful error warning, and stop properly the programme ...
    I put an error class, and put try {] catch {} everywhere, and run my exception class,
    this class detect the error exception and run a properly beautiful and clear french message (I'm french :d)
    Well, If you have the BEST other idea, tell me, I read your message with a lot of regard
    see you soon
    bye

Maybe you are looking for

  • Selected set assignment to code group

    I have maintained a catalog " S", under which i have maintained code groups and codes in QS41, but here the usage indicator is deactive. I cannot select it. Now when i use QS51,i am unable to view the codes. the selected set is empty. In this case ho

  • Bluescreen - Caught in an infinite loop

    Hello, I have a strange Problem with my System. Everytime I use a 2D/3D progam it freeze after about 30 minutes. But the strangest thing is, new games like Quake4 , F.E.A.R and Oblivion do not freeze. I tried everything that I know. - Ran Memtest86+

  • Call log disappears Q5

    Hello, I´m having trouble with  my call logs disappearing on my Q5. They are completely gone, also from the hub. No textmsg disappears, only call logs. It seems as if the log stays on the phone for two-three days, and then it´s gone. I have also expe

  • When synching music in I tunes there is an error saying it can't be read

    I have a whole bunch of music on my pc for synching to my Sony Walkman. I tunes converts this before registering in I tunes but then when I try and synch that music to I pad it won't synch and says that the files are not readable. Does anyone know wh

  • Feature Request: More Local Adjustments

    Sometimes it's nessesary to correct hue/saturation locally - change face colour or something like that. And it would be good to have such brush. Together with ability to change Fill Light, Black and Vibrance in a part of image. Why the current select