Question about public void characters(char []ch, int start, int length) thr

Can anyone tell me how you would keep all the characters from within one pair of tags together each time characters() is called?
the character() method doesn't read all the character data at once, and i would like to create a buffer of what it has read.
thank you.

I recommend using getNodeName and/or/combination
with
getNodeValue to get the strings.i have tried using a buffer, and i have got that to work!
At long last I am seeing the string I would like to see as it is in the xml file!
thank you for your help
here is an example of my code:
private boolean isDescription = false;
StringBuffer sb = new StringBuffer();
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
     if(localName.equals("description")) {
          sb = new StringBuffer();
          isDescription = true;
public void characters(char []ch, int start, int length) throws SAXException {
     if(isDescription == true) {
          String desc = new String(ch, start, length);
          sb.append(desc);
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
     if(localName.equals("description")) {
          isDescription == false;
          System.out.println(sb.toString());
}

Similar Messages

  • [SOLVED] Question about public inheritance (C++)

    So I'm using OpenCV, and want to use the cv::Mat class. However I need to add some additional data points to the class. My (simple) idea was simply to create a new class, asMat, which inherits publicly from cv::Mat.
    class asMat : public cv::Mat {
    public:
    int my_variable;
    It 'works' in a sense, I can create a cv::Mat, static cast it to asMat, and use it in a few opencv functions, while also saving values into my_instant_name.my_variable.
    However, I can't do the following:-
    asMat inLeft(height,width,CV_8UC1);
    Basically, I'm trying to call a particular constructor from cv::Mat. My understanding is that if I publicly inherit from cv::Mat I would also inherit all its functions. Do constructors work differently somehow (have to be explicitly specified)?
    Last edited by ngoonee (2010-04-26 10:27:52)

    ngoonee wrote:As I understand, the crashing comes because they objects are not the same 'size' in memory. Unfortunately my asMat objects will have to begin life as cv::Mat instants, probably need some wrapper code to convert them.
    Some very common code for what I think your case is:
    cv::Mat *crateMat(int width, int height)
    asMat *myMat = new asMat(width, height); // This calls the constructor you make that actually calls cvMat( height, width, CV_8UC1)
    // some operations in asMat but not in cvMat
    return myMat;
    or
    bool crateMat(cv::Mat *mat, int width, int height)
    asMat *myMat = new asMat(width, height); // This calls the constructor you make that actually calls cvMat( height, width, CV_8UC1)
    // some operations in asMat but not in cvMat
    mat = myMat;
    return true; // or false based on your operations
    or if you just want to construct and not call functions only in asMat:
    cv::Mat *mat = new asMat(width, height);
    If you use the functions just be sure to clean up the pointers.  Also, as jdarnold said, do not use static cast the way you are.  This is what dynamic_cast is for:
    bool doSomethingOnlyAsMatCanDo(cv::Mat *mat)
    asMat *myMat = dynamic_cast<asMat*>(mat);
    if (myMat)
    // some operations in asMat but not in cvMat
    return true;
    return false;

  • Simple question about telnet and characters

    Hi all,
    We've installed for the first time a SUN machine. So i think it's for a SUN expert a very simple question.
    Normally when i type a special character it will be dispayed like " � " [alt+132]
    But when i use a telnet session and i type "alt+132" i get a "d" and not "�".
    Does someone know where i must start to find out how this works ?
    Thanks you very much.
    ESP

    This is probably related to the locale your server is in. I don't remember the default locale a box is installed in if you don't specify. I think its "C". I use the UTF-8 or en_US.ISO8859-1 locales at home. At work, usually C but sometimes applications may require UTF-8. BEA Weblogic required this for a project a while back. This is defined in /etc/init/tz.

  • Question about special characters in XML documents

    Hi,
    I need to create some XML documents based on documents containing elements containing strings containing accentuated and special characters such as ��� or Asian characters.
    I have found the following code claiming that XML documents created by the xformer will have a utf-8 format:
    // Write the DOM document to the file
    Transformer xformer = TheTF.newTransformer();
    xformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");and I have found the InputSource object to be used to read UTF-8 XML documents:
    InputSource in = new InputSource(new FileReader(filename));
    in.setEncoding("UTF-8");Is this enough to make sure that accentuated and Asian characters (or any other characters) will be converted properly when creating and re-reading the XML document? If one of my elements contain the following text '���33445tata', will the string remain the same when re-read from the XML? Do I need more code to make sure that all conversion will be performed properly and transparently? If yes, can one provide an example?
    Thanks!

    Hi Dr.Clap,
    Thanks for your answer, but I am not really sure I understand you. I have performed a test to generate a simple document containing one element. An attribute containing some special characters is added to the element. The element text also contains specials characters.
    When I generate the XML into a byte array input and print the content, I get:
    <?xml version="1.0" encoding="utf-8" standalone="no"?><UTF8TEST BIBI="��ii��������">tre33������</UTF8TEST>When I parse the document, and print the result, I get:
    -- Begin of Parsing
    Element Name = UTF8TEST
    Attribute Name = BIBI
    Attribute Value = �ii����
    Found text : tre33���
    -- End of Parsingwhich is correct. I am worried by the ��ii� ������-like characters generated in the XML. Should I be worried or shouldn't I? Should I convert these into something looking a more like ASCII, or is this fine?
    I am including the code of my example (excluding imports):
    public class XMLUTF8_Test extends DefaultHandler {
        // Logger
        private final static Logger LOG = Logger.getLogger(XMLUTF8_Test.class.getName());
        // Static
        public static DocumentBuilderFactory DOCUMENT_BUILDER_FACTORY;
        public static DocumentBuilder DOCUMENT_BUILDER;
        public static TransformerFactory TRANSFORMER_FACTORY;
        private static SAXParserFactory FACTORY;
        private static SAXParser SAXPARSER;   
        private static XMLReader XMLREADER;
        static {
            // Preparing the writting
            DOCUMENT_BUILDER_FACTORY = DocumentBuilderFactory.newInstance();
            try {
                DOCUMENT_BUILDER = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder();
            } catch (ParserConfigurationException Ex) {
                Debugger.LogUnreachableCodeReachedSituation(LOG, Ex);
            TRANSFORMER_FACTORY = TransformerFactory.newInstance();
            // Preparing the reading
            try {
                FACTORY = SAXParserFactory.newInstance();
                SAXPARSER = FACTORY.newSAXParser();
                XMLREADER = SAXPARSER.getXMLReader();
            } catch (ParserConfigurationException Ex) {
                Debugger.LogUnreachableCodeReachedSituation(LOG, Ex);
            } catch (SAXException Ex) {
                Debugger.LogUnreachableCodeReachedSituation(LOG, Ex);
        public static void main(String[] args) {
            // Perform test
            new XMLUTF8_Test();
        public XMLUTF8_Test() {
            // Saving to File
            Document NewDoc = DOCUMENT_BUILDER.newDocument();
            Element Root = NewDoc.createElement("UTF8TEST");
            Root.setAttribute("BIBI", "�ii����");
            Root.setTextContent("tre33���");
            NewDoc.appendChild(Root);
            ByteArrayOutputStream TheBAOS = new ByteArrayOutputStream();
            try {
                Source source = new DOMSource(NewDoc);
                Result result = new StreamResult(TheBAOS);
                Transformer xformer = TRANSFORMER_FACTORY.newTransformer();
                xformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
                xformer.transform(source, result);
            } catch (TransformerConfigurationException Ex) {
                Debugger.LogUnreachableCodeReachedSituation(LOG, Ex);
            } catch (TransformerException Ex) {
                Debugger.LogUnreachableCodeReachedSituation(LOG, Ex);
            // Printing result
            System.out.println(TheBAOS.toString());
            // Parsing the result
            ByteArrayInputStream TheBAIS = new ByteArrayInputStream(TheBAOS.toByteArray());
            XMLREADER.setContentHandler(this);
            try {
                XMLREADER.parse(new InputSource(TheBAIS));
            } catch (IOException Ex) {
                Debugger.LogUnreachableCodeReachedSituation(LOG, Ex);
            } catch (SAXException Ex) {
                Debugger.LogUnreachableCodeReachedSituation(LOG, Ex);
        @Override
        public void startDocument() throws SAXException {
            System.out.println("-- Begin of Parsing");
        @Override
        public void endDocument() throws SAXException {
            System.out.println("-- End of Parsing");
        @Override
        public void startElement(String namespaceURI, String LocalName, String QualifiedName,
                Attributes TheAttributes) throws SAXException {
            String ElementName = LocalName;
            if ("".equals(ElementName)) {
                ElementName = QualifiedName; // namespaceAware = false
            System.out.println("Element Name = " + ElementName);
            if (TheAttributes != null) {
                for (int i = 0; i < TheAttributes.getLength(); i++) {
                    String AttributeName = TheAttributes.getLocalName(i); // Attr name
                    if ("".equals(AttributeName)) AttributeName = TheAttributes.getQName(i);
                    System.out.println("Attribute Name = " + AttributeName);
                    System.out.println("Attribute Value = " + TheAttributes.getValue(AttributeName));
        @Override
        public void endElement(String namespaceURI, String SimpleName, String QualifiedName) throws SAXException {
        @Override
        public void characters(char[] buf, int offset, int len) throws SAXException {
            String s = new String(buf, offset, len);
            System.out.println("Found text : " + s);
    }Thanks!

  • Question about .swf and HTML5 output and passing variables via querystring

    Hello,
    I am using Captivate 7. We're developing a program that we would like to output both for desktop users and mobile users.If I'm correct, multiscreen.html will determine whether or not to load index.html (which is for mobile users) or yourprogram.htm (for desktop users).
    Currently, we pull and push data from the database using .NET via a querystring and Javascript into yourprogram.htm. In the program, there's a Response.Redirect which sends that data (what screen you've finished reviewing as well as quiz data). So it basically reloads yourprogram.htm after each "save" point. We're wondering how to best approach it if multiscreen.html is first loaded, we imagine the variables may not get passed back and forth correctly into the index.html(HTML5 output)? Has anyone had experience with developing a program this way?
    Looking forward to your insights, recommendations and anything to look out for.
    Thanks,
    Ruth

    Basically, the code is meant to be an example of using a wrapper to modify output before it gets written to the file. So, println is called and the wrapper just alters any text that comes to it before it gets printed to the file. Think of writing to a message to an error log and appending the Date and time to the front.
    The code works fine if you only work on the string that is passed in by itself such as:
    s = s.replace('1', '2');When I try to add text onto the string s I run into problems. I need to send the length of the string to the write function but then length ends up being 8202 on the new string. I don't understand why. I am wondering if this has to do with converting chars to string or the way strings are passed to methods.
    This method is called first and then calls the write method with the string as a param.
    public void write(char[] cbuf, int off, int len) throws IOException {
                    String s= new String(cbuf);
                    this.write(s, off, len);
            }but for some reason when I try to create a new string from the string passed in or try to append text to it, the length of the string gets message up.
    Does that help?
    Sorry, I am just trying to understand what is going on here.
    Thanks.

  • A question about ResultSet.UpdateObject(int column, Object x)

    hi, I write some code which use the TableModel to represent the data fetched from MS-ACCESS.
    the problem is about the UpdateObject(...) method which is in the implement of the AbstractTableModel method setAtValue(). when transfered OBJECT TYPE is java.lang.String, I can't get the correct result in the JTable view.
    my code is as below, could somebody point me out my problem
    public class MyTableModel extends AbstractTableModel {
        private ResultSet rs ;
        private ResultSetMetaData rsmd;
        /** Creates a new instance of MyTableModel */
        public MyTableModel() {
            try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            String url = "jdbc:odbc:CoffeeBreak";
            try {
                Connection con = DriverManager.getConnection(url,"","");
                String strSQL = "SELECT * FROM COFFEES";
                Statement pSt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
                rs = pSt.executeQuery(strSQL);
                rsmd = rs.getMetaData();
            } catch (SQLException ex) {
                ex.printStackTrace();
    /* table model retrieve the Class type of a column method here*/
    public Class getColumnClass(int c){
            try {
                return Class.forName(rsmd.getColumnClassName(c+1));
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            } catch (SQLException ex) {
                ex.printStackTrace();
            return String.class;
    //method of update database and JTable after user edited a table cell
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            try {
                int concurrency = rs.getConcurrency();
                if(concurrency == 1008){
                    rs.absolute(rowIndex+1);    //the JTable row index is start from 0,so plus 1
                    rs.updateObject(columnIndex+1, aValue);//the JTable column index is start from 0, so plus 1
                    rs.updateRow();
            } catch (SQLException ex) {
                ex.printStackTrace();
        }when the column type is about java.lang.String, the cell's result is incorrect, it looks like "[B@1f8f72f" and database can't update.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    It's me again.
    I post the whole class code here
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.sql.Statement;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.AbstractTableModel;
    * @author qhj
    public class MyTableModel extends AbstractTableModel {
        /** Creates a new instance of MyTableModel */
        private ResultSet rs ;
        private ResultSetMetaData rsmd;
        private Statement pSt;
        private String strSQL;
        public MyTableModel() {
            try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            String url = "jdbc:odbc:CoffeeBreak";
            try {
                Connection con = DriverManager.getConnection(url,"","");
                strSQL = "SELECT * FROM COFFEES";
                pSt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
                rs = pSt.executeQuery(strSQL);
                rsmd = rs.getMetaData();
            } catch (SQLException ex) {
                ex.printStackTrace();
        public int getRowCount() {
            try {
                rs.last();
                return rs.getRow();
            } catch (SQLException ex) {
                ex.printStackTrace();
            return 0;
        public int getColumnCount() {
            try {
                return rsmd.getColumnCount();
            } catch (SQLException ex) {
                ex.printStackTrace();
            return 0;
        public Object getValueAt(int rowIndex, int columnIndex) {
            try {
                rs.absolute(rowIndex+1);
                return rs.getObject(columnIndex+1);
            } catch (SQLException ex) {
                ex.printStackTrace();
            return null;
        public String getColumnName(int column){
            try {
                return rsmd.getColumnName(column+1);
            } catch (SQLException ex) {
                ex.printStackTrace();
            return "N/A";
        public Class getColumnClass(int c){
            try {
                return Class.forName(rsmd.getColumnClassName(c+1));
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            } catch (SQLException ex) {
                ex.printStackTrace();
            return String.class;
        public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
            return true;
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            try {
                int concurrency = rs.getConcurrency();
                if(concurrency == 1008){
                    rs.absolute(rowIndex+1);
                    rs.updateObject(columnIndex+1, aValue);
                    //rs.updateRow();
                    //rs = pSt.executeQuery(strSQL);
            } catch (SQLException ex) {
                ex.printStackTrace();
            fireTableDataChanged();
    }

  • Characters(char,int,int) problem ???

    Hello, I'm using SAX to parse an XML file, but i run into a problem with the characters() method (well that's what I think). I use it to get the contents of text nodes, but sometimes (actually, only once) it will return only half of the text. But, you will tell me, this should be normal since the parser is allowed to call it twice in a row.
    But I create a StringBuffer myStringBuffer, then in characters(char[] buffer,int offset,int length) i do myStringBuffer.append(buffer,offset,length) and in endElement i try to process myStringBuffer, but still it contains only half of the text. This is all the more strange to me that my XML file is full of text nodes much longer than the troublesome one and i have no problem with those...and when i extract this s***** node and put it into another XML file, it works fine.
    So I'm somehow confused.
    Thanks in advance.

    Your logic certainly looks like it should work, but obviously it doesn't. Here's what I do:
    1. In the startElement() method, create an empty StringBuffer.
    2. In the characters() method, append the characters to it. Incidentally you don't need to create a String like you do, there's an "append(char[] str, int offset, int len)" method in StringBuffer which is very convenient in this case.
    3. In the endElement() method, use the contents of the StringBuffer.
    As for why parsers split text nodes, don't try to second-guess that. It's not your business as a user of the SAX parser. Some parsers will read the XML in blocks, and if a block happens to end in the middle of a text node, it splits the text node there. Others will see the escape "&amp;" in a text node and split the node into three parts, the part before the escape, a single "&" character, and the part after it. Saves on string manipulation, you see. There could be other reasons, too.

  • Please, help a newbie:  Question about animating expanding containers

    Hi All,
    Short Version of my Question:
    I'm making a media player that needs to have an animation for panels sliding up and down and left and right, and the method I've been using to do this performs far slower than the speed I believe is possible, and required. What is a fast way to make a high performance animation for such an application?
    Details:
    So far, to do the animation, I've been using JSplitPanes and changing the position of the divider in a loop and calling paintImmediately or paintDirtyRegion like so:
    public void animateDividerLocation( JSplitPane j, int to, int direction) {
    for(int i=j.getDividerLocation(); i>=to; i-=JUMP_SIZE) {
    j.setDividerLocation(i);
    j.validate();
    j.paintImmediately(0, 0, j.getWidth(), j.getHeight());
    The validate and paintImmediately calls have been necessary to see any changes while the loop is going. I.e., if those calls are left out, the components appear to just skip right to where they were supposed to animate to, without having been animated at all.
    The animation requirement is pretty simple. Basically, the application looks like it has 3 panels. One on the right, one on the left, and a toolbar at the bottom. The animation just needs to make the panels expand and contract.
    Currenly, the animation only gets about, say, 4 frames a second on the 800 MHz Transmeta Crusoe processor, 114 MB Ram, Windows 2000 machine I must use (to approximate the performance of the processor I'll be using, which will run embedded Linux), even though I've taken most of the visible components out of the JPanels during the animation. I don't think this has to do with RAM reaching capacity, as the harddrive light does not light up often. Even if this were the case, the animation goes also goes slow (about 13 frames a second) on my 3 GHz P4 Windows XP if I keeps some JButtons, images etc., inside the JPanels. I get about 50 frames/sec on my 3 GHz P4, if I take most of the JButtons out, as I do for the 800 MHz processor. This is sufficient to animate the panels 400 pixels across the screen at 20 pixels per jump, but it isn't fast or smooth enough to animate across 400 pixels moving at 4 pixel jumps. I know 50 frames/sec is generally considered fast, but in this case, there is hardly anything changing on the screen (hardly any dirty pixels per new frame) and so I'd expect there to be some way to make the animation go much faster and smoother, since I've seen games and other application do much more much faster and much smoother.
    I'm hoping someone can suggest a different, faster way to do the animation I require. Perhaps using the JSplitPane trick is not a good idea in terms of performance. Perhaps there are some tricks I can apply to my JSplitPane trick?
    I haven't been using any fancy tricks - no double buffering, volatile images, canvas or other animation speed techniques. I haven't ever used any of those things as I'm fairly new to Swing and the 2D API. Actually I've read somewhere that Swing does double buffering without being told to, if I understood what I read. Is doing double buffering explicitly still required? And, if I do need to use double buffering or canvas or volatile images or anything else, I'm not sure how I would apply those techiniques to my problem, since I'm not animating a static image around the screen, but rather a set of containers (JSplitPanes and JPanels, mostly) and components (mostly JButtons) that often get re-adjusted or expanded as they are being animated. Do I need to get the Graphics object of the top container (would that contain the graphics objects for all the contained components?) and then double buffer, volatile image it, do the animation on a canvas, or something like that? Or what?
    Thanks you SO much for any help!
    Cortar
    Related Issues(?) (Secondary concerns):
    Although there are only three main panels, the actual number of GUI components I'm using, during the time of animation, is about 20 JPanels/JSplitPanes and 10 JButtons. Among the JPanels and the JSplitPanes, only a few JPanels are set to visible. I, for one, don't think this higher number of components is what is slowing me down, as I've tried taking out some components on my 3GHz machine and it didn't seem to affect performance much, if any. Am I wrong? Will minimizing components be among the necessary steps towards better performance?
    Anyhow, the total number of JContainers that the application creates (mostly JPanels) is perhaps less than 100, and the total number of JComponents created (mostly JButtons and ImageIcons) is less than 200. The application somehow manages to use up 50 MBs RAM. Why? Without looking at the code, can anyone offer a FAQ type of answer to this?

    You can comment out the lines that add buttons to the panels to see the behavior with empty panels.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.Timer;
    public class DancingPanels
        static GridBagLayout gridbag = new GridBagLayout();
        static Timer timer;
        static int delay = 40;
        static int weightInc = 50;
        static boolean goLeft = false;
        public static void main(String[] args)
            final GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0;
            gbc.weighty = 1.0;
            gbc.fill = gbc.HORIZONTAL;
            final JPanel leftPanel = new JPanel(gridbag);
            leftPanel.setBackground(Color.blue);
            gbc.insets = new Insets(0,30,0,30);
            leftPanel.add(new JButton("1"), gbc);
            leftPanel.add(new JButton("2"), gbc);
            final JPanel rightPanel = new JPanel(gridbag);
            rightPanel.setBackground(Color.yellow);
            gbc.insets = new Insets(30,50,30,50);
            gbc.gridwidth = gbc.REMAINDER;
            rightPanel.add(new JButton("3"), gbc);
            rightPanel.add(new JButton("4"), gbc);
            final JPanel panel = new JPanel(gridbag);
            gbc.fill = gbc.BOTH;
            gbc.insets = new Insets(0,0,0,0);
            gbc.gridwidth = gbc.RELATIVE;
            panel.add(leftPanel, gbc);
            gbc.gridwidth = gbc.REMAINDER;
            panel.add(rightPanel, gbc);
            timer = new Timer(delay, new ActionListener()
                    gbc.fill = gbc.BOTH;
                    gbc.gridwidth = 1;
                public void actionPerformed(ActionEvent e)
                    double[] w = cycleWeights();
                    gbc.weightx = w[0];
                    gridbag.setConstraints(leftPanel, gbc);
                    gbc.weightx = w[1];
                    gridbag.setConstraints(rightPanel, gbc);
                    panel.revalidate();
                    panel.repaint();
            JFrame f = new JFrame("Dancing Panels");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(panel);
            f.setSize(400,300);
            f.setLocation(200,200);
            f.setVisible(true);
            timer.start();
        private static double[] cycleWeights()
            if(goLeft)
                weightInc--;
            else
                weightInc++;
            if(weightInc > 100)
                weightInc = 100;
                goLeft = true;
            if(weightInc < 0)
                weightInc = 0;
                goLeft = false;
            double wLeft = weightInc/ 100.0;
            double wRight = (100 - weightInc)/100.0;
            return new double[]{wLeft, wRight};
    }

  • Questions about Using Vector To File And JTable

    hi all
    I want to write all data from Vector To File and read from file To Vector
    And I want To show all data from vector to JTable
    Note: I'm using the JBuilder Compiler
    This is Class A that my datamember  And Methods in it
    import java.io.*;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2008</p>
    * <p>Company: </p>
    * @author unascribed
    * @version 1.0
    public  class A implements Serializable {
      int no;
      String name;
      int age;
      public void setA (int n,String na,int a)
        no=n;
        name=na;
        age=a;
      public void set_no(int n)
        no = n;
      public void set_age(int a)
        age = a;
        public int getage ()
        return age;
      public void setName(String a)
        name  = a;
      public String getname ()
        return name;
      public int getno ()
        return no;
    This is The Frame That the JTextFeild And JButtons & JTable in it
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import com.borland.jbcl.layout.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2008</p>
    * <p>Company: </p>
    * @author unascribed
    * @version 1.0
    public class Frame1 extends JFrame {
    /* Vector v = new Vector ();
      public int i=0;*/
      A a = new A();
      XYLayout xYLayout1 = new XYLayout();
      JTextField txtno = new JTextField();
      JTextField txtname = new JTextField();
      JTextField txtage = new JTextField();
      JButton add = new JButton();
      JButton search = new JButton();
      /*JTable jTable1 = new JTable();
      TableModel tableModel1 = new MyTableModel(*/
                TableModel dataModel = new AbstractTableModel() {
              public int getColumnCount() { return 2; }
              public int getRowCount() { return 2;}
              public Object getValueAt(int row, int col) { return new A(); }
          JTable table = new JTable(dataModel);
          JScrollPane scrollpane = new JScrollPane(table);
      TitledBorder titledBorder1;
      TitledBorder titledBorder2;
      ObjectInputStream in;
      ObjectOutputStream out;
      JButton read = new JButton();
      public Frame1() {
        try {
          jbInit();
        catch(Exception e) {
          e.printStackTrace();
      private void jbInit() throws Exception {
        titledBorder1 = new TitledBorder(BorderFactory.createEmptyBorder(),"");
        titledBorder2 = new TitledBorder("");
        this.getContentPane().setLayout(xYLayout1);
        add.setBorder(BorderFactory.createRaisedBevelBorder());
        add.setNextFocusableComponent(txtno);
        add.setMnemonic('0');
        add.setText("Add");
        add.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            add_actionPerformed(e);
        add.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            add_actionPerformed(e);
        search.setFocusPainted(false);
        search.setText("Search");
        search.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            search_actionPerformed(e);
        xYLayout1.setWidth(411);
        xYLayout1.setHeight(350);
        read.setText("Read");
        read.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            read_actionPerformed(e);
        this.getContentPane().add(txtno, new XYConstraints(43, 35, 115, 23));
        this.getContentPane().add(txtname,  new XYConstraints(44, 67, 114, 22));
        this.getContentPane().add(txtage,      new XYConstraints(44, 97, 115, 23));
        this.getContentPane().add(add,      new XYConstraints(60, 184, 97, 26));
        this.getContentPane().add(search,  new XYConstraints(167, 185, 88, 24));
        this.getContentPane().add(table,   new XYConstraints(187, 24, 205, 119));
        this.getContentPane().add(read,   new XYConstraints(265, 185, 75, 24));
        this.setSize(450,250);
        table.setGridColor(new Color(0,0,255));
      void add_actionPerformed(ActionEvent e)
        a.set_no(Integer.parseInt(txtno.getText()));
        a.setName(txtname.getText());
        a.set_age(Integer.parseInt(txtage.getText()));
        fileOutput();
        txtno.setText(null);
        txtname.setText(null);
        txtage.setText(null);
        try
          out.writeObject(a);
          out.close();
        }catch (Exception excep){};
    /*  try
           add.setDefaultCapable(true);
          v.addElement(new A());
         ((A)v.elementAt(i)).setA(Integer.parseInt(txtno.getText()),txtname.getText(),Integer.parseInt(txtage.getText()));
        JOptionPane.showMessageDialog(null,"The Record is Added");
        txtno.setText(null);
        txtname.setText(null);
        txtage.setText(null);
        i++;
      }catch (Exception excep){};*/
      void search_actionPerformed(ActionEvent e) {
        int n = Integer.parseInt(JOptionPane.showInputDialog("Enter No:"));
        for (int i=0;i<v.size();i++)
          if (((A)v.elementAt(i)).getno()==n)
            txtno.setText(Integer.toString(((A)v.elementAt(i)).getno()));
            txtname.setText(((A)v.elementAt(i)).getname() );
            txtage.setText(Integer.toString(((A)v.elementAt(i)).getage()));
      public void fileOutput()
        try
          out = new ObjectOutputStream(new FileOutputStream("c:\\UserData.txt",true));
        }catch(Exception excep){};
      public void fileInput()
        try
          in = new ObjectInputStream(new FileInputStream("c:\\UserData.txt"));
        }catch(Exception excep){};
      void read_actionPerformed(ActionEvent e) {
      fileInput();
        try
          a = (A)in.readObject();
          txtno.setText(Integer.toString(a.getno()));
          txtname.setText(a.getname());
          txtage.setText(Integer.toString(a.getage()));
        }catch (Exception excep){};
    }

    //program which copies string data between vector and file
    import java.util.*;
    import java.io.*;
    class Util
    private Vector v;
    private FileReader filereader;
    private FileWriter filewriter;
    Util(String data[])throws Exception
      v=new Vector();
      for(String o:data)
        v.add(o);
    public void listData()throws Exception
      int size=v.size();
      for(int i=0;i<size;i++)
       System.out.println(v.get(i));
    public void copyToFile(String data,String fname)throws Exception
      filewriter =new FileWriter(fname);
      filewriter.write(data);
      filewriter.flush();
      System.out.println("Vector content copied into file..."+fname);
    public void copyFromFile(String fname)throws Exception
      filereader=new FileReader(fname);
      char fcont[]=new char[(int)new File(fname).length()];
      filereader.read(fcont,0,fcont.length);
      String temp=new String(fcont); 
      String fdata[]=temp.substring(1,temp.length()-1).split(",");
      for(String s:fdata)
        v.add(s.trim()); 
      System.out.println("File content copied into Vector...");
    public String getData()throws Exception
       return(v.toString());
    class TestUtil
    public static void main(String a[])throws Exception
      String arr[]={"siva","rama","krishna"};
      Util util=new Util(arr);
      System.out.println("before copy from file...");
      util.listData();
      String fname=System.getProperty("user.home")+"\\"+"vecdata";
      util.copyToFile(util.getData(),fname);
      util.copyFromFile(fname);
      System.out.println("after copy from file...");
      util.listData();
    }

  • A question about JTable .setValueAt(...)

    hi, I write some code which use the Table to represent the data fetched from MS-ACCESS.
    the problem is about the UpdateObject(...) method which is in the implement of the AbstractTableModel method setAtValue(). when transfered OBJECT TYPE is java.lang.String, I can't get the correct result in the JTable view.
    by the way, I use java2SE 6 Beta version
    my code is as below, could somebody point me out my problem
    public class MyTableModel extends AbstractTableModel {
        private ResultSet rs ;
        private ResultSetMetaData rsmd;
        /** Creates a new instance of MyTableModel */
        public MyTableModel() {
            try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            String url = "jdbc:odbc:CoffeeBreak";
            try {
                Connection con = DriverManager.getConnection(url,"","");
                String strSQL = "SELECT * FROM COFFEES";
                Statement pSt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
                rs = pSt.executeQuery(strSQL);
                rsmd = rs.getMetaData();
            } catch (SQLException ex) {
                ex.printStackTrace();
    /* table model retrieve the Class type of a column method here*/
    public Class getColumnClass(int c){
            try {
                return Class.forName(rsmd.getColumnClassName(c+1));
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            } catch (SQLException ex) {
                ex.printStackTrace();
            return String.class;
    //method of update database and JTable after user edited a table cell
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            try {
                int concurrency = rs.getConcurrency();
                if(concurrency == 1008){
                    rs.absolute(rowIndex+1);    //the JTable row index is start from 0,so plus 1
                    rs.updateObject(columnIndex+1, aValue);//the JTable column index is start from 0, so plus 1
                    rs.updateRow();
            } catch (SQLException ex) {
                ex.printStackTrace();
        } when the column type is about java.lang.String, the cell's result is incorrect, it looks like "[B@1f8f72f" and database can't update.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Yes, I have implemented them all.
    I paste them all now. thank all here, first.
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.sql.Statement;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.AbstractTableModel;
    * @author qhj
    public class MyTableModel extends AbstractTableModel {
        /** Creates a new instance of MyTableModel */
        private ResultSet rs ;
        private ResultSetMetaData rsmd;
        public MyTableModel() {
            try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            String url = "jdbc:odbc:CoffeeBreak";
            try {
                Connection con = DriverManager.getConnection(url,"","");
                String strSQL = "SELECT * FROM COFFEES";
                Statement pSt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
                rs = pSt.executeQuery(strSQL);
                rsmd = rs.getMetaData();
            } catch (SQLException ex) {
                ex.printStackTrace();
        public int getRowCount() {
            try {
                rs.last();
                return rs.getRow();
            } catch (SQLException ex) {
                ex.printStackTrace();
            return 0;
        public int getColumnCount() {
            try {
                return rsmd.getColumnCount();
            } catch (SQLException ex) {
                ex.printStackTrace();
            return 0;
        public Object getValueAt(int rowIndex, int columnIndex) {
            try {
                rs.absolute(rowIndex+1);
                return rs.getObject(columnIndex+1);
            } catch (SQLException ex) {
                ex.printStackTrace();
            return null;
        public String getColumnName(int column){
            try {
                return rsmd.getColumnName(column+1);
            } catch (SQLException ex) {
                ex.printStackTrace();
            return "N/A";
        public Class getColumnClass(int c){
            try {
                return Class.forName(rsmd.getColumnClassName(c+1));
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            } catch (SQLException ex) {
                ex.printStackTrace();
            return String.class;
        public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
            return true;
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
            try {
                int concurrency = rs.getConcurrency();
                if(concurrency == 1008){
                    rs.absolute(rowIndex+1);
                    rs.updateObject(columnIndex+1, aValue);
                    rs.updateRow();
            } catch (SQLException ex) {
                ex.printStackTrace();
            fireTableDataChanged();
    }

  • Question about writing a web server

    I was asked to write a simple Web server that responds to HTTP requests received on port 808
    It has the following features:
    1.a request for an HTML document or image file should generate a response with the appropriate MIME type
    2.a request for a directory name with a trailing / should return the contents of the index.html file in that directory (if it exists) or else a suitably formatted HTML listing of the directory contents, including information about each file
    3.a request for a directory name without a trailing / should generate an appropriate Redirect response
    4.a request for a non-existent file or directory should generate an appropriate error response
    5/the Web server should be multi-threaded so that it can cope with multiple
    how to do it?
    may anyone help me please?

    As a startert for ten, try this that I had lying around form a previous
    forum response.
    java -cp <whatever> Httpd 808
    and connect to http://localhost:808 to get an eye-full.
    If you should use this for anything approacing a commercial
    purpose, I will, of course, expect sizable sums of money to be
    deposited in my Swiss bank account on a regular basis.
    Darn it! I'm serious!
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class Httpd
         implements Runnable
         private static String HTTP_400=
              "<HTML><BODY><H2>400 Bad Request</H2></BODY></HTML>";
         private static String HTTP_403=
              "<HTML><BODY><H2>403 Forbidden</H2></BODY></HEAD>";
         private static String HTTP_404=
              "HTML><BODY><H2>404 Not Found</H2></BODY></HTML>";
         public static void main(String[] argv)
              throws Exception
              new Thread(new Httpd(Integer.parseInt(argv[0]))).start();
         private int mPort;
         public Httpd(int port) { mPort= port; }
         public void run()
              try {
                   ServerSocket listenSocket= new ServerSocket(mPort);
                   System.err.println("HTTPD listening on port " +mPort);
                   System.setSecurityManager(new SecurityManager() {
                        public void checkConnect(String host, int p) {};
                        public void checkCreateClassLoader() {};
                        public void checkAccess(Thread g) {};
                        public void checkListen(int p) {};
                        public void checkLink(String lib) {};
                        public void checkPropertyAccess(String key) {};
                        public void checkAccept(String host, int p) {};
                        public void checkAccess(ThreadGroup g) {};
                        public void checkRead(FileDescriptor fd) {};
                        public void checkWrite(String f) {};
                        public void checkWrite(FileDescriptor fd) {};
                        // Make sure the client is not attempting to get behind
                        // the root directory of the server
                        public void checkRead(String filename) {
                             if ((filename.indexOf("..") != -1) || (filename.startsWith("/")))
                                  throw new SecurityException("Back off, dude!");
                   while (true) {
                        final Socket client= listenSocket.accept();
                        new Thread(new Runnable() {
                             public void run() {
                                  try {
                                       handleClientConnect(client);
                                  catch (Exception e) {
                                       e.printStackTrace();
                        }).start();
              catch (Exception e) {
                   e.printStackTrace();
         private void handleClientConnect(Socket client)
              throws Exception
              BufferedReader is= new BufferedReader(
                   new InputStreamReader(client.getInputStream()));
              DataOutputStream os= new DataOutputStream(client.getOutputStream());
              // get a request and parse it.
              String request= is.readLine();
              StringTokenizer st= new StringTokenizer(request);
              if (st.countTokens() >= 2) {
                   String szCmd= st.nextToken();
                   String szPath= st.nextToken();
                   if (szCmd.equals("GET")) {
                        try {
                             handleHttpGet(os, szPath);
                        catch (SecurityException se) {
                             os.writeBytes(HTTP_403);
                   else
                        os.writeBytes(HTTP_400);
              else
                   os.writeBytes(HTTP_400);
              os.close();
         private void handleHttpGet(DataOutputStream os, String request)
              throws Exception
              if (request.startsWith("/"))
                   request= request.substring(1);
              String path= request;
              File f;
              if (request.endsWith("/") || request.equals("")) {
                   path= request +"index.html";
                   f= new File(path);
                   if (!f.exists()) {
                        if (request.endsWith("/"))
                             path= request.substring(0, request.length()-1);
                        else if (request.equals(""))
                             path= ".";
                        f= new File(path);
              else
                   f= new File(path);
              if (!f.exists())
                   os.writeBytes(HTTP_404);
              else if (f.isFile())
                   getFile(os, f);
              else if (f.isDirectory())
                   getDirectory(os, f);
         private void getDirectory(DataOutputStream os, File f)
              throws Exception
              getDirectory(os, f, "");
         private void getDirectory(DataOutputStream os, File f, String prefix)
              throws Exception
              StringBuffer szBuf= new StringBuffer();
              String szTitle= "Index of /";
              if (!f.getPath().equals("."))
                   szTitle= "Index of " +f.getPath().substring(prefix.length());
              szBuf.append("<HTML><HEAD><TITLE>");
              szBuf.append(szTitle);
              szBuf.append("</TITLE></HEAD><BODY><H1>");
              szBuf.append(szTitle);
              szBuf.append("</H1><BR><PRE>");
              szBuf.append(
                   "Name                              Last Modified              Size<HR>");
              String dir= "";
              if (!f.getPath().equals(".")) {
                   dir= f.getPath() +"/";
                   szBuf.append("<A HREF=\"..\">Parent Directory</A><BR>");
              java.text.SimpleDateFormat fmt=
                   new java.text.SimpleDateFormat("EEE MMM d yyyy hh:m:ss");
              String[] list= f.list();
              for (int i= 0; i< list.length; i++) {
                   String path= list;
                   File d= new File(dir + path);
                   if (d.isDirectory())
                        path += "/";
                   szBuf.append("<A HREF=\"");
                   szBuf.append(path);
                   szBuf.append("\">");
                   szBuf.append(path);
                   szBuf.append("</A>");
                   for (int j= path.length(); j< 34; j++)
                        szBuf.append(" ");
                   if (d.isDirectory())
                        szBuf.append("[DIR]");
                   else {
                        szBuf.append(fmt.format(new java.util.Date(f.lastModified())));
                        szBuf.append(" ");
                        szBuf.append(formatFileSize(d.length()));
                   szBuf.append("<BR>");
              szBuf.append("</PRE></BODY></HTML>");
              byte[] buf= szBuf.toString().getBytes();
              os.write(buf,0,buf.length);
         private String formatFileSize(long size)
              if (size < 1024)
                   return "" +size;
              if (size < (1024*1024))
                   return (new Float(size/1024).intValue()) +"K";
              if (size < (1024*1024*1024))
                   return (new Float(size/(1024*1024)).intValue()) +"M";
              if (size < (1024*1024*1024*1024))
                   return (new Float(size/(1024*1024*1024)).intValue()) +"G";
              return "Massive!";
         private void getFile(DataOutputStream os, File f)
              throws Exception
              DataInputStream in= new DataInputStream(new FileInputStream(f));
              int len= (int) f.length();
              byte[] buf= new byte[len];
              in.readFully(buf);
              os.write(buf,0,len);
              in.close();

  • NEWBIE question about java

    Why is the java compiler making two .class files for my swing applet?
    input > applet1.java
    output> applet1.class , applet1$1.class
    This is annoyin because it appears the applet1.class needs applet1$1.class
    to run. Unfortunately, my webserver (FreeBSD) doesn't support $ characters in filenames,
    converting the second file to applet1_1.class

    Yes, I do have an anonymous listener...
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    import java.net.*;
    public class applet1 extends JApplet
        JLabel label1 = new JLabel("Please enter street address of organization here");
        JLabel label2 = new JLabel("Enter unique ID here");
        JTextField textbox1 = new JTextField();
        JTextField textbox2 = new JTextField();
        JButton button1 = new JButton("Submit");
       public void init(){
          Container c1 = getContentPane(); 
          GridBagLayout gridbag = new GridBagLayout();
          GridBagConstraints constraints = new GridBagConstraints();
          c1.setLayout(gridbag);
          constraints.weighty = 1;
          constraints.fill = GridBagConstraints.NONE;
          constraints.weightx = 1;
          constraints.anchor = GridBagConstraints.WEST;
          gridbag.setConstraints(label1,constraints);
          c1.add(label1);
           constraints.fill = GridBagConstraints.HORIZONTAL;
           constraints.gridwidth = GridBagConstraints.REMAINDER;
           gridbag.setConstraints(textbox1,constraints);
           c1.add(textbox1);
            constraints.weightx = 1;
                       constraints.gridwidth = GridBagConstraints.WEST;
            gridbag.setConstraints(label2,constraints);
            c1.add(label2);
           constraints.weightx = 1;
                     constraints.gridwidth = GridBagConstraints.REMAINDER;
           gridbag.setConstraints(textbox2,constraints);
           c1.add(textbox2);
           constraints.fill = GridBagConstraints.NONE;
           constraints.gridwidth = GridBagConstraints.REMAINDER;
           constraints.anchor = GridBagConstraints.CENTER;
                      gridbag.setConstraints(button1,constraints);
           c1.add(button1);
    button1.addActionListener(new ActionListener()
        public void actionPerformed(ActionEvent event)
            int i=0;
            int f=0;
            Date myDate = new Date();
            int day = myDate.getDate();
            int month = myDate.getMonth() + 1;
            int code = Integer.parseInt(textbox2.getText());
            boolean matchFound=false;
            String h = (new String(textbox1.getText()).substring(0,10));
            String str;
            //search database
            try{
                URL url = new URL(getCodeBase(), "address.txt");
                InputStream inStream = url.openStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(inStream));
                StringBuffer l = new StringBuffer(10);
                StringBuffer r = new StringBuffer(20);
                while((str = br.readLine())!=null){
                r.append(str);
                //take out spaces
                for (i=1;i<r.length();i=i+2)
                    l.append(r.charAt(i));
                if (h.equalsIgnoreCase(l.toString().substring(0,10))){
                       //we have a match
                       matchFound =  true;
                //clear buffers for next record
                r.setLength(0);
                l.setLength(0);
                br.close();        
                inStream.close();
                if (matchFound==true)
                    //if match found, perform date conversion
                    day = (code/month)/day;
                    textbox2.hide();
                  textbox1.hide();
                  button1.hide();     
                   label1.setText("Confirmed! Use this number to unlock: ");
                    label2.setText(String.valueOf(day));
                else
                textbox1.setText("Address not found");
            catch (Exception e)
                textbox1.setText("Data file missing");
    }

  • Urgent question about Thread-safety

    Hi all,
    the new tiger release provides an "isReachable()" method for the "InetAddress" object.
    I've found, this method is not thread-safe (see the source and output below).
    It returns true for all threads, when multiple threads using this method with different adresses are running at a time and one of the addresses is reachable. This happens only on WinXp. Running on Linux, the output is like expected.
    I've tried to report this as a bug. But the gurus answered, taking care of thread safety would be a "programmers task".
    My question is, what can I do, to be thread-safe in my case?
    W.U.
    import java.util.*;
    import java.net.*;
    public class IsReachableTest_1 extends Thread{
        static volatile int inst=1;
        static final String NET_ADDR="192.168.111.";
        int instance=inst++;
        public void run(){
            for(int i=19;i<23;i++){
                try{
                    long start=System.nanoTime();
                    if(InetAddress.getByName(NET_ADDR+i).isReachable(1000))
                        System.out.println(""+instance+"--host found at:"+NET_ADDR+i+"--time:"+(System.nanoTime()-start)/1000000);
                    else
                        System.out.println(""+instance+"--no host at:"+NET_ADDR+i);
                }catch(Exception e){System.out.println(""+instance+"--ERROR "+e.toString());}
            System.out.println(""+instance+"--done.");
        public static void main(String[] args) {
            System.out.println(
                System.getProperty("java.vendor")+" "+
                System.getProperty("java.version")+" running on "+
                System.getProperty("os.name")+" "+
                System.getProperty("os.version"));
            Vector v=new Vector();
            System.out.println("\nTest 1: One after another:");
            for(int i=0;i<10;i++){
                IsReachableTest_1 t;
                t=new IsReachableTest_1();
                t.start();
                try{
                    t.join();
                }catch(Exception e){System.out.println("MAIN1: "+e.toString());}
            System.out.println("\nTest 2: All together:");
            inst=1;
            for(int i=0;i<10;i++){
                IsReachableTest_1 t;
                t=new IsReachableTest_1();
                t.start();
                v.addElement(t);
            for(Iterator i=v.iterator();i.hasNext();)
                try{
                    ((IsReachableTest_1)i.next()).join();
                }catch(Exception e){System.out.println("MAIN2: "+e.toString());}
                System.out.println("\nALL DONE");
    And here is the output, when running on WinXp:
    Sun Microsystems Inc. 1.5.0-beta running on Windows XP 5.1
    Test 1: One after another:
    1--no host at:192.168.111.19
    1--no host at:192.168.111.20
    1--host found at:192.168.111.21--time:2
    1--no host at:192.168.111.22
    1--done.
    2--no host at:192.168.111.19
    2--no host at:192.168.111.20
    2--host found at:192.168.111.21--time:4
    2--no host at:192.168.111.22
    2--done.
    3--no host at:192.168.111.19
    3--no host at:192.168.111.20
    3--host found at:192.168.111.21--time:1
    3--no host at:192.168.111.22
    3--done.
    4--no host at:192.168.111.19
    4--no host at:192.168.111.20
    4--host found at:192.168.111.21--time:1
    4--no host at:192.168.111.22
    4--done.
    5--no host at:192.168.111.19
    5--no host at:192.168.111.20
    5--host found at:192.168.111.21--time:3
    5--no host at:192.168.111.22
    5--done.
    6--no host at:192.168.111.19
    6--no host at:192.168.111.20
    6--host found at:192.168.111.21--time:1
    6--no host at:192.168.111.22
    6--done.
    7--no host at:192.168.111.19
    7--no host at:192.168.111.20
    7--host found at:192.168.111.21--time:1
    7--no host at:192.168.111.22
    7--done.
    8--no host at:192.168.111.19
    8--no host at:192.168.111.20
    8--host found at:192.168.111.21--time:1
    8--no host at:192.168.111.22
    8--done.
    9--no host at:192.168.111.19
    9--no host at:192.168.111.20
    9--host found at:192.168.111.21--time:1
    9--no host at:192.168.111.22
    9--done.
    10--no host at:192.168.111.19
    10--no host at:192.168.111.20
    10--host found at:192.168.111.21--time:1
    10--no host at:192.168.111.22
    10--done.
    Test 2: All together:
    1--no host at:192.168.111.19
    2--no host at:192.168.111.19
    3--no host at:192.168.111.19
    4--no host at:192.168.111.19
    5--no host at:192.168.111.19
    6--no host at:192.168.111.19
    7--no host at:192.168.111.19
    8--no host at:192.168.111.19
    9--no host at:192.168.111.19
    10--no host at:192.168.111.19
    2--no host at:192.168.111.20
    3--no host at:192.168.111.20
    6--host found at:192.168.111.20--time:924 <----- this host does not exist!!
    5--host found at:192.168.111.20--time:961 <----- this host does not exist!!
    10--host found at:192.168.111.20--time:778 <----- this host does not exist!!
    9--host found at:192.168.111.20--time:815 <----- this host does not exist!!
    2--host found at:192.168.111.21--time:37
    7--host found at:192.168.111.20--time:888 <----- this host does not exist!!
    8--host found at:192.168.111.20--time:852 <----- this host does not exist!!
    4--host found at:192.168.111.20--time:997 <----- this host does not exist!!
    1--host found at:192.168.111.20--time:1107 <----- this host does not exist!!
    3--host found at:192.168.111.21--time:38
    6--host found at:192.168.111.21--time:1
    5--host found at:192.168.111.21--time:1
    10--host found at:192.168.111.21--time:2
    2--host found at:192.168.111.22--time:3 <----- this host does not exist!!
    9--host found at:192.168.111.21--time:2
    7--host found at:192.168.111.21--time:1
    4--host found at:192.168.111.21--time:3
    1--host found at:192.168.111.21--time:39
    2--done.
    1--host found at:192.168.111.22--time:5 <----- this host does not exist!!
    1--done.
    10--host found at:192.168.111.22--time:40 <----- this host does not exist!!
    3--host found at:192.168.111.22--time:192 <----- this host does not exist!!
    6--host found at:192.168.111.22--time:75 <----- this host does not exist!!
    8--host found at:192.168.111.21--time:230
    5--host found at:192.168.111.22--time:155 <----- this host does not exist!!
    4--host found at:192.168.111.22--time:78 <----- this host does not exist!!
    9--host found at:192.168.111.22--time:77 <----- this host does not exist!!
    7--host found at:192.168.111.22--time:76 <----- this host does not exist!!
    10--done.
    6--done.
    4--done.
    5--done.
    3--done.
    7--done.
    9--done.
    8--no host at:192.168.111.22
    8--done.
    ALL DONE

    I created this test (it's basically the same as your class):
    import java.util.*;
    import java.net.*;
    public class IsReachableTest_2 implements Runnable {
        private final String[] addresses = new String[] {
             "www.sun.com",
             "129.42.16.99" // www.ibm.com which is not reachable
        public void run(){
            try {
                for (int i = 0; i < addresses.length; i++) {
                    final long start = System.nanoTime();
                    final String address = addresses;
         if (InetAddress.getByName(address).isReachable(5000)) {
         System.out.println(Thread.currentThread().getName() + ": Host found at: " + address +
              " --time: " + (System.nanoTime() - start) / 1000);
         } else System.out.println("no host at: " + address);
    } catch(Exception e){
    e.printStackTrace();
    System.out.println("Thread " + Thread.currentThread().getName() + " DONE");
    public static void main(String[] args) {
    System.out.println(
         System.getProperty("java.vendor") +
         " " +
         System.getProperty("java.version") +
         " running on " +
         System.getProperty("os.name") +
         " " +
         System.getProperty("os.version")
    for (int i = 0; i < 10; i++) {
         final Thread t = new Thread(new IsReachableTest_2(), "THREAD " + (i+1));
         t.start();
    And I get:
    Sun Microsystems Inc. 1.5.0-beta running on Windows 2000 5.0
    THREAD 1: Host found at: www.sun.com --time: 217653
    THREAD 3: Host found at: www.sun.com --time: 214404
    THREAD 6: Host found at: www.sun.com --time: 214900
    THREAD 4: Host found at: www.sun.com --time: 215901
    THREAD 5: Host found at: www.sun.com --time: 216666
    THREAD 10: Host found at: www.sun.com --time: 216620
    THREAD 9: Host found at: www.sun.com --time: 217405
    THREAD 2: Host found at: www.sun.com --time: 220705
    THREAD 7: Host found at: www.sun.com --time: 220845
    THREAD 8: Host found at: www.sun.com --time: 221384
    no host at: 129.42.16.99
    Thread THREAD 4 DONE
    no host at: 129.42.16.99
    Thread THREAD 6 DONE
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    Thread THREAD 5 DONE
    Thread THREAD 10 DONE
    Thread THREAD 9 DONE
    Thread THREAD 7 DONE
    Thread THREAD 3 DONE
    Thread THREAD 1 DONE
    Thread THREAD 2 DONE
    Thread THREAD 8 DONE
    HOWEVER: I was getting some strange results every so often. Results like:
    Sun Microsystems Inc. 1.5.0-beta running on Windows 2000 5.0
    THREAD 3: Host found at: www.sun.com --time: 261132
    THREAD 9: Host found at: www.sun.com --time: 264183
    THREAD 2: Host found at: www.sun.com --time: 266447
    THREAD 6: Host found at: www.sun.com --time: 266596
    THREAD 8: Host found at: www.sun.com --time: 267192
    THREAD 5: Host found at: www.sun.com --time: 268610
    THREAD 4: Host found at: www.sun.com --time: 269849
    THREAD 1: Host found at: www.sun.com --time: 280978
    THREAD 7: Host found at: www.sun.com --time: 272589
    THREAD 10: Host found at: www.sun.com --time: 273162
    THREAD 3: Host found at: 129.42.16.99 --time: 13657
    Thread THREAD 3 DONE
    THREAD 4: Host found at: 129.42.16.99 --time: 4123
    THREAD 2: Host found at: 129.42.16.99 --time: 9439
    THREAD 5: Host found at: 129.42.16.99 --time: 6681
    THREAD 8: Host found at: 129.42.16.99 --time: 7655
    THREAD 6: Host found at: 129.42.16.99 --time: 8627
    THREAD 9: Host found at: 129.42.16.99 --time: 10586
    Thread THREAD 4 DONE
    Thread THREAD 2 DONE
    Thread THREAD 5 DONE
    Thread THREAD 8 DONE
    Thread THREAD 6 DONE
    Thread THREAD 9 DONE
    no host at: 129.42.16.99
    Thread THREAD 7 DONE
    no host at: 129.42.16.99
    no host at: 129.42.16.99
    Thread THREAD 10 DONE
    Thread THREAD 1 DONE
    Usually the first run after I had compiled the class (!?) This isn't a thread safety problem.

  • Question about the EDT

    Hi everybody,
    Here my issue: I have to write a little something about EDT and the use of SwingUtilities to avoid common issues with the use of Swing. Sure of my knowledge I wrote a little exemple using a progressBar to show how it doesn't work when you don't use SwingUtilities :
    import javax.swing.JDialog;
    import javax.swing.JProgressBar;
    public class UITesting{
        public static void          main                                            ( String[] args ) {
            JProgressBar    jProgressBar    =   new JProgressBar(0, 100) ;
            jProgressBar.setValue(0);
            jProgressBar.setStringPainted(true);
            JDialog         dialog          =   new JDialog() ;
            dialog.setSize(400, 70) ;
            dialog.setContentPane(jProgressBar) ;
            dialog.setLocationRelativeTo(null) ;
            dialog.setVisible(true);
            int flag = 0 ;
            for (int i = 0 ; i < 100000 ; i++) {
                System.out.println(i);
                if ( i%1000 == 0 ) {
                    jProgressBar.setValue(++flag);
                    System.out.println("Increase ProgressBar " + flag);
    }And surprise (at least for me)... it's working... means that my ProgressBar increase well...
    So I write an exemple closer to reality
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JPanel;
    import javax.swing.JProgressBar;
    public class UITesting{
        public static void          main                                            ( String[] args ){
            final JProgressBar    jProgressBar    =   new JProgressBar(0, 100) ;
            jProgressBar.setValue(0);
            jProgressBar.setStringPainted(true);
            JButton         start           =   new JButton("Start") ;
            start.addActionListener( new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    int flag = 0 ;
                    for (int i = 0 ; i < 100000 ; i++) {
                        System.out.println(i);
                        if ( i%1000 == 0 ) {
                            jProgressBar.setValue(++flag);
                            System.out.println("Increase ProgressBar " + flag);
            JPanel          panel           =   new JPanel() ;
            panel.add(start) ;
            panel.add(jProgressBar) ;
            JDialog         dialog          =   new JDialog() ;
            dialog.setSize(400, 70) ;
            dialog.setContentPane(panel) ;
            dialog.setLocationRelativeTo(null) ;
            dialog.setVisible(true);
    }That time it's perfect, the ProgressBar doesn't work, it going from 0 to 100% at the end of my for loop and the button freeze during the process, I can illustrate my point and introduce the use of SwingUtilities... But why it's working in my first exemple?
    I know that a call to an ActionListener in a Swing composant insure that the code specified is executed in EDT, but I still can't get it? Someone can help me to understand that ?
    thx in advance,
    yannig
    Edited by: yannig on 24 mars 2011 10:57

    Hi,
    [url http://download.oracle.com/javase/tutorial/uiswing/concurrency/worker.html]Worker Threads and SwingWorker
    When a Swing program needs to execute a long-running task, it usually uses one of the worker threads, also known as the background threads. Each task running on a worker thread is represented by an instance of javax.swing.SwingWorker.
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.*;
    import javax.swing.*;
    public class UITesting2 {
      private SwingWorker<Void, Void> worker;
      public JComponent makeUI() {
        final JProgressBar jProgressBar = new JProgressBar(0, 100);
        jProgressBar.setValue(0);
        jProgressBar.setStringPainted(true);
        final JButton start = new JButton("Start") ;
        start.addActionListener( new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            start.setEnabled(false);
            worker = new SwingWorker<Void, Void>() {
              @Override
              public Void doInBackground() throws InterruptedException {
                int current = 0;
                int lengthOfTask = 1024;
                while (current<=lengthOfTask && !isCancelled()) {
                  Thread.sleep(5);
                  setProgress(100 * current / lengthOfTask);
                  current++;
                return null;
              @Override public void done() {
                start.setEnabled(true);
            worker.addPropertyChangeListener(
                new ProgressListener(jProgressBar));
            worker.execute();
        JPanel panel = new JPanel();
        panel.add(start);
        panel.add(jProgressBar);
        return panel;
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          @Override public void run() { createAndShowGUI(); }
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new UITesting2().makeUI());
        f.setSize(400, 70);
        f.setVisible(true);
    class ProgressListener implements PropertyChangeListener {
      private final JProgressBar progressBar;
      ProgressListener(JProgressBar progressBar) {
        this.progressBar = progressBar;
        this.progressBar.setValue(0);
      @Override public void propertyChange(PropertyChangeEvent evt) {
        String strPropertyName = evt.getPropertyName();
        if ("progress".equals(strPropertyName)) {
          progressBar.setIndeterminate(false);
          int progress = (Integer)evt.getNewValue();
          progressBar.setValue(progress);
    }

  • Questions About Printing

    Hi, i am currently having problems with using java print .
    What i need is selecting the printer without using a popup dialog by parsing in a string hardcoded which i would implement a registry reader that would take in the printer name and use that specific printer to read, however i am clueless to edit the codes i had done, by using JobAttributes? or others . please help :=) thankx
    belows are my current codes
    package javaapplication1;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.print.*;
    import java.io.*;
    import java.util.*;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    import javax.print.*;
    import java.awt.JobAttributes.*;
    public class PrintSample  implements Printable {
       static JTextArea textarea = new JTextArea(10,40);
       static JFrame   window = new JFrame("Fax Services");
       String filename;
      public static  void main(String args[])   {
         final JFileChooser fc;
         fc = new JFileChooser();
         JButton openButton = new JButton("Open");
        final Container cp = window.getContentPane();
        JButton buttonPJ = new JButton("Use Printable");
        LayoutManager lm = new FlowLayout(FlowLayout.CENTER, 20,20);
        // fill in text to display (and later print)
        textarea.setEditable(false);
         // set up layout and fill in sample
         cp.setLayout(lm);
         cp.add(new JScrollPane(textarea));
         cp.add(buttonPJ);
         cp.add(openButton);
         //fc.showOpenDialog(cp);
         // add the button press response for buttons
    openButton.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
           int ret=fc.showOpenDialog(cp);
        if(ret==fc.APPROVE_OPTION){
           FileInputStream filein = null;
                        try {
                            java.io.File file = fc.getSelectedFile();
                            //textarea.append(file.getName());
                            filein = new java.io.FileInputStream(file);
                            int x = filein.available();
                            byte b[]=new byte[x];
                            filein.read(b);
                            String content = new String(b);
                            textarea.append(content);
                        } catch (FileNotFoundException ex) {
                            Logger.getLogger("global").log(Level.SEVERE, null, ex);
                        } catch(IOException ex2){
                            Logger.getLogger("global").log(Level.SEVERE, null, ex2);
                        }finally {
                            try {
                                filein.close();
                            } catch (IOException ex) {
                                Logger.getLogger("global").log(Level.SEVERE, null, ex);
        }else{
               textarea.append("Errors Occur");
         buttonPJ.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
               printPrinterJob();
         // set up WindowListener to close the program
         window.addWindowListener(new WindowAdapter() {
                @Override
    public void windowClosing(WindowEvent e) {
             System.exit(0);
        window.setSize(475,300);
        window.setVisible(true);                  // frame starts out invisible
       // PrinterJob implementation
       static void printPrinterJob() {
          PrinterJob printerjob = PrinterJob.getPrinterJob();
          // set the characteristics of
          // the job to be printed - use setPageable and book if
          // outputing a document. Use setPrintable for "simple" printing - all pages formatted the same
          printerjob.setPrintable(new PrintSample());
          try {
              //JobAttributes j = new JobAttributes();
             printerjob.print();            // print the page(s)  (this method with call the page painters)
          } catch (PrinterException exception) {
             System.err.println("Printing error: " + exception);
       // print  - draw the page
       // Parameters:    graphics - context in which to draw the page
       //                pageFormat - size and orientation of page being drawn
       //               pageIndex - zero-based index position of the  page in the print job
       public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
          throws PrinterException {
           String strText =null;    // text string to output
          int lineStart;           // start index of line in textarea
           int lineEnd;             // end index of line in textarea
           int lineNumber;          // current line in textarea
           int lineCount;           // total number of lines in textarea
           if (pageIndex >= 1 ) return Printable.NO_SUCH_PAGE;
           // move the drawing origin to the imageable area ( makes sure its drawn where the printer can )
           graphics.translate((int)(pageFormat.getImageableX()), (int)(pageFormat.getImageableY()));
           graphics.setColor(Color.black);
           // get the text from the textarea one line at a time
           lineNumber = 0;
           lineCount = textarea.getLineCount();
           strText = textarea.getText();
           while (lineNumber < lineCount) {
              try {
                 lineStart = textarea.getLineStartOffset(lineNumber);
                 lineEnd = textarea.getLineEndOffset(lineNumber);
                 strText = textarea.getText(lineStart, lineEnd-lineStart);
              } catch( Exception exception) {
                 System.out.println("Printing error:" + exception);                  // have to catch BadLocationException
              // determine drawing location of each successive line
              graphics.drawString(strText,0,(lineNumber + 1) *20);
              lineNumber = lineNumber + 1;
            return Printable.PAGE_EXISTS;                      // page was drawn successfully (return NO_SUCH_PAGE if not)
    }

    Since JTextArea is a descendant of JTextComponent all you need is :
    java.text.MessageFormat header = null; // header to print null or text
    java.text.MessageFormat footer = null; // footer to print null or text
    boolean showPrintDialog = true; // display the print dialog true || false
    javax.print.PrintService service = javax.print.PrintServiceLookup.lookupDefaultPrintService();
    javax.print.attribute.PrintRequestAttributeSet attributes = null;
    boolean interactive = true;
    jTextComponent.print(header, footer, showPrintDialog, service, attributes, interactive);
    you can put this into a separate thread so it doesn't stall the application
    or inside your printPrinterJob method, discard the overwritten print method
    and let JTextComponent do the print handling for you.
    (print method is inherited for most swing components such as JTextArea etc, look in the API)

Maybe you are looking for

  • Windows Xp sound driver for Presario A 975em

    I just downgraded my Os from Vista to Xp and i cant find any sound driver for my Notebook pls help.I about Compaq Presario A975em Thanks in advance. Best regards

  • Does anyone have experience selling or giving away their Nano?

    I'm considering selling my Nano and hope to replace it with a Touch. My question is, what do I need to do before selling the Nano to a buyer? Do I need to do any preparation? What does a buyer need to do to make a used Nano his? Can I just give him t

  • Idoc not getting posted into XI

    Hello Experts, I am trying IDoc-XI-File senario... I have configured, ALE on backend system. Configured IDX1 and IDX2 in XI system. At sender the Idoc has been sent without any errors. But when I check in XI using SXMB_MONI there are no messages. Ido

  • /etc/postfix/virtual_users.db is older than source file...

    /etc/postfix/virtual_users.db is older than source file /etc/postfix/virtual_users is the error I am getting. My server is working great, but my mailing lists are not working for my virtual domains. I tried deleting the entire mailing list, re-adding

  • Linking graphics to sound and mouse activation

    Hello everyone, The following code shows nine colored rectangles: * Graphics Test import java.awt.*; import java.awt.event.*; public class GraphicsTest extends Frame      public static void main(String[] args)           //The frame constructor