"getBounds" of a String

i am writing a program that can generate report.
but i have problem on right-alignmnet Chinese when printing..
the getBounds() function not return correct string width.
how can i solve the problem??

Check out the link shown below:
http://forum.java.sun.com/thread.jsp?forum=20&thread=319214
I find that the getStringBounds method returns the most accurate info compared to other method such as getBounds or getStringWidth.
;o)
V.V.

Similar Messages

  • Is there any use for Class.getTypeParameters()?

    This is a quote from another Thread in this forum:
    How does erasure destroy reflection-related information? Methods getGenericInterfaces, getGenericSuperclass and getTypeParameters on java.lang.Class allow you to retrieve a lot of information on generic issues regarding a class. Obviously, that information is thus not destroyed.
    While I do agree that Generics do not destroy reflection, I wonder what they add to it.
    New types and methods are Class.getTypeParameters(), the interfaces java.lang.GenericDeclaration, java.lang.reflect.TypeParameter, java.lang.reflect.ParameterizedType etc...
    Could someone please give me an example of what I could do with all these new types and methods?
    It has been decided that Generics are implemented as a compile-time feature. At runtime, no information about the instantiated type parameters exists anymore. OK, so why clutter the core Java packages with a lot of seemingly useless new types and methods?

    Could someone please give me an example of what I
    could do with all these new types and methods?
    It has been decided that Generics are implemented as a
    compile-time feature. At runtime, no information about
    the instantiated type parameters exists anymore. OK,
    so why clutter the core Java packages with a lot of
    seemingly useless new types and methods?This is a very good question, and something I've been wondering about myself. I cannot determine how to get the runtime to give me an instance of WildcardType or ParamaterizedType, for example.
    Here's an extremely contrived example of how you can use Type bounds to effect runtime behaviour:
        class Processor<T> {       
        class StringProcessor<S extends String> extends Processor<S> {       
        public void whatKindOfProcessorIsItAnyway(Processor p) {
            Type processorType = p.getClass().getTypeParameters()[0].getBounds()[0];
            if ( String.class.equals(processorType) ) {
                System.out.println("I'm a string processor");
            } else {
                System.out.println("I process these: " + processorType);           
    whatKindOfProcessorIsItAnyway(new StringProcessor<String>());
            whatKindOfProcessorIsItAnyway(new Processor<Integer>());Outputs:
    I'm a string processor
    I process these: class java.lang.Object
    So you can see I can switch based on the type bounds compiled into the program, but I have no way of knowing that the second processor is actually instantiated with Integer, due to erasure.
    Infact, the only reason I would know anything about the actual type argument in the first instance is because String is final so '? extends String' -> String, for what its worth.
    Whether I can write a program that's actually useful using this information I've yet to determine, but I can imagine it could be useful for code generation.

  • Draw string in center

    Hi,
    I would like to draw a string into center of my own Lable component. How can I know what position of x , y ?
    I'm using g.drawString(mytext, x , y ); in paintComponent() method.

    I guess you could use one of these:
    - Font.getStringBounds()
    - TextLayout.getBounds()
    - FontMetrics.getStringBounds()

  • GetBound().contains() not working well

    Hi,
    I have a number of ovals created. Then I will dragged and create a rectangle over this ovals. So here I'm trying to use the getBound().contain function to identfiy which are ovals inside the rectangle. The problem is that it doesn't seem to work. What are the other possible alternatives ? The code is below
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.util.*;
    public class vshape extends JFrame
    int currentX, currentY, startX, startY;
    boolean dragMode = true;
    JLabel label;
    Vector shape = new Vector();
    Shape ellipse;
    Color color = Color.black;
    public vshape()
    JPanel panel = new DisplayPanel();
    label = new JLabel(" ", SwingConstants.CENTER);
    label.setOpaque(true);
    label.setBackground(Color.red);
    Container cp = getContentPane();
    cp.setLayout(new BorderLayout());
    cp.add(panel, "Center");
    cp.add(label, "South");
    int x=20;
    int y=20;
         for(int i=0 ; i<3 ; i++)
         x = x+20;
         y = y+20;
         ellipse = new Ellipse2D.Double(x, y, 10, 10);
         shape.addElement(ellipse);
    private class DisplayPanel extends JPanel implements MouseMotionListener {    
    public DisplayPanel() {     
    setBackground(Color.cyan);
    addMouseMotionListener(this); }
    public void paintComponent(Graphics g)
    int beginX, beginY, width, height;
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    if (dragMode == true) {
                   beginX = Math.min(startX, currentX);
                   beginY = Math.min(startY, currentY);
                   width = Math.abs(currentX - startX);
                   height = Math.abs(currentY - startY);
              g.drawRect(beginX, beginY, width, height);
         Shape testing;
              for(int j=0; j<shape.size() ; j++)
    testing = (Shape)shape.elementAt(j);
         if (testing.getBounds().contains(currentX,currentY))
    System.out.println("THE OVAL IS is then rectangle : "+j);
         g2.setPaint(color);
         for(int j=0; j<shape.size() ; j++)
         g2.draw ((Shape)shape.elementAt(j));
    public void mouseMoved(MouseEvent e) {     
    public void mouseDragged(MouseEvent e) {
    currentX = e.getX();
    currentY = e.getY();
    label.setText("x = " + currentX + ", y = " + currentY);
    repaint();
    public void mouseDown(MouseEvent e, int x, int y) {
              dragMode = true;
              startX = x;
              startY = y;
              //return true;
    public void mouseUp(MouseEvent e) {
              dragMode = false;
              repaint();
    public static void main(String[] args)
         JFrame frame = new vshape();
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setSize(300,200);
         frame.setLocation(300,200);
         frame.setVisible(true);
    }

    Hi,
    I have a number of ovals created. Then I will dragged and create a rectangle over this ovals. So here I'm trying to use the getBound().contain function to identfiy which are ovals inside the rectangle. The problem is that it doesn't seem to work. What are the other possible alternatives ? The code is below
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.util.*;
    public class vshape extends JFrame
    int currentX, currentY, startX, startY;
    boolean dragMode = true;
    JLabel label;
    Vector shape = new Vector();
    Shape ellipse;
    Color color = Color.black;
    public vshape()
    JPanel panel = new DisplayPanel();
    label = new JLabel(" ", SwingConstants.CENTER);
    label.setOpaque(true);
    label.setBackground(Color.red);
    Container cp = getContentPane();
    cp.setLayout(new BorderLayout());
    cp.add(panel, "Center");
    cp.add(label, "South");
    int x=20;
    int y=20;
         for(int i=0 ; i<3 ; i++)
         x = x+20;
         y = y+20;
         ellipse = new Ellipse2D.Double(x, y, 10, 10);
         shape.addElement(ellipse);
    private class DisplayPanel extends JPanel implements MouseMotionListener {    
    public DisplayPanel() {     
    setBackground(Color.cyan);
    addMouseMotionListener(this); }
    public void paintComponent(Graphics g)
    int beginX, beginY, width, height;
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    if (dragMode == true) {
                   beginX = Math.min(startX, currentX);
                   beginY = Math.min(startY, currentY);
                   width = Math.abs(currentX - startX);
                   height = Math.abs(currentY - startY);
              g.drawRect(beginX, beginY, width, height);
         Shape testing;
              for(int j=0; j<shape.size() ; j++)
    testing = (Shape)shape.elementAt(j);
         if (testing.getBounds().contains(currentX,currentY))
    System.out.println("THE OVAL IS is then rectangle : "+j);
         g2.setPaint(color);
         for(int j=0; j<shape.size() ; j++)
         g2.draw ((Shape)shape.elementAt(j));
    public void mouseMoved(MouseEvent e) {     
    public void mouseDragged(MouseEvent e) {
    currentX = e.getX();
    currentY = e.getY();
    label.setText("x = " + currentX + ", y = " + currentY);
    repaint();
    public void mouseDown(MouseEvent e, int x, int y) {
              dragMode = true;
              startX = x;
              startY = y;
              //return true;
    public void mouseUp(MouseEvent e) {
              dragMode = false;
              repaint();
    public static void main(String[] args)
         JFrame frame = new vshape();
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setSize(300,200);
         frame.setLocation(300,200);
         frame.setVisible(true);
    }

  • Insert String to JTextPane as hyperlink

    Hi,
    I have a JTabbedPane with 2 tabs, on each tab is one panel.
    On first pannel I add JTextPane and I would like to insert in this JTextPane some hyperlinks.
    I found some examples in forum, but doesn't work for me.
    Could somebody help me ?
    Thank's.
    Here is my code :
    JTextPane textPane = new JTextPane();
    textPane.setPreferredSize(new Dimension(500,300));
    HTMLEditorKit m_kit = new HTMLEditorKit();
    textPane.setEditorKit(m_kit);
    StyledDocument m_doc = textPane.getStyledDocument();
    textPane.setEditable(false); // only then hyperlinks will work
    panel1.add( textPane,BorderLayout.CENTER); //add textPane to panel of
    //JTabbedPane
    String s = new String("http://google.com");
    SimpleAttributeSet attr2 = new SimpleAttributeSet();
    attr2.addAttribute(StyleConstants.NameAttribute, HTML.Tag.A);
    attr2.addAttribute(HTML.Attribute.HREF, s);
    try{
    m_doc.insertString(m_doc.getLength(), s, attr2);
    }catch(Exception excp){};
    The String s is displayed like text not like hyperlink..

    Hi , You can take a look at this code , this code inserts a string into a StyledDocument in a JTextPane as a hyperlink and on clicking fires the URL on the browser.
    /* Demonstrating creation of a hyperlink inside a StyledDocument in a JTextPane */
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.Border;
    import javax.swing.text.*;
    public class Hyperlink extends JFrame {
        private Container container = getContentPane();
        private int toolXPosition;
        private int toolYPosition;
        private JPanel headingPanel = new JPanel();
        private JPanel closingPanel = new JPanel();
        private final static String LINK_ATTRIBUTE = "linkact";
        private JTextPane textPane;
        private StyledDocument doc;
        Hyperlink() {
              try {
                   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
                   setSize(300, 200);
                   Rectangle containerDimension = getBounds();
                   toolXPosition = (screenDimension.width - containerDimension.width) / 10;
                            toolYPosition = (screenDimension.height - containerDimension.height) / 15;
                            setTitle("HYPERLINK TESTER");
                         setLocation(toolXPosition, toolYPosition);
                         container.add(BorderLayout.NORTH, headingPanel);
                         container.add(BorderLayout.SOUTH, closingPanel);
                   JScrollPane scrollableTextPane;
                   textPane = new JTextPane();
                   //for detecting clicks
                   textPane.addMouseListener(new TextClickListener());
                   //for detecting motion
                   textPane.addMouseMotionListener(new TextMotionListener());
                   textPane.setEditable(false);
                   scrollableTextPane = new JScrollPane(textPane);
                   container.add(BorderLayout.CENTER, scrollableTextPane);
                   container.setVisible(true);
                   textPane.setText("");
                   doc = textPane.getStyledDocument();
                   Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
                   String url = "http://www.google.com";
                   //create the style for the hyperlink
                   Style regularBlue = doc.addStyle("regularBlue", def);
                   StyleConstants.setForeground(regularBlue, Color.BLUE);
                   StyleConstants.setUnderline(regularBlue,true);
                   regularBlue.addAttribute(LINK_ATTRIBUTE,new URLLinkAction(url));
                   Style bold = doc.addStyle("bold", def);
                   StyleConstants.setBold(bold, true);
                   StyleConstants.setForeground(bold, Color.GRAY);
                   doc.insertString(doc.getLength(), "\nStarting HyperLink Creation in a document\n\n", bold);
                   doc.insertString(doc.getLength(), "\n",bold);
                   doc.insertString(doc.getLength(),url,regularBlue);
                   doc.insertString(doc.getLength(), "\n\n\n", bold);
                   textPane.setCaretPosition(0);
              catch (Exception e) {
         public static void main(String[] args) {
              Hyperlink hp = new Hyperlink();
              hp.setVisible(true);
         private class TextClickListener extends MouseAdapter {
                 public void mouseClicked( MouseEvent e ) {
                  try{
                      Element elem = doc.getCharacterElement(textPane.viewToModel(e.getPoint()));
                       AttributeSet as = elem.getAttributes();
                       URLLinkAction fla = (URLLinkAction)as.getAttribute(LINK_ATTRIBUTE);
                      if(fla != null)
                           fla.execute();
                  catch(Exception x) {
                       x.printStackTrace();
         private class TextMotionListener extends MouseInputAdapter {
              public void mouseMoved(MouseEvent e) {
                   Element elem = doc.getCharacterElement( textPane.viewToModel(e.getPoint()));
                   AttributeSet as = elem.getAttributes();
                   if(StyleConstants.isUnderline(as))
                        textPane.setCursor(new Cursor(Cursor.HAND_CURSOR));
                   else
                        textPane.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
         private class URLLinkAction extends AbstractAction{
              private String url;
              URLLinkAction(String bac)
                   url=bac;
                 protected void execute() {
                          try {
                               String osName = System.getProperty("os.name").toLowerCase();
                              Runtime rt = Runtime.getRuntime();
                        if (osName.indexOf( "win" ) >= 0) {
                                   rt.exec( "rundll32 url.dll,FileProtocolHandler " + url);
                                    else if (osName.indexOf("mac") >= 0) {
                                      rt.exec( "open " + url);
                              else if (osName.indexOf("ix") >=0 || osName.indexOf("ux") >=0 || osName.indexOf("sun") >=0) {
                                   String[] browsers = {"epiphany", "firefox", "mozilla", "konqueror",
                                     "netscape","opera","links","lynx"};
                                   // Build a command string which looks like "browser1 "url" || browser2 "url" ||..."
                                   StringBuffer cmd = new StringBuffer();
                                   for (int i = 0 ; i < browsers.length ; i++)
                                        cmd.append((i == 0  ? "" : " || " ) + browsers[i] +" \"" + url + "\" ");
                                   rt.exec(new String[] { "sh", "-c", cmd.toString() });
                   catch (Exception ex)
                        ex.printStackTrace();
                 public void actionPerformed(ActionEvent e){
                         execute();
    }Here , what I have done is associated a mouseListener and a mouseMotionListener with the JTextPane and I have created the hyperlink look with a Style of blue color and underline and have added the LINK_ATTRIBUTE to that Style which takes care of listening to mouse clicks and mouse motion.
    The browser can be started in windows using the default FileProtocolHandler using rundll32 and in Unix/Sun we have to take a wild guess at which browser could be installed , the first browser encountered is started , in Mac open command takes care of starting the browser.
    Hope this is useful.

  • Length of a string (text) in pixels.

    I'm trying to locate a String's center on an exact position, drawing it to a JPanel. But since i don't know the exact length of the string, it's not that easy. Can anybody help me out there?

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class CenteringStrings
        public static void main(String[] args)
            StringDemoPanel demo = new StringDemoPanel();
            DemoActionPanel action = new DemoActionPanel(demo);
            JFrame f = new JFrame("Centering Strings");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(action, "East");
            f.getContentPane().add(demo);
            f.setSize(500,300);
            f.setLocation(200,200);
            f.setVisible(true);
    class StringDemoPanel extends JPanel
        String text;
        Font font;
        final int
            ASCENT   = 0,
            DESCENT  = 1,
            LEADING  = 2,
            BASELINE = 3;
        int index = -1;
        boolean sizeFlag, boundsFlag;
        public StringDemoPanel()
            text = "Centered text";
            font = new Font("lucida sans oblique", Font.PLAIN, 36);
            sizeFlag = false;
            boundsFlag = false;
            setBackground(Color.white);
        public void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setFont(font);
            FontRenderContext frc = g2.getFontRenderContext();
            LineMetrics lm = font.getLineMetrics(text, frc);
            TextLayout tl = new TextLayout(text, font, frc);
            int w = getWidth();
            int h = getHeight();
            float textWidth = (float)font.getStringBounds(text, frc).getWidth();
            float ascent  = lm.getAscent();
            float descent = lm.getDescent();
            float leading = lm.getLeading();
            float height  = lm.getHeight();
            float x = (w - textWidth)/2;
            float y = (h + height)/2 - descent;
            g2.drawString(text, x, y);
            // marker for string origin (x,y) on baseline
            //g2.setPaint(Color.blue);
            //g2.fill(new Ellipse2D.Double(x - 1, y - 1, 2, 2));
            // physical space of text
            Rectangle2D textSize = tl.getBounds();
            textSize.setFrame(x, y - textSize.getHeight(),
                              textSize.getWidth(), textSize.getHeight());
            // string bounds
            Rectangle2D bounds = font.getStringBounds(text, frc);
            bounds.setFrame(x, y - ascent - leading, bounds.getWidth(), bounds.getHeight());
            switch(index)
                case ASCENT:
                    Rectangle2D r1 = new Rectangle2D.Double(x, y - ascent, textWidth, ascent);
                    g2.setPaint(Color.magenta);
                    g2.draw(r1);
                    break;
                case DESCENT:
                    Rectangle2D r2 = new Rectangle2D.Double(x , y, textWidth, descent);
                    g2.setPaint(Color.orange);
                    g2.draw(r2);
                    break;
                case LEADING:
                    Rectangle2D r3 = new Rectangle2D.Double(x, y - ascent - leading,
                                                            textWidth, leading);
                    g2.setPaint(Color.yellow);
                    g2.draw(r3);
                    break;
                case BASELINE:
                    Line2D line = new Line2D.Double(x, y, x + textWidth, y);
                    g2.setPaint(Color.blue);
                    g2.draw(line);
            if(sizeFlag)
                g2.setPaint(Color.green);
                g2.draw(textSize);
                System.out.println("above size = " + (int)textSize.getY() + "\n" +
                                   "below size = " +
                                   (int)(h - (textSize.getY() + textSize.getHeight())));
            if(boundsFlag)
                g2.setPaint(Color.red);
                g2.draw(bounds);
                System.out.println("above bounds = " + (int)bounds.getY() + "\n" +
                                   "below bounds = " +
                                   (int)(h - (bounds.getY() + bounds.getHeight())));
        public void setIndex(int i)
            index = i;
            repaint();
        public void setSizeFlag(boolean flag)
            sizeFlag = flag;
            repaint();
        public void setBoundsFlag(boolean flag)
            boundsFlag = flag;
            repaint();
    class DemoActionPanel extends JPanel
        StringDemoPanel sdp;
        JRadioButton
            ascentButton, descentButton, leadingButton, baselineButton, clearButton;
        JRadioButton[] buttons;
        JCheckBox
            sizeCheck, boundsCheck;
        JCheckBox[] checks;
        public DemoActionPanel(StringDemoPanel p)
            sdp = p;
            createComponents();
        private void createComponents()
            ascentButton   = new JRadioButton("ascent");
            descentButton  = new JRadioButton("descent");
            leadingButton  = new JRadioButton("leading");
            baselineButton = new JRadioButton("baseline");
            clearButton    = new JRadioButton("clear");
            buttons = new JRadioButton[] {
                ascentButton, descentButton, leadingButton, baselineButton, clearButton
            ButtonGroup group = new ButtonGroup();
            RadioButtonListener buttonListener = new RadioButtonListener();
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weighty = 1.0;
            gbc.insets = new Insets(2,2,2,2);
            gbc.gridwidth = gbc.REMAINDER;
            gbc.anchor = gbc.WEST;
            for(int i = 0; i < buttons.length; i++)
                add(buttons, gbc);
    group.add(buttons[i]);
    buttons[i].addActionListener(buttonListener);
    sizeCheck = new JCheckBox("text size");
    boundsCheck = new JCheckBox("bounds");
    checks = new JCheckBox[] { sizeCheck, boundsCheck };
    CheckBoxListener checkBoxListener = new CheckBoxListener();
    for(int i = 0; i < checks.length; i++)
    add(checks[i], gbc);
    checks[i].addActionListener(checkBoxListener);
    private class RadioButtonListener implements ActionListener
    public void actionPerformed(ActionEvent e)
    JRadioButton button = (JRadioButton)e.getSource();
    if(button == clearButton)
    sdp.setIndex(-1);
    return;
    for(int i = 0; i < buttons.length; i++)
    if(button == buttons[i])
    sdp.setIndex(i);
    break;
    private class CheckBoxListener implements ActionListener
    public void actionPerformed(ActionEvent e)
    JCheckBox checkBox = (JCheckBox)e.getSource();
    if(checkBox == sizeCheck)
    sdp.setSizeFlag(sizeCheck.isSelected());
    if(checkBox == boundsCheck)
    sdp.setBoundsFlag(boundsCheck.isSelected());

  • Cannot assign an empty string to a parameter with JDBC type VARCHAR

    Hi,
    I am seeing the aforementioned error in the logs. I am guessing its happening whenever I am starting an agent instance in PCo. Can somebody explain whats going on?
    Regards,
    Chanti.
    Heres the complete detail from logs -
    Log Record Details   
    Message: Unable to retreive path for , com.sap.sql.log.OpenSQLException: Failed to set the parameter 1 of the statement >>SELECT ID, PARENTID, FULLPATH, CREATED, CREATEDBY, MODIFIED, MODIFIEDBY, REMOTEPATH, CHECKEDOUTBY FROM XMII_PATHS WHERE FULLPATH =  ?  <<: Cannot assign an empty string to a parameter with JDBC type >>VARCHAR<<.
    Date: 2010-03-12
    Time: 11:32:37:435
    Category: com.sap.xmii.system.FileManager
    Location: com.sap.xmii.system.FileManager
    Application: sap.com/xappsxmiiear

    Sounds like a UI browsing bug (when no path is selected from a catalog tree folder browser) - I would suggest logging a support ticket so that it can be addressed.

  • Problems with string comparison and\or If statement

    Right now I'm trying to make a program that will look into all of my music folders, and rename the .mp3 files to a format i want, based on the id3 tags. The program so far looks in all of the folders I want it to, but I get stuck when I need to check if the files are .mp3 files or not. Here is my code so far:
    package fileRenamer;
    import java.io.File;
    public class FileRenamer {
    public static void main(String[] argv) {
         File artistsFolders = new File("F:/Music (MP3)");
         File[] artists = artistsFolders.listFiles();
         for(int i = 0; i < artists.length; i++){
              if(artists.isFile()) {
                   System.out.println(artists[i].getName());
         } else if (artists[i].isDirectory()) {
              System.out.println(artists[i].getName());
              File albumsFolders = new File("F:/Music (MP3)/"+artists[i].getName());
              File[] albums = albumsFolders.listFiles();
              for(int a = 0; a < albums.length; a++){
                   if(albums[a].isFile()) {
                        System.out.println("-" + albums[a].getName());
                   } else if (albums[a].isDirectory()) {
                        System.out.println("-" + albums[a].getName());
                   File songsFolders = new File("F:/Music (MP3)/"+artists[i].getName()+"/"+albums[a].getName());
                   File[] songs = songsFolders.listFiles();
                   for(int s = 0; s < songs.length; s++){
                        if(songs[s].isFile()) {
                             int dotPos = songs[s].getName().toString().lastIndexOf(".");
                             String extension = songs[s].getName().toString().substring(dotPos);
                             System.out.println(extension);
                             if(extension == ".mp3"){
                                  System.out.println("--" + songs[s].getName());
                   } else if (songs[s].isDirectory()) {
                             System.out.println("--" + songs[s].getName());
    When I test the code, the line System.out.println(extension); prints .mp3 into the console for all of the .mp3 files. Whatever I try, the if(extension == ".mp3") never seems to declare the two equal. If anyone knows what my problem is, I greatly appreciate the advice and help.
    Thanks in Advance,
    James

    Pojo226 wrote:
    I just tried that and it worked perfectly. Thanks.You're welcome.

  • Oracle, Null and empty Strings

    Currently I'm facing problems with a class, which contains a String, which
    is set to "" (empty String).
    When the class is persistent, oracle writes null to the table column
    (which seems to be common oracle behaviour) and when retrieving the class,
    the field is set to null as well, giving me a lot of null-pointer
    exceptions.
    Anyway ... I can cope with that (just a lot of extra work)
    far worse is the problem, wenn searching objects, that have this field set
    to "" oder null.
    Oracle can't find the records because JDO creates Querys "where
    string=null" or "where string=''" , where oracle expects "where string is
    null" to find the records.
    Is there a workaround or solution ?

    Yeah, that would work as well, thx, but since I have to cope with
    null-Strings now everywhere in my program, it doesn't hurt just to forbid
    empty strings on the program side.
    In future times I'll test on Oracle first, then porting to DB/2 - this way
    I suppose work is far less to garant compability.
    Nevertheless ... having to set the bankcode into quotes is a kodo bug in
    my opinion.
    Kodo knows the type of classfields (in this case string) and shouldn't
    send the parameter as a BigDecimal to the database.
    Given that, and having only bankcodes of null (only neccesary when using
    Oracle), the method would look like:
    public Collection getAccounts (String bankCode)
    throws Exception
    return getAccounts (Account.class, "bankcode=="+bankcode);
    which is how a transparent persistent layer, um, should be , um , I mean
    ... just transparent ;-D
    Marc Prud'hommeaux wrote:
    Stefan-
    Couldn't you just do something like:
    public Collection getAccounts (String bankCode)
    throws Exception
    String filter;
    if (bankCode == null || bankCode.length () == 0)
    filter = "(bankCode == null || bankCode == "")";
    else
    filter = "bankCode == "" + bankCode + """;
    return getAccounts (Account.class, filter);
    If I understand the problem correctly, this should work for all the
    databases.
    In article <[email protected]>, Stefan wrote:
    What operations are you performing to cause this SQL to be issued? You
    say you are having trouble removing objects, but this is clearly not a
    DELETE statement. Is this the SQL that is issued when looking up
    objects by identity?I'm not removing objects, I was removing just quotes from parameters ;-)
    A string column... is it also represented as a string field in your class?Yeah ... just to give you an impression of the code:
    First we have a class, representing a bank account:
    public class Account {
    private AccountMgr myAccountMgr;
    private String bankCode;
    private String id;
    Note, that in nearly all cases bankCode will be a number or null.
    I have a second class "AccountMgr", which does all of the persistant stuff
    (seaching, making persistent etc.)
    This class has two methods, one versatile (protected) to retrieve accounts
    by a given filterString and one who just returns accounts by bankCode,
    building the expected filterstring. Here is my current working version:
    public class AccountMgr {
    public Collection getAccounts(String bankCode) throws Exception {
    if (bankCode!=null) {
    if (bankCode.equals("")) {
    throw new Exception("check code, bankCode='' not allowed to get
    same behavior from DB2 and Oracle");
    // if set, quote the bankCode
    bankCode="""+bankCode+""";
    return getAccounts(Account.class,"bankCode=="+bankCode);
    protected Collection getAccounts(Class accountClass, String filterAdd)
    throws Exception {
    PersistenceManager pm = MyHelper.getPersistenceManager();
    String filter="";
    if (filterAdd!=null && !filterAdd.trim().equals("")) {
    filter+=filterAdd + " && ";
    filter += "myAccountMgr==_accMgr";
    Query query = pm.newQuery(accountClass, filter);
    query.declareParameters("AccountMgr _accMgr");
    return (Collection) query.execute(this);
    As you can see, in the first method I have to set the bankCode into
    quotes, when it's not null.
    This is because otherwise a filter like "bankCode=1234" will be translated
    in a way, where 1234 is send as a BigDecimal to the database:
    [...] executing statement <4239745>: (SELECT [...] FROM JDO_ACCOUNT t0
    WHERE t0.BANKCODE = ? : [reused=1;params={(BigDecimal) 1234}]
    Marc Prud'hommeaux [email protected]
    SolarMetric Inc. http://www.solarmetric.com

  • NULL and Empty String

    Hi There,
    As far as I know, Null is not the same as an empty string; however, when I try this out, I get some unexpected results (well, at least unexpected for my liking):
    SQL> CREATE TABLE TS (MID NUMBER,
      2  MDESC VARCHAR2(20) DEFAULT '' NOT NULL);
    Table created.
    SQL> INSERT INTO TS VALUES(1,'');
    INSERT INTO TS VALUES(1,'')
    ERROR at line 1:
    ORA-01400: cannot insert NULL into ("TT"."TS"."MDESC")So, according to the above scenario, I can't insert an empty string!! However, an empty string is a valid string that doesn't have tuples/data!!
    How come Oracle translates the null string '' as NULL?
    Thanks

    William Robertson wrote:
    There is a special case to do with CHAR values, whereby '' counts as a string and so gets blank-padded, whereas NULL does not.Are you referring to:
    SQL> DECLARE
      2      flag CHAR(2);
      3      PROCEDURE check_null (p_flag IN CHAR)
      4      IS
      5      BEGIN
      6        IF p_flag = '  '
      7        THEN
      8          dbms_output.put_line ('flag is equal to ''  ''');
      9        ELSIF p_flag IS NULL
    10        THEN
    11          dbms_output.put_line ('flag is null');
    12        ELSE
    13          dbms_output.put_line ('other');
    14        END IF;
    15      END;
    16    BEGIN
    17      flag := '';
    18      check_null (flag);
    19      flag := NULL;
    20      check_null (flag);
    21    end;
    22  /
    flag is equal to '  '
    flag is null
    PL/SQL procedure successfully completed.
    SQL> alter session set events '10932 trace name context forever, level 16384';
    Session altered.
    SQL> DECLARE
      2      flag CHAR(2);
      3      PROCEDURE check_null (p_flag IN CHAR)
      4      IS
      5      BEGIN
      6        IF p_flag = '  '
      7        THEN
      8          dbms_output.put_line ('flag is equal to ''  ''');
      9        ELSIF p_flag IS NULL
    10        THEN
    11          dbms_output.put_line ('flag is null');
    12        ELSE
    13          dbms_output.put_line ('other');
    14        END IF;
    15      END;
    16    BEGIN
    17      flag := '';
    18      check_null (flag);
    19      flag := NULL;
    20      check_null (flag);
    21    end;
    22  /
    flag is null
    flag is null
    PL/SQL procedure successfully completed.
    SQL> SY.
    P.S. Don't ask me why normal (or at least consistent) behavior is not the default.

  • Null and empty string not being the same in object?

    Hello,
    I know that null and empty string are interpreted the same in oracle.
    However I discovered the strange behaviour concerning user defined objects:
    create or replace
    TYPE object AS OBJECT (
    value VARCHAR2(2000)
    declare
    xml xmltype;
    obj object;
    begin
    obj := object('abcd');
    xml := xmltype(obj);
    dbms_output.put_line(xml.getStringVal());
    obj.value := '';
    xml := xmltype(obj);
    dbms_output.put_line(xml.getStringVal());
    obj.value := null;
    xml := xmltype(obj);
    dbms_output.put_line(xml.getStringVal());
    end;
    When creating xml from object, all not-null fields are transformed into xml tag.
    I supposed that obj.value being either '' or null will lead to the same result.
    However this is output from Oracle 9i:
    <OBJECT_ID><VALUE>abcd</VALUE></OBJECT_ID>
    <OBJECT_ID><VALUE></VALUE></OBJECT_ID>
    <OBJECT_ID/>
    Oracle 10g behaves as expected:
    <OBJECT><VALUE>abcd</VALUE></OBJECT>
    <OBJECT/>
    <OBJECT/>
    However Oracle 9i behaviour leads me to the conclusion that oracle
    must somehow distinguish between empty string and null in user defined objects...
    Can someone clarify this behaviour?
    Thus is it possible to test if object's field is empty or null?

    However Oracle 9i behaviour leads me to the conclusion that oracle
    must somehow distinguish between empty string and null in user defined objects...
    Can someone clarify this behaviour?
    Thus is it possible to test if object's field is empty or null?A lot of "fixes" were done, relating to XML in 10g and the XML functionality of 9i was known to be buggy.
    I think you can safely assume that null and empty strings are treated the same by Oracle regardless. If you're using anything less than 10g, it's not supported any more anyway, so upgrade. Don't rely on any assumptions that may appear due to bugs.

  • Difference in Null and Empty String

    Hi,
    I have been wondering about the difference between Null and Empty String in Java. So I wrote a small program like this:
    public class CompareEmptyAndNullString {
         public static void main(String args[]) {
              String sNull = null;
              String sEmpty = "";
              try {
                   if (sNull.equalsIgnoreCase(sEmpty)) {
                        System.out.println("Null and Empty Strings are Equal");
                   } else {
                        System.out.println("Null and Empty Strings are Equal");
              } catch (Exception e) {
                   e.printStackTrace();
    This program throws Exception: java.lang.NullPointerException
         at practice.programs.CompareEmptyAndNullString.main(CompareEmptyAndNullString.java:10)
    Now if I change the IF Clause to if (sEmpty.equalsIgnoreCase(sNull)) then the Program outputs this: Null and Empty Strings are Equal
    Can anyone explain why this would happen ?
    Thanks in Advance !!

    JavaProwler wrote:
    Saish,
    Whether you do any of the following code, the JUnit Test always passes: I mean he NOT Sign doesnt make a difference ...
    assert (! "".equals(null));
    assert ("".equals(null));
    You probably have assertions turned off. Note the the assert keyword has nothing to do with JUnit tests.
    I think that older versions of JUnit, before assert was a language keyword (which started in 1.4 or 1.5), had a method called assert. Thus, if you have old-style JUnit tests, they might still compile, but the behavior is completely different from what it was in JUnit, and has nothing to do with JUnit at all.
    If you turn assertions on (-ea flag in the JVM command line, I think), the second one will throw AssertionError.

  • SSRS Report Returning Double Quote string from a Single Quote String

    Hi, I'm getting weird thing in resultset from SSRS report when executed. When I pass parameter to a report, which passes String that has single quote value to a split function , it returns rows with double quote. 
    For example  following string:
    'N gage, Wash 'n Curl,Murray's, Don't-B-Bald
    Returns: 
    ''N gage, Wash ''n Curl,Murray''s, Don''t-B-Bald
    through SSRS report.
    Here is the split function Im using in a report.
    CREATE Function [dbo].[fnSplit] (
    @List varchar(8000), 
    @Delimiter char(1)
    Returns @Temp1 Table (
    ItemId int Identity(1, 1) NOT NULL PRIMARY KEY , 
    Item varchar(8000) NULL 
    As 
    Begin 
    Declare @item varchar(4000), 
    @iPos int 
    Set @Delimiter = ISNULL(@Delimiter, ';' ) 
    Set @List = RTrim(LTrim(@List)) 
    -- check for final delimiter 
    If Right( @List, 1 ) <> @Delimiter -- append final delimiter 
    Select @List = @List + @Delimiter -- get position of first element 
    Select @iPos = Charindex( @Delimiter, @List, 1 ) 
    While @iPos > 0 
    Begin 
    -- get item 
    Select @item = LTrim( RTrim( Substring( @List, 1, @iPos -1 ) ) ) 
    If @@ERROR <> 0 Break -- remove item form list 
    Select @List = Substring( @List, @iPos + 1, Len(@List) - @iPos + 1 ) 
    If @@ERROR <> 0 Break -- insert item 
    Insert @Temp1 Values( @item ) If @@ERROR <> 0 Break 
    -- get position pf next item 
    Select @iPos = Charindex( @Delimiter, @List, 1 ) 
    If @@ERROR <> 0 Break 
    End 
    Return 
    End
    FYI: I'm getting @List value from a table and passing it as a string to split function. 
    Any help would be appreciated!
    ZK

    Another user from TSQL forum posted this code which is returning the same resultset but when I execute both codes in SQL server it works and return single quote as expected.
    https://social.msdn.microsoft.com/Forums/sqlserver/en-US/8d5c96f5-c498-4f43-b2fb-284b0e83b205/passing-string-which-has-single-quote-rowvalue-to-a-function-returns-double-quoate?forum=transactsql
    CREATE FUNCTION dbo.splitter(@string VARCHAR(MAX), @delim CHAR(1))
    RETURNS @result TABLE (id INT IDENTITY, value VARCHAR(MAX))
    AS
    BEGIN
    WHILE CHARINDEX(@delim,@string) > 0
    BEGIN
    INSERT INTO @result (value) VALUES (LEFT(@string,CHARINDEX(@delim,@string)-1))
    SET @string = RIGHT(@string,LEN(@string)-CHARINDEX(@delim,@string))
    END
    INSERT INTO @result (value) VALUES (@string)
    RETURN
    END
    GO
    ZK

  • How can I convert an int to a string?

    Hi
    How can I convert an int to a string?
    /ad87geao

    Here is some the code:
    public class GUI
        extends Applet {
      public GUI() { 
        lastValue = 5;
        String temp = Integer.toString(lastValue);
        System.out.println(temp);
        showText(temp);
      private void showText(final String text) {
        SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            tArea2.setText(text + "\n");
    }

  • No calendar change for a single event in a recurrring string of events

    Why won't iCal allow me to change the calendar for a single event in a string of recurring events? Why am I not allowed this, but can change other details and even get prompted whether I want these changes to take effect over the single event or all the recurring events????
    Could this be implemented in a future version of iCal???
    Thanks.

    How are you making the .ics file? What value has the METHOD: entry?
    AK

Maybe you are looking for