ObjectInputStream returns a wrong boolean value of a object

ObjectOutputStream.writeObject once, then change the boolean value of the Contact object, ObjectOutputStream.writeObject again, but when ObjectInputStream.readObject, it returns SAME boolean values which should be different. can somebody explain me this? please. thx
   1. import java.io.*; 
   2. import java.util.*; 
   3.  
   4. public class TestSerializable { 
   5.      
   6.     /** Creates a new instance of TestSerializable */ 
   7.     public static void main(String args[]){ 
   8.         new TestSerializable(); 
   9.     } 
  10.      
  11.     public TestSerializable() { 
  12.         try{ 
  13.             Contact contact = new Contact("email","group",1); // contact.isOnline = true for default; 
  14.              
  15.             FileOutputStream fos = new FileOutputStream("ser"); 
  16.             ObjectOutputStream oos = new ObjectOutputStream(fos); 
  17.  
  18.             oos.writeObject(contact); 
  19.              
  20.             contact.setOnline(false); 
  21.             oos.writeObject(contact); 
  22.  
  23.             oos.flush(); 
  24.  
  25.              
  26.             FileInputStream fis = new FileInputStream("ser"); 
  27.             ObjectInputStream ois = new ObjectInputStream(fis); 
  28.             Contact ccRead1 = (Contact)ois.readObject(); 
  29.             Contact ccRead2 = (Contact)ois.readObject(); 
  30.              
  31.             System.out.println("ccRead1.isOnline() = "+ccRead1.isOnline()); 
[u]  32.             System.out.println("ccRead2.isOnline() = "+ccRead2.isOnline() + " which should be FALSE. ERROR");  [/u]
  33.                        
  34.             oos.close(); 
  35.             ois.close(); 
  36.              
  37.         } 
  38.         catch(Exception e){ 
  39.             e.printStackTrace(); 
  40.         } 
  41.          
  42.     } 
  43.      
  44. } 
  45.  
  46.  
  47.  
  48.  
  49.  
  50. import javax.swing.tree.DefaultMutableTreeNode; 
  51. import javax.swing.tree.*; 
  52. import java.util.*; 
  53.  
  54. public class Contact extends DefaultMutableTreeNode { 
  55.      
  56.     private String email; 
  57.     private int arrayIndex; 
  58.     private String group; 
  59.     private boolean online; 
  60.      
  61.   
  62.     public Contact(String email,String group,int arrayIndex, boolean online){ 
  63.         this.email = email; 
  64.         this.group = group; 
  65.         this.setArrayIndex(arrayIndex); 
  66.         this.setOnline(online); 
  67.         this.setUserObject(this); 
  68.         this.setAllowsChildren(false);         
  69.     } 
  70.      
  71.     public Contact(String email, String group){ 
  72.         this(email,group,-1,false); 
  73.     } 
  74.      
  75.     public Contact(String email, String group, int arrayIndex){ 
  76.         this(email,group,arrayIndex,true); 
  77.     } 
  78.      
  79.  
  80.      
  81.     public String toString(){ 
  82.         return this.email; 
  83.     } 
  84.  
  85.     public String getEmail() { 
  86.         return email; 
  87.     } 
  88.  
  89.     public int getArrayIndex() { 
  90.         return arrayIndex; 
  91.     } 
  92.  
  93.     public String getGroup() { 
  94.         return group; 
  95.     } 
  96.  
  97.     public boolean isOnline() { 
  98.         return online; 
  99.     } 
100.  
101.     public void setOnline(boolean online) { 
102.         this.online = online; 
103.     } 
104.  
105.     public void setArrayIndex(int arrayIndex) { 
106.         this.arrayIndex = arrayIndex; 
107.     } 
108.  
109.      
110. } 

Did you try the reset() technique again?
You could also have a look at ObjectOutputStream.writeUnshared().
And it's not returning a 'wrong value', it is conserving the object graph of the original object sent, which is what it's specified to do and what it's supposed to do. If you don't want that behaviour use reset() or writeUnshared().

