Jtree's ValueChange method problem

my code are as follow:
i'm now doing a JTree which will list all the directory in the computers(every node is a directory) ..
When i click on each node, i wanna it to display all files names in this directory ...
but i just fail that statement:
DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
this statement will cause an error
anyone know how to solve it ??
Thanks very very much !!!
my codes:
import java.io.*;
import javax.swing.*;
import java.awt.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.util.*;
import java.awt.event.*;
public class PDThumnailer extends JFrame {
     private JTree tree;
     private JScrollPane scpTree;
     private JSplitPane split;
     private JPanel leftPane;
     public PDThumnailer() {
          super();
          Vector dirs = new Vector();
          File[] roots = File.listRoots();
          for(int i=0; i<roots.length; i++) {
               dirs.add(roots);
          leftPane = new JPanel();
          tree = new JTree(new FileTreeModel(dirs));
          tree.setCellRenderer(new FileTreeCellRenderer());
          tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
          scpTree = new JScrollPane(tree);
          split = new JSplitPane(1, scpTree, leftPane);
          split.setOneTouchExpandable(true);
split.setDividerLocation(200);
          this.getContentPane().add(split);
          this.setSize(550,400);
          this.setVisible(true);
          this.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                         //setVisible(false);
                         System.exit(-1);
          tree.addTreeSelectionListener(new TreeSelectionListener() {
                    public void valueChanged(TreeSelectionEvent e) {
                              DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
                              if (node == null)
                                   return;
                              Object nodeInfo = node.getUserObject();
                              System.out.println("nodeInfo");
                              if(nodeInfo instanceof File) {
                                   File file = (File) nodeInfo;
                                   File[] allFiles = file.listFiles();
                                   for(int i=0;i<allFiles.length;i++)
                                        System.out.println(allFiles[i].getName());
     public static void main(String[] arg){
               new PDThumnailer();
class FileTreeCellRenderer extends JLabel implements TreeCellRenderer {
public FileTreeCellRenderer() {
     super("", JLabel.LEFT);
     this.setOpaque(true);
/* implements TreeCellRenderer BEGIN */
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
     if (selected) {
          this.setBackground(Color.black);
          this.setForeground(Color.white);
     else {
          this.setBackground(Color.white);
          this.setForeground(Color.black);
     if (value instanceof File) {
          File file = (File) value;
          if (file.isDirectory()) {
                    this.setText(file.getPath());
                    this.setIcon(new ImageIcon("icon/folder.gif"));
          else {
                    this.setText(file.getName());
                    this.setIcon(new ImageIcon("icon/file.gif"));
     else {
               setText("");
     return this;
/* implements TreeCellRenderer END */
class FileTreeModel implements TreeModel {
private Vector dirs;
public FileTreeModel(Vector dirs) {
this.dirs = dirs;
/* implements TreeModel BEGIN */
public void addTreeModelListener(TreeModelListener l) {
public Object getChild(Object parent, int index) {
if (parent instanceof Vector) {
return dirs.get(index);
else if (parent instanceof File) {
File file = (File) parent;
if (file.isDirectory()) {
File[] allFiles = file.listFiles(new DirectoryFilter());
if (allFiles != null) {
          return allFiles[index];
return null;
public int getChildCount(Object parent) {
if (parent instanceof Vector) {
return dirs.size();
else if (parent instanceof File) {
File file = (File) parent;
if (file.isDirectory()) {
File[] allFiles = file.listFiles(new DirectoryFilter());
     int count =0;
if (allFiles != null) {
return allFiles.length;
return 0;
public int getIndexOfChild(Object parent, Object child) {
     if (parent instanceof Vector) {
          return dirs.indexOf(child);
     else if (parent instanceof File) {
          File file = (File) parent;
               if (file.isDirectory()) {
                         File[] allFiles = file.listFiles(new DirectoryFilter());
                         if (allFiles != null) {
                              for (int i=0; i<allFiles.length; i++) {
                                   if (child.equals(allFiles[i])) {
                                             return i;
     return -1;
public Object getRoot() {
return this.dirs;
public boolean isLeaf(Object node) {
     if (node instanceof Vector) {
          return dirs.isEmpty();
     else if (node instanceof File) {
     File file = (File) node;
     if (file.isDirectory()) {
               File[] allFiles = file.listFiles(new DirectoryFilter());
               if (allFiles != null) {
                    return allFiles.length == 0;
     return true;
public void removeTreeModelListener(TreeModelListener l) {
public void valueForPathChanged(TreePath path, Object newValue) {
/* implements TreeModel END */
class DirectoryFilter implements FileFilter
     public boolean accept(File f) {
          return f.isDirectory();

Replace this line with
DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
DefaultMutableTreeNode node = (DefaultMutableTreeNode)(event.getPath().getLastPathComponent());Tell me whether that helps to solve your problem.

Similar Messages

  • How to call valueChanged method ?

    Hello everybody
    I'm using JTree component in my application. I have handled method valueChanged(TreeSelectionEvent e) when I select some node in this component. But this method is not called when I select same node(node was selected before). That means that first I have to select other node and follows select mentioned node aggain.
    Can somebody help me how to set up this component ?
    Thanks

    Hello
    My source code is very large.
    I have some nodes as buttons in my JTree component(for example one node rus instalation,second uninstall ...)
    and I need run functionality when I clicked on these node everytime.
    Is here possibitity to call valueChanged method or not?
    Thanks

  • How to get the old selection in ListSelectionListener valueChanged() method

    Hi,
    Is anyone know how to get the old selection index/value in the ListSelectionListener valueChanged() method? The list.selectedValue() always return the same value which is the new selection. The ListSelectionEvent.getFirstIndex() and getLastIndex are always firstIndex <= lastIndex so that you cant' tell which one is the old selection.
    Please help and thanks!

    Just test the two indexes (first and last): if the corresponding row is selected, then the other is unselected. That gives you the old (unselected) and new (selected) item.
    Of course, I have supposed that you were using a SINGLE_SELECTION model...
    Hope this helped,
    Regards.

  • BufferedReader's readLine() method problem (REPOST)

    Hello,
    If anyone can help me out I would not have to struggle :)
    Here is the thing. I have a file like this:
    1 srjetnuaazcebsqfbzerhxfbdfcbxyvihswlygzsfvjleengcftwvxcjriwdohjisnzppipiwpnniui yjpeppaezftgjfviwxunu
    2 ekjghqflatrcdteurofahxoiyvrwhvaxjgcuvkkpondsqhedxylxyjizflfbgusoizogbffgwnswohe njixwufcdlbjlkoqevqdy
    3 stfhcbslgcrywwrgbsqdkcxfbizvniyookceonscwugixgrxvvkxiqezltsiwhhepqusjdlkhadvkzg iefgarenbxnxtxnqdqpfh
    4 dcuefkdrkoovjwdrqbpgoirruutphuiobqweknxhboyktxzcczgekrlbfsbfuygjpheydiwaasxifph tldawxsfepotkgqqsivur
    5 fpfrspbuhangkeugfuwexsgivetovkoyloddgofdcajwwlrocgjrhonsrfrfxozvgohwoytycfjoycr xdhnhxyitkeqynedrbroh
    6 hgzqqsfgnotfepywbpccrosxborslqtkanyffrwknjapnzjnesjlkbbsckbyvgrxujqyocpcpctsqyz apcinhjyysxsdwfjugndr
    7 pltzealtrklzrugxdcskndqyvsrzncitqvjcnndeqossyrifzvbqovtdzsixjlizsbxwutgqipuxfid xyoktwupsuqbqgnxdfbze
    8 avpxfjgwpxnzfsfosgsryhpyaezigrqsxsgdvwdbwovhcchrijbitvbcvltrgvadogokaennwpjjpku uttidlnqftdnzqpqafels
    9 oyvztgletdwdtibshpzeuqryvulnubrqtgxwizfsdzqlgxvsebhslnovphgehfigbjyyqsirqcwflbn bnrflotpqytqzbgnkeyrk
    10 unvryrnlqucuydrasyzyiclnjvospzdoviqchdhasxzffblwsewikzbznyegrqtjvxfxfjenvrboofb xfsynlxhyuvqprqbvoruk
    and my java programs is like this:
    public String searchForAString(String fileName, int lineNumber)
    File fileObject = new File(fileName);
    String finalString ="";
    String record = "";
    int line;
    try
    FileInputStream fileInputStreamObject = new FileInputStream(fileObject);
    BufferedInputStream bufferedInputStreamObject = new BufferedInputStream(fileInputStreamObject);
    //DataInputStream dataInputStreamObject = new DataInputStream(bufferedInputStreamObject);
    BufferedReader bufferedReaderObject = new BufferedReader(new InputStreamReader(bufferedInputStreamObject));
    //System.out.println(bufferedReaderObject.readLine());
    //System.out.println("_____________________");
    while((bufferedReaderObject.readLine()) != null)
    System.out.println(bufferedReaderObject.readLine());
    Last System.out.println statement only displays second, forth, sixth, eigth, tenth and null lines. Why not every line? Any ideas? Thanks!
    Re: BufferedReader's readLine() method problem.
    Author: EagleEye101 Feb 18, 2005 8:48 PM (reply 1 of 1)
    You do relize that when you call the in.readLine() in your loop conditional and in your loop body it reads in diffrent lines. Try this:
    public String searchForAString(String fileName, int lineNumber)
    File fileObject = new File(fileName);
    String finalString ="";
    String record = "";
    int line;
    try
    FileInputStream fileInputStreamObject = new FileInputStream(fileObject);
    BufferedInputStream bufferedInputStreamObject = new BufferedInputStream(fileInputStreamObject);
    //DataInputStream dataInputStreamObject = new DataInputStream(bufferedInputStreamObject);
    BufferedReader bufferedReaderObject = new BufferedReader(new InputStreamReader(bufferedInputStreamObject));
    //System.out.println(bufferedReaderObject.readLine());
    //System.out.println("_____________________");
    String s = bufferedReaderObject.readLine();
    while(s != null)
    System.out.println(bufferedReaderObject.readLine());
    s = bufferedReaderObject.readLine();
    Every time you call the readLine method, it does read a diffrent line. Java does not know you want to read the same line twice.
    Tried it, did not work. I need to go through each line of the file I have. Any ideas?

    solution should be in your other thread.
    Please do not repeat threads--it really bugs the people here, just some 'nettiquite' --I don't mean to be a grouch.
    --later.  : )                                                                                                                                                                                                                                                                                                                                                       

  • JTree setRoot method problem!!! Maybe swing bug???

    Hi all,
    i have problem with setRoot method of the DefaultTreeModel class. Sometimes when i've switched the root element of my tree (i've called setRoot method) ...swing has fired this exception....
    java.lang.NullPointerException
         at javax/swing/SizeRequirements.calculateAlignedPositions (SizeRequirements.java:333)
         at javax/swing/OverlayLayout.layoutContainer (OverlayLayout.java:214)
         at java/awt/Container.layout (Container.java)
         at java/awt/Container.doLayout (Container.java)
         at java/awt/Container.validateTree (Container.java)
         at java/awt/Container.validate (Container.java)
         at javax/swing/plaf/basic/BasicTreeUI$NodeDimensionsHandler.getNodeDimensions (BasicTreeUI.java:2509)
         at javax/swing/tree/AbstractLayoutCache.getNodeDimensions (AbstractLayoutCache.java:402)
         at javax/swing/tree/VariableHeightLayoutCache$TreeStateNode.updatePreferredSize (VariableHeightLayoutCache.java:1289)
         at javax/swing/tree/VariableHeightLayoutCache$TreeStateNode.expand (VariableHeightLayoutCache.java:1421)
         at javax/swing/tree/VariableHeightLayoutCache$TreeStateNode.expand (VariableHeightLayoutCache.java:1216)
         at javax/swing/tree/VariableHeightLayoutCache.rebuild (VariableHeightLayoutCache.java:669)
         at javax/swing/tree/VariableHeightLayoutCache.treeStructureChanged (VariableHeightLayoutCache.java:573)
         at javax/swing/plaf/basic/BasicTreeUI$TreeModelHandler.treeStructureChanged (BasicTreeUI.java:2286)
         at javax/swing/tree/DefaultTreeModel.fireTreeStructureChanged (DefaultTreeModel.java:513)
         at javax/swing/tree/DefaultTreeModel.nodeStructureChanged (DefaultTreeModel.java:339)
         at javax/swing/tree/DefaultTreeModel.setRoot (DefaultTreeModel.java:115)
    Had someone similar problem like me..??????

    sounds like something in the tree structure is null...
    or possibly you are changing it from a different thread then the event dispatch thread, in which case, use SwingUtilities.invokeLater() or invokeAndWait() to change the root, otherwise there could be timing issues with repaints.

  • Edit method problem???

    Hi,forgive for all the code but i've asked this question before and people asked for more code.The problem is i get an error in publicationmain saying "undefined varible newpublication" so how do i fix this?and is my edit method goin to work?using the get and set method?can u show me how do do this please?feel free to make any other changes.thanxs a reply would be most heplful
    public class publication
    public int PublicationID;
    public String publicationname;
    public String publisher;
    public String PricePerIssue;
    public String pubstatus;
    public String publicationtype;
    public publication(int NewPublicationID, String Newpublicationname, String Newpublisher, String NewPricePerIssue, String Newpubstatus, String Newpublicationtype)
    PublicationID = NewPublicationID;
    publicationname = Newpublicationname;
    publisher = Newpublisher;
    PricePerIssue = NewPricePerIssue;
    pubstatus = Newpubstatus;
    publicationtype = Newpublicationtype;
    public String toString ()
    String pubreport = "---------------------------Publication-Information-----------------------------";
    pubreport += "Publication ID:" PublicationID"/n";
    pubreport += " Publication Title:" publicationname"/n";
    pubreport += " publisher: " publisher"/n";
    pubreport += " price Per Issue: " PricePerIssue"/n";
    pubreport += " publication Status: " pubstatus"/n";
    pubreport += " publication Type: " publicationtype"/n";
    return pubreport;
    public void SetPublicationID(int PubID)
    PublicationID = PubID;
    public int GetPublicationID()
    return PublicationID;
    public void Setpublicationname(String pubname)
    publicationname = pubname;
    public String Getpublicationname()
    return publicationname;
    public void Setpublisher(String Pub)
    publisher = Pub;
    public String Getpublisher()
    return publisher;
    public void SetPricePerIssue(String PPI)
    PricePerIssue = PPI;
    public String GetPricePerIssue()
    return PricePerIssue;
    public void Setpubstatus(String Status)
    pubstatus = Status;
    public String Getpubstatus()
    return pubstatus;
    public void Setpublicationtype(String Pubtype)
    publicationtype = Pubtype;
    public String Getpublicationtype()
    return publicationtype;
    import java.util.*;
    import publication;
    public class PublicationContainer
    LinkedList PubList;
    public PublicationContainer()
    PubList = new LinkedList();
    public int add (publication newpublication)
    PubList.addLast(newpublication);
    return PubList.size();
    private class PubNode
    public publication pubrecord;
    public PubNode next;
    public PubNode (publication thepublicationrecord)
    publication p = thepublicationrecord;
    next = null;
    public String toString()
    return PubList.toString();
    public void remove(int PubID)
    PubList.remove(PubID);
    public publication get(int PubID)
    return (publication)PubList.get(PubID);
    public void set(int PubID,publication newpublication)
    PubList.set(PubID, newpublication);
    import cs1.Keyboard;
    import publication;
    import java.util.*;
    public class publicationmain
    public static void main(String args[])
    PublicationContainer pubdatabase = new PublicationContainer();
    int userchoice;
    boolean flag = false;
    while (flag == false)
    System.out.println("------------------------------------Publications--------------------------------");
    System.out.println();
    System.out.println("please Make a Selection");
    System.out.println();
    System.out.println("1 to add publication");
    System.out.println("2 to delete publication");
    System.out.println("0 to quit");
    System.out.println("3 to View all publications");
    System.out.println("4 to Edit a publication");
    System.out.println("5 to select view of publication");
    System.out.println("6 to produce daily summary");
    System.out.println();
    userchoice = Keyboard.readInt();
    switch (userchoice)     
    case 1:
    String PubName;
    String PricePerIssue;
    String Publisher;
    String Pubstatus;
    String Pubtype;
    int PubID;
    System.out.println ("Enter Publication ID:");
    PubID = Keyboard.readInt();
    System.out.println("Enter Publication Name:");
    PubName = Keyboard.readString();
    System.out.println("Enter Publisher Name");
    Publisher = Keyboard.readString();
    System.out.println("Enter Price per Issue:");
    PricePerIssue = Keyboard.readString();
    System.out.println("Enter Publication status");
    Pubstatus = Keyboard.readString();
    System.out.println("Enter Publication type:");
    Pubtype = Keyboard.readString();
    pubdatabase.add (new publication(PubID, PubName, Publisher, PricePerIssue, Pubstatus, Pubtype));
    break;
    case 0:
    flag = true;
    case 2:
    System.out.println ("Enter Publication ID:");
    PubID = Keyboard.readInt();
    pubdatabase.remove (PubID);
    System.out.println ("publication: "+(PubID)+" removed");
    System.out.println();
    break;
    case 3:
    System.out.println (pubdatabase);
    break;
    case 4:
    System.out.println ("Enter Publication to be edited by Publication ID: ");
    PubID = Keyboard.readInt();
    pubdatabase.get(PubID);
    pubdatabase.set(PubID, newpublication);
    default:
    System.out.println("Incorrect Entry");
    }

    Whoops! Anyone spot the mistake?
    I (blush) forgot to re-instate the serial key for the publications after reading them in from disk.
    Works now ;)
    import javax.swing.JComponent;
    import javax.swing.JList;
    import javax.swing.DefaultListModel;
    import javax.swing.JPanel;
    import javax.swing.JOptionPane;
    import javax.swing.JButton;
    import javax.swing.JScrollPane;
    import javax.swing.JLabel;
    import javax.swing.JComboBox;
    import javax.swing.JTextField;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.Dimension;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.Serializable;
    class Publication
         implements Serializable
         private static final String sFileName= "Publications.ser";
         public static final byte UNKNOWN=     0;
         public static final byte HARDBACK=    1;
         public static final byte PAPERBACK=   2;
         public static final byte AUDIO=       3;
         public static final byte BRAIL=       4;
         public static final byte LARGE_PRINT= 5;
         public static final byte INSTOCK=      1;
         public static final byte BACK_ORDER=   2;
         public static final byte OUT_OF_PRINT= 3;
         private static final String[] sTypeNames=
              { "Unknown", "Hardback", "Paperback", "Audio", "Brail", "Large Print" };
         private static final String[] sStatusNames=
              { "Unknown", "In Stock", "Back Order", "Out of Print" };
         private int mId;
         private String mTitle;
         private String mAuthor;
         private String mPublisher;
         private float mPrice;
         private byte mStatus;
         private byte mType;
         private static Object sIdLock= new Object();
         static int sId;
         public Publication(
              String title, String author, String publisher,
              float price, byte status, byte type)
              setTitle(title);
              setPublisher(publisher);
              setAuthor(author);
              setPrice(price);
              setStatus(status);
              setType(type);
              synchronized (sIdLock) {
                   mId= ++sId;
         public int getId() { return mId; }
         public void setTitle(String title) { mTitle= title; }
         public String getTitle() { return mTitle; }
         public void setAuthor(String author) { mAuthor= author; }
         public String getAuthor() { return mAuthor; }
         public void setPublisher(String publisher) { mPublisher= publisher; }
         public String getPublisher() { return mPublisher; }
         public void setPrice(float price) { mPrice= price; }
         public float getPrice() { return mPrice; }
         public void setStatus(byte status)
              if (status >= INSTOCK && status <= OUT_OF_PRINT)
                   mStatus= status;
              else
                   mStatus= UNKNOWN;
         public byte getStatus() { return mStatus; }
         public String getStatusName() { return sStatusNames[mStatus]; }
         public void setType(byte type)
              if (type >= HARDBACK && type <= LARGE_PRINT)
                   mType= type;
              else
                   mType= UNKNOWN;
         public byte getType() { return mType; }
         public String getTypeName() { return sTypeNames[mType]; }
         public String toString ()
              return
                   " id= " +getId() +
                   ", title= " +getTitle() +
                   ", author= " +getAuthor() +
                   ", publisher= " +getPublisher() +
                   ", price= " +getPrice() +
                   ", status= " +getStatus() +
                   " (" +getStatusName() +")" +
                   ", type= " +getType() +
                   " (" +getTypeName() +")";
         private static void addPublication(DefaultListModel listModel) {
              editPublication(listModel, null);
         private static void editPublication(
              DefaultListModel listModel, Publication publication)
              JPanel panel= new JPanel(new BorderLayout());
              JPanel titlePanel= new JPanel(new GridLayout(0,1));
              JPanel fieldPanel= new JPanel(new GridLayout(0,1));
              JTextField fTitle= new JTextField(20);
              JTextField fAuthor= new JTextField();
              JTextField fPublisher= new JTextField();
              JTextField fPrice= new JTextField();
              JComboBox cbStatus= new JComboBox(sStatusNames);
              JComboBox cbType= new JComboBox(sTypeNames);
              fieldPanel.add(fTitle);
              fieldPanel.add(fAuthor);
              fieldPanel.add(fPublisher);
              fieldPanel.add(fPrice);
              fieldPanel.add(cbStatus);
              fieldPanel.add(cbType);
              titlePanel.add(new JLabel("Title:"));
              titlePanel.add(new JLabel("Author:"));
              titlePanel.add(new JLabel("Publisher: "));
              titlePanel.add(new JLabel("Price:"));
              titlePanel.add(new JLabel("Status:"));
              titlePanel.add(new JLabel("Type:"));
              panel.add(titlePanel, BorderLayout.WEST);
              panel.add(fieldPanel, BorderLayout.EAST);
              if (publication != null) {
                   fTitle.setText(publication.getTitle());
                   fTitle.setEditable(false);
                   fAuthor.setText(publication.getAuthor());
                   fPublisher.setText(publication.getPublisher());
                   fPrice.setText("" +publication.getPrice());
                   cbStatus.setSelectedIndex((int) publication.getStatus());
                   cbType.setSelectedIndex((int) publication.getType());
              int option= JOptionPane.showOptionDialog(
                   null, panel, "New Publication",
                   JOptionPane.OK_CANCEL_OPTION,
                   JOptionPane.PLAIN_MESSAGE,
                   null, null, null
              if (option != JOptionPane.OK_OPTION)
                   return;
              String title=
                   fTitle.getText().length() < 1 ? "Unknown" : fTitle.getText();
              String author=
                   fAuthor.getText().length() < 1 ? "Unknown" : fAuthor.getText();
              String publisher=
                   fPublisher.getText().length() < 1 ? "Unknown" : fPublisher.getText();
              float price= 0.0f;
              try { price= Float.parseFloat(fPrice.getText()); }
              catch (NumberFormatException nfe) { }
              byte status= (byte) cbStatus.getSelectedIndex();
              byte type= (byte) cbType.getSelectedIndex();
              if (publication != null) {
                   publication.setAuthor(author);
                   publication.setPublisher(publisher);
                   publication.setPrice(price);
                   publication.setStatus(status);
                   publication.setType(type);
              else {
                   listModel.addElement(
                        new Publication(title, author, publisher, price, status, type));
         private static void deletePublications(JList list, DefaultListModel listModel)
              if (list.getSelectedIndex() >= 0) {
                   Object[] values= list.getSelectedValues();
                   for (int i= 0; i< values.length; i++)
                        listModel.removeElement(values);
         private static DefaultListModel getListModel()
              DefaultListModel listModel;
              try {
                   ObjectInputStream is=
                        new ObjectInputStream(new FileInputStream(sFileName));
                   listModel= (DefaultListModel) is.readObject();
                   is.close();
                   if (listModel.getSize() > 0) {
                        Publication.sId=
                             ((Publication)
                                  listModel.get(listModel.getSize() -1)).getId();
              catch (Exception e) {
                   JOptionPane.showMessageDialog(
                        null, "Could not find saved Publications, creating new list.",
                        "Error", JOptionPane.ERROR_MESSAGE);
                   listModel= new DefaultListModel();
                   // add a known book to the list (I'm pretty sure this one exists ;)
                   listModel.addElement(
                        new Publication("The Bible", "Various", "God", 12.95f,
                             Publication.INSTOCK, Publication.HARDBACK));
              // add a shutdown hook to save the list model to disk when we exit
              final DefaultListModel model= listModel;
              Runtime.getRuntime().addShutdownHook(new Thread() {
                   public void run() {
                        saveListModel(model);
              return listModel;
         private static void saveListModel(DefaultListModel listModel)
              try {
                   ObjectOutputStream os=
                        new ObjectOutputStream(new FileOutputStream(sFileName));
                   os.writeObject(listModel);
                   os.close();
              catch (IOException ioe) {
                   System.err.println("Failed to save Publications!");
                   ioe.printStackTrace();
         public static void main(String args[])
              // store all the publications in a list model which drives the JList
              // the user will see - we save it on exit, so see if there's one on disk.
              final DefaultListModel listModel= getListModel();
              final JList list= new JList(listModel);
              // two panels, the main one for the dialog and one for buttons
              JPanel panel= new JPanel(new BorderLayout());
              JPanel btnPanel= new JPanel(new GridLayout(1,0));
              // an add button, when pressed brings up a dialog where the user can
              // enter details of a new publication
              JButton btnAdd= new JButton("Add");
              btnAdd.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        addPublication(listModel);
              btnPanel.add(btnAdd);
              // a delete button, when pressed it will delete all the selected list
              // items (if any) and then disable itself
              final JButton btnDelete= new JButton("Delete");
              btnDelete.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        deletePublications(list, listModel);
              btnDelete.setEnabled(false);
              btnPanel.add(btnDelete);
              // hook into the list selection model so we can de-activate the delete
              // button if no list items are selected.
              list.getSelectionModel().addListSelectionListener(
                   new ListSelectionListener() {
                        public void valueChanged(ListSelectionEvent e) {
                             if (list.getSelectedIndices().length > 0)
                                  btnDelete.setEnabled(true);
                             else
                                  btnDelete.setEnabled(false);
              // Watch out for double clicks in the list and edit the document
              // selected
              list.addMouseListener(new MouseListener() {
                   public void mouseClicked(MouseEvent e) {
                        if (e.getClickCount() == 2) {
                             editPublication(
                                  listModel, (Publication) list.getSelectedValue());
                   public void mousePressed(MouseEvent e) { }
                   public void mouseReleased(MouseEvent e) { }
                   public void mouseEntered(MouseEvent e) { }
                   public void mouseExited(MouseEvent e) { }
              // Now keep an eye out for the user hitting return (will edit the selected
              // publication) or delete (will delete it)
              // Note: we have do the ugly "pressed" flag because JOptionPane closes
              // on keyPressed and we end up getting keyReleased. Can't use keyTypes
              // because it does not contain the virtual key code 8(
              list.addKeyListener(new KeyListener() {
                   boolean pressed= false;
                   public void keyTyped(KeyEvent e) { }
                   public void keyPressed(KeyEvent e) {
                        pressed= true;
                   public void keyReleased(KeyEvent e) {
                        if (pressed && e.getKeyCode() == e.VK_ENTER) {
                             editPublication(
                                  listModel, (Publication) list.getSelectedValue());
                        else if (pressed && e.getKeyCode() == e.VK_DELETE)
                             deletePublications(list, listModel);
                        pressed= false;
              // Put the list in a scroll pane so we can see it all. Make it resonably
              // wide so we don't have top scroll horizonatly to see most publications
              JScrollPane listScrollPane= new JScrollPane(list);
              listScrollPane.setPreferredSize(new Dimension(640, 300));
              // layout the list and button panel
              panel.add(listScrollPane, BorderLayout.CENTER);
              panel.add(btnPanel, BorderLayout.SOUTH);
              // ok, ready to rumble, lets show the user what we've got
              JOptionPane.showOptionDialog(
                   null, panel, "Publications",
                   JOptionPane.DEFAULT_OPTION,
                   JOptionPane.PLAIN_MESSAGE,
                   null, new String[0], null
              // leg it
              System.exit(0);

  • JTree's setRootVisible method

    I have extended the DefaultTreeModel class and made my own model.
    I have used the nodeWereInserted and nodeWereRemoved to notify the model changes.
    Every thing worked perfect: the tree responded to all kind of changes: insertion, deletion.
    But when I invoked the method: setRootVisible(false) the tree is completely invisible.
    I have seen that this behavior was reported as a bug:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4699927
    But Sun says that this is not a bug, but they are very confusing in their arguments in saying so.
    Sincerely while the model is working perfectely I don't see why a simple visual tweakening has this effect.
    ;)

    I have found the answer. There is no problem in fact, but there is a small trick.
    When the root is invisible and the tree is empty - not realy empty, it has the root, but the root is a leaf - when a node is added as a child to the root then you must expand the root programatically. You can't expand it visually - by keyboard or mouse.
    To do this you must add a TreeModelListener on the tree's model and in the appropiate methods - treeNodesInserted by example - expand the root using the JTree's expandPath(TreePath path) method.
    Using the method above the tree will corectly display its nodes.

  • Using Calendar.set() method problem

    Hi all,
    First of all sorry to bother with such a trivial(?) matter but I cannot solve it by myself.
    I have a piece of code which I simply want to handle the current date with the GregorianCalendar object so that the date would be set to the Calendar.SUNDAY (of the current week). Simple enough?
    Code as follows:
    import java.util.*;
    import java.text.*;
    public class Foo
    public static void main(String[] args)
         Foo foo = new Foo();
         Date newdate = foo.bar();
    public Date bar()
         GregorianCalendar m_calendar = new GregorianCalendar(new Locale("fi","FI"));
         m_calendar.setFirstDayOfWeek(Calendar.MONDAY);
         Date newDate = null;
         try
              m_calendar.setTime(new Date());
              System.out.println("Calendar='" + m_calendar.toString() + "'");
              m_calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
              SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
              StringBuffer sb = new StringBuffer();
              sdf.format(m_calendar.getTime(), sb, new FieldPosition(0));
              System.out.println("Date in format (" + sdf.toPattern()          + ") = '" + sb.toString() + "'");
         catch(Exception e)
              e.printStackTrace();
         return m_calendar.getTime();
    This should work at least accoring to my understanding of the SDK documentation as follows with
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.1_01-b01)
    Java HotSpot(TM) Client VM (build 1.4.1_01-b01, mixed mode)
    Calendar='java.util.GregorianCalendar[time=1054636838494,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Helsinki",offset=7200000,dstSavings=3600000,useDaylight=true,transitions=118,lastRule=java.util.SimpleTimeZone[id=Europe/Helsinki,offset=7200000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2003,MONTH=5,WEEK_OF_YEAR=23,WEEK_OF_MONTH=1,DAY_OF_MONTH=3,DAY_OF_YEAR=154,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=1,HOUR_OF_DAY=13,MINUTE=40,SECOND=38,MILLISECOND=494,ZONE_OFFSET=7200000,DST_OFFSET=3600000]'
    Date in format (yyyy.MM.dd) = '2003.06.08'
    Which is the sunday of this week. But as I run the same code with:
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.1.06-020625-14:20)
    Java HotSpot(TM) Server VM (build 1.3.1 1.3.1.06-JPSE_1.3.1.06_20020625 PA2.0, mixed mode)
    Calendar='java.util.GregorianCalendar[time=1054636630703,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=java.util.SimpleTimeZone[id=Europe/Helsinki,offset=7200000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2003,MONTH=5,WEEK_OF_YEAR=23,WEEK_OF_MONTH=1,DAY_OF_MONTH=3,DAY_OF_YEAR=154,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=1,HOUR_OF_DAY=13,MINUTE=37,SECOND=10,MILLISECOND=703,ZONE_OFFSET=7200000,DST_OFFSET=3600000]'
    Date in format (yyyy.MM.dd) = '2003.06.01'
    Which is sunday of the previous week and incorrect in my opinion. The latter result is run on HP-UX B.11.11 U 9000/800 and first on NT.
    Any ideas why this is happening? Thanks in advance!
    Greets, Janne

    Thanks for your answer!
    The problem is that I have to work with this older SDK version. :) But I got it solved by using the roll method with the following syntax:
    int delta = [dayToSet] - m_calendar.get(Calendar.DAY_OF_WEEK);
    in which the delta is of course the difference (negative or positive to the current day of the week)
    and then using the roll call:
    m_calendar.roll(Calendar.DAY_OF_WEEK, delta);
    which doesn't alter the current week. So this works if someone else has a similar problem with the version 1.3.1
    Greets, Janne

  • Enhance Method Problem

    I try to enhance a Method like described in this Thread...
    Re: Sending Email using the Outlook Client
    What I did so far...
    1) In Transaction "bsp_WD_CMPWB"  I choosed Component "BP_ADDR" and created a copy in our "Z_CRM" EnhancementSet
    2) I used the right Mousebutton to Enhance the "BP_ADDR/StandardAddress" View
    Two things had been automatically generated/created...
    - Table Contents BSPWD_CMP_C_REPL
    - Object ZL_BP_ADDR_STANDARDADDRES_CTXT
    3) I doubleclick on the enhanced View "BP_ADDR/StandardAddress"
        (-> In the "View Layout" node the StandardAddress.html is still using the Super Classes / Implementation Class CL_BP_ADDR_STANDARDADDRES_CN01 )
    4) If I go to Implemetation Class CL_BP_ADDR_STANDARDADDRESS_CN01
    5) Select method "GET_P_E_MAILSMT" (and look into the coding)
       The enhancement Functions there are not working for meu2026
       I tried the Button with the (Sprial / helix)
       and the Menu "Edit"-> "Enhancement Operations"
    Where is my error?! (I think I have to create a ZClass for the CL_BP_ADDR_STANDARDADDRES_CN01?!?!? But how to???)
    I will give all possible points for good answers
    Thanks for helpingu2026

    hi,
    Some times I also faced problems to create Zclass for standard ones. But you can do one trick to create Zclass.
    Try to create one dummy attribute in your context node, then it will creates  automatically Zclass for that node. Later you can delete that attribute.
    If you get any problems to create P-getter method, then copy the IF_BSP_WD_MODEL_SETTER_GETTER~_GET_P_XYZ template method and rename to GET_P_E_MAILSMT.
    regards
    Ismail

  • Multiple Payment Methods problem in F110 - Parameters

    <b>Prob : Wehn I enter more than one payment method in Parameters in F110 only the 1st Payment method entered is saved. The other payment method gets deleted automatically.</b>
    Following is already done :
    1. All the payment methods entered in F110 Parameters is already maintained in
    the vendor master.
    2. In FBZP - Payment Method for Country & Payment Method for Company Code
    is configured for all the payment methods.
    3. Also Invoices in FI (FB60) are posted for all the payment methods without any
    errors.
    4. Ranking order is maintained for each payment method & for the house bank
    used.
    5. Account determination is also maintained for all the payment methods for the
    respective house bank.
    6. The maximum amount is also maintained for all the payment methods under "Payment Methods for Comapany Code".
    Pl help to resolve this problem.

    hi,
    My problem is in the parameter stage 1st Screen.
    Also you cannot assign more than one Payment Method in the Print Variant.
    Also this variant is used only for printing. Its not called at the stage when I am entering the Payment Method in the 1st screen in the Parameter.
    I have somewhat found out what the problem is.
    I guess there is some change done in the standard SAP program, becuase if i type more than one payment method in the Parameter 1st screen and try to save it, it returns with a warning message "Only one Payment Method can be entered". This is a unique msg which has been written through a Z Program.
    Thanks.
    Bye.

  • Help with JTree's opaque methods

    I have been looking through the methods provided for JTree in Netbeans GUIBuilder and I do not see accessor methods for actions like insertion, retrieval, deletion and replacement. I am looking for something like this.
    JTree.insert('object', JTree.getSelectedNode());
    JTree.getSelectedNode().getObject();
    JTree.deleteNode(JTree.getSelected());
    JTree. supplantObject(‘object’, JTree.getSelectedNode());
    JTree.insert('object', JTree.getSelectedNode()) should accept to inputs; the object you wish to insert and the location you wish to insert it. JTree.getSelectedNode() would be an accessor method returning the selected node. The insert would have to find the next available element in the LinkedList, array, hashtable, stack, (or whatever it uses) and inserts the object.
    JTree.getSelectedNode().getObject(); I assume that if I have “apple” selected in the JTree, “apple” will be returned.
    JTree.deleteNode(JTree.getSelected()); deleting the node wipes out all its children as well.
    JTree. supplantObject(‘object’, JTree.getSelectedNode()); overwrites the object in the selected with a new object.
    These seem like the more obvious accessor methods and I am astonished to find them missing or named something inconsistent with java standards.
    So I guess my question is, what are the equivalent method names for the aforementioned methods?
    BM

    Take a look at [http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/tree/DefaultMutableTreeNode.html|http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/tree/DefaultMutableTreeNode.html] which has most of the methods that you are interested in. A JTree has a single root node, which by default is of this type.

  • JTree multiple nodes selection problem !

    I can not make my JTree to be in multiple node selection mode.
    I have custom tree model and tree node class, the tree model class
    implements javax.swing.tree.TreeModel, and the tree node is an ordinary
    Java object.
    In this setting, my JTree is always in single selection mode.
    I have tried set the selection model after the JTree has initialized, and
    it didn't work.
    What I missed in TreeModel implementation ? Or should my tree node class
    also implements javax.swing.tree.TreeNode ?
    Don't tell me just call
    xxtree.getSelectionModel().setSelectionMode(javax.swing.tree.TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    It didn't work.

    Just in case anyone wants to know, I did find the magic number of files, and what the problem is. I talked with tech suppot at Adobe, and they know the problem exists, but won't fix it. I did put in a request in the "Request a Feature" form. Read on:
    The magic number is 40 Canon 1Ds Mark III Raw files, and clicking on three or more keywords. The key to not having the numbers of keywords counted incorrectly in the filter pane is to click on the keywords as fast as you can before it starts to write to the metadata. If you click on each keyword one at a time, and wait about a second or more between selecting the keywords, then the counts in the filter panel for the number of keywords is not correct in relation to the number of files that you have chosen to apply keywords to. The cure for this is to click as many keywords as possible as fast as you can before the software starts incorporating the keywords into the metadata.
    I would suggest to Adobe, that a nice feature would be that one could click on as many keywords as one would want, to as many files one would want, and then have a button or icon that would enable one to then apply all the keywords at once, instead of applying them as you click them as it is now. I also would love it if Adobe fixed it now instead of waiting to fix it in the version of CS5. Someone on Adobe's support line told me that Adobe would rather wait to put this into the CS5 version than fix it now. I don't think that is right, but heck, I am only one guy who depends on this software to provide images keyworded to my clients in a timely manner. I would never run my business like this Adobe. If there is a problem, and there is, please fix it now, or give me some of my money back since your product has a design flaw that is having a negative impact in my ability to to my job and run my business.
    Thanks!
    Daniel Root
    Portland, OR

  • PaintComponent method problems...

    Hi, I am developing an game application ( just for fun ) and I have a huge problem with paintComponent method. I Have a class ImagePanel that extends JPanel class. The ImagePanel class overrides the paintComponent method and paintChildren method ( since i have added components inside the JPanel also these must be painted ). The ImagePanel is instantied in my main class IntroView which extends JFrame where it's added. Now when the IntroPanel is created i have noticed that the paintComponent and paintChildren method is called all over again . I Have a soundclip playing in background in it's own thread and this continously paintComponent method call causes the sound clip to break off in few seconds. I Have tried to use JLabel instead of JPanel, but then the image is not shown( alltougth the methods are called only once ). I Have also tried next code to get rid of continous paintComponent call
    ...from ImagePanel class
    ImagePanel extends JPanel.....
    public final void paintComponent( Graphics g )
    if( firstTime )
    super.paintComponent( g );
    g.drawImage( myImage, 0, 0, this );
    firstTime = false;
    public final void paintChildrens( Graphics g )
    if( paintChildren )
    super.paintChildren( g );
    add( startLabel );
    add( optionsLabel );
    paintChildren = false;
    public boolean isOpaque()
    return true;
    Now the paintComponent and paintChildren is called only once. There is still a "little problem" since the paintComponent doesen't paint the image, it paints only the background( I think g.drawImage(...) didint have time to paint the image? ). Also the labels added in paintChildren method are not shown. Sounds paly now just fine.This situation makes me grazy. Please consult me with this problem.....i can surely send also the whole source if needed. There is no effect if I change isOpaque to true or false.

    Hi,
    Thanks for advices, I solved the problem...it was simplier than i thought. When the g.drawImage(.... is called ) i just added Thread.sleep( time ) after that line. This gives the sound therad time to play the sound without interrput and time to main thread to handle the image. All works now pretty much as i thought, except when JFrame is overlapped the image is not drawn again...this can be corrected ( maybe?)by adding windoslistener and implement the methods in that inteface and make some repainting in different situations. But cause you gave me the magic work Thread priority I hox! the problem, so here goes 10 duke dollars.

  • APPLET'S STOP METHOD - PROBLEM!!

    I'm learning java on my own, and I have a problem. Could you help me.
    The stop()** method in my applet does not show on the appletviewer until I close the appletviewer.
    I open another program like notepad, but when I come back to the appletviewer it doesen't show!
    It only shows right before I close it.
    Why is that?
    Thanks
    stop() {
    showStatus("STOPPED");

    Dear JustAnotherProgramer,
    pillaged from the docs
    stop
    public void stop()
    Called by the browser or applet viewer to inform this applet that it should stop its execution. It is called when the Web page that contains this applet has been replaced by another page, and also just before the applet is to be destroyed.
    It seems that if you run it in a browser and you go to the other page(same browser) it will be called.
    I guess by changing focus between different application(notepad) it will not work.
    Thank
    Joey

  • ActiveX Server Method Problem

    LabView men help me!
    I have a problem with using ActiveX Server Method object.Run(async) with
    async = TRUE in MS Visual C++ program.
    I want to call ActiveX Server and continue program execution.
    I call this metod in program block.
    COleVariant No_Wait;
    No_Wait.boolVal = TRUE;
    pVI->Run(No_Wait);
    After this operator I can not return from VI, until VI does not close, inspite
    of parameter async = TRUE.
    I ask your send me example how to use this metod and wait for you recomendations.
    Gregory.

    I think I have exactly the example program both of you are looking for. Take a look and post to let us know if you have any questions. Thanks!
    Best Regards,
    Chris C
    Applications Engineering
    National Instruments
    Chris Cilino
    National Instruments
    LabVIEW Product Marketing Manager
    Certified LabVIEW Architect
    Attachments:
    Calling_LabVIEW_from_C++_Using_ActiveX.zip ‏4972 KB

Maybe you are looking for

  • Address book-multiple names in 1 entry

    How do I add multiple names to one address card? For example, if a married couple has different last names, like John Smith and Jane Doe, when I try to enter in the name field it only lets me enter 1 last name and 1 first name.

  • Bootcamp missing after Yosemite upgrade

    So I had OS-X Mavericks installed and a Windows 7 Bootcamp partition. Now I've installed OS-X Yosemite and I’ve run into a problem. Here are the steps I took: First, I resized partitions manually using Disk Utility to even up the space a bit. Install

  • Soap to File Scenario with BPM

    Hi Guys I have create my Soap to File Scenario using BPM to split the file on "Transformation step" into 7 files and it must save these files to my FTP Server, when testing on sxmb_moni I don't get any errors but when checking on the FTP server no fi

  • Calculated Item in Pivot failed to be entered

    Hello There, I'm sorry that I ask again, but I haven't found an answer to the following issue: Calculated Item in Pivot is not apearing in Chart While trying to add a calculated item to a Pivot table to display the growth, we receive the error: the s

  • Form not going in Query mode

    hello freinds, Happy Christmas ..! i have a Master_Detail form, FORM2 "LN_HEAD" table, that has 3 primary key; ln_code ln_no ln_emp_code "LN_DET" table has foreign key; Relation is set at form design time. lnd_ln_code lnd_ln_no lnd_ln_emp_code Form2