Output Resultset in JTextArea

Hi,
I have encountered a problem which catch the sql exception... when i try to display my selected data in a jTextArea of another tab pane.
displayResultsQ(res);
when this method is called it goes to exception and couldnt go thru to display my result in make_mining_panel.
but the result set: res works as it print on screen for the result set when call
System.out.println("Mining select:"+ res);
does anyone know how to overcome this problem since I have been trying many times and still couldnt figure out why. the displayResultsQ(Resultset rs) method did work previously when try to put a result set and output in the MakeSearchPanel class.
thks
z
Below are the codes
Class MakeSearchPanel{
else if (s=="Display Data")
//handleQuery();
TableModel model = doSQL(jTextq1.getText());
table.setModel(model);
System.out.println("table Create");
try{
ResultSet res = executeSQLMining(jTextq1.getText());
System.out.println("Mining select:"+ res);
//try{
displayResultsQ(res);
System.out.println("display result");
// catch(Exception e){
// System.out.println("didnt go thru");}
catch(Exception e){System.out.println("didnt go thru");}
void displayResultsQ(ResultSet r) throws SQLException
ResultSetMetaData rmeta = r.getMetaData();
int numColumns=rmeta.getColumnCount();
String text="";
for(int i=1;i<=numColumns;++i)
if(i<numColumns)
text+=rmeta.getColumnName(i)+" | ";
else
text+=rmeta.getColumnName(i);
text+="\n";
while(r.next())
for(int i=1;i<=numColumns;++i)
if(i<numColumns)
text+=r.getString(i)+" | ";
else
text+=r.getString(i).trim();
text+="\n";
//m_OutText.setText(text);
make_mining_panel.m_OutText.setText(text);
//make_mining_panel is a another class extends jpanel that hold jtextarea:m_OutText
System.out.println("output to mining panel");
}

Check out the link shown below:
http://support.microsoft.com/default.aspx?scid=http://support.microsoft.com:80/support/kb/articles/Q232/5/80.ASP&NoWebContent=1
If that doesn't solve your problem, also check out the discussions at the link shown below:
http://forum.java.sun.com/thread.jsp?forum=48&thread=415887
;o)
V.V.