Similar Messages

  • AudiCLip.play should return a boolean value

    Java Experts,
    looks like it's a bug in java, the audioClip.play method should return a boolean value indicating whether it was able to play the clip or not. Because sometimes the method doesn't play anything. Right now the method plays asynchronously that may be the reason that it returns a void. Thoughts???
    Q.

    i agree with you..i also encountered this problem sometimes the play method doesn't play and the programmer has no clue to figure this out programmetically...Looks like this problem has no solution..where are java experts in this forum??

  • SXPG_COMMAND_EXECUTE  return wrong parameter value

    Dear all.
    We have an Abap program that pulls an encrypted FTP file and saves it to our network.
    After that we activate an external command via transaction SM69 by calling FM SXPG_COMMAND_EXECUTE.
    This command is an execution of a batch file that executes a decryption method via PGP decryption software.
    The problem is that we get an output parameter of this FM (STATUS) as u201CEu201D (error) although the decryption is being executed successfully.
    We have the same process being activated same way successfully with another folders (rest is exactly the same).
    Why does SXPG_COMMAND_EXECUTE return wrong status value ?
    Regards,
    Rebeka

    SXPG_COMMAND_EXECUTE runs under certain operating system user account. Looks like that account does not have enough privileges to do what you want it to do. Look at the operating system for privileges (read,write,execute) of the user account SAPServiceuser or equivalent.
    /Simo

  • JTable.getSelectedRow seems to return wrong index value in J2SDK 1.4

    OS version: Microsoft Windows 2000 [Version 5.00.2195]
    JDK version: J2RE, Standard Edition (build 1.4.2_07-b05)
    I have a pretty simple JTable in which when a user selects a particular value in the first column of a row, the remainder of the columns in that row are populated with text values. The way we tell the JTable which row to populate the column values for is via the getSelectedRow() method. This worked fine using 1.3.1.08. However, when we upgraded to 1.4.2.07, we get an ArrayIndexOutOfBoundsException thrown because for some reason the getSelectedRow method returns the wrong value (e.g. if the user selects the first row, instead of returning an index of 0, the method returns an index of 2, even if there is only 1 row in the table, thus the out-of-bounds). The code has not changed at all -- all we have done is upgrade the version of the JDK. I have seen similar issues on various postings on the web, but these all have to do with removing rows and the like, and having to cancel or stop cell editing before removing the row(s). However, this does not apply in my case, so I think this might be a new bug. Before I post all kinds of code, does anybody know if this is a known bug and/or is there a workaround?
    Here is my stack trace:
    In Thread[AWT-EventQueue-0,6,main]
    caught java.lang.ArrayIndexOutOfBoundsException: 2 >= 2
         at java.util.Vector.elementAt(Vector.java:431)
         at javax.swing.table.DefaultTableModel.setValueAt(DefaultTableModel.java:633)
         at com.sra.kdd.tools.view.NtwrkDefnVW.propertyChange(NtwrkDefnVW.java:475)
         at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:330)
         at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:257)
         at com.sra.kdd.tools.model.NtwrkSourceDSMDL.setDsNM(NtwrkSourceDSMDL.java:298)
         at com.sra.kdd.tools.view.NtwrkCTRL.handleSourceTableEvent(NtwrkCTRL.java:464)
         at com.sra.kdd.tools.view.NtwrkCTRL.tableChanged(NtwrkCTRL.java:120)
         at javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableModel.java:280)
         at javax.swing.table.AbstractTableModel.fireTableCellUpdated(AbstractTableModel.java:259)
         at javax.swing.table.DefaultTableModel.setValueAt(DefaultTableModel.java:635)
         at javax.swing.JTable.setValueAt(JTable.java:1794)
         at javax.swing.JTable.editingStopped(JTable.java:3167)
         at javax.swing.AbstractCellEditor.fireEditingStopped(AbstractCellEditor.java:124)
         at javax.swing.DefaultCellEditor$EditorDelegate.stopCellEditing(DefaultCellEditor.java:329)
         at javax.swing.DefaultCellEditor$3.stopCellEditing(DefaultCellEditor.java:139)
         at javax.swing.DefaultCellEditor.stopCellEditing(DefaultCellEditor.java:214)
         at javax.swing.DefaultCellEditor$EditorDelegate.actionPerformed(DefaultCellEditor.java:346)
         at javax.swing.JComboBox.fireActionEvent(JComboBox.java:1197)
         at javax.swing.JComboBox.setSelectedItem(JComboBox.java:561)
         at javax.swing.JComboBox.setSelectedIndex(JComboBox.java:597)
         at javax.swing.plaf.basic.BasicComboPopup$ListMouseHandler.mouseReleased(BasicComboPopup.java:749)
         at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:232)
         at java.awt.Component.processMouseEvent(Component.java:5100)
         at javax.swing.plaf.basic.BasicComboPopup$2.processMouseEvent(BasicComboPopup.java:452)
         at java.awt.Component.processEvent(Component.java:4897)
         at java.awt.Container.processEvent(Container.java:1569)
         at java.awt.Component.dispatchEventImpl(Component.java:3615)
         at java.awt.Container.dispatchEventImpl(Container.java:1627)
         at java.awt.Component.dispatchEvent(Component.java:3477)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3483)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3198)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3128)
         at java.awt.Container.dispatchEventImpl(Container.java:1613)
         at java.awt.Window.dispatchEventImpl(Window.java:1606)
         at java.awt.Component.dispatchEvent(Component.java:3477)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:456)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)
    I do have a workaround -- this is definitely not a recommended workaround whatsoever, but it's what I've done just to get by for now, so I thought it might possibly shed some light into the problem. It seems that the index is always off by 2, so I just subtract 2 from the result of getSelectedRow() and then everything works just fine.
    Any ideas? Thank you!

    If I remember correctly there was a big change in the focus subsystem between JDK1.3 and JDK1.4
    Before I post all kinds of code,...Write a 10 line demo program that shows this behaviour. We aren't interested in all kinds of code. If you can't duplicate the problem in 10 lines of code, then the problem is with the rest of your code. So compare you demo code to see why its working and your current code to see why its not working.

  • FM returns wrong total value for Limit type PO's

    Hi all,
    I am working on SRM 5.0 (SP13) ECS.
    I have implemented the BADI "BBP_WFL_APPROVAL_BADI" for determining the Approvers for PO whenevr a PO is changed.If the diference between the Old PO value and new PO value is > 1000 and the approval text field(custom text under "Documents" link) is set to "YES",then the WF approval is required and the approvers are determined.
    The above logic works fine for the Standard type PO's where the difference between the old value and new value is determined using FM "BBP_PD_PO_GETDETAIL"  by passing the GUID (for the change version and the active vesion) obtained at runtime in the BADI.
    However for the limit type PO's,whenevr I change the total value for the Limit item,I see that the FM "BBP_PD_PO_GETDETAIL" doesnt return the changed value but  always returns blank!
    Bcause I need to check bth the values i.e. Custom text set to "YES" as well as Total value diff ,I cant use the start conditions in tcode SWB_COND.ALso I need to fetch the approvers based on the price diff so I need this value at runtime in the BADI using the FM "BBP_PD_PO_GETDETAIL".
    Please advise why the FM is not returning the changed values for the Limit type PO and is there any other way(other table/FM) to get the changed value at runtime for the LIMIT type PO.
    Thanks for your time.
    Edited by: Rads1234 on Nov 18, 2010 4:39 AM

    Thanks for the rpely.
    Yes.I am using the GUID available at runtime in the  BADI "BBP_WFL_APPROV_BADI" which is the current change version GUID.I tried using that GUID to get the data from both FM as well as CDHDR and CDPOS tables.
    I think this is something related to LImit type PO because for Standard type PO's the FM returns the corretc changed value (as in the screen) for the change version GUID.I fail to understand why the changed values are shwon on the screen but are not stored anywhere in the system before actually ordering the PO!

  • Cell with boolean value not rendering properly in Swing (custom renderer)

    Hello All,
    I have a problem rendenring boolean values when using a custom cell renderer inside a JTable; I managed to reproduce the issue with a dummy application. The application code follows:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.lang.reflect.InvocationTargetException;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import java.util.logging.Logger;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.SwingUtilities;
    * Simple GUI that uses custom cell rendering
    * @author josevnz
    public final class SimpleGui extends JFrame {
         private static final long serialVersionUID = 1L;
         private Logger log = Logger.getLogger(SimpleGui.class.getName());
         private JTable simpleTable;
         public SimpleGui() {
              super("Simple GUI");
              setPreferredSize(new Dimension(500, 500));
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setLayout(new BorderLayout());
         public void constructGui() {
              simpleTable = new JTable(new SimpleTableModel());
              simpleTable.getColumnModel().getColumn(2).setCellRenderer(new HasItCellRenderer());
              SpecialCellRenderer specRen = new SpecialCellRenderer(log);
              simpleTable.setDefaultRenderer(Double.class, specRen);
              simpleTable.setDefaultRenderer(String.class, specRen);
              simpleTable.setDefaultRenderer(Date.class, specRen);
              //simpleTable.setDefaultRenderer(Boolean.class, specRen);
              add(new JScrollPane(simpleTable), BorderLayout.CENTER);          
              pack();
              setVisible(true);
         private void populate() {
              List <List<Object>>people = new ArrayList<List<Object>>();
              List <Object>people1 = new ArrayList<Object>();
              people1.add(0, "Jose");
              people1.add(1, 500.333333567);
              people1.add(2, Boolean.TRUE);
              people1.add(3, new Date());
              people.add(people1);
              List <Object>people2 = new ArrayList<Object>();
              people2.add(0, "Yes, you!");
              people2.add(1, 100.522222);
              people2.add(2, Boolean.FALSE);
              people2.add(3, new Date());
              people.add(people2);
              List <Object>people3 = new ArrayList<Object>();
              people3.add(0, "Who, me?");
              people3.add(1, 0.00001);
              people3.add(2, Boolean.TRUE);
              people3.add(3, new Date());
              people.add(people3);
              List <Object>people4 = new ArrayList<Object>();
              people4.add(0, "Peter Parker");
              people4.add(1, 11.567444444);
              people4.add(2, Boolean.FALSE);
              people4.add(3, new Date());
              people.add(people4);
              ((SimpleTableModel) simpleTable.getModel()).addAll(people);
          * @param args
          * @throws InvocationTargetException
          * @throws InterruptedException
         public static void main(String[] args) throws InterruptedException, InvocationTargetException {
              final SimpleGui instance = new SimpleGui();
              SwingUtilities.invokeAndWait(new Runnable() {
                   @Override
                   public void run() {
                        instance.constructGui();
              instance.populate();
    }I decided to write a more specific renderer just for that column:
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.JTable;
    import javax.swing.UIManager;
    import javax.swing.table.DefaultTableCellRenderer;
    * Cell renderer used only by the DividendElement table
    * @author josevnz
    final class HasItCellRenderer extends DefaultTableCellRenderer {
         protected static final long serialVersionUID = 2596173912618784286L;
         private Color hasIt = new Color(255, 225, 0);
         public HasItCellRenderer() {
              super();
              setOpaque(true);
         @Override
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
              Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
              int desCol = table.convertColumnIndexToView(1);
              if (! isSelected && value instanceof Boolean && column == desCol) {
                   if (((Boolean) value).booleanValue()) {
                        comp.setForeground(hasIt);     
                   } else {
                        comp.setForeground(UIManager.getColor("table.foreground"));
              return comp;
          * Override for performance reasons
         @Override
         public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {
              // EMPTY
         @Override
         protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
              // EMPTY
         @Override
         public void revalidate() {
              // EMPTY
         @Override
         public void validate() {
              // EMPTY
    } // end classBut the rendering comes all wrong (a String saying true or false, not the expected checkbox from the default renderer) and also there is a weird flickring effect as this particular boolean column is editable (per table model, not show here)...
    I can post the table model and the other renderer if needed (didn't want to put too much code on the question, at least initiallty).
    Should I render a checkbox myself for this cell in the custom renderer? I'm puzzled as I expected the default renderer part of the code to do this for me instead.
    Thanks!
    Edited by: josevnz on Apr 14, 2009 12:35 PM
    Edited by: josevnz on Apr 14, 2009 12:37 PM

    camickr
    Thats because the default render is a JLabel and it just displays the text from the toString() method of the Object in the table model.What I meant to say is that I expected the JCheckbox not a String representation of the boolean value.
    Thats because a different renderer is used depending on the Class of data in the column. Look at the source code for the JTable class to see what the "default >renderer for the Boolean class" is. Then you can extend that or if its a private class then you will need to copy all the code and customize it.At the end I looked at the code and replicated the functionality I needed. I thought than maybe there was a way to avoid replicating the same logic all over again in order to implement this functionality. Good advice, though.
    see you learned nothing from your last posting. This is NOT a SSCCE. 90% of the code you posted is completely irrelevant for the described problem. There is abosutelly no need to post the custom TableModel, because there is no need to use a custom TableModel for this problem. The TableModel has nothing to do with how a column is rendererd.The custom table model returns the type of the column (giving a hint to the renderer on what to expect, right?) and for the one that had a problem it says than the class is Boolean. That's why I mentioned it:
    public Class getColumnClass(int columnIndex) {
        // Code omited....
    You also posted data for 4 columns worth of data. Again, irrelevant. Your question is about a single column containing Boolean data, so forget about the other columns.
    When creating a SSCCE you don't start with your existing code and "remove" code. You start with a brand new class and only add in what is important. That way hopefully if you made a mistake the first time you don't repeat it the second time.That's what I did, is not the real application. I copy & pasted code in a haste from this dummy program on this forum, not the best approach as it gave the wrong impression.
    Learn how to write a proper SSCCE if you want help in the future. Point taken, but there is NO need for you to be rude. Your help is appreciated.
    Regards,
    Jose.

  • Can oracle  function return more than one value

    Hi All
    please answer can oracle function return more than one value
    need one schenario
    regards

    Can any function, irrespective of the language, return multiple values?
    OF COURSE NOT!!
    So why do you think Oracle will now suddenly do it differently than all other languages? Never mind that it is impossible for a function (a unit/module of code) returning a memory address, to return multiple memory addresses. The machine code that does that, has not been yet been designed/implemented.
    I am continually amazed that this question is asked. It is about something so fundamental in almost every single 3rd and 4th generation language... something that is taught right at the start... the definition of what a procedure and what a function is.
    Sorry, but I simply cannot pull punches on this subject and smooth it over. There is something fundamentally wrong with your training as a programmer if you have to ask such a question about a function.
    And whatever programming skills you build on such a foundation, will be seriously lacking.
    I kindly suggest that you get back to the very basics of programming - and review and revisit until you fully understand it. There are no shortcuts in becomming a good programmer.
    Message was edited by:
    Billy Verreynne

  • Return value of Custom object in HashMap

    I have created a custom object (TableValue) that should represent the key value in aHashMap. When reading data from a file, the custom object should be either a String or a Double. I want the custom object to return the proper type. That is, I am trying to avoid the use of an Object as a key value in the HashMap. However, I want TableValue to return the proper value. Some example code is listed below. My question is this, how do I get TableValue to return the proper type?
    Thanks
    import java.util.HashMap;
    public class Table {
    HashMap<TableValue,Frequency>table=new HashMap<TableValue,Frequency>();
         public void count(TableValue aElement){
              Frequency fq=table.get(aElement);
              if(fq==null){
                   fq=new Frequency();
                   table.put(aElement, fq);
              }else{
                   fq.add();
         public double getCount(TableValue aElement){
              Frequency fq=table.get(aElement);
              if(fq==null){
                   return 0.0;
              }else{
                   return fq.getFrequency();
         public static void main(String[] args) {
              Table tab=new Table();
              tab.count(new TableValue("s"));
              tab.count(new TableValue(5.0));
    public class TableValue {
         private double dValue;
         private String sValue;
         private boolean isDouble=false;
         public TableValue(Object o){
              try{
                   if(o.getClass().getName().equals("java.lang.String")){
                        sValue=(String)o;
                   }else if(o.getClass().getName().equals("java.lang.Double")){
                        dValue=(Double)o;
              }catch(ClassCastException ex){
            //next two methods not correct, can not overload like this
         public double getValue(){
              //want to return a double
              return dValue;
         public String getValue(){
              //want to returna string
              return sValue;
    public class Frequency {
         private double total, cummulativeFrequency;
         public Frequency(){
              total = 1.0;
              cummulativeFrequency = 0.0;
         public void add(){
              total++;
              cummulativeFrequency++;
         public void addCummulativeFrequency(double aLowerCount){
              cummulativeFrequency += aLowerCount;
         public double getFrequency(){
              return total;
         public double getCummulativeFrequency(){
              return cummulativeFrequency;
    }

    OK, thanks to everyone for your help. Here is what I have done. I added equals(), hashCode(), and compareTo().
    My compareTo() method seems a bit sloppy. Basically, I want Strings to appear before Doubles in a sort. Is there a better way to do this?
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.Iterator;
    public class Table {
         HashMap<TableValue,Frequency>table=new HashMap<TableValue,Frequency>();
         public void count(TableValue aElement){
              Frequency fq=table.get(aElement);
              if(fq==null){
                   fq=new Frequency();
                   table.put(aElement, fq);
              }else{
                   fq.add();
         public double getCount(TableValue aElement){
              Frequency fq=table.get(aElement);
              if(fq==null){
                   return 0.0;
              }else{
                   return fq.getFrequency();
         public Object[] getKeyArray(boolean sorted){
              TableValue[] keys=new TableValue[table.size()];
              int i=0;
              for(Iterator iter=table.keySet().iterator();iter.hasNext(); ){
                   keys[i++]=(TableValue)iter.next();
              if(sorted){
                   Arrays.sort(keys);
              return keys;
         public static void main(String[] args) {
              Table tab=new Table();
              tab.count(new TableValue("a"));
              tab.count(new TableValue("a"));
              tab.count(new TableValue("d"));
              tab.count(new TableValue(5.3));
              tab.count(new TableValue(6.123));
              Object[] keys = tab.getKeyArray(true);
              System.out.println("count " + tab.getCount((TableValue)keys[0]));
    public class TableValue implements Comparable{
         private Double dValue;
         private String sValue;
         public TableValue(String sValue){
              this.sValue=sValue;
         public TableValue(double dValue){
              this.dValue=dValue;
         public Double getDoubleValue(){
              return dValue;
         public String getStringValue(){
              return sValue;
         public boolean isDouble(){
              if(dValue!=null) return false;
              return true;
         public boolean equals(Object o) {
              return o.equals(sValue) || o.equals(dValue);
         public int hashCode(){
              int hash=0;
              hash += (null == dValue ? 0 : dValue.hashCode());
              hash += (null == sValue ? 0 : sValue.hashCode());
              return hash;
           public int compareTo(Object anotherTableValue) throws ClassCastException{
                if(!(anotherTableValue instanceof TableValue))
                     throw new ClassCastException("TableValue object expected.");
                //compareTo for two Doubles
                if(((TableValue)anotherTableValue).getDoubleValue()!=null &&
                          this.getDoubleValue()!=null){
                     System.out.println("yes" +((TableValue)anotherTableValue).getDoubleValue()!=null &&
                               this.getDoubleValue()!=null);
                     Double anotherDouble=((TableValue)anotherTableValue).getDoubleValue();
                     return this.dValue.compareTo(anotherDouble);
                //compareTo for two Strings
                if(((TableValue)anotherTableValue).getStringValue()!=null &&
                          this.getStringValue()!=null){
                     String anotherString=((TableValue)anotherTableValue).getStringValue();
                     return this.sValue.compareTo(anotherString);
                //sort Strings before Doubles
                if(((TableValue)anotherTableValue).getStringValue()!=null &&
                          this.getStringValue()==null){
                     return 1;
                //sort Strings before Doubles
                return -1;
           public String toString(){
                if(dValue==null){
                     return sValue;
                return dValue.toString();
    }

  • How to display result set boolean value as a check box

    Hi guys,
    I am getting the data which include boolean from the database, i need to display the boolean values as check box, see my code, its displaying the data into the table with the boolean values as true and false, how to make it in check boxes
    package swing2.org;
    import java.awt.GridBagLayout;
    import javax.swing.JPanel;
    import java.awt.Color;
    import javax.swing.BorderFactory;
    import javax.swing.border.BevelBorder;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import java.awt.Container;
    import java.awt.GridBagConstraints;
    import java.awt.ComponentOrientation;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.ArrayList;
    public class Panel2 extends JPanel {
         private static final long serialVersionUID = 1L;
         private JScrollPane jScrollPane = null;
         private JTable jTable = null;
          * This is the default constructor
         public Panel2() {
              super();
              initialize();
          * This method initializes this
          * @return void
         private void initialize() {
         //     Panel2.ResultSetFrame();
              GridBagConstraints gridBagConstraints = new GridBagConstraints();
              gridBagConstraints.fill = GridBagConstraints.BOTH;
              gridBagConstraints.gridy = 0;
              gridBagConstraints.weightx = 1.0;
              gridBagConstraints.weighty = 1.0;
              gridBagConstraints.gridx = 0;
              this.setSize(340, 200);
              this.setLayout(new GridBagLayout());
              this.setBackground(new Color(171, 211, 224));
              this.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED), null));
              this.add(getJScrollPane(), gridBagConstraints);
          * This method initializes jScrollPane     
          * @return javax.swing.JScrollPane     
         private JScrollPane getJScrollPane() {
              if (jScrollPane == null) {
                   jScrollPane = new JScrollPane();
                   jScrollPane.setViewportView(getJTable());
              return jScrollPane;
          String[] columnNames = {"Task Description",
                 "Time ",
                 "Pop-up",
                 "Sound",
                 "Delete"};
          * This method initializes jTable     
          * @return javax.swing.JTable     
         private JTable getJTable() {
                      ResultSetFrame oo = new ResultSetFrame();
                      JTable table = new JTable(oo.model);
                      table.setBackground(new Color(195, 217, 230));
                      table.setComponentOrientation(ComponentOrientation.UNKNOWN);
                      table.setShowGrid(true);
                      table.setShowVerticalLines(true);
                      table.setRowHeight(17);
                      table.setShowHorizontalLines(true);
                      return table;
    abstract class ResultSetTableModel extends AbstractTableModel
         public ResultSetTableModel(ResultSet aResultSet)
              rs = aResultSet;
          try
               rsmd = rs.getMetaData();     
          catch(SQLException e)
               System.out.println("Error " + e);
       public String getColumnName(int c)
       {  try
          {  return rsmd.getColumnName(c + 1);
          catch(SQLException e)
          {  System.out.println("Error " + e);
             return "";
       public int getColumnCount()
       {  try
          {  return rsmd.getColumnCount();
          catch(SQLException e)
          {  System.out.println("Error " + e);
             return 0;
       protected ResultSet getResultSet()
       {  return rs;
       private ResultSet rs;
       private ResultSetMetaData rsmd;
    class CachingResultSetTableModel extends ResultSetTableModel
    {  public CachingResultSetTableModel(ResultSet aResultSet)
       {  super(aResultSet);
          try
          {  cache = new ArrayList();
             int cols = getColumnCount();
             ResultSet rs = getResultSet();
             /* place all data in an array list of Object[] arrays
                We don't use an Object[][] because we don't know
                how many rows are in the result set
             while (rs.next())
             {  Object[] row = new Object[cols];
                for (int j = 0; j < row.length; j++)
                   row[j] = rs.getObject(j + 1);
                cache.add(row);
          catch(SQLException e)
          {  System.out.println("Error " + e);
       public Object getValueAt(int r, int c)
       {  if (r < cache.size())
             return ((Object[])cache.get(r))[c];
          else
             return null;
       public int getRowCount()
       {  return cache.size();
       private ArrayList cache;
    class ResultSetFrame 
    {  public ResultSetFrame()
          /* find all tables in the database and add them to
             a combo box
          try
          {  Class.forName("com.mysql.jdbc.Driver");
             con = DriverManager.getConnection("jdbc:mysql://localhost:3306/task","root","nbuser");
                stmt = con.prepareStatement("SELECT * FROM tasky");
                   try
                    String query = "SELECT * FROM tasky";
                    rs = stmt.executeQuery(query);
                    model = new CachingResultSetTableModel(rs);
                    JTable table = new JTable(model);
                    scrollPane = new JScrollPane(table);
                catch(SQLException e)
                     System.out.println("Error " + e);
          catch(ClassNotFoundException e)
          {  System.out.println("Error " + e);
          catch(SQLException e)
          {  System.out.println("Error " + e);
       private JScrollPane scrollPane;
       public ResultSetTableModel model;
       private ResultSet rs;
       private Connection con;
       private Statement stmt;
    }

    add a
    public Class getColumnClass(int col) {
         return getValueAt(0, col).getClass();
    }in your ResultSetTableModel which extends AbstractTableModel.
    A simple example
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.SwingUtilities;
    import javax.swing.table.AbstractTableModel;
    public class SimpleDemo extends JFrame {
        public SimpleDemo() {
            createAndShowUI();
        private void createAndShowUI(){
            String[] columnName = {"CheckBox Column", "Data Column"};
            Object[][] data = {{new Boolean(true), "Data 1"},
            {new Boolean(false), "Data 2"}, {new Boolean(true), "Data 3"}};
            MyModel model = new MyModel();
            model.setData(columnName, data);
            JTable myTable = new JTable(model);
            JScrollPane scrollPane = new JScrollPane(myTable);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            getContentPane().add(scrollPane);
            pack();
            setLocationRelativeTo(null);
        class MyModel extends AbstractTableModel {
            String[] columnName;
            Object[][] data;
            public void setData(String[] colName, Object[][] theData) {
                this.columnName = colName;
                this.data = theData;
                fireTableStructureChanged();
            public String getColumnName(int column) {
                return columnName[column];
            public Object getValueAt(int rowIndex, int columnIndex) {
                return data[rowIndex][columnIndex];
            public int getRowCount() {
                return data.length;
            public int getColumnCount() {
                return columnName.length;
            public Class getColumnClass(int c) {
                return getValueAt(0, c).getClass();
        public static void main(String[] args){
            Runnable run = new Runnable(){
                public void run(){
                    new SimpleDemo().setVisible(true);
            SwingUtilities.invokeLater(run);
    }

  • The Boolean value getting null?

    Hello EveryBody........
    Any one help me why the Boolean value gives always null instead of false;
    what will the default value of this.........
           private Boolean result;
         public Boolean getResult() {
              return result;
         public void setResult(Boolean result) {
              this.result = result;
         }please help how to set the default false without initialize private Boolean result = false;

    Default initialization for Instance reference variable is null reference .
    Default initialization for Instance primitive variable is depends on its type.
    Local variable should be initialize before they used.
    got it?
    But this question should be in "New to Java" this forum.

  • Boolean Values in CALL TRANSFORMATION id ?

    Hi,
    I have Boolean values of the XSDBOOLEAN Domain, so ABAP->XML "id" transformation returns  "True" and "False" for these values. What I need are "X" and " " respectively.
    The questions is: can I use the modified transformation "id" to replace the "True" and "False" with "X" and " ", and how the modified transformation should look like?
    Thanks, Srdjan

    I couldn't find domain XSDBOOLEAN in our system, however you should use the values defined in the Value range tab.
    Peter

  • How to generate pulse during changing boolean value?

    I need to generate short pulse during changing boolean value from 0 to 1. This pulse is needed to reset counter. 
    I was trying with Event Structure with Value Change but I think that I did something wrong.
    Maybe sambody can give me some tips to do it in other way?
    Thank you in advance.
    Regards
    Solved!
    Go to Solution.

    Rogal wrote:
    I need to generate short pulse during changing boolean value from 0 to 1. This pulse is needed to reset counter. 
    I was trying with Event Structure with Value Change but I think that I did something wrong.
    Maybe sambody can give me some tips to do it in other way?
    Thank you in advance.
    Regards
    We assumed you wanted a pulse when a front panel button (boolean) was clicked.
    I am still not sure just what it is you want.
    Do you want a single pulse when x is greater than 4?
    You don't need an event structure for that.
    Omar

  • Time a boolean value

    I am reading the status of 10 lamps from a serial string. My VI
    returns a boolean value according to the status of the lamp. Now I
    need to time the on time of each lamp. As soon as a lamp turns off it
    should save the time and start adding the time again once the lamp
    comes on again. Once the VI is closed and reopend the on time should
    appear in the VI for each lamp. And once a lamp comes on it should
    start adding to that time. I should also be able to reset the time and
    I should also be able to enter a number of hours that a lamp has been
    on already. Any suggestions ? Thanks

    Hello wv,
    do you want someone to develop a program for you? Then you have to pay him/her :-)
    Some hints: Make an array for your time values. To reset a timevalue you just need to clear it. To have an offset you just set it in that array. Let the status-vi run in a loop and get the time difference for one loop iteration. Add that delay to the timevalues, if the status of the lamp is on. If you need that timevalues after restarting your VI you should think about a subVI for saving and reading the timevalues.
    Best regard,
    GerdW
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • Java & Acces: pass boolean values

    Ok I'm totally new at this so the following text will hopefully be understandable. I hope you guys can give me a hand over here.
    The case:
    I'm making a java function that has to create a new user of my database. This user is supposed to get a name, a password and can have 4 functions (Administrator, Author, Reader, Coreader).
    To identify the 4 functions i used a checkbox in my database. So when the box is checked the person is a Admin/author/... Now I was wondering how i can use Java (using a query) to set these values checked or non-checked.
    I thought I'd use booleans, however, my compiler says there is a General Error (all the names of the columns are right, so that's not the deal, my database is working properly and such, ...)
    So here's my code:
    (note that i used these marks ' ' here for the booleans, i tried all kinds of things such as dropping them, using them, ... it doesn't seem the problem...)
    public void addNewUser(String username, String password, boolean admin, boolean author, boolean reader, boolean coreader)
    String query1 = "UPDATE user SET username = '" + username + "' AND password = '"
    + password + "' AND administrator = '" + admin + "' AND author ='" + author
    + "' AND reader ='" + reader + "' AND coreader ='" + coreader + "'";
    try
    stmt = global.createStatement();
    stmt.executeUpdate(query1);
    global.showMessage("The new user, " + username + ", has been added successfuly", "Succesfuly added");
    catch(Exception e)
    global.showError("An error has occured while connecting to the database" + e.toString(), "SQL Error");
    finally
    global.closeConnection();
    Hope you guys can help. Thanks a lot!

    It's possible to do this; it's just that your SQL syntax is completely wrong. An SQL UPDATE statement looks as follows:
    UPDATE table SET column1 = value1, column2 = value2, column3 = value3 WHERE expression
    You're using 'AND' instead of commas, which is the first thing that goes wrong. The second thing that goes wrong is that you're building the SQL statement from bits of string and values. This is a habit that many novice programmers use, and open the door wide for SQL injection attacks. I you do this sort of thing on a web site, you could end up with your customers' credit card details being exposed.
    But because you're just passing the boolean values into the string, they get expanded to a string value, hence TRUE or FALSE. However, because they are string literals, they should be surrounded by single quotes.
    This brings us to the third problem: you're using an UPDATE statement to insert a new record. Use an INSERT statement instead.
    It would be better to use a PreparedStatement. In this case, your code would look as follows:
    PreparedStatement stmt =
        global.prepareStatement( "INSERT INTO user " +
                "( username, password, administrator, author, reader, coreader ) " +
                "VALUES ( ?, ?, ?, ?, ?, ? )" );
        stmt.setString( 1, username );
        stmt.setString( 2, password );
        stmt.setBoolean( 3, admin );
        stmt.setBoolean( 4, author );
        stmt.setBoolean( 5, reader );
        stmt.setBoolean( 6, coreader );I have no idea whether this will work: I don't know Access, and booleans are not a standard feature of SQL. I also don't know whether Microsoft have created their own flavour of SQL, as they are wont to do with any standard.
    All in all, though, you have to really work on your SQL. Three major mistakes in such a simple piece of code means that you don't understand SQL syntax. You may copy and paste this for your assignment, but unless you understand what you're actually doing, you're going to run into trouble again very soon.
    - Peter

  • Binding a boolean value to a Checkbox in Dashcode

    I can't seem to bind a boolean value in my JSON model to a checkbox in Dashcode. I can create the binding, and it shows up properly in the datasource and in the bindings inspector for the checkbox part, but if I launch the application through the simulator, or if I save the project, the binding disappears.
    To reproduce:
    1. create an empty (custom) web application project.
    2. Drag a checkbox part onto the canvas.
    3. Create a datasource with the JSON model:
    doit: "false"
    4. Load the datasource, and drag a binding from the doit boolean field to the checkbox. The binding is created. Save the project. The binding is gone.
    Anyone else seen this? What am I doing wrong?

    happybuddha wrote:
    The question really is, if my pojo has lets say 10 setter methods which will set a boolean to variables in the class. Is there a way I can pass a boolean parameter to 9 out of 10 setters (since the 10th one will be true)?
    Or to all setters is also fine I can then set the one I am interested to true. In case the properties of your PoJOs are <tt>boolean</tt> (and not <tt>Boolean</tt>) they get initialized to false on Object creation.
    bye
    TPD

Maybe you are looking for