Similar Messages

  • Redirecting cmd output to a JTextArea

    can anyone help me, im curious how can the compilers for java e.g.: Netbeans, JCreator, redirect the command promt output to a JTextArea..
    can anyone guide me on what class to look at??
    thanks a lot

    here is a simple class that redirects the standard output to a file called a.txt. you have to look into the class java.class.System. and other i/o classes
    import java.io.PrintStream;
    public class A {
        public A() {
        public static void main(String[] args) throws Exception {
            PrintStream fileOut = new PrintStream("a.txt");
            System.setOut(fileOut);
            for (int i = 0; i < 10; i++) {
                System.out.println(i);
    }for your case where output goes to a textArea you might wanna use a multithreaded solution. redirect your output to a file as above and use the thread to read the file and paste text into your text area. there is other better solution that directly passes data into the textArea. i'll post it if can find it in my code base.

  • Redirecting System.out() output to a JTextArea control

    I want to be able to redirect System.out() and System.err() messages to a JTextArea control:
    I know how to redirect output to a file as follows:
    FileOutputStream fos =
    new FileOutputStream(filename, true);
    PrintStream ps = new PrintStream(fos, true);
    System.setOut(ps);
    System.setErr(ps);
    How can I set it up so that I can recognise when messages have been to System.out() with a view to displaying the message within the JTextArea?
    I guess I need to set it up so that the JTextArea control acts as an Observer. The bit I'm having difficulty with is figuring out how I can automatically determine when information has been written to System.out()?
    Hopefully I'm explaining my issue in enough detail and clarity.
    thanks
    - Garry

    I would suggest you set up a separate thread to monitor System.out. Use a PipedOutputStream and redirect System.out to that, then connect that to a PipedInputStream that your other thread is continually waiting to read. Each time that thread reads a line, it should append the line to the JTextArea, using SwingUtilities.invokeLater.
    This is just a rough outline of something that might work. Hope it helps.

  • Output Stream to JTextArea

    Hi there,
    I would like to have the output stream coming from the server to the client displayed on a JTextArea. However, because the coming file is a text document that had its file name passed as a local variable in the main method header with String a[ ], I am having difficulty setting this as the area text because of the incompatible types. This text prints on my command prompt window but I cannot figure out how to get this stream into the JTextArea. This is my code. The objective is to ask a file from the server and have the server send this file to the client so the client can then make changes and save.
    import java.io.*;
    import java.net.*;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JScrollPane;
    import javax.swing.JButton;
    import javax.swing.Box;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.FileNotFoundException;
    import java.io.PrintWriter;
    import java.util.Scanner;
    import java.util.Formatter;
    public class Client extends JFrame{
            public static JTextArea enterArea1;
            public static JTextArea enterArea2;
            public JButton change;
            public JButton save;
      public Client()
            super ("Client to Server");
            Box box = Box.createHorizontalBox();
            enterArea1 = new JTextArea(10, 15);
            enterArea1.setEditable (true);
            box.add (new JScrollPane (enterArea1));
            change = new JButton("Make Changes");
            box.add(change);
            change.addActionListener(
             new ActionListener()
                public void actionPerformed(ActionEvent event)
                Scanner console = new Scanner (System.in);
             System.out.print ("Input File: ");
             String inputFileName = console.next ();
             System.out.print ("Enter the text that you want to change");
             String inputText1 = console.next ();
             System.out.print ( "Output File: ");
             String outputFileName = console.next();
              try
              FileReader reader = new FileReader (inputFileName);
              Scanner in = new Scanner (reader);
              PrintWriter out = new PrintWriter (outputFileName);
                   String line1 = in.nextLine();
                   out.println( " " + inputText1 );
              out.close();
              catch (IOException exception)
              System.out.println ("Error processing file: " + exception);
            save = new JButton("Save to File");
            box.add(save);
            save.addActionListener(
             new ActionListener()
                public void actionPerformed(ActionEvent event)
                enterArea2.setText (enterArea1.getSelectedText());
            enterArea2 = new JTextArea (10, 15);
            enterArea2.setEditable (false);
            box.add (new JScrollPane (enterArea2));
            add (box);
      public static void main(String a[]) throws IOException {
            Socket sock;
            BufferedReader dis;
            PrintWriter dat;
            Client sendServer = new Client();
            sendServer.setSize (500, 200);
            sendServer.setVisible(true);
            sendServer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
            sock = new Socket("127.0.0.1",4444);
            dis = new BufferedReader( new InputStreamReader(sock.getInputStream()) );
            dat = new PrintWriter( sock.getOutputStream() );
            dat.println(a[0]);
            dat.flush();
            enterArea1.setText(a[0]);
            PrintStream os = new PrintStream (new FileOutputStream ("out.txt"));
            String fromServer = dis.readLine();
            while (fromServer != null )
               System.out.println(fromServer);
               os.println(fromServer);
               fromServer = dis.readLine();
            sock.close();
    }

    I believe that the logic is to append the text to the JTextArea with something along the lines of this, but since String a[0] is passed in my void method, it is not accepted as a string anymore. The question then becomes how to create a variable that is referenced to the output text on the command window so that this variable can be used to append the same text to the JTextArea. I will appreciate any comments. Right now, it sees the String text as null.
    String text = dat.println(a[0]);
                          dat.flush();
            enterArea1.append(text]);

  • Outputting ResultSet into a JTextField

    I use this method to execute queries on the database
    public ResultSet runQuery(String s) throws java.sql.SQLException
    Statement stmt = connection.createStatement();
    System.out.println(s);
    return stmt.executeQuery(s);
    For the query I'm having problems with there is only 1 result in the ResultSet. Can anyone tell me how I get this to output into a JTextField. I think I've tried almost everything!!!

    ResultSet rs = runQuery(yoursqlStatement);
    Stringbuffer b = new StringBuffer();
    while(rs.next){
    b.append(rs.getString(1) + "; ");
    yourTextField.settext(b.toString());

  • Sending output to a JTextArea

    ok so i have a muntithread program which is working exactly as it should except for one thing. The output isnt reaching the JTextArea
    here is my code:
    import java.util.concurrent.*;
    import java.util.concurrent.locks.*;
    import java.awt.*;
    import javax.swing.*;
    import java.lang.*;
    import java.io.*;
    import java.util.*;
    import java.awt.event.*;
    import java.awt.Graphics;
    import java.util.Scanner;
    import javax.swing.JTextArea.*;
    public class TaskThreadDemo extends JFrame{
      TaskThreadDemo(){
           outputPanel p1 = new outputPanel();
             setLayout(new FlowLayout());
             add(p1);
      public static void main(String[] args) {
        // Create tasks
        Runnable printA = new PrintChar('a', 100);
        Runnable printB = new PrintChar('b', 100);
        Runnable print100 = new PrintNum(100);
        // Create threads
        Thread thread1 = new Thread(printA);
        Thread thread2 = new Thread(printB);
        Thread thread3 = new Thread(print100);
        // Start threads
        thread1.start();
        thread2.start();
        thread3.start();
        TaskThreadDemo frame = new TaskThreadDemo();
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("lab9");
        frame.setVisible(true);
        frame.setSize(500,500);
    class Output{
              char input1;
              int input2;
              String out;
              Output(){
              public Output(char text, int n)
                   this.input1 = text;
                   this.input2 = n;
              public void setOutput(char text, int n){
                   String internal = " ";
                   if (text != '\\')
                        internal = Character.toString(text);
                        out +=internal;
                        internal = " ";
                   if (n != 0)
                        internal = Integer.toString(n);
                        out += internal;
                        internal = " ";
                   this.out = out;
                   System.out.println(text + n);//used for checking output at this point
              public String getOutput(){
                   System.out.println(out);//used for checking output at this point
                   return out;
    class outputPanel extends JPanel{
         Output outtext = new Output();
         String text = outtext.getOutput();
         outputPanel()
              System.out.println(text);
              JTextArea jtaOutput = new JTextArea(text,10,20);
              jtaOutput.setLineWrap(true);
              jtaOutput.setWrapStyleWord(true);
              jtaOutput.setEditable(false);
              JScrollPane scrollPane = new JScrollPane(jtaOutput);
              setLayout(new FlowLayout());
              add(scrollPane);
    // The task for printing a specified character in specified times
    class PrintChar implements Runnable
           Output output = new Output();
           private char charToPrint; // The character to print
           private int times; // The times to repeat
           private static Lock lock = new ReentrantLock();
           /** Construct a task with specified character and number of
            *  times to print the character
           public PrintChar(char c, int t)
             charToPrint = c;
             times = t;
           /** Override the run() method to tell the system
            *  what the task to perform
           public void  run()
              lock.lock();
                try{
                        Thread.sleep(100);
                        for (int i = 0; i < times; i++)
                              output.setOutput(charToPrint, 0);
                              System.out.print(charToPrint);//used for checking output at this level
              catch (InterruptedException ex){
                   ex.printStackTrace();
              finally
                   lock.unlock();
    // The task class for printing number from 1 to n for a given n
    class PrintNum implements Runnable
         Output output = new Output();
         private int lastNum;
         private static Lock lock = new ReentrantLock();
           /** Construct a task for printing 1, 2, ... i */
           public PrintNum(int n)
             lastNum = n;
           /** Tell the thread how to run */
           public void run()
             lock.lock();
             try{
                     for (int i = 1; i <= lastNum; i++)
                         output.setOutput('\\', i);
                         System.out.print(" " + i);//used for checking output at this point
           finally{
                lock.unlock();
    }

    rgfirefly24 wrote:
    right it may be shorter and it may work. I'm not denying that fact.
    and i <know> my code as it is doesnt work. But if you remove all the extra classes (output, outputPanel) and run it straight to system.out.print it does exactly what its sapposed to. Its the fact that i'm getting confused on how to send the data from the thread method run to the JTextArea. Well I can't say this any clearer I think. Take my code. Read it. Figure out why it works.
    I mean you use a print stream to System.out.println and you know that works. So I created you a PrintStream that instead of outputting to the console outputs to a text area. But this isn't good enough? Why?
    Especially in light of the fact that connecting the threads back to this text area is your admitted problem and I solved that. The outputstream class I wrote does exactly that.
    But whatever if you don't want to go that route fine. For the love of all though it's been mentioned a few times that your code cannot possibly work. Why? Because you never update the JTextArea. So I have no idea why you would think it would work. Your output stuff and method are useless. You update a String in them after a bunch of gyrations. Okay fine. Where is the part where you update the JTextArea?
    You feel free to point out where in this code of yours you think the text area would get updated.
    public void setOutput(char text, int n){
                   String internal = " ";
                   if (text != '\\')
                        internal = Character.toString(text);
                        out +=internal;
                        internal = " ";
                   if (n != 0)
                        internal = Integer.toString(n);
                        out += internal;
                        internal = " ";
                   this.out = out;
                   System.out.println(text + n);//used for checking output at this point
              }

  • How to display ResultSet in JTextArea?

    Hey,
    I'm trying to write a method which displays the data from a ResultSet.
    Currently I'm only able to display the last line of information, what is thye best way to go about displaying all info? The method I'm using is below. Thanks in advance for your time!
    public void Retrieve() {
    try {
    String url;
    Connection connect;
    Statement statement;
    url = "jdbc:odbc:CoffeeDSN";
    connect = DriverManager.getConnection(url);
    statement = connect.createStatement();
    ResultSet rs = statement.executeQuery("SELECT * FROM COFFEES");
    if( rs.next() ) {
    jTextArea1.setText(rs.getString(1));
    jTextArea1.setText(rs.getString(3));
    catch (SQLException ex) {
    System.err.println("SQLException: " + ex.getMessage());
    }

    jTextArea1.setText(rs.getString(1));
    jTextArea1.setText(rs.getString(3));Calling 'jTextArea1.setText(...)' overwrites any text that was previously written, hence you only see the last line of information.
    You should change 'setText(...)' to 'append(...)' - don't forget to add newline characters ("\n") as necessary.

  • Dynamic Output parameters count

    Hi All,
    I have a requirement in which the number of output cursors from a procedure depends on the input parameter.
    That is for a input parameters value A & B, I have to throw out two resultset and for A & C, I have to throw out 5 resultset. I have more than 10 such combinations.
    Is it possible to do that by any means?
    BTW I am in oracle 9i.
    Thanks in Advance,
    Subbu S.

    That is for a input parameters value A & B, I have to
    throw out two resultset and for A & C, I have to
    throw out 5 resultset. I have more than 10 such
    combinations.Is there a logic to selecting the number of output resultsets? Or is it hard-coded that if it is A & B, then you have to throw out 2 resultsets, etc.?
    Do you have any sample code that we could see?
    Thanks

  • Reading native process standard output stream with ProcessBuilder

    Hi,
    I'd like to launch an native process (windows application) which writes on standard output during its running.
    I'd like to view my application output on a JTextArea on my Java frame (Swing). But I do get all process output
    on text area only when the process is finished (it takes about 20 seconds to complete). My external process is
    launched by using a ProcessBuilder object.
    Here is my code snippet with overridden doInBackground() and process() methods of ProcessBuilder class:
    @Override
    public String doInBackground() {
    jbUpgrade.setEnabled(false);
    ProcessBuilder pb = new ProcessBuilder();
    paramFileName = jtfParameter.getText();
    command = "upgrade";
    try {
    if (!(paramFileName.equals(""))) {
    pb.command(command, jtfRBF.getText(), jtfBaseAddress.getText(), "-param", paramFileName);
    } else {
    pb.command(command, jtfRBF.getText(), jtfBaseAddress.getText());
    pb.directory(new File("."));
    pb.redirectErrorStream(false);
    p = pb.start();
    try {
    InputStream is = p.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line;
    jtaOutput.setText("");
    while ((line = br.readLine()) != null) {
    publish(line);
    } catch (IOException ex) {
    Logger.getLogger(CVUpgradeFrame.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
    Logger.getLogger(CVUpgradeFrame.class.getName()).log(Level.SEVERE, null, ex);
    jtaOutput.setText("");
    jtaOutput.setLineWrap(true);
    jtaOutput.append("Cannot execute requested commmad:\n" + pb.command());
    jtaOutput.append("\n");
    jtaOutput.setLineWrap(false);
    return "done";
    @Override
    protected void process(List<String> line) {
    jtaOutput.setLineWrap(true);
    Iterator<String> it = line.iterator();
    while (it.hasNext()) {
    jtaOutput.append(it.next() + newline);
    jtaOutput.repaint();
    //Make sure the new text is visible, even if there
    //was a selection in the text area.
    jtaOutput.setCaretPosition(jtaOutput.getDocument().getLength());
    How can I get my process output stream updated while it is running and not only when finished?
    Thanks,
    jluke

    1) Read the 4 sections of http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html and implement the recommendations. Although it is concerned with Runtime.exec() the recommendations still apply to Process generated by ProcessBuilder.
    2) Read about concurrency in Swing - http://java.sun.com/docs/books/tutorial/uiswing/concurrency/ .
    3) Use SwingUtilities.invokeLater() to update your GUI.

  • JScrollPane w/ JTextArea problems

    I've written a simple terminal for a project I'm working on, with a JTextField for inputs and a JTextArea to display outputs. The JTextArea uses a JScrollPane to let it scroll vertically, and wraps text to avoid horizontal scrolling.
    My problem is this: when I append text to the text area, the scroll pane sometimes scrolls to the bottom, sometimes scrolls part-way, and sometimes doesn't move at all. Ideally, I'd like to have the scroll pane always pushed to the bottom. Does anyone know what causes this kind of behaviour? What input causes the bar to scroll, and what input doesn't?
    thanks,
    Andrew

    I don't know what causes the kind if behaviour you described, but this is how you get the scrollPane to scroll to the bottom:
    int bottom = scrollPane.getVerticalScrollBar().getMaximum();
    scrollPane.getVerticalScrollBar().setValue(bottom);

  • JScrollPane is not making my JTextArea scrollable....

    I'm making a little chat client for school and I'm having trouble getting my GUI to work right. I'm basically having two problems:
    1. When I put my JTextArea's in JScrollPane's, they aren't becoming scrollable. When I type on it the text just goes off the JTextArea and doesn't scroll. I can't understand why.
    2. When I don't specify a preferred size for my JTextArea's they shrink up to as small as possible and are unusable. When I do specify one they don't stretch if I increase or decrease the size of the window. I basically want them to use up as much space as possible.
    Here's my code:
    package main;
    import javax.swing.*;
    import java.awt.*;
    public class Main {
         private JFrame frame;
         private JPanel panel,output,input;
         private JTextArea area,field;
         private JButton button;
         public Main(){
              frame = new JFrame("Chat Window");
              panel = new JPanel();
              output = new JPanel();
              input = new JPanel();
              area = new JTextArea();
              field = new JTextArea();
              button = new JButton("Send");
              button.setSize(50,20);
              //area.setPreferredSize(new Dimension(300,300));
              //field.setPreferredSize(new Dimension(240,100));
              output.add(new JScrollPane(area),"Center");
              input.add(new JScrollPane(field),"West");
              input.add(button,"East");
              panel.add(new JSplitPane(JSplitPane.VERTICAL_SPLIT,true,output,input));
              frame.add(panel);
              frame.setSize(300,450);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setResizable(true);
              frame.setVisible(true);
         public static void main(String...a){
              Main main = new Main();
    }

    How about something like this?:
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    public class Main
        private JFrame frame3;
        private JPanel outputPnl, inputPnl;
        private JTextArea outputTxt, inputTxt;
        private JButton btn3;
        private void wtf3()
            frame3 = new JFrame();
            outputTxt = new JTextArea();
            inputTxt = new JTextArea();
            btn3 = new JButton("Send");
            outputPnl = new JPanel();
            inputPnl = new JPanel();
            outputPnl.setLayout(new GridLayout());
            outputPnl.add(new JScrollPane(outputTxt));
            inputPnl.setLayout(new BorderLayout());
            inputPnl.add(new JScrollPane(inputTxt), BorderLayout.CENTER);
            JPanel btnPanel = new JPanel();
            btnPanel.add(btn3, BorderLayout.CENTER);
            btnPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
            inputPnl.add(btnPanel, BorderLayout.EAST);
            JSplitPane splitP3 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true, outputPnl, inputPnl);
            frame3.getContentPane().add(splitP3);
            frame3.setSize(600, 450);
            frame3.setLocationRelativeTo(null);
            frame3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame3.setVisible(true);
            splitP3.setDividerLocation(0.8);       
        public Main()
            wtf3();
        private static void createAndShow()
            javax.swing.SwingUtilities.invokeLater(new Runnable()
                public void run()
                    Main mn = new Main();
        public static void main(String[] args)
            createAndShow();
    }

  • Trying to pass and object variable to a method

    I have yet another question. I'm trying to display my output in succession using a next button. The button works and I get what I want using test results, however what I really want to do is pass it a variable instead of using a set number.
    I want to be able to pass the object variables myProduct, myOfficeSupplies, and maxNumber to method actionPerformed so they can be in-turn passed to the displayResults method which is called in the actionPerformed method. Since there is no direct call to actionPerformed because it is called within one of the built in methods, I can't tell it to receive and pass those variables. Is there a way to do it without having to pass them through the built-in methods?
    import javax.swing.JToolBar;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JTextArea;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import java.net.URL;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    public class Panel extends JPanel implements ActionListener
         protected JTextArea myTextArea;
         protected String newline = "\n";
         static final private String FIRST = "first";
         static final private String PREVIOUS = "previous";
         static final private String NEXT = "next";
         public Panel( Product myProduct, OfficeSupplies myOfficeSupplies, int maxNumber )
                 super(new BorderLayout());
              int counter = 0;
                 //Create the toolbar.
                 JToolBar myToolBar = new JToolBar( "Still draggable" );
                 addButtons( myToolBar );
                 //Create the text area used for output.
                 myTextArea = new JTextArea( 450, 190 );
                 myTextArea.setEditable( false );
                 JScrollPane scrollPane = new JScrollPane( myTextArea );
                 //Lay out the main panel.
                 setPreferredSize(new Dimension( 450, 190 ));
                 add( myToolBar, BorderLayout.PAGE_START );
                 add( scrollPane, BorderLayout.CENTER );
              myTextArea.setText( packageData( myProduct, myOfficeSupplies, counter ) );
              setCounter( counter );
         } // End Constructor
         protected void addButtons( JToolBar myToolBar )
                 JButton myButton = null;
                 //first button
                 myButton = makeNavigationButton( FIRST, "Display first record", "First" );
                 myToolBar.add(myButton);
                 //second button
                 myButton = makeNavigationButton( PREVIOUS, "Display previous record", "Previous" );
                 myToolBar.add(myButton);
                 //third button
                 myButton = makeNavigationButton( NEXT, "Display next record", "Next" );
                 myToolBar.add(myButton);
         } //End method addButtons
         protected JButton makeNavigationButton( String actionCommand, String toolTipText, String altText )
                 //Create and initialize the button.
                 JButton myButton = new JButton();
                     myButton.setActionCommand( actionCommand );
                 myButton.setToolTipText( toolTipText );
                 myButton.addActionListener( this );
                   myButton.setText( altText );
                 return myButton;
         } // End makeNavigationButton method
             public void actionPerformed( ActionEvent e )
                 String cmd = e.getActionCommand();
                 // Handle each button.
              if (FIRST.equals(cmd))
              { // first button clicked
                          int counter = 0;
                   setCounter( counter );
                 else if (PREVIOUS.equals(cmd))
              { // second button clicked
                   counter = getCounter();
                      if ( counter == 0 )
                        counter = 5;  // 5 would be replaced with variable maxNumber
                        setCounter( counter );
                   else
                        counter = getCounter() - 1;
                        setCounter( counter );
              else if (NEXT.equals(cmd))
              { // third button clicked
                   counter = getCounter();
                   if ( counter == 5 )  // 5 would be replaced with variable maxNumber
                        counter = 0;
                        setCounter( counter );
                      else
                        counter = getCounter() + 1;
                        setCounter( counter );
                 displayResult( counter );
         } // End method actionPerformed
         private int counter;
         public void setCounter( int number ) // Declare setCounter method
              counter = number; // stores the counter
         } // End setCounter method
         public int getCounter()  // Declares getCounter method
              return counter;
         } // End method getCounter
         protected void displayResult( int counter )
              //Test statement
    //                 myTextArea.setText( String.format( "%d", counter ) );
              // How can I carry the myProduct and myOfficeSupplies variables into this method?
              myTextArea.setText( packageData( product, officeSupplies, counter ) );
                 myTextArea.setCaretPosition(myTextArea.getDocument().getLength());
             } // End method displayResult
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event dispatch thread.
         public void createAndShowGUI( Product myProduct, OfficeSupplies myOfficeSupplies, int maxNumber )
                 //Create and set up the window.
                 JFrame frame = new JFrame("Products");
                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                 //Add content to the window.
                 frame.add(new Panel( myProduct, myOfficeSupplies, maxNumber ));
                 //Display the window.
                 frame.pack();
                 frame.setVisible( true );
             } // End method createAndShowGUI
         public void displayData( Product myProduct, OfficeSupplies myOfficeSupplies, int maxNumber )
              JTextArea myTextArea = new JTextArea(); // textarea to display output
              JFrame JFrame = new JFrame( "Products" );
              // For loop to display data array in a single Window
              for ( int counter = 0; counter < maxNumber; counter++ )  // Loop for displaying each product
                   myTextArea.append( packageData( myProduct, myOfficeSupplies, counter ) + "\n\n" );
                   JFrame.add( myTextArea ); // add textarea to JFrame
              } // End For Loop
              JScrollPane scrollPane = new JScrollPane( myTextArea ); //Creates the JScrollPane
              JFrame.setPreferredSize(new Dimension(350, 170)); // Sets the pane size
              JFrame.add(scrollPane, BorderLayout.CENTER); // adds scrollpane to JFrame
              JFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); // Sets program to exit on close
              JFrame.setSize( 350, 170 ); // set frame size
              JFrame.setVisible( true ); // display frame
         } // End method displayData
         public String packageData( Product myProduct, OfficeSupplies myOfficeSupplies, int counter ) // Method for formatting output
              return String.format( "%s: %d\n%s: %s\n%s: %s\n%s: %s\n%s: $%.2f\n%s: $%.2f\n%s: $%.2f\n%s: $%.2f",
              "Product Number", myOfficeSupplies.getProductNumber( counter ),
              "Product Name", myOfficeSupplies.getProductName( counter ),
              "Product Brand",myProduct.getProductBrand( counter ),
              "Number of Units in stock", myOfficeSupplies.getNumberUnits( counter ),
              "Price per Unit", myOfficeSupplies.getUnitPrice( counter ),
              "Total Value of Item in Stock is", myOfficeSupplies.getProductValue( counter ),
              "Restock charge for this product is", myProduct.restockingFee( myOfficeSupplies.getProductValue( counter ) ),
              "Total Value of Inventory plus restocking fee", myOfficeSupplies.getProductValue( counter )+
                   myProduct.restockingFee( myOfficeSupplies.getProductValue( counter ) ) );
         } // end method packageData
    } //End Class Panel

    multarnc wrote:
    My instructor has not been very forthcoming with assistance to her students leaving us to figure it out on our own.Aren't they all the same! Makes one wonder why they are called instructors. <sarcasm/>
    Of course it's highly likely that enough information was imparted for any sincere, reasonably intelligent student to actually figure it out, and learn the subject in the process.
    And if everything were spoonfed, how would one grade the performance of the students? Have them recite from memory
    public class HelloWorld left-brace
    indent public static void main left-parenthesis String left-bracket right-bracket args right-parenthesis left-brace
    And everywhere that Mary went
    The lamb was sure to go
    db

  • JNI - How to use the error reporting mechanism?

    I've developed a C++ DLL which is loaded from a commercial Win32 application (not written by me) as a plug-in for external calculations. On its initialization the C++ DLL launches the Java VM via the JNI invocation interface. When the DLL functions are called by the application, they forward the calls to Java objects inside the Java VM, again via JNI invocation interface.
    This works well, but I have encountered a weird error.
    From Java I open a JFrame containing a JTextArea as small console for debug output messages. If I turn output to this debug console off (my printToConsole routine checks whether a boolean flag is set), the string concatenation operator may lead to a crash of the Java VM.
    For example, if in one of the Java functions called from the
    DLL via JNI invocation interface the following is the first statement,
    it leads to a crash of the Java VM and the application that loaded the C++ proxy DLL.
    String test=""+Math.random(); // String test not used later
    Interestingly, if I comment this statement out, the Java code works fine WITHOUT any crash. I've already thought about potential races and synchronization issues in my code, but I don't see where this is the case. And the string concatenation error fails as well, if I insert sleep() statements in front of it and at other places in the code. However, if I turn on log messages printed to my JFrame debug console (containing a JTextArea), the String concatenation works without problems.
    So maybe the JNI interface has a bug and affects the Java VM; I don't see where my JNI code is wrong.
    One problem is that I do not get any stdout output, as the C++ proxy DLL is loaded by the Windows application, even if I start the Windows application from the DOS command line (under Windows).
    Does anyone know how to use the error reporting mechanism?
    http://java.sun.com/j2se/1.4.2/docs/guide/vm/error-handling.html
    Is it possible that the JVM, when it crashes, writes debug information about the crash into a file instead of stdout/stderr?
    My C++ proxy DLL was compiled in debug mode, but the commercial application (which loaded the DLL) is very likely not.
    I do not know hot to find the reason why the String concatenation fails inside the Java function called from the C++ DLL via JNI.

    Yes, I've initially thought about errors in the C++ code too. But the C++ code is actually very simple and short. It doesn't allocate anything on the C++ side. It allocates a couple of ByteBuffers inside the Java VM however via JNI invocation interface calls of env->NewDirectByteBuffer(). The native memory regions accessed via the ByteBuffers are allocated not by my own C++ code, but by the program that calls my DLL (the program is Metastock).
    The interesting thing is that everything works fine if output to my debug console is enabled, which means that in the Java print routine getConsoleLoggingState() returns true and text is appended to the jTextArea.
    static synchronized void print(String str)
    { MetaStockMonitor mMon=getInstance();
    if ( mMon.getFileLoggingState() && mMon.logFileWriter!=null) {
    mMon.logFileWriter.print(str);
    mMon.logFileWriter.flush();
    if ( mMon.getConsoleLoggingState() ) {
    mMon.jTextArea1.append(str);
    Only if output to the JTextArea is turned off (ie. getConsoleLoggingState()==false), the crash happens when the FIRST statement in the Java routine called via JNI invocation interface is a (useless) String concatenation operation, as described above.
    String test=""+Math.random(); // String test not used later
    Moreover, the crash happens BEFORE the allocated ByteBuffer objects are accessed in the Java code. But again, if console output is turned on, it works stable. If console output is turned off, it works when the (useless) String concatenation operation is removed in the Java routine called from C++.
    I've already thought about potential races (regarding multiple threads), but this can be ruled out in my case. It almost appears as if the JVM can have problems when called by the invocation interface (I tested it with Java 1.4.2 b28).
    All the calls between C++ and Java go ALWAYS in the direction from C++ code to Java. Unfortunately, there is no special JRE version with extensive logging capabilities to facilitate debugging. And the problem is not easily reproducible either.
    JNIEnv* JNI_GetEnv()
    JNIEnv *env;
    cached_jvm->AttachCurrentThread((void**)&env,NULL);
    fprintf(logfile,"env=%i\n",env);
    fflush(logfile);
    return env;
    // function called by Metastock's MSX plug-in interface
    BOOL __stdcall createIndEngine (const MSXDataRec *a_psDataRec,
    const MSXDataInfoRecArgsArray *a_psDataInfoArgs,
    const MSXNumericArgsArray *a_psNumericArgs,
    const MSXStringArgsArray *a_psStringArgs,
    const MSXCustomArgsArray *a_psCustomArgs,
    MSXResultRec *a_psResultRec)
    a_psResultRec->psResultArray->iFirstValid=0;
    a_psResultRec->psResultArray->iLastValid=-1;
    jthrowable ex;
    jmethodID mid;
    JNIEnv* env=JNI_GetEnv();
    jobject chart=getChart(env, a_psDataRec);
    if ( chart==NULL) {
    return MSX_ERROR;
    jobject getChart (JNIEnv* env, const MSXDataRec *a_psDataRec)
    jthrowable ex;
    jmethodID mid;
    int closeFirstValid, closeLastValid;
    closeFirstValid=a_psDataRec->sClose.iFirstValid;
    closeLastValid=a_psDataRec->sClose.iLastValid;
    long firstDate, firstTime;
    if (closeFirstValid>=1 && closeFirstValid<=closeLastValid) {
    firstDate = a_psDataRec->psDate[closeFirstValid].lDate;
    firstTime = a_psDataRec->psDate[closeFirstValid].lTime;
    } else {
    firstDate=0;
    firstTime=0;
    jclass chartFactoryClass = env->FindClass("wschwendt/metastock/msx/ChartFactory");
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot find class ChartFactory\n");
    printSBufViaJava(sbuf);
    return NULL;
    mid = env->GetStaticMethodID(chartFactoryClass, "getInstance", "()Lwschwendt/metastock/msx/ChartFactory;");
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot find method ID for ChartFactory.getInstance()\n");
    printSBufViaJava(sbuf);
    return NULL;
    jobject chartFactory=env->CallStaticObjectMethod(chartFactoryClass, mid);
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Exception while calling ChartFactory.getInstance()");
    printSBufViaJava(sbuf);
    return NULL;
    mid = env->GetMethodID(chartFactoryClass, "getChartID", "(Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;IIIIIII)F");
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot find method ID for ChartFactory.getChartID()\n");
    printSBufViaJava(sbuf);
    return NULL;
    jobject symbolBuf=env->NewDirectByteBuffer(a_psDataRec->pszSymbol, strlen(a_psDataRec->pszSymbol) );
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot allocate symbolBuf\n");
    printSBufViaJava(sbuf);
    return NULL;
    jobject securityNameBuf=env->NewDirectByteBuffer(a_psDataRec->pszSecurityName, strlen(a_psDataRec->pszSecurityName) );
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot allocate securityNameBuf\n");
    printSBufViaJava(sbuf);
    return NULL;
    jobject securityPathBuf=env->NewDirectByteBuffer(a_psDataRec->pszSecurityPath, strlen(a_psDataRec->pszSecurityPath) );
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot allocate securityPathBuf\n");
    printSBufViaJava(sbuf);
    return NULL;
    jobject securityOnlineSourceBuf=env->NewDirectByteBuffer(a_psDataRec->pszOnlineSource, strlen(a_psDataRec->pszOnlineSource) );
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot allocate onlineSourceBuf\n");
    printSBufViaJava(sbuf);
    return NULL;
    // Java Function call leads to crash, if console output is turned off and
    // the first statement in the Java routine is a (useless) string concatenation.
    // Otherwise it works stable.
    jfloat chartID=env->CallFloatMethod(chartFactory, mid, securityNameBuf, symbolBuf,
    securityPathBuf, securityOnlineSourceBuf, (jint)(a_psDataRec->iPeriod),
    (jint)(a_psDataRec->iInterval), (jint)(a_psDataRec->iStartTime),
    (jint)(a_psDataRec->iEndTime), (jint)(a_psDataRec->iSymbolType),
    (jint)firstDate, (jint)firstTime );
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Exception while calling ChartFactory.getChartID()");
    printSBufViaJava(sbuf);
    return NULL;

  • Copy in sand-boxed app. in 1.6.0_24+

    <ul>
    <li>Problem Summary
    <li>Question
    <li>Typical Output
    <li>See Also
    <li>Accumulated Results
    <ul>
    <li>Not grabbing focus
    <li>Grabbing focus
    </ul>
    <li>Source
    <ul>
    <li>PropertyProbe.java
    <li>propertyprobe.jnlp
    <li>js.html
    <li>Java Scripts
    </ul>
    <li>Post Revisions
    </ul>
    <h2><a name="summary"></a>Problem Summary</h2>
    A security bug was fixed recently in the JRE (1.6.0_24 in Sun's JRE). The result of the fix is that sand-boxed apps. no longer provide 'Ctrl-c' copy (or cut/paste) functionality by default on text output controls like JTextArea & JTable.
    While Ctrl-c copy no longer works by default, it is possible to add the functionality back in for any applet run in a 'Next Generation' Java Plug-In. Since Java Web Start existed, JWS provided sand-boxed copy via. the JNLP API's javax.jnlp.ClipboardService, & since Sun 1.6.0_10, & the next gen. plug-in, embedded applets can be deployed using JWS & can access the JNLP API.
    I have redesigned an applet that relied on the old functionality, to now use the JNLP API Services if available.
    <h2><a name="question"></a>Question</h2>
    Does it work for you?
    To answer that question:
    <ol>
    <li>Surf on over to the applet at http://pscode.org/prop/js.html and attempt to copy the data. See the instructions in the page for details of how to copy using the old and new forms of the applet. If the button appears, you should be prompted as to whether to allow the copy.
    <li>Paste the data here (assuming the copy is successful). Or report if it fails to copy or the applet fails to appear.
    </ol>
    <h2><a name="egoutput"></a>Typical Output</h2>
    This is what you might see at the applet.
    ||Property||Value||
    |java.version|1.6.0_24|
    |java.vendor|Sun Microsystems Inc.|
    |os.name|Windows 7|
    |os.version|6.1|
    <h2><a name="related"></a>See Also</h2>
    This relates to the thread Copy & Paste Function in Java JDK 6 Update 24. That thread contains some interesting comments, including:
    <ul>
    <li>A link to Sami Koivu's blog entry that explains the security bug.
    <li>My Re: Copy & Paste Function in Java JDK 6 Update 24 table.
    </ul>
    <h2><a name="results"></a>Accumulated Results</h2>
    <p>The first form of the applet showed a variety of problems with 'post copy focus', if the security prompt appeared in the JWS form of the applet.
    <h3><a name="nograbfocus"></a>Not grabbing focus</h3>
    ||Reporter||Browser||Version||OS name||OS version||Java Vendor||Java version||Focus post dialog||Comments||
    |Andrew Thompson|IE|8.0.7600.16385|Windows 7|6.1|Sun Microsystems Inc.|1.6.0_24|applet|(1)|
    |Andrew Thompson|Chrome|10.0.648.151|Windows 7|6.1|Sun Microsystems Inc.|1.6.0_24|page|(2)|
    |Andrew Thompson|FF|3.6.16|Windows 7|6.1|Sun Microsystems Inc.|1.6.0_24|*nothing*|(3)|
    |Walter Laan|FF|3.6.16|Windows 7|6.1|Sun Microsystems Inc.|1.6.0_20|*locked*|(4)|
    |almightywiz|FF|3.6.16|Windows 7|6.1|Sun Microsystems Inc.|1.6.0_24|?|(5)|
    |camickr|IE|8|Windows XP|5.1|Sun Microsystems Inc.|1.6.0_07|N/A|(6)|
    |Christian|FF|3.6.15|Windows XP|5.1|Sun Microsystems Inc.|1.6.0_24|no problems|(7)|
    |Walter Laan|?|?|Windows XP|5.1|Sun Microsystems Inc.|1.7.0-ea|page?|(8)|
    |abillconsl|FF|3.6.13|Windows XP|5.1|Sun Microsystems Inc.|1.6.0_12|?|(9)|
    <ol>
    <li>Makes 'Ding' sound when copying the alert is dismissed (who said MS was not security conscious?).
    <li>The only way to refocus the applet in Chrome is to click in it with the mouse.
    <li>'Alt space' allowed me to minimize/restore FF, but no key combo. I could think of would restore focus to controls in the browser or applet.
    <li>Reported serious problems with focus for FF on 1st start-up using 1.6.0_20 JRE. Unable to reproduce on the 1.6.0_24 JRE. Ref. {message:id=9470476}, {message:id=9470587}
    <li>Reported no problems with focus. Ref. {message:id=9470371}
    <li>1st report for a pre plug-in2 JRE. IE 8 produced no prompts (as expected), so the 'Focus post dialog' does not apply. No auditory warnings. Ref. {message:id=9470761}
    <li>'No problems with focus.'. Ref. {message:id=9474121}
    <li>Focus returned to page, presumably. Ref. {message:id=9474513}
    <li>Ctrl-a seemed to do nothing. No mention of focus. Ref. {message:id=9477829}
    </ol>
    <h3><a name="grabfocus"></a>Grabbing focus</h3>
    <p>The second form of the applet has a provision to grab the focus immediately after the copy (and presumably after the trust dialog).
    ||Reporter||Browser||Version||OS name||OS version||Java Vendor||Java version||Focus post dialog||Comments||
    |camickr|IE|8|Windows XP|5.1|Sun Microsystems Inc.|1.6.0_07|N/A|(1)|
    |Andrew Thompson|IE|8.0.7600.16385|Windows 7|6.1|Sun Microsystems Inc.|1.6.0_24|applet|-|
    |Andrew Thompson|Chrome|10.0.648.151|Windows 7|6.1|Sun Microsystems Inc.|1.6.0_24|applet|-|
    |Andrew Thompson|FF|3.6.16|Windows 7|6.1|Sun Microsystems Inc.|1.6.0_24|applet|-|
    |Paŭlo Ebermann|FF?|?|Linux2.6.34.7-0.7-desktop|2.6.34.7-0.7-desktop|Sun Microsystems Inc.|1.6.0_20|?|(2)|
    |bogdana|IE|9.0.8112.16421|Windows 7 |6.1|Sun Microsystems Inc.|1.6.0_22 |applet|(3)|
    <ol>
    <li>The first result for camickr can be inferred from the fact that a pre plug-in2 applet should behave the same in both forms of the applet. Ref. {message:id=9470761}
    <li>There are further updates on that thread that have not yet been reflected here. See the thread for details. Ref. P.E. comments at SO
    <li>Also reported the auditory warning in IE when dialog disappears. Ref. {message:id=9488352}
    </ol>
    <h3><a name="java"></a>PropertyProbe.java</h3>
    package org.pscode.tool.property;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.datatransfer.StringSelection;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.border.EmptyBorder;
    import java.util.Locale;
    import java.security.AccessControlException;
    import javax.jnlp.*;
    /** Adds a comma delimited list of property names defined in the
    props param, to the constructor of a new PropertiesPanel and
    displays it. */
    public class PropertyProbe extends JApplet {
        static String[] defaultProps = {
            "os.name",
            "os.version",
            "os.arch",
            "java.vendor",
            "java.version",
            "java.vm.version",
            "default_locale",
            "display_mode",
            "win.highContrast.on",
            "win.text.fontSmoothingOn",
            "win.defaultGUI.font",
            "awt.font.desktophints",
            "awt.mouse.numButtons",
            "awt.multiClickInterval"
        public void init() {
            String propertyNames = getParameter("prop");
            String[] props;
            if (propertyNames==null) {
                //getContentPane().add( new JLabel("Must specify 'prop' to query!") );
                props = defaultProps;
            } else {
                props = propertyNames.split(",");
            boolean grabFocus = getParameter("jnlp.grab.focus")!=null;
            System.out.println("jnlp.grab.focus: " + grabFocus);
            boolean jnlpServicesAvailable = getParameter("jnlp.launched")!=null;
            PropertyPanel pp = new PropertyPanel(props, jnlpServicesAvailable, grabFocus);
            pp.setPreferredSize(new Dimension(200,140));
            getContentPane().add( pp );
            validate();
        public static void main(final String[] args) {
            Runnable r = new Runnable() {
                public void run() {
                    String[] props = defaultProps;
                    if (args.length>0) {
                        props = args;
                    boolean jnlpServicesAvailable = false;
                    try {
                        Class.forName("javax.jnlp.ServiceManager");
                        jnlpServicesAvailable = true;
                        System.out.println("JNLP services available!");
                    } catch(Throwable t) {
                        t.printStackTrace();
                        System.out.println("JNLP services ***NOT*** available!");
                    PropertyPanel pp = new PropertyPanel(props, jnlpServicesAvailable, false);
                    pp.setPreferredSize(new Dimension(200,200));
                    JPanel mainPanel = new JPanel(new BorderLayout());
                    mainPanel.setPreferredSize(new Dimension(400,200));
                    mainPanel.add( pp );
                    JFrame f = new JFrame("Property Probe");
                    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    f.setContentPane(mainPanel);
                    f.pack();
                    try {
                        f.setLocation(50,50);
                        f.setLocationRelativeTo(null);
                        f.setLocationByPlatform(true);
                        f.setMinimumSize( f.getSize() );
                    } catch(Exception e) {
                    f.setVisible(true);
            EventQueue.invokeLater(r);
    class PropertyPanel extends JPanel {
        /** The JNLP API service used for copy in apps. deployed using JWS. */
        private ClipboardService clipboardService;
        private boolean grabFocus = false;
        private JTable table;
        /** A widget (JTable) of values for properties specified in the
        array of property names.  The properties are sourced from the
        system, environment and AWT toolkit properties.If there is no
        value defined in one of those three, 'null' is displayed. */
        PropertyPanel(String[] props, boolean jnlpServicesAvailable, boolean grabFocus) {
            super(new BorderLayout());
            this.grabFocus = grabFocus;
            setBorder( new EmptyBorder(5,5,5,5) );
            String[][] propValuePairs = new String[props.length][2];
            for ( int ii=0; ii<props.length; ii++ ) {
                propValuePairs[ii][0] = props[ii];
                propValuePairs[ii][1] = getProperty( props[ii] );
            String[] header = {"Property","Value"};
            table = new JTable( propValuePairs, header );
            try {
                table.setAutoCreateRowSorter(true);
            } catch (Exception e) {
                // pre 1.6 JRE, go with an unsorted table
            this.add( new JScrollPane( table ) );
            if (jnlpServicesAvailable) {
                try {
                    clipboardService =
                        (ClipboardService)ServiceManager.
                            lookup("javax.jnlp.ClipboardService");
                    Action action = new CopyAction(
                        "Copy",
                        null,
                        "Copy data",
                        new Integer(KeyEvent.VK_CONTROL+KeyEvent.VK_C));
                    table.getActionMap().put( "copy", action );;
                    final JButton copy = new JButton("Copy to clipboard");
                    copy.setMnemonic('c');
                    copy.addActionListener( action );
                    JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
                    bottomPanel.add(copy);
                    add(bottomPanel, BorderLayout.SOUTH);
                // Expecting only javax.jnlp.UnavailableServiceException.  But if we
                // try to catch it, we get a NoClassDefFoundError in non JWS apps.!
                } catch(Throwable use) {
                    use.printStackTrace();
                    System.err.println("Copy services not available.  Copy using 'Ctrl-c'.");
        /** Check for properties in the order of the toolkit, system
        then environment, on the basis that all the toolkit properties
        are    available to sandboxed apps., as well as some of the system
        properties, but none of the environment properties. */
        public String getProperty(String prop) {
            String value = null;
            if ( prop.equals("default_locale") ) {
                return Locale.getDefault().toString();
            if ( prop.equals("display_mode") ) {
                return getDisplayModeString();
            value = getDesktopProperty(prop);
            if (value!=null) {
                return value;
            value = getSystemProperty(prop);
            if (value!=null) {
                return value;
            value = getEnvironmentProperty(prop);
            if (value!=null) {
                return value;
            return "null";
        public String getSystemProperty( String prop ) {
            try {
                return System.getProperty( prop );
            } catch(AccessControlException ace) {
                // this property is either restricted, /or/ 'null'
                // the plug-in will not reveal which, for a sandboxed
                // app.
                return "unknown";
        public String getEnvironmentProperty(String prop) {
            try {
                Object value = System.getenv().get(prop);
                if (value==null) {
                    return null;
                } else {
                    return value.toString();
            } catch(AccessControlException ace) {
                return null;
        public String getDesktopProperty(String prop) {
            Object value = Toolkit.
                getDefaultToolkit().
                getDesktopProperty(prop);
            if (value==null) {
                return null;
            } else {
                return value.toString();
        public String getDisplayModeString() {
            DisplayMode dm = GraphicsEnvironment.
                getLocalGraphicsEnvironment().
                getDefaultScreenDevice().
                getDisplayMode();
            String value =
                dm.getWidth()
                +
                "x"
                +
                dm.getHeight()
                +
                +
                dm.getRefreshRate()
                +
                "Hz "
                +
                dm.getBitDepth()
                +
                "bit"
            return value;
        public void copyData(Component source) {
            TableModel model = table.getModel();
            StringBuilder sb = null;
            if (true) {
                sb = new StringBuilder();
                for (int ii=0; ii<model.getRowCount(); ii++) {
                    for (int jj=0; jj<model.getColumnCount(); jj++) {
                        sb.append( model.getValueAt(ii,jj).toString() );
                        sb.append( "\t" );
                    sb.append( "\n" );
            String s = sb.toString();
            if (s==null || s.trim().length()==0) {
                JOptionPane.showMessageDialog(this,
                    "There is no data in the table!");
            } else {
                StringSelection selection =
                    new StringSelection(s);
                clipboardService.setContents( selection );
            if (grabFocus) {
                source.requestFocus();
        class CopyAction extends AbstractAction {
            public CopyAction(String text, ImageIcon icon,
                String desc, Integer mnemonic) {
                super(text, icon);
                putValue(SHORT_DESCRIPTION, desc);
                putValue(MNEMONIC_KEY, mnemonic);
            public void actionPerformed(ActionEvent e) {
                copyData((Component)e.getSource());
    }<h3><a name="jnlp"></a>propertyprobe.jnlp</h3>
    <?xml version='1.0' encoding='UTF-8' ?>
    <jnlp spec='1.0'
        href='propertyprobe.jnlp'>
        <information>
            <title>Property Probe</title>
            <vendor>PSCode.org - Andrew Thompson</vendor>
            <description kind='one-line'>
                Table for common Java properties.
            </description>
            <shortcut online='false'>
                <desktop/>
            </shortcut>
        </information>
        <resources>
            <j2se version='1.2+' />
            <jar href='propprobe.jar' main='true' />
        </resources>
        <applet-desc
            main-class='org.pscode.tool.property.PropertyProbe'
            name='applet'
            width='600'
            height='300' >
            <param name='jnlp.launched' value='true' />
        </applet-desc>
    </jnlp><h3><a name="html"></a>js.html</h3>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <HTML>
    <HEAD>
    <title>
    Property Probe - applet
    </title>
    <script type='text/javascript' src="http://www.java.com/js/deployJava.js"></script>
    <script type='text/javascript' src='http://pscode.org/file/urlcode.js'></script>
    <script type='text/javascript' src='http://pscode.org/file/queryprm.js'></script>
    <script type='text/javascript' src='http://pscode.org/file/urlquery.js'></script>
    <script type='text/javascript' src='http://pscode.org/file/appletparams.js'></script>
    <script type='text/javascript'>
    archiveName = "";
    if (true) {
        archiveName = 'propprobe.jar';
    } else {
        archiveName = 'propprobe-trusted.jar';
    var attributes = {
        code:'org.pscode.tool.property.PropertyProbe',
        codebase:'../lib',
        archive:archiveName,
        width:'600',
        height:'400'
    var version = '1.2';
    var params;
    params.jnlp_href='../lib/propertyprobe.jnlp';
    </script>
    </HEAD>
    <BODY>
    <H1>Property Probe</H1>
    <script type='text/javascript'>
    deployJava.runApplet( attributes, params, version );
    </script>
    <P>.. (text & instructions)
    </BODY>
    </HTML><h3><a name="scripts"></a>JavaScripts linked in the HTML</h3>
    'Sold separately' - pull them by direct fetch into your browser window, if you're that interested.
    <h2><a name="revisions"></a>Post Revisions</h2>
    Edited by: Andrew Thompson on Mar 26, 2011 5:32 AM
    Changed subject.
    Edited by: Andrew Thompson on Mar 26, 2011 5:19 PM
    Added accumulated results and index, other tweaks.
    Edited by: Andrew Thompson on Mar 31, 2011 11:08 AM
    Removed 'how output appears in code tags'. Added latest results, 'grab focus' results. Changed URL to invoke 'grab focus'.
    Edited by: Andrew Thompson on Apr 2, 2011 4:20 AM
    Added 1st result from SO - on Linux system.
    Edited by: Andrew Thompson on Apr 2, 2011 6:15 AM
    Added latest result.

    Walter Laan wrote:
    almightywiz wrote:
    Walter Laan wrote:
    The security popup really messes with the focus in Firefox (3.6.16) though.Not saying you're wrong, but I'm using FireFox 3.6.16, as well, and I have none of the focus troubles you've described.Cannot reproduce it now either. Weird.I got the impression you were referring to keyboard focus, so I did some further tests on focus behavior. The test results are listed in the Accumulated Results table on the 1st post.
    The only browser so far that works as I'd expect, or at least as I'd like, is IE.
    Applets and keyboard navigation have always been a PITA. Some time ago I vaguely recall seeing an update involving a new parameter to regulate initial focus (applet or page, ..or another applet), but for the life of me I cannot locate it now. Given that it was a parameter for initial focus, I doubt it would help in this case.
    Edited by: Andrew Thompson on Mar 26, 2011 6:18 PM
    Removed table which has now been expanded & added to 1st post.

  • How do I compare these text files (aka spell check)

    I'm having the hardest time figuring out how to get this spell check to work. Basically, I need to open the dictionary.txt file and then another file which will be spell checked. Ignoring case sensitivity, punctuation, and word endings (such as ly, ing, s). And then output to the user the words that were not found in the dictionary. Here is what I have so far (and it is very basic.... there is no attempt to compare yet since I don't know how to approach this). I only have it outputting to a JTextArea what is opened minus punctuation and upper case....
    import java.util.Scanner;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    //  Created Sept 4, 2004
    *   @version 1.0
    *   This program will store dictionary.txt to a String array and
    *   open another text file to be specified by the user of the program.
    *   As the scanner proceeds through the document, it will spell check
    *   and output any (case insensitive) words not found in the
    *   dictionary.txt file.
    public class Spell extends JFrame {
        /** Area to place the individual words in the file */
        JTextArea outputDictionary, outputWord;
    *  Constructor for the class.  Sets up the swing components.
    *  Prompts the user for the files to be processed.  Then invokes
    *  the process method to actually do the work.
    public Spell() {
         // A JTextArea is used to display each word found in the file.
         outputDictionary=new JTextArea("Dictionary List\n\n");
         add (new JScrollPane(outputDictionary));
         //Set the size to 300 wide by 600 pixels high
         setSize(300,600);
         setVisible(true);
            outputWord=new JTextArea("Opened Document\n\n");
            add (new JScrollPane(outputWord));
            setSize(300,600);
            setVisible(true);
        //Prompts user for the dictionary.txt file
        JFileChooser dictionary = new JFileChooser();
        int returnVal = dictionary.showOpenDialog(this);
         if  (returnVal == JFileChooser.APPROVE_OPTION) {
              storeDictionary(dictionary.getSelectedFile());
        //Prompt user to open file to be checked          
        JFileChooser word = new JFileChooser();
        int returnVal2 = word.showOpenDialog(this);
            if (returnVal2 == JFileChooser.APPROVE_OPTION){
                storeOpenFile(word.getSelectedFile());
    public void storeDictionary(File dictionaryFile) {
         String dictionary="";
         Scanner scanner=null;
        try {
            // Delimiters specifiy where to parse tokens in a scanner
           scanner = new Scanner(dictionaryFile).useDelimiter("\\s*[\\p{Punct}*\\s+]\\s*");
        catch (FileNotFoundException fnfe) {
            JOptionPane.showMessageDialog(this,"Could not open the file");
           System.exit(-1);
         while (scanner.hasNext()) {         
              dictionary=scanner.next();
              if (!dictionary.equals(""))
                 outputDictionary.append(dictionary.toLowerCase()+"\n");
            System.out.println("Thank you, your dictionary is stored.");
    public void storeOpenFile(File openFile){
        String word="";
        Scanner scanner2 = null;
        try {
            // Delimiters specifiy where to parse tokens in a scanner
           scanner2 = new Scanner(openFile).useDelimiter("\\s*[\\p{Punct}*\\s+]\\s*");
        catch (FileNotFoundException fnfe) {
            JOptionPane.showMessageDialog(this,"Could not open the file");
           System.exit(-1);
        //stores the words in the opened text file in a String array
         while (scanner2.hasNext()) {         
              word=scanner2.next();
                 if(!word.equals(""))
                        outputWord.append(word.toLowerCase()+"\n");
        System.out.println("Thanks, your file has successfully been opened.");
    public static void main(String args[]) {
       Spell spellck = new Spell();
       spellck.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    Yes, he actually recommends us to use java 1.5. I have revised my code to read into a TreeSet from the dictionary.txt, but I keep getting the following error when I compile:
    Note: C:\Jwork\spell1.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.
    Finished spell1.
    Also, when I execute, nothing happens. It looks like it is going to try to do something, but the "open" dialog box never opens and no errors pop up. It just sits there executing. Any suggestions??
    here is the code:
    import java.util.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    //  Created Sept 4, 2004
    *   @version 1.0
    *   This program will store dictionary.txt to a String array and
    *   open another text file to be specified by the user of the program.
    *   As the scanner proceeds through the document, it will spell check
    *   and output any (case insensitive) words not found in the
    *   dictionary.txt file.
    public class spell1 extends JFrame{
        JTextArea output = new JTextArea(500,500);
        Set dict = new TreeSet();
        Set file = new HashSet();
        public spell1(){
        Set dict = new TreeSet();
        Set file = new HashSet();
        //Prompts user for the dictionary.txt file
        JFileChooser dictionary = new JFileChooser();
        JFileChooser wordFiles = new JFileChooser();
        int returnVal = dictionary.showOpenDialog(this);
         if (returnVal == JFileChooser.APPROVE_OPTION) {
         storeDictionary(dictionary.getSelectedFile());
        int returnVal2 = wordFiles.showOpenDialog(this);
            if (returnVal2 == JFileChooser.APPROVE_OPTION){
                storeFile(wordFiles.getSelectedFile());
        public void storeDictionary(File dictionaryFile){
            String dictionary="";
         Scanner scanner=null;
        try {
           // Delimiters specifiy where to parse tokens in a scanner
           scanner = new Scanner(dictionaryFile).useDelimiter("\\s*[\\p{Punct}*\\s+]\\s*");
        catch (FileNotFoundException fnfe) {
            JOptionPane.showMessageDialog(this,"Could not open the file");
           System.exit(-1);
         while (scanner.hasNext()) {
              if (!dictionary.equals(""))
                 dict.add(scanner.next());
            System.out.println("Thank you, your dictionary is stored.");
        public void storeFile(File wordFile){
            String word="";
            Scanner scanner2=null;
        try{
            scanner2 = new Scanner(wordFile).useDelimiter("\\s*[\\p{Punct}*\\s+]\\s*");
        catch (FileNotFoundException fnfe){
            JOptionPane.showMessageDialog(this,"Could not open the file");
            System.exit(-1);
            while(scanner2.hasNext()){
                if(!word.equals(""))
                    file.add(scanner2.next());
        public static void main(String args[]){
            spell1 spellck = new spell1();
            spellck.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

Maybe you are looking for