JTree in JDialog

Hello,
How can I display a binded JTree (or any other component like JCombo, JTable ) in a JDialog ?
Thankx

Hi,
check this out
package jclient.view;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import oracle.jbo.RowIterator;
import oracle.jbo.Row;
import oracle.jbo.uicli.mom.JUMetaObjectManager;
import oracle.jbo.uicli.binding.*;
import oracle.jbo.uicli.controls.*;
import oracle.jbo.uicli.*;
import oracle.jbo.uicli.jui.*;
import java.awt.Dimension;
import javax.swing.JPanel;
import java.awt.Rectangle;
public class FormAppModule extends JFrame
// form layout
private GridLayout gridLayout = new GridLayout();
private BorderLayout borderLayout = new BorderLayout();
// The form's top panel
private JPanel topPanel = new JPanel();
private JPanel dataPanel = new JPanel();
// panel definition used in design time
private JUPanelBinding panelBinding = new JUPanelBinding("JClientJDialog.AppModule", null);
// Navigation bar
// the statusbar
private JUStatusBar statusBar = new JUStatusBar();
private JUNavigationBar hiddenNavBar = new JUNavigationBar();
PanelAppModule panelAppModule;
* The default constructor for form
public FormAppModule()
addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
_popupTransactionDialog();
JUApplication juApp = panelBinding.getApplication();
if (juApp != null)
juApp.release();
System.exit(0);
public FormAppModule(JUPanelBinding panelBinding)
this();
setPanelBinding(panelBinding);
* the JbInit method
public void jbInit() throws Exception
// form layout
dataPanel.setLayout(null);
panelAppModule = new PanelAppModule();
panelAppModule.setPanelBinding(this.getPanelBinding());
panelAppModule.setBounds(new Rectangle(75, 50, 280, 185));
this.getContentPane().setLayout(gridLayout);
topPanel.setLayout(borderLayout);
this.getContentPane().add(topPanel);
this.setSize(new Dimension(435, 361));
dataPanel.add(panelAppModule, null);
topPanel.add(dataPanel, BorderLayout.CENTER);
topPanel.add(statusBar, BorderLayout.SOUTH);
hiddenNavBar.setModel(JUNavigationBar.createPanelBinding(panelBinding, hiddenNavBar));
statusBar.setModel(JUStatusBar.createPanelBinding(panelBinding, statusBar));
public static void main(String [] args)
try
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
catch(Exception exemp)
exemp.printStackTrace();
try
// bootstrap application
JUMetaObjectManager.setBaseErrorHandler(new JUErrorHandlerDlg());
JUApplication app = JUMetaObjectManager.createApplicationObject("JClientJDialog.AppModule", null, new JUEnvInfoProvider());
JUPanelBinding panelBinding = new JUPanelBinding("JClientJDialog.AppModule", null);
panelBinding.setApplication(app);
FormAppModule frame = new FormAppModule(panelBinding);
panelBinding.execute();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = frame.getSize();
// run this form
if (frameSize.height > screenSize.height)
frameSize.height = screenSize.height;
if (frameSize.width > screenSize.width)
frameSize.width = screenSize.width;
frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
frame.setVisible(true);
catch(Exception ex)
JUMetaObjectManager.reportException(null, ex);
System.exit(1);
private void _popupTransactionDialog()
if (panelBinding == null || panelBinding.getPanel() == null)
return;
if (panelBinding.getApplicationModule().getTransaction().isDirty())
Object [] options = {"Commit", "Rollback"};
int action = JOptionPane.showOptionDialog(FormAppModule.this, "How do you want to close the transaction?", "Transaction open", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
switch (action)
case JOptionPane.NO_OPTION:
case JOptionPane.CLOSED_OPTION:
hiddenNavBar.doAction(JUNavigationBar.BUTTON_ROLLBACK);
break;
case JOptionPane.YES_OPTION:
default:
hiddenNavBar.doAction(JUNavigationBar.BUTTON_COMMIT);
break;
public JUPanelBinding getPanelBinding()
return panelBinding;
public void setPanelBinding(JUPanelBinding binding)
if (binding.getPanel() == null)
binding.setPanel(topPanel);
if (panelBinding == null || panelBinding.getPanel() == null)
try
panelBinding = binding;
jbInit();
catch(Exception ex)
panelBinding.reportException(ex);
Frank
}

Similar Messages

  • JTree in JDialog .... addTreeSelectionListener doesn't work ????

    Hi friends,
    jTree1.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
    public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
    jTree1ValueChanged(evt);
    i was trying to display the node position when user selects a node in the JTree.
    but i'm able to do it in JFrame but i'm in need to do it in a JDialog. Please do help me.
    public class Dialog extends JDialog implements TreeSelectionListener
    jTree1 = new JTree(xTn);
    jScrollPane1.setViewportView(jTree1);
    private void jTree1ValueChanged(javax.swing.event.TreeSelectionEvent evt) {
    System.out.println("1");
    private void initComponents()
    jScrollPane1 = new javax.swing.JScrollPane();
    jTree1 = new javax.swing.JTree();
    jLabel1 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    jTabbedPane1 = new javax.swing.JTabbedPane();
    jPanel1 = new javax.swing.JPanel();
    jScrollPane2 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jPanel2 = new javax.swing.JPanel();
    jScrollPane3 = new javax.swing.JScrollPane();
    jEditorPane1 = new javax.swing.JEditorPane();
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    jTree1.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
    public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
    jTree1ValueChanged(evt);
    }// </editor-fold>
    public void valueChanged(TreeSelectionEvent e) {
    System.out.println("2");
    I want to print either "1" or "2"....
    Thanks for the help :-)

    Anandababu_Babu wrote:
    Thanks for the feedback thompson , here is my SSCCE, hope this will help me in better result.You learn quickly. That bodes well. Try this code, note the comments.
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JTree;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    public class Test_Dialog extends JDialog implements TreeSelectionListener
        public Test_Dialog(JFrame frame, boolean modal)
            super(frame, modal);
            jScrollPane1 = new javax.swing.JScrollPane();
            // effectively, the code is instatiating TWO JTrees
            //jTree1 = new javax.swing.JTree();
            setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            getContentPane().setLayout(new java.awt.FlowLayout());
            jScrollPane1.setAutoscrolls(true);
            getContentPane().add(jScrollPane1);
            pack();
            // here is no point calling this twice
            // pack();
            // if a GUI can be shown to break at 800x600, why make it so HUGE?
            //this.setBounds(0, 0, 1025, 735);
            setBounds(0, 0, 800, 600);
            this.setResizable(false);
            DefaultMutableTreeNode xTn = new DefaultMutableTreeNode("Sample");
            for(int i=0; i< 10;i++)
                xTn.add(new DefaultMutableTreeNode("Click "+i));
            jTree1 = new JTree(xTn);
            jScrollPane1.setViewportView(jTree1);
            // this will output "Method 1"
            jTree1.addTreeSelectionListener(this);
            // this will output "Method 2"
            jTree1.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
                public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                    jTree1ValueChanged(evt);
            jScrollPane1.setViewportView(jTree1);
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTree jTree1;
        private void jTree1ValueChanged(javax.swing.event.TreeSelectionEvent evt) {
            System.out.println("Method 1");
        public void valueChanged(TreeSelectionEvent e) {
           System.out.println("Method 2");
        public static void main(String aregsadf[])
            // these changes ensure the user is able to end the
            // JVM easily when running from the command line
            JFrame frame = new JFrame();
            frame.setSize(400,300);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
            // end 'easy end' changes
            new Test_Dialog(frame, true).setVisible(true);
    }

  • Help needed redrawing a JTree

    Hi,
    I'm writing a simple Swing program to examine the entries in a JAR file as a JTree. It is not meant to be professional grade, it's simply for my own fun.
    I have the program so that it displays a Window with a Menus. When the user chooses a JAR file, the program opens the JAR file, reads the entries in the file, and builds a DefaultTreeModel for the entries in the JAR file. Then, it builds a JTree from the DefaultTreeModel.
    The program works great, except, once the tree is created, I don't know how to force Swing to redraw the JFrame.
    Can someone please tell me what I'm doing wrong?
    The code is as follows:
    <pre>
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.io.*;
    import java.util.jar.*;
    import java.util.*;
    * <p>This class is used to display the contents of a JAR file.
    * The entries of the JAR file will be displayed in Swing Tree.
    * @version 1.0
    * @author Kevin Yetman
    public class JarFileTree
    * <p>This method is used to display the GUI.
    public static void main(String[] args)
    {  JFrame frame=new JarTreeFrame();
    frame.show();
    * <p>This class is used to define the javax.swing.JFrame based object that
    * will contain the tree from the JAR file.
    class JarTreeFrame extends JFrame implements ActionListener
    private JTree tree;
    private DefaultTreeModel treeModel;
    private DefaultMutableTreeNode root;
    private JScrollPane scrollPane;
    * <P>This constructor is used create and display the frame.
    public JarTreeFrame()
    {  setTitle("JAR Viewer");
    setSize(800, 600);
    addWindowListener(new WindowAdapter()
    {  public void windowClosing(WindowEvent e)
    {  System.exit(0);
    JMenuBar menuBar=setupMenuBar();
    setJMenuBar(menuBar);
    root = new DefaultMutableTreeNode("No file selected yet.");
    treeModel=new DefaultTreeModel(root);
    tree = new JTree(treeModel);
    scrollPane=new JScrollPane(tree);
    Container contentPane=getContentPane();
    contentPane.add(scrollPane);
    public void processString(String currentEntry, DefaultMutableTreeNode currentNode, DefaultTreeModel treeModel)
    if( currentEntry.length()==0 )
    {  return;
    int slashPos=currentEntry.indexOf('/');
    String currentToken="";
    String remainingPartOfCurrentEntry="";
    if( slashPos!=-1 )
    {  currentToken=currentEntry.substring(0, slashPos);
    remainingPartOfCurrentEntry=currentEntry.substring(slashPos+1, currentEntry.length());
    else
    {  currentToken=currentEntry;
    boolean childFound=false;
    for(Enumeration e=currentNode.children(); e.hasMoreElements(); )
    DefaultMutableTreeNode currentChild=(DefaultMutableTreeNode)e.nextElement();
    if( currentChild.toString().equals(currentToken) )
    processString(remainingPartOfCurrentEntry, currentChild, treeModel);
    childFound=true;
    if( !childFound )
    DefaultMutableTreeNode newChild=new DefaultMutableTreeNode(currentToken);
    treeModel.insertNodeInto(newChild, currentNode, currentNode.getChildCount());
    protected JMenuBar setupMenuBar()
    JMenuBar menuBar=new JMenuBar();
    JMenu helpMenu =new JMenu("Help");
    JMenuItem aboutItem=new JMenuItem("About");
    aboutItem.setActionCommand("HelpAbout");
    aboutItem.addActionListener(this);
    helpMenu.add(aboutItem);
    JMenu fileMenu = new JMenu("File");
    JMenuItem openItem=new JMenuItem("Open");
    openItem.setActionCommand("FileOpen");
    openItem.addActionListener(this);
    JMenuItem exitItem=new JMenuItem("Exit");
    exitItem.addActionListener( new ActionListener()
    {  public void actionPerformed(ActionEvent evt)
    { System.exit(0);
    fileMenu.add(openItem);
    fileMenu.add(exitItem);
    menuBar.add(fileMenu);
    menuBar.add(helpMenu);
    return menuBar;
    public void setupTree(String fileName)
    try
    JarFile jarFile=new JarFile(new File(fileName));
    for(Enumeration e=jarFile.entries(); e.hasMoreElements(); )
    String currentEntry=(e.nextElement().toString()).trim();
    processString(currentEntry, root, treeModel);
    DefaultMutableTreeNode lastLeaf=root.getLastLeaf();
    TreePath path=new TreePath(treeModel.getPathToRoot(lastLeaf));
    tree.makeVisible(path);
    catch(IOException e)
    {  JOptionPane.showMessageDialog(this, "ERROR: " + e.toString());
    public void actionPerformed(ActionEvent evt)
    if(evt.getActionCommand().equals("FileOpen"))
    FileOpenSaveAs fosa=new FileOpenSaveAs(this, true);
    if(fosa.approveOptionClicked())
    String fileName=fosa.getSelectedFile();
    fileName+=".jar";
    setupTree(fileName);
    Container contentPane=getContentPane();
    contentPane.removeAll();
    contentPane.add(new JScrollPane(tree));
    contentPane.repaint();
    if(evt.getActionCommand().equals("HelpAbout"))
    {  JOptionPane.showMessageDialog(this, "JAR Viewer Version 1.0\nKevin Yetman");
    // FileOpenSaveAs.java
    // Author: Kevin Yetman
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.event.*;
    // this class handles the display of the
    // File Open or File Save As box.
    public class FileOpenSaveAs {
    // the constructor takes one argument, a
    // boolean which if true opens the File Open
    // box. If false it opens the save as box.
    public FileOpenSaveAs(JFrame baseWindow, boolean fileOpenBox) {
    // initailze the result varialbe
    result=-1;
    // store the value of the fileOpenBox.
    openBox=fileOpenBox;
    // initialize the fileNameSelected string.
    fileNameSelected=new String();
    // first build a JFileChooser.
    JFileChooser fc=new JFileChooser();
    // next tell the file chooser to look in the
    // current directory.
    fc.setCurrentDirectory(new File(CURRENT_DIRECTORY));
    // if the file open box is true, display the file open box.
    // otherwise, display the file save as box.
    if( fileOpenBox ) {
    fc.setDialogTitle(OPEN_TITLE);
    displayBox(baseWindow, fc);
    else {
    fc.setDialogTitle(SAVE_AS_TITLE);
    displayBox(baseWindow, fc);
    // the constructor takes one argument, a
    // boolean which if true opens the File Open
    // box. If false it opens the save as box.
    public FileOpenSaveAs(JDialog baseWindow, boolean fileOpenBox) {
    // initailze the result varialbe
    result=-1;
    // store the value of the fileOpenBox.
    openBox=fileOpenBox;
    // initialize the fileNameSelected string.
    fileNameSelected=new String();
    // first build a JFileChooser.
    JFileChooser fc=new JFileChooser();
    // next tell the file chooser to look in the
    // current directory.
    fc.setCurrentDirectory(new File(CURRENT_DIRECTORY));
    // if the file open box is true, display the file open box.
    // otherwise, display the file save as box.
    if( fileOpenBox ) {
    fc.setDialogTitle(OPEN_TITLE);
    displayBox(baseWindow, fc);
    else {
    fc.setDialogTitle(SAVE_AS_TITLE);
    displayBox(baseWindow, fc);
    // this method displays the File Open box on the base window.
    public void displayBox(JFrame baseWindow, JFileChooser fc) {
    // display the file open box and get the result.
    result=-1;
    if( openBox==true ) {
    result=fc.showOpenDialog(baseWindow);
    else {
    result=fc.showSaveDialog(baseWindow);
    // get the file name.
    if( approveOptionClicked() ) {
    fileNameSelected=fc.getName(fc.getSelectedFile());
    else {
    fileNameSelected="";
    // this method displays the File Open box on the base window.
    public void displayBox(JDialog baseWindow, JFileChooser fc) {
    // display the file open box and get the result.
    result=-1;
    if( openBox==true ) {
    result=fc.showOpenDialog(baseWindow);
    else {
    result=fc.showSaveDialog(baseWindow);
    // get the file name.
    if( approveOptionClicked() ) {
    fileNameSelected=fc.getName(fc.getSelectedFile());
    else {
    fileNameSelected="";
    // check to see if the result is APPROVE_OPTION. If so, we
    // will return true.
    public boolean approveOptionClicked() {
    return (result == JFileChooser.APPROVE_OPTION );
    // get the file name chosen by the user.
    public String getSelectedFile() {
    return fileNameSelected;
    // private attributes for this class.
    private boolean openBox;
    private static final String CURRENT_DIRECTORY=".";
    private static final String SAVE_AS_TITLE="Save As";
    private static final String OPEN_TITLE="Open";
    private int result;
    private String fileNameSelected;
    </pre>
    Thanks!
    Kevin Yetman

    Without looking at all your code, I would suggest that you only redraw the part of the tree that changes (addition or deletion of nodes). To do this, you can call a method of DefaultTreeModel, nodeStructureChanged(TreeNode nodeThatChanged). This fires the appropriate event which in turn causes the node and only its descendents to be redrawn. Good luck.
    -Matt

  • Chinese characters in JDialog title?

    Hi all,
    I'm running the JDK on an english language machine, but starting a program with the command line prompt -Duser.language=zh to display Chinese characters.
    If I have some chinese characters in a JDialog title, or a JOptionPane message or title, the characters are replaced with boxes. I can see Chinese characters everywhere else, in JLabels, text boxes, JTrees, etc, so its not a problem with fonts.
    Has anybody else had this problem? Is there a work around for this? Is it something to do with the UIManager setting the fonts for JOptionPane's?
    thanks,
    Justin

    Try calling these at the start of your app before showing any windows:
    JFrame.setDefaultLookAndFeelDecorated(true);
    JDialog.setDefaultLookAndFeelDecorated(true);
    If that doesn't work, I don't know what would. The default is that the OS draws the frame titlebar, and on English systems, it's not going to display chars that aren't in the charset. I'm sure you could change that by installing other charsets, but you can't really do that on other people's machines.

  • Help with JTree

    I wrote a cls that extends JTree....I have defined the root node in this class.
    Public class a extends JTree{
    /// global variable nd constructor
    public void JTReader()
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
               m_model = new DefaultTreeModel(root);
                //program logic to get the parent and child nodes
           //method defined for adding child to parent
           addNode (child,parent);
          //rest of the code
         expandRoot();
         setBounds(0,0,500,500);
    public void addNodeTo(String childNodeName, String parentNodeName)
              //code for chking if the node is already present
              //add child to parent at the end of child list
              ((DefaultTreeModel)getModel()).insertNodeInto(childNode, parentNode, parentNode.getChildCount());     
         }     I want to call this class in my main program which extends Jpanel�.
    I have written this
    public class LibGui extends JDialog{
    private JTreeReader tree;
      JTree newtree;
    Constructor{
        libInit();
    void libInit() throws Exception {
    initializing the panel�
             updateclslist(projectName);
            libScrollPane = new JScrollPane(tree);
            libScrollPane.add(tree);
           clslistHolder.add(libScrollPane, BorderLayout.CENTER);
          cbPanel.add(clslistHolder, BorderLayout.CENTER);
    //rest of code
    protected void updateclslist(String projectName){
        JTreeReader tr = new JTreeReader(projectName);
        tree.JTReader();
         }       

    Swing related questions should be posted in the Swing forum.
    The Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html]How to Use Trees has working examples.

  • Popup JTree

    I created a subclass of JWindow which acts as a popup when the appropriate mousebutton is clicked. A JTree is shown in an etched border and when the user selects an item in the tree it updates the JTextField the popup is connected to. It is similar in concept to a JComboBox but rather then a list, it uses a tree. It is connected to two JTextFields in a subclass of JDialog. This works great when dialog box is run in the applet window under VAJ. However, when the dialog box is created (.show()) from within a JApplet in the browser it appears fine when the right mouse button is pressed in the appropriate JTextField but as soon as a mouse button is pressed within the popped up JTree, the popped up window (JWindow subclass) is forced behind the other window. If the roller on the microsoft mouse is used the jtree can be scrolled but if I try to manipulate the scrollbar the window disappears behind the parent window. How can I lock the window in place until I dispose of it??
    Thanks,
    Walt

    The problem is actually a problem in VAJ. The code generated by the VCE does not allow for creating the popup with a parent window. It is still unclear why when it was created on top of the 'parent' window and the scrollbar should have digested the mouse event, that the mouse event percolated through the popup to the underlying window, causing it to gain focus and be placed on top in the Z order. Anyone that can answer that one get the duke bucks too. What I did was modify the alternative constructors for the popup to initialize the window (set the listeners) which appears to be another bug in VAJ and then manually create the popup as invisible. Normally VAJ uses lazy construction to only construct the object upon first reference. Since that code is automatically regenerated by the VCE I couldn't modify it.
    Another question is why does the JWindow appear with the foolish "Java Applet Window" text in a status area. And why does a JWindow even have a status area? The drop down list of a JComboBox doesn't have one. And that was really all I wanted was a JComboBox with a tree instead of a list. So if anyone can address that, there are duke dollars available for it as well.
    So the questions are:
    1) why does the mouse action percolate through the popup window, which should have captured and digested it, even if only through the scrollbar logic?
    2) what does the JWindow based popup get stuck with the "Java Applet Window" text in an unwanted status area.
    3) how could this simply be like a JComboBox with a drop down JTree, as opposed to drop down list?
    Thanks,
    Walt

  • Jtree custom nodes

    Hi there,
    the "How to Use Trees" tutorial shows how to create simple JTrees where each node is a String:
    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html
    I need to have tree structure where each node is like a form entry.
    For example some like this:
    + name: [ ........... ]
    + surname: [ ........... ]
    + child
    ---------+ name: [ ........... ]
    ---------+ surname: [ ........... ]
    and so on...
    The best way that I can think of to do that is to make each node be a JPanel and add to it a JLabel and a JTextField. If this is really the best way to do that then my JTree needs to have something different than DefaultMutableTreeNode as nodes because they can only be used to display Strings.
    So provided there is no better way to do what I want to do, the question is, how do I put a JPanel in a JTree node?

    I think the better way is to use a UserObject giving a summary String in its toString method for standard node display, and to display an extra JDialog for editing all the details of the UserObject if the user chooses to edit the node. Imho, displaying complex nodes directly in the tree tends to confuse the user.

  • Update JPanel in JDialog

    Hey,
    need some help please....
    I've searched long and hard but can't find anything.
    I've got an application that opens a JDialog, then jDialog has a JPanel within
    it.
    Once the JDialog has loaded on the screen i want to update the Jpanel based on
    a button click.
    My problem is that the JPanel wont update.
    I've made a simple program that displays the same behaviour.
    Frame with a button on it to open a JDialog :
    public class testFrame extends javax.swing.JFrame {
        /** Creates new form testFrame */
        public testFrame() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            jButton1 = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jButton1.setText("Show Dialog");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(150, 150, 150)
                    .addComponent(jButton1)
                    .addContainerGap(159, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(135, 135, 135)
                    .addComponent(jButton1)
                    .addContainerGap(142, Short.MAX_VALUE))
            pack();
        }// </editor-fold>
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            testJDialog test = new testJDialog(this,true);
            test.setVisible(true);
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new testFrame().setVisible(true);
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        // End of variables declaration
    }JDialog code :
    import javax.swing.JTree;
    * @author  wesley
    public class testJDialog extends javax.swing.JDialog {
        /** Creates new form testJDialog */
        public testJDialog(java.awt.Frame parent, boolean modal) {
            super(parent, modal);
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            jPanel1 = new javax.swing.JPanel();
            jButton1 = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
            jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("TitleBorder"));
            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 347, Short.MAX_VALUE)
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGap(0, 128, Short.MAX_VALUE)
            jButton1.setText("Add Tree");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(145, 145, 145)
                            .addComponent(jButton1)))
                    .addContainerGap(31, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(jButton1)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            pack();
        }// </editor-fold>
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            this.jPanel1.add(new JTree());
            this.pack();
            this.repaint();
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    testJDialog dialog = new testJDialog(new javax.swing.JFrame(), true);
                    dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                        public void windowClosing(java.awt.event.WindowEvent e) {
                            System.exit(0);
                    dialog.setVisible(true);
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JPanel jPanel1;
        // End of variables declaration
    }Ive tried
    this.pack();
    this.repaint();but i cant get the JPanel to repaint.
    Im using Vista Java version
    C:\Users\wesley>java -version
    java version "1.6.0_03"
    Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
    Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)Cheers
    Wesley

    wesleyelder wrote:
    Thanks so much for taking the time to reply, that worked a treat.you're welcome
    i agree the netbeans code is a mess sometimes but when i just need a simple JDialog i sometimes use it, just lazy a guess :)But then you run into problems like this one. I'd much prefer to make my own simple JDialog:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    public class TestMyDialog
        private JPanel mainPanel = new JPanel();
        private JPanel centerPanel = new JPanel();
        public TestMyDialog()
            JButton addTreeBtn = new JButton("Add Tree");
            addTreeBtn.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    addTreeAction();
            JPanel buttonPanel = new JPanel();
            buttonPanel.add(addTreeBtn);
            centerPanel.setBorder(BorderFactory.createTitledBorder("Title Border"));
            centerPanel.setPreferredSize(new Dimension(400, 200));
            centerPanel.setLayout(new BorderLayout());
            mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
            mainPanel.setLayout(new BorderLayout(20, 20));
            mainPanel.add(centerPanel, BorderLayout.CENTER);
            mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        private void addTreeAction()
            JTree tree = new JTree();
            tree.setOpaque(false);
            centerPanel.add(new JScrollPane(tree), BorderLayout.CENTER);
            centerPanel.revalidate();
        public JPanel getMainPanel()
            return mainPanel;
        private static void createAndShowUI()
            final JFrame frame = new JFrame("Test My Dialog");
            JPanel framePanel = new JPanel();
            framePanel.setBorder(BorderFactory.createEmptyBorder(200, 200, 200, 200));
            framePanel.setPreferredSize(new Dimension(500, 500));
            JButton showDialogBtn = new JButton("Show Dialog");
            showDialogBtn.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    showDialogAction(frame);
            framePanel.add(showDialogBtn);
            frame.getContentPane().add(framePanel);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        private static void showDialogAction(JFrame frame)
            JDialog dialog = new JDialog(frame, "My Dialog", true);
            dialog.getContentPane().add(new TestMyDialog().getMainPanel());
            dialog.pack();
            dialog.setLocationRelativeTo(null);
            dialog.setVisible(true);
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }

  • Connecting lines in JTree

    Hi,
    I have a JTree with each node having bigger icons, and bigger font.
    So the connecting lines are kind of misplaced
    for example the vertical line that connect the root node to it's children doesn't come from the center of the root node rather it is placed leftwards from the root node center.
    Is it possible to shift the connecting lines in a JTree?
    Thanks
    -desiguy

    import java.awt.*;
    import java.awt.geom.AffineTransform;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    import javax.swing.plaf.*;
    import javax.swing.tree.*;
    public class TreeLines {
        private Icon[] getScaledIcons(Component c) {
            String[] iconIds = { "closed", "collapsed", "expanded", "leaf", "open" };
            Icon[] icons = new Icon[iconIds.length];
            for(int j = 0; j < icons.length; j++) {
                icons[j] = UIManager.getIcon("Tree." + iconIds[j] + "Icon");
            ImageIcon[] imageIcons = new ImageIcon[icons.length];
            double scale = 1.25;
            for(int j = 0; j < icons.length; j++) {
                int w = (int)(scale * icons[j].getIconWidth());
                int h = (int)(scale * icons[j].getIconHeight());
                int type = BufferedImage.TYPE_INT_ARGB_PRE;
                BufferedImage image = new BufferedImage(w, h, type);
                Graphics2D g2 = image.createGraphics();
                g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                    RenderingHints.VALUE_INTERPOLATION_BICUBIC);
                AffineTransform at = AffineTransform.getScaleInstance(scale, scale);
                g2.setTransform(at);
                icons[j].paintIcon(c, g2, 0, 0);
                g2.dispose();
                imageIcons[j] = new ImageIcon(image);
            //JOptionPane.showMessageDialog(null, imageIcons, "", JOptionPane.PLAIN_MESSAGE);
            //JOptionPane.showMessageDialog(null, icons, "", JOptionPane.PLAIN_MESSAGE);
              return imageIcons;
        private void expandTree(JTree tree)
            DefaultMutableTreeNode root = (DefaultMutableTreeNode)tree.getModel().getRoot();
            java.util.Enumeration e = root.breadthFirstEnumeration();
            while(e.hasMoreElements())
                DefaultMutableTreeNode node = (DefaultMutableTreeNode)e.nextElement();
                if(node.isLeaf()) break;
                int row = tree.getRowForPath(new TreePath(node.getPath()));
                tree.expandRow(row);
        private JScrollPane getContent() {
            JTree tree = new JTree();
            expandTree(tree);
            return new JScrollPane(tree);
        public static void main(String[] args) {
            TreeLines treeLines = new TreeLines();
            Icon[] icons = treeLines.launchDialog();
            UIManager.put("Tree.closedIcon",    new IconUIResource(icons[0]));
            UIManager.put("Tree.collapsedIcon", new IconUIResource(icons[1]));
            UIManager.put("Tree.expandedIcon",  new IconUIResource(icons[2]));
            UIManager.put("Tree.leafIcon",      new IconUIResource(icons[3]));
            UIManager.put("Tree.openIcon",      new IconUIResource(icons[4]));
            UIManager.put("Tree.font", new FontUIResource(
                                       new Font("Dialog", Font.PLAIN, 18)));
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(treeLines.getContent());
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
        /** To get and scale some images to use. */
        private Icon[] launchDialog() {
            JTree tree = new JTree();
            JDialog d = new JDialog(new JFrame(), false);
            d.getContentPane().add(tree);
            d.pack();
            Icon[] icons = getScaledIcons(tree);
            d.dispose();
            return icons;
    }

  • Problem updating JTree via RMI

    I'm programming an Instant Messenger application in Java using RMI extensively. Much like most IM applications, my IM clients display a "buddy list" window upon successful authentication with the server. I have reached a huge stumbling block at this point. My Buddylist JFrame contains a JTree that is used to display the status of the user's buddies (i.e. online, offline). I am able to populate the JTree without any problems BEFORE the JFrame is displayed by using the DefaultTreeModel's insertNodeInto() method. But the problem I'm having is that, once the Buddylist is displayed to the user, I can't successfully update the JTree to reflect changing user status. For example, let's say a user with the screename "qwerty" logs in to the server. Now "qwerty" sees his Buddylist pop up on screen. His Buddylist contains 1 user (for simplicity's sake) with screename "foo". "foo" is currently not logged into the system so "foo" is shown in the Buddylist as a child of node Offline. But right now, let's say that "foo" logs into the system. "qwerty's" Buddylist should be updated to reflect the fact that "foo" just signed in by removing "foo" as a child node of Offline and adding a new node to Online called "foo".
    I currently have this functionality implemented as an RMI callback method on the server side. When "foo" logs in, the server calls the method fireBuddyLoggedOnEvent() with "foo" as the argument. Because "qwerty" is already logged in, and both users are each other's buddy, the statement
         c.getCallback().buddySignedOn(screenname);
    will be executed on the client side. Unfortunately, even though this code is successfully executed remotely, "qwerty's" Buddylist's JTree does not update to show that "foo" is now online. My only suspicion is that this is due to the fact that the Buddylist is already visible and this somehow affects its ability to be updated (remember that I have no problem populating the tree BEFORE it's visible). However, I've weeded out this possibility by creating a test frame in which its JTree is successfully updated, but in response to an ActionEvent in response to a button click. Of course, this test case was not an RMI application and does not come with the complexities of RMI. Please help me resolve this issue as it's preventing me from proceeding with my project.
    ~BTW, sorry for the poor code formatting. I added all the code in wordpad and pasted it in here, which stripped the formatting.
    * Frame that allows the user to enter information to
    * be used to login to the server.
    public class LoginFrame extends JFrame {
         signonButton.addActionListener(new java.awt.event.ActionListener() {
              public void actionPerformed(java.awt.event.ActionEvent e) {
                   if (!screenameTextField.getText().equals("") &&
                   !passwordTextField.getPassword().equals("")) {
                        try {
                             serverInter = (ServerInter) Naming.lookup(serverName);
                             String username = screenameTextField.getText();
                             String password = String.valueOf(passwordTextField.getPassword());
                             int connectionID = serverInter.connect(username, password);
                             System.out.println("authenticate successful");
                             dispose();
                             Buddylist buddyList = new Buddylist(username, connectionID);
                             // Registers the buddylist with the server so that
                             // the server can remotely call methods on the
                             // Buddylist.
                             serverInter.registerCallback(buddyList, connectionID);
                             return;
                             } catch (Exception e1) {
                                  JOptionPane.showMessageDialog(LoginFrame.this, e1.getMessage(),
                                            "Connection Error", JOptionPane.ERROR_MESSAGE);
                                  passwordTextField.setText("");
                                  signonButton.setEnabled(false);
                                  e1.printStackTrace();
         public static void main(String[] args) {
              new LoginFrame();
    public class Buddylist extends JFrame implements BuddylistInter {
         public Buddylist(String username, int connectionID) {
              try {
                   serverInter = (ServerInter) Naming.lookup(serverName);
                   this.username = username;
                   this.connectionID = connectionID;
                   this.setTitle(username + "'s BuddyList");
                   initialize();
                   } catch (Exception e) {
                        e.printStackTrace();
         * Method of interest. Note that this method uses a DynamicTree
         * object as included in the Sun tutorial on JTree's
         * (located at http://www.iam.ubc.ca/guides/javatut99/uiswing/components/tree.html#dynamic).
         * Don't worry too much about where the node is getting added
         * but rather, that i wish to verify that an arbitrary node
         * can successfully be inserted into the tree during this
         * remote method call
         public void buddySignedOn(String screenname) throws RemoteException {
              // should add screename at some location in the tree
              // but doesn't!
              treePanel.addObject(screename);
    * Oversimplified interface for the Buddylist that is intended
    * to be used to allow callbacks to the clientside.
    public interface BuddylistInter extends Remote {
         public void buddySignedOn(String screenname) throws RemoteException;
    * Another oversimplified interface that is to be
    * implemented by the server so that the client can
    * call remote server methods.
    public interface ServerInter extends java.rmi.Remote {
         // "Registers" the given Buddylist with this server to allow
         // remote callbacks on the Buddylist.
         public void registerCallback(Buddylist buddylist, int connectionID)
                             throws RemoteException;
    public class Server extends UnicastRemoteObject implements ServerInter {
         private Vector loggedInUsers = new Vector();
         // Note that this method assumes that a Connection object
         // representing the Buddylist with connectionID was added
         // to the loggedInUsers list during authentication.
         public void registerCallback(Buddylist buddylist, int connectionID) throws RemoteException {          
              int index = loggedInUsers.indexOf(new Connection(connectionID));
              Connection c = (Connection) loggedInUsers.get(index);
              c.setCallback(buddylist);
         // Method that's called whenever a client successfully
         // connects to this server object.
         // screename is the name of the user that successfully
         // logged in.
         private void fireBuddyLoggedOnEvent(String screenname) {
              // Examines each logged in client to determine whether
              // or not that client should be notified of screename's
              // newly logged in status.
              for (int i = 0; i < loggedInUsers.size(); i++) {
                   Connection c = (Connection) loggedInUsers.get(i);
                   if (database1.areBuddies(screenname, c.getUsername())) {
                        try {
                             // getCallback() returns a reference to
                             // the Buddylist that was registered
                             // with this server. At this point,
                             // the server attempts to notify the
                             // client that one of his "buddies" has
                             // just logged into the server.
                             c.getCallback().buddySignedOn(screenname);
                        } catch (RemoteException e) {
                             e.printStackTrace();
    }

    Ok, I deleted all .class files, recomplied, and rmic'd, and I still get the IllegalArgumentException. So I've decided to just post all the code here because I don't want to make an assumption that all the code is correct. Thanks for helping me out with this very stressful problem.
    * Created on Nov 13, 2006
    import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.rmi.Naming;
    import java.rmi.NotBoundException;
    import java.rmi.RemoteException;
    import java.rmi.server.UnicastRemoteObject;
    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JPanel;
    import javax.swing.JSeparator;
    import javax.swing.SwingUtilities;
    import javax.swing.tree.DefaultMutableTreeNode;
    public class Buddylist extends JFrame implements BuddylistInter {
         private String serverName = "//Broom:" + "5001" + "/IMServer";
         private DynamicTree treePanel = null;
         private String onlineString = "Online";
         private String offlineString = "Offline";
         private DefaultMutableTreeNode onlineNode = null;
         private DefaultMutableTreeNode offlineNode = null;
         private ImageUpdater imageUpdater = null;
         private javax.swing.JPanel jContentPane = null;
         private ServerInter serverInter = null;
         private String username = null;
         // A connectionID of -1 indicates that this Buddylist
         // has not yet received a valid id from the server.
         private int connectionID = -1;
         private JMenuBar jJMenuBar = null;
         private JMenu jMenu = null;
         private JMenu jMenu1 = null;
         private JMenu jMenu2 = null;
         private JPanel imagePanel = null;
         private JSeparator jSeparator1 = null;
         public Buddylist(String username, int connectionID) {
             try {
                   serverInter = (ServerInter) Naming.lookup(serverName);
                   this.username = username;
                   this.connectionID = connectionID;
                   this.setTitle(username + "'s BuddyList");
                   imageUpdater = new ImageChooser(this);
                   initialize();
                    * This statement is causing an IllegalArgumentException
                    * to be thrown! I've tried inserting it at the beginning
                    * of the constructor and that doesn't help.
                   UnicastRemoteObject.exportObject(this);
              } catch (MalformedURLException e) {
                   e.printStackTrace();
              } catch (RemoteException e) {
                   e.printStackTrace();
              } catch (NotBoundException e) {
                   e.printStackTrace();
          * This method initializes this
          * @return void
         private void initialize() {
              this.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
              this.setJMenuBar(getJJMenuBar());
              this.setPreferredSize(new java.awt.Dimension(196,466));
              this.setMinimumSize(new java.awt.Dimension(150,439));
              this.setSize(196, 466);
              this.setContentPane(getJContentPane());
              this.setLocationRelativeTo(null);
              this.setVisible(true);
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private javax.swing.JPanel getJContentPane() {
              if(jContentPane == null) {
                   jContentPane = new javax.swing.JPanel();
                   jContentPane.setLayout(null);
                   jContentPane.add(getImagePanel(), null);
                   jContentPane.add(getJSeparator1(), null);
                   jContentPane.add(getTreePanel(), null);
              return jContentPane;
         private DynamicTree getTreePanel() {
              if (treePanel == null) {
                   treePanel = new DynamicTree();
                   onlineNode = treePanel.addObject(null, onlineString);
                   offlineNode = treePanel.addObject(null, offlineString);
                   treePanel.setBounds(6, 138, 177, 196);
                   populateTree();
                   return treePanel;
              return null;
         private void populateTree() {
              try {
                   String [] buddies = serverInter.getBuddyList(this.username);
                   for (int i = 0; i < buddies.length; i++) {
                        try {
                             if (serverInter.isBuddyOnline(buddies)) {
                                  treePanel.addObject(onlineNode, buddies[i]);
                             else {
                                  treePanel.addObject(offlineNode, buddies[i]);
                        } catch (RemoteException e1) {
                             e1.printStackTrace();
              } catch (RemoteException e) {
                   e.printStackTrace();
         * This method initializes jJMenuBar     
         * @return javax.swing.JMenuBar     
         private JMenuBar getJJMenuBar() {
              if (jJMenuBar == null) {
                   jJMenuBar = new JMenuBar();
                   jJMenuBar.add(getJMenu());
                   jJMenuBar.add(getJMenu1());
                   jJMenuBar.add(getJMenu2());
              return jJMenuBar;
         * This method initializes jMenu     
         * @return javax.swing.JMenu     
         private JMenu getJMenu() {
              if (jMenu == null) {
                   jMenu = new JMenu();
                   jMenu.setText("My IM");
              return jMenu;
         * This method initializes jMenu1     
         * @return javax.swing.JMenu     
         private JMenu getJMenu1() {
              if (jMenu1 == null) {
                   jMenu1 = new JMenu();
                   jMenu1.setText("People");
              return jMenu1;
         * This method initializes jMenu2     
         * @return javax.swing.JMenu     
         private JMenu getJMenu2() {
              if (jMenu2 == null) {
                   jMenu2 = new JMenu();
                   jMenu2.setText("Help");
              return jMenu2;
         * This method initializes imagePanel     
         * @return javax.swing.JPanel     
         private JPanel getImagePanel() {
              if (imagePanel == null) {
                   imagePanel = new JPanel();
                   imagePanel.setBounds(6, 2, 176, 125);
                   try {
                        BufferedImage bi =
                             ImageIO.read(
                                       getClass().getClassLoader().getResourceAsStream("images/cute_dog.jpg"));
                        Image scaled = bi.getScaledInstance(
                                  imagePanel.getWidth(), imagePanel.getHeight(), BufferedImage.SCALE_FAST);
                        final JLabel imageLabel = new JLabel(new ImageIcon(scaled));
                        imageLabel.setToolTipText("Double click to change image");
                        imagePanel.add(imageLabel, imageLabel.getName());
                        imageLabel.addMouseListener(new java.awt.event.MouseAdapter() {
                             public void mouseClicked(java.awt.event.MouseEvent e) {
                                  if (e.getClickCount() == 2) {
                                       Image selected = imageUpdater.getSelectedImage();
                                       if (selected != null) {
                                            BufferedImage bi = (BufferedImage) selected;
                                            Image scaled = bi.getScaledInstance(
                                                      imageLabel.getWidth(), imageLabel.getHeight(), BufferedImage.SCALE_DEFAULT);
                                            imageLabel.setIcon(new ImageIcon(scaled));
                   } catch (IOException e) {
                        e.printStackTrace();
              return imagePanel;
         * This method initializes jSeparator1     
         * @return javax.swing.JSeparator     
         private JSeparator getJSeparator1() {
              if (jSeparator1 == null) {
                   jSeparator1 = new JSeparator();
                   jSeparator1.setBounds(6, 132, 176, 1);
              return jSeparator1;
         public void buddySignedOn(String screenname) throws RemoteException {
              final String temp = screenname;
              Runnable addBuddy = new Runnable() {
                   public void run() {
                        treePanel.addObject(onlineNode, temp);
              SwingUtilities.invokeLater(addBuddy);
         public void buddySignedOff(String screenname) throws RemoteException {
              // TODO Auto-generated method stub
         public boolean equals(Object o) {
              Buddylist buddylist = (Buddylist) o;
              return connectionID == buddylist.connectionID;
         public int hashCode() {
              return connectionID;
    } // @jve:decl-index=0:visual-constraint="10,11"
    * Created on Nov 4, 2006
    import java.rmi.Remote;
    import java.rmi.RemoteException;
    public interface BuddylistInter extends Remote {
         public void buddySignedOn(String screenname) throws RemoteException;
         public void buddySignedOff(String screenname) throws RemoteException;
    * Created on Oct 14, 2006
    * Models a single endpoint of a connection between machines.
    * @author Josh Feldman
    public class Connection {
         private String username;
         private final int connectionID;
         private Buddylist callback = null;
         public Connection(String username, int connectionID) {
              this.username = username;
              this.connectionID = connectionID;
         public Connection(int connectionID) {
              this.connectionID = connectionID;
         public String getUsername() {
              return username;
         public int getConnectionID() {
              return connectionID;
         public void setCallback(Buddylist buddylist) {
              this.callback = buddylist;
         public Buddylist getCallback() {
              return callback;
         public boolean equals(Object o) {     
              Connection otherConnection = (Connection) o;
              if (otherConnection.getConnectionID() == this.connectionID) {
                   return true;
              else {
                   return false;
         public int hashCode() {
              return connectionID;
    * Created on Nov 4, 2006
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.Serializable;
    import java.util.Properties;
    public class Database implements Serializable{
         private final String regex = ";";
         private Properties db = null;
         private String dbPath = "buddies.txt";
         public Database() throws IOException {
              db = new Properties();
              File buddiesFile = new File(dbPath);
              if (!buddiesFile.canRead()) {
                   throw new IOException("Can't read database!");
              try {
                   FileInputStream fis = new FileInputStream(buddiesFile);
                   db.load(fis);
                   System.out.println("database loaded from file");
              } catch (IOException e) {
                   e.printStackTrace();
                   System.err.println("Can't load the database! Exiting program...");
                   System.exit(0);
          * called when a user adds/deletes a user from the buddylist
         public void changeBuddyList() {
              //TODO
         public boolean doesUserExist(String username) {
              System.out.println(db.getProperty(username));
              return db.getProperty(username) != null;
         public String getPassword(String username) {
              String temp = db.getProperty(username);
              String [] split = temp.split(regex);
              if (split.length == 2)
                   return split[0];
              else {
                   return null;
         public String getBuddies(String username) {
              String temp = db.getProperty(username);
              if (temp == null)
                   return null;
              String [] split = temp.split(regex);
              if (split.length != 2)
                   return null;
              else {
                   return split[1];
          * Determines whether screename1 is a buddy of screename2
          * @return
         public boolean areBuddies(String screename1, String screename2) {
              String [] buddies = getUserBuddies(screename2);
              if (buddies == null) {
                   return false;
              else {
                   for (int i = 0; i < buddies.length; i++) {
                        if (buddies.equals(screename1)) {
                             return true;
              return false;
         public String [] getUserBuddies(String username) {
              System.out.println("in db getUserBuddies: username = " + username);
              String temp = db.getProperty(username);
              if (temp == null)
                   return null;
              String [] split = temp.split(regex);
              if (split.length != 2)
                   return null;
              else {
                   return split[1].split(",");
    import java.awt.GridLayout;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.event.TreeModelEvent;
    import javax.swing.event.TreeModelListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.MutableTreeNode;
    import javax.swing.tree.TreePath;
    import javax.swing.tree.TreeSelectionModel;
    // Note that this is not my code but rather code taken
    // from java Sun tutorial
    public class DynamicTree extends JPanel {
        protected DefaultMutableTreeNode rootNode;
        protected DefaultTreeModel treeModel;
        protected JTree tree;
        public DynamicTree() {
            rootNode = new DefaultMutableTreeNode("Root Node");
            treeModel = new DefaultTreeModel(rootNode);
            treeModel.addTreeModelListener(new MyTreeModelListener());
            tree = new JTree(treeModel);
            tree.setRootVisible(false);
            tree.setEditable(false);
            tree.getSelectionModel().setSelectionMode
                    (TreeSelectionModel.SINGLE_TREE_SELECTION);
            tree.setShowsRootHandles(false);
            JScrollPane scrollPane = new JScrollPane(tree);
            setLayout(new GridLayout(1,0));
            add(scrollPane);
        /** Remove all nodes except the root node. */
        public void clear() {
            rootNode.removeAllChildren();
            treeModel.reload();
        /** Remove the currently selected node. */
        public void removeCurrentNode() {
            TreePath currentSelection = tree.getSelectionPath();
            if (currentSelection != null) {
                DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)
                             (currentSelection.getLastPathComponent());
                MutableTreeNode parent = (MutableTreeNode)(currentNode.getParent());
                if (parent != null) {
                    treeModel.removeNodeFromParent(currentNode);
                    return;
        public void removeObject(DefaultMutableTreeNode child) {
             treeModel.removeNodeFromParent(child);
    //         treeModel.reload();
        /** Add child to the currently selected node. */
        public DefaultMutableTreeNode addObject(Object child) {
            DefaultMutableTreeNode parentNode = null;
            TreePath parentPath = tree.getSelectionPath();
            if (parentPath == null) {
                parentNode = rootNode;
            } else {
                parentNode = (DefaultMutableTreeNode)
                             (parentPath.getLastPathComponent());
            return addObject(parentNode, child, true);
        public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
                                                Object child) {
            return addObject(parent, child, false);
        public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent,
                                                Object child,
                                                boolean shouldBeVisible) {
            DefaultMutableTreeNode childNode =
                    new DefaultMutableTreeNode(child);
            if (parent == null) {
                parent = rootNode;
            treeModel.insertNodeInto(childNode, parent,
                                     parent.getChildCount());
            // Make sure the user can see the lovely new node.
            if (shouldBeVisible) {
                tree.scrollPathToVisible(new TreePath(childNode.getPath()));
            return childNode;
        class MyTreeModelListener implements TreeModelListener {
            public void treeNodesChanged(TreeModelEvent e) {
                DefaultMutableTreeNode node;
                node = (DefaultMutableTreeNode)
                         (e.getTreePath().getLastPathComponent());
                 * If the event lists children, then the changed
                 * node is the child of the node we've already
                 * gotten.  Otherwise, the changed node and the
                 * specified node are the same.
                try {
                    int index = e.getChildIndices()[0];
                    node = (DefaultMutableTreeNode)
                           (node.getChildAt(index));
                } catch (NullPointerException exc) {}
                System.out.println("The user has finished editing the node.");
                System.out.println("New value: " + node.getUserObject());
            public void treeNodesInserted(TreeModelEvent e) {
            public void treeNodesRemoved(TreeModelEvent e) {
            public void treeStructureChanged(TreeModelEvent e) {
        public DefaultTreeModel getModel() {
             return treeModel;
    * Created on Sep 24, 2006
    import java.awt.Frame;
    import java.awt.Image;
    import javax.swing.JComponent;
    * Generic Dialog for allowing a user to browse
    * his filesystem for an image file. Dialog
    * displays a preview of the image (if it is in fact
    * displayable).
    * @author Josh Feldman
    public class ImageChooser extends JComponent implements ImageUpdater{
         private Frame parent = null;
         public ImageChooser(Frame parent) {
              super();
              this.parent = parent;
         public Image getSelectedImage() {
              ImageChooserDialog dialog = new ImageChooserDialog(parent);
              if (dialog.showDialog() == ImageChooserDialog.OK_OPTION) {
                   return dialog.getSelectedImage();
              return null;
    }  //  @jve:decl-index=0:visual-constraint="10,10"
    * Created on Sep 24, 2006
    import java.awt.Frame;
    import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.JDialog;
    import javax.swing.ImageIcon;
    import javax.swing.JFileChooser;
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.JButton;
    * Class that displays a dialog that allows a user
    * to browse his/her filesystem for an image file
    * for selection.
    * @author Josh Feldman
    public class ImageChooserDialog extends JDialog {
         private Frame parent = null;
         private JFileChooser fileChooser = new JFileChooser();
         private int option;
         public final static int OK_OPTION = 1;
         public final static int CANCEL_OPTION = 2;
         private Image selectedImage = null;
         private javax.swing.JPanel jContentPane = null;
         private JPanel previewPanel = null;
         private JLabel jLabel = null;
         private JTextField filenameTextField = null;
         private JButton browseButton = null;
         private JButton cancelButton = null;
         private JButton okButton = null;
         private JLabel previewLabel = null;
          * This is the default constructor
         public ImageChooserDialog(Frame parent) {
              super();
              this.parent = parent;
              this.setTitle("Select Image");
              initialize();
         public ImageChooserDialog(Frame parent, String title) {
              super();
              this.parent = parent;
              this.setTitle(title);
              initialize();
          * This method initializes this
          * @return void
         private void initialize() {
              this.setModal(true);
              this.setSize(377, 246);
              this.setContentPane(getJContentPane());
              this.setVisible(false);
              this.setLocationRelativeTo(parent);
              this.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowClosing(java.awt.event.WindowEvent e) {
                        selectedImage = null;
                        option = CANCEL_OPTION;
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private javax.swing.JPanel getJContentPane() {
              if(jContentPane == null) {
                   jLabel = new JLabel();
                   jContentPane = new javax.swing.JPanel();
                   jContentPane.setLayout(null);
                   jLabel.setBounds(87, 192, 58, 10);
                   jLabel.setText("Preview");
                   jContentPane.add(getPreviewPanel(), null);
                   jContentPane.add(jLabel, null);
                   jContentPane.add(getFilenameTextField(), null);
                   jContentPane.add(getBrowseButton(), null);
                   jContentPane.add(getCancelButton(), null);
                   jContentPane.add(getOkButton(), null);
              return jContentPane;
          * This method initializes previewPanel     
          * @return javax.swing.JPanel     
         private JPanel getPreviewPanel() {
              if (previewPanel == null) {
                   previewPanel = new JPanel();
                   previewLabel = new JLabel();
                   previewPanel.setLayout(null);
                   previewPanel.setLocation(25, 62);
                   previewPanel.setSize(172, 125);
                   previewPanel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
                   previewLabel.setText("");
                   previewLabel.setLocation(2, 2);
                   previewLabel.setSize(172, 125);
                   previewPanel.add(previewLabel, null);
              return previewPanel;
          * This method initializes jTextField     
          * @return javax.swing.JTextField
         private JTextField getFilenameTextField() {
              if (filenameTextField == null) {
                   filenameTextField = new JTextField();
                   filenameTextField.setBounds(26, 17, 212, 23);
                   filenameTextField.setEditable(false);
              return filenameTextField;
          * This method initializes jButton     
          * @return javax.swing.JButton     
         private JButton getBrowseButton() {
              if (browseButton == null) {
                   browseButton = new JButton();
                   browseButton.setBounds(254, 18, 102, 21);
                   browseButton.setText("Browse");
                   browseButton.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent e) { 
                             ImageFilter imageFilter = new ImageFilter();
                             fileChooser.setFileFilter(imageFilter);
                             int value = fileChooser.showOpenDialog(ImageChooserDialog.this);
                             if (value == JFileChooser.APPROVE_OPTION) {
                                  File selected = fileChooser.getSelectedFile();
                                  if (selected.canRead()) {
                                       try {
                                            BufferedImage bi = ImageIO.read(selected);
                                            selectedImage = bi;
                                            Image scaled = bi.getScaledInstance(
                                                      previewPanel.getWidth(), previewPanel.getHeight(), BufferedImage.SCALE_FAST);
                                            ImageIcon imageIcon = new ImageIcon(scaled);
                                            previewLabel.setIcon(imageIcon);
                                            filenameTextField.setText(selected.getAbsolutePath());
                                       } catch (IOException e1) {
                                            previewLabel.setText("Preview unavailable...");
                                            selectedImage = null;
                                            e1.printStackTrace();
              return browseButton;
          * This method initializes jButton1     
          * @return javax.swing.JButton     
         private JButton getCancelButton() {
              if (cancelButton == null) {
                   cancelButton = new JButton();
                   cancelButton.setBounds(254, 122, 100, 24);
                   cancelButton.setText("Cancel");
                   cancelButton.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent e) {
                             selectedImage = null;
                             option = CANCEL_OPTION;
                             ImageChooserDialog.this.dispose();
              return cancelButton;
          * This method initializes jButton2     
          * @return javax.swing.JButton     
         private JButton getOkButton() {
              if (okButton == null) {
                   okButton = new JButton();
                   okButton.setBounds(256, 159, 97, 24);
                   okButton.setText("OK");
                   okButton.addActionListener(new java.awt.event.ActionListener() {
                        public void actionPerformed(java.awt.event.ActionEvent e) {
                             option = OK_OPTION;
                             ImageChooserDialog.this.dispose();
              return okButton;
          * Displays this chooser dialog.
          * @return - The user selected option
          *                (i.e. OK_OPTION, CANCEL_OPTION)
         public int showDialog() {
              this.setVisible(true);
              return option;
          * Returns the image chosen by the user.
          * @return
         public Image getSelectedImage() {
              return selectedImage;
    import java.io.File;
    import javax.swing.filechooser.FileFilter;
    public class ImageFilter extends FileFilter {
        //Accept all directories and all gif, jpg, tiff, or png files.
        public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            String extension = Utils.getExtension(f);
            if (extension != null) {
                if (extension.equals(Utils.tiff) ||
                    extension.equals(Utils.tif) ||
                    extension.equals(Utils.gif) ||
                    extension.equals(Utils.jpeg) ||
                    extension.equals(Utils.jpg) ||
                    extension.equals(Utils.png)) {
                        return true;
                } else {
                    return false;
            return false;
        //The description of this filter
        public String getDescription() {
            return "Just Images";
    * Created on Sep 24, 2006
    import java.awt.Image;
    * Contract that specifies how a class can update
    * the view in its graphical display.
    * @author Josh Feldman
    public interface ImageUpdater {
         public Image getSelectedImage();
    * Created on Nov 4, 2006
    import java.awt.Image;
    import java.awt.Toolkit;
    import java.awt.event.KeyEvent;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import java.rmi.Naming;
    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JPasswordField;
    import javax.swing.JTextField;
    public class LoginFrame extends JFrame {
         private String serverName = "//Broom:5001/IMServer";
         private ServerInter serverInter = null;
         // The icon to be used when this frame is minimized
         private Image icon;
         // The main image to be displayed on this frame
         private Image robotImage;
         private javax.swing.JPanel jContentPane = null;
         private JPanel imagePanel = null;
         private JLabel screenameLabel = null;
         private JTextField screenameTextField = null;
         private JPanel jPanel1 = null;
         private JLabel passwordLabel = null;
         private JPasswordField passwordTextField = null;
         private JButton signonButton = null;
         private JButton helpButton = null;
          * This is the default constructor
         public LoginFrame() {
              initialize();
          * This method initializes this
          * @return void
         private void initialize() {
              this.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
              this.setResizable(false);
              this.setSize(210, 368);
              this.setContentPane(getJContentPane());
              this.setTitle("Sign On");
              try {
                   this.setIconImage(ImageIO.read(new File("images/robby3.jpg")));
              } catch (IOException e) {
                   e.printStackTrace();
              this.setLocationRelativeTo(null);
              this.setVisible(true);
          * This method initializes jPanel     
          * @return javax.swing.JPanel     
         private JPanel getImagePanel() {
              if (imagePanel == null) {
                   imagePanel = new JPanel();
                   imagePanel.setBounds(7, 7, 190, 159);
                   imagePanel.setBorder(javax.swing.BorderFactory.createLineBorder(java.awt.Color.gray,0));
                   try {
                        BufferedImage bi =
                             ImageIO.read(
                                       getClass().getClassLoader().getResourceAsStream("images/robby_big.bmp"));
                        Image scaled = bi.getScaledInstance(190, 169, BufferedImage.SCALE_FAST);
                        JLabel robotLabel = new JLabel(
                                  new ImageIcon(scaled));
                        imagePanel.add(robotLabel);
                   } catch (IOException e) {
                        e.printStackTrace();
              return imagePanel;
          * This method initializes jTextField     
          * @return javax.swing.JTextField     
         private JTextField getScreenameTextField() {
              if (screenameTextField == null) {
                   screenameTextField = new JTextField();
                   screenameTextField.setBounds(22, 208, 168, 20);
                   screenameTextField.addKeyListener(new java.awt.event.KeyAdapter() {  
                        public void keyTyped(java.awt.event.KeyEvent e) {
                             if (!isAllowedCharacter(e.getKeyChar())) {
                                  e.consume();
                                  Toolkit.getDefaultToolkit().beep();
                        public void keyPressed(java.awt.event.KeyEvent e) {
                             int keycode = e.getKeyCode();
                             if(keycode == KeyEvent.VK_ENTER && signonButton.isEnabled()) {
                                  signonButton.doClick();
                                  passwordTextField.setText("");
                             else if (keycode == KeyEvent.VK_ESCAPE) {
                                  dispose();
                                  System.exit(0);
                        public void keyReleased(java.awt.event.KeyEvent e) {
                             String screename = screenameTextField.getText();
                             char [] password = passwordTextField.getPassword();
                             if (screename.equals("") ||
                                       password.length <= 0) {
                                  signonButton.setEnabled(false);
                             else if (!screename.equals("") &&
                                       password.length > 0) {
                                  signonButton.setEnabled(true);
                             clearPasswordArray(password);
              return screenameTextField;
          * This method initializes jPanel1     
          * @return javax.swing.JPanel     
         private JPanel getJPanel1() {
              if (jPanel1 == null) {
                   jPanel1 = new JPanel();
                   jPanel1.setBounds(8, 173, 188, 1);
                   jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(java.awt.Color.gray,5));
              return jPanel1;
          * This method initializes jPasswordField     
          * @return javax.swing.JPasswordField     
         private JPasswordField getPasswordTextField() {
              if (passwordTextField == null) {
                   passwordTextField = new JPasswordField();
                   passwordTextField.setBounds(20, 259, 170, 20);
                   passwordTextField.addKeyListener(new java.awt.event.KeyAdapter() {
                        public void keyTyped(java.awt.event.KeyEvent e) {
                             if (!isAllowedCharacter(e.getKeyChar())) {
                                  e.consume();
                                  Toolkit.getDefaultToolkit().beep();
                        public void keyPressed(java.awt.event.KeyEvent e) {
                             int keycode = e.getKeyCode();
                             if(keycode == KeyEvent.VK_ENTER && signonButton.isEnabled()) {
                                  signonButton.doClick();
                                  passwordTextField.setText("");
                             else if (keycode == KeyEvent.VK_ESCAPE) {
                                  dispose();
                                  System.exit(0);
                        public void keyReleased(java.awt.event.KeyEvent e) {
                             String screename = screenameTextField.getText();
                             char [] password = passwordTextField.getPassword();
                             if (screename.equals("") ||
                                       password.length <= 0) {
                                  signonButton.setEnabled(false);
                             else if (!screename.equals("") &&
                                       password.length > 0) {
                                  signonButton.setEnabled(true);
                             clearPasswordArray(password);
              return passwordTextField;
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private javax.swing.JPanel getJContentPane() {
              if(jContentPane == null) {
                   passwordLabel = new JLabel();
                   screenameLabel = new JLabel();
                   jContentPane = new javax.swing.JPanel();
                   jContentPane.setLayout(null);
                   screenameLabel.setBounds(22, 182, 132, 20);
                   screenameLabel.setText("Screename");
                   screenameLabel.setEnabled(true);
                   screenameLabel.setFont(new java.awt.Font("Century Gothic", java.awt.Font.BOLD, 12));
                   passwordLabel.setBounds(21, 238, 135, 17);
                   passwordLabel.setText("Password");
                   jContentPane.add(getImagePanel(), null);
                   jContentPane.add(screenameLabel, null);
                   jContentPane.add(getScreenameTextField(), null);
                   jContentPane.add(getJPanel1(), null);
                   jCon                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             

  • Changed behaviour of setCursor in JTree

    since Java HotSpot(TM) Client VM (build 1.4.2_02-b03, mixed mode) there seems to be a change in setCursor in JTree.
    I set a wait cursor in treeWillExpand, and reset it in treeExpanded. This works fine with that version of the jre. With a newer one, e.g. Java HotSpot(TM) Client VM (build 1.4.2_08-b03, mixed mode), the wait cursor is reset to the default cursor shortly after treeWillExpand, and before the call of treeExpaned.
    I will add a short piece of code to reproduce that behaviour. Just collapse the root node and expand it again.
    Might that be a bug in the jvm or is there a misstake in the code?
    import java.awt.Cursor;
    import javax.swing.JDialog;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.event.TreeExpansionEvent;
    import javax.swing.event.TreeExpansionListener;
    import javax.swing.event.TreeWillExpandListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.ExpandVetoException;
    public class Tester extends JDialog implements TreeExpansionListener,
              TreeWillExpandListener {
         private JTree tree = new JTree();
         private JScrollPane spTree = new JScrollPane(tree);
         private DefaultTreeModel model;
         // used to "simulate" some work
         boolean isExpanding = false;
         public void treeWillCollapse(TreeExpansionEvent event)
                   throws ExpandVetoException {
         public void treeWillExpand(TreeExpansionEvent event)
                   throws ExpandVetoException {
              System.err.println("treeWillExpand");
              tree.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
              // "simulate" some work during expand
              isExpanding = true;
         public void treeCollapsed(TreeExpansionEvent event) {
         public void treeExpanded(TreeExpansionEvent event) {
              System.err.println("treeExpanded");
              tree.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
              // work is done and cached
              isExpanding = false;
         public Tester() {
              setModal(true);
              setSize(640, 480);
              this.getContentPane().add(spTree);
              tree.addTreeExpansionListener(this);
              tree.addTreeWillExpandListener(this);
              MyTreeNode root = new MyTreeNode("root");
              model = new DefaultTreeModel(root);
              root.add(new MyTreeNode("test1"));
              root.add(new MyTreeNode("test2"));
              root.add(new MyTreeNode("test3"));
              tree.setModel(model);
              tree.setShowsRootHandles(true);
              setVisible(true);
              System.exit(0);
         public static void main(String[] args) {
              new Tester();
         class MyTreeNode extends DefaultMutableTreeNode {
              public MyTreeNode(String text) {
                   super(text);
              public int getChildCount() {
                   if (isExpanding) {
                        System.err.println("getChildCount");
                        try {
                             Thread.sleep(200);
                        } catch (InterruptedException e) {
                   return super.getChildCount();
    }

    I think it is reset when you release the mouse button. If you keep the button down, it works as usual.

  • How to reopen same Jdialog.

    Hi,
    In my application,when user press the button, its going to open one JDialog where user is asked to Select Node on Jtree with the help of checkbox.
    Same dialog consist of Ok and Cancel button.
    Ok button must save the changes made by user and process the required task where as Cancel button must discard the changes.
    At the end,both button should close the Jdialog.
    What i want is , if user clicks same button again it should open previous JDialog which was got closed.
    How can i do it.
    please help.
    code to pop-up jdialog in Main GUI class
    private void repositoryMetadataButtonActionPerformed(java.awt.event.ActionEvent evt) {
    RepositoryMetadataFrame.showDialog(AID_GUI.this,target_nameFormattedField);
    public class RepositoryMetadataFrame extends javax.swing.JDialog {
    public RepositoryMetadataFrame(Frame frame,Component locationComp) {
    super(frame,"AID-Options", true);
    RepositoryMetadataFrame.location = location;
    initComponents();
    public static void showDialog(Component frameComp,Component locationComp){
    Frame frame = JOptionPane.getFrameForComponent(frameComp);
    dialog = new RepositoryMetadataFrame(frame,locationComp);
    dialog.setVisible(true);
    return;
    initComponent(){
      //to intialize all component and display it on system
    private void okButtonActionPerformed(java.awt.event.ActionEvent evt){
         //Do Something
         setVisible(false);
    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {
         //simply close
         setVisible(false);
    }

    In my application,when user press the button, its going to open one JDialog where user is asked to Select Node on Jtree with the help of checkbox.
    Same dialog consist of Ok and Cancel button.Don't code a custom dialog if it's only that. Use one of the methods JOptionPane.showConfirmDialog(...).
    Even if you want to display something more complex than a simple label (one of the forms accepts a custom Component).
    These methods are likely to be more robust (threading bugs, memory leaks) than whatever custom dialog caching you may devise.
    What i want is , if user clicks same button again it should open previous JDialog which was got closed.Do you mean, "open the same instance"? Why would you want that (I mean, there can be reasons, but it complexifies the code, so are you sure you need it)?
    Or do you mean "open an identicial dialog"?
    Then no problem: the first button's actionPerformed() will be invoked each time the button is clicked - the same code will execute each time.

  • Help with JTree data by user input

    I am trying to read data into a JTree without it being hardcoded.
    An example of the data is:
    String data[] = {"a","b","c",";","b","g","h",";","c","t",";","g","u"};
    The above data is taken from user input and stored in an array and checked for errors.
    I want to somehow read take the above array's data and put it into following format in some kind of loop but I am not sure how.
    Object[] hierarchy = {"a", new Object[]{"b",new Object[]{"g","u"},"h"},new Object[]{"c","t"}};
    This Object is then passed to a function that interpets it and prints out the appropriate JTREE structure. For the values above it would be:
    a
    ..b
    ....g
    ......l
    ......u
    ....h
    ..c
    ....t
    Tha problem is how to take the string array and put that data correctly into the Object array. I have been racking my feeble mind for quite sometime and if any one out there can see it or has a better idea of how to get my data into the JTree please let me know.
    Thanks

    //OutlookClient.java
    //uses also Console class from Bruce Eckel 
    //<applet code=OutlookClient width=500 height=300>
    //</applet>
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import java.util.*;
    import javax.swing.UIManager;
    import javax.swing.SwingUtilities;
    import BruceEckel.*;
    import DynamicTree.*;
    import DynamicTreeNode.*;
    import java.lang.reflect.*;
    /* a class creating a dialog with the version, and other details about the program*/
    class AboutDialog extends JDialog {
         private JButton ok = null;
         private Container cp = null;
         private JTextField tname = null;
            public AboutDialog() {
                   //System.out.println("constructor");
                   ok = new JButton("OK");
                   cp = getContentPane();
                   cp.setLayout(new FlowLayout());
                   JLabel tlab = new JLabel("Outlook - client side");
                   cp.add(tlab);
                   //tname.setMinimumSize(new Dimension(50,10));
                   //tname.setSize(new Dimension(70,10));
                   tlab = new JLabel("Author: Jiri Machotka");
                   cp.add(tlab);
                   tlab = new JLabel("version 1.0 (September 2001)");
                   cp.add(tlab);
                   tlab = new JLabel("----------------------------------------------");
                   cp.add(tlab);
                   ok.addActionListener( new ActionListener() {
                      public void actionPerformed(ActionEvent e) {
                        dispose();
                      }//actionPerformed
                   });//addActionListener
                   cp.add(ok);
                   setSize(200,150);
                   setTitle("About the program");  
                   setModal(true);
         }//constructor
      *      <P>This class more-or-less contains a graphic design object used for interaction with a user.</P>
      *     Apart from all ScrollPanes, Buttons, and MenuItems, it contains also 3 interesting members:
      *     <ol>
      *     <li> <I>protected final DefaultMutableTreeNode topNode</I>, which is initialized with
      * a potent, non-removable object of the class <I>Node</I>
      *     <li> <I>protected final DefaultTreeModel treeModel</I>, which is initialized with the <I>topNode</I>
      *     <li> and finally <I>protected final DynamicTree dyn_tree</I>, which uses the 2 objects above
      *     </ol>
      *     <P> The <I>OutlookClient</I> is an applet, but it can be also processed as an application (thanks to
      *     a library by BruceEckel).</P>
    public class OutlookClient extends JApplet {
    //------------- properties -----------------------------------------
       private Action
            newMail = new AbstractAction ("New Mail", new ImageIcon("images/NewMailIcon.gif")){
              public void actionPerformed(ActionEvent e) {
                         txt.setText("NewMail");
         reply     = new AbstractAction ("Reply", new ImageIcon("images/ReplyIcon.gif")){
              public void actionPerformed(ActionEvent e) {
                         txt.setText("Reply");
       private JButton
         /*b1 = new JButton("Add a Node"),
         b2 = new JButton("Remove the current Node"),*/ //not used now
         tb1 = new JButton (newMail),
         tb2 = new JButton (reply);
       private JTextField
         txt = new JTextField(10);
       private Container
         leftArea = new Container(),
         rightArea = new Container();
       private JScrollPane
            left = new JScrollPane (leftArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS),
            right = new JScrollPane (rightArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
       private JSplitPane
            sp = new JSplitPane (JSplitPane.HORIZONTAL_SPLIT, left, right);
       private JToolBar
         toolBar = new JToolBar();
       private JMenuBar
         menuBar = new JMenuBar();
       /*ActionListener al = new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            String name = ( (JButton)e.getSource()).getText();
            txt.setText(name);
       };*/     //not used now - used as an action listener for buttons b1, b2
       private JMenu
         mainOutlookMenu = new JMenu ("Outlook activities"),
         othersMenu      = new JMenu ("Others"),
         mailMenu     = new JMenu ("Mails"),
         chatMenu     = new JMenu ("Chat"),
         look_and_feelMenu = new JMenu ("Look&Feel");
       private JMenuItem
         closeAppItem     = new JMenuItem ("Exit",KeyEvent.VK_F3),
         newMailItem     = new JMenuItem (newMail),
         replyItem     = new JMenuItem (reply);
       private JRadioButtonMenuItem
         windowsLookAndFeelItem;
       protected final DefaultMutableTreeNode topNode = new DefaultMutableTreeNode(new Node ("Outlook", false, true));
       protected final DefaultTreeModel treeModel = new DefaultTreeModel(topNode);
       protected final DynamicTree dyn_tree = new DynamicTree(topNode, treeModel);
    //-------------inner classes----------------------------------------
    /** <P>The class <I>MyRenderer</I> sets the renderer of the tree - by doing that icons can be assigned to
       * the tree's nodes. </P>
       * <P> It sould be probably a standard member of a class <I>DynamicTreeWithIcons</I>.</P>
       * <P> However, it uses the knowledge that the class <B>Node</B>, which is the only object that can be
       * found in the dynamic tree in this application, has a method <I>getIcon()</I>, which returns a
       * reference to the icon object assigned to the node.</P>
       * <P><B>This is the only place, where the class Node, or its methods are called explicitely.</B></P>
       protected class MyRenderer extends DefaultTreeCellRenderer {
         /** The constructor of the class.
           * - sets folders icons (opened, closed folder)
         public MyRenderer() {
                 //setLeafIcon(new ImageIcon("images/middle.gif")); //for leaves' icon, all at once!
              setOpenIcon(new ImageIcon("images/folder_open.gif"));
              setClosedIcon(new ImageIcon("images/folder_close.gif"));
         /** This overridden method gets the user-specified icon for leaf nodes. */
         public Component getTreeCellRendererComponent(
                   JTree tree,
                   Object value,
                   boolean sel,
                   boolean expanded,
                   boolean leaf,
                   int row,
                   boolean hasFocus) {
              super.getTreeCellRendererComponent(tree,value,sel,expanded,leaf,row,hasFocus);
              if (leaf) 
              //workaround: test if icon not eq. null
                     ImageIcon ic = getRightIcon(value);
                     if (ic == null) return this;
                     else
                          setIcon(ic);
              return this;
         }//overridden: getTreeCellRendererComponent
         private ImageIcon getRightIcon(Object value) {
           DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
              try{
              Node node_object = (Node)(node.getUserObject());   
                 return (node_object.getIcon());
           catch (Exception e) { return null; }
         }// ImageIcon getRightIcon(Object value)
      }//class MyRenderer
    //-------------OutlookClient methods-----------------------------------------
       private void assignListeners(){
         dyn_tree.addTreeSelectionListener(new TreeSelectionListener() {
             public void valueChanged(TreeSelectionEvent e) {
              DefaultMutableTreeNode node = (DefaultMutableTreeNode)dyn_tree.getLastSelectedPathComponent();
              if (node == null) return;
              if (node.isLeaf()) { txt.setText(node.toString()); }
       }//assignListeners()
       private void createLayout(){
         leftArea.setLayout(new BoxLayout(leftArea,BoxLayout.Y_AXIS));
         rightArea.setLayout(new BoxLayout(rightArea,BoxLayout.Y_AXIS));
         //left.setMinimumSize(new Dimension(120,200));
         right.setMinimumSize(new Dimension(50,50));
         //rightArea.add(b1);
         //rightArea.add(b2);
         rightArea.add(txt);
         //leftArea.add(tree);  ... not nice (why?)
           left = new JScrollPane (dyn_tree, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);       
         left.setMinimumSize(new Dimension(180,200));
         sp.setLeftComponent(left);
       }//createLayout()
       private void createMenu(){
         ButtonGroup group = new ButtonGroup();
            JRadioButtonMenuItem rbMenuItem;
         closeAppItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, ActionEvent.ALT_MASK));
         closeAppItem.getAccessibleContext().setAccessibleDescription("Closes application");
         closeAppItem.addActionListener( new ActionListener() {
              public void actionPerformed(ActionEvent e) {System.exit(0);}
         othersMenu.setMnemonic(KeyEvent.VK_O);
         othersMenu.getAccessibleContext().setAccessibleDescription("System settings&Others");
            rbMenuItem = new JRadioButtonMenuItem("Java");
            rbMenuItem.setSelected(true);
            rbMenuItem.setMnemonic(KeyEvent.VK_J);
            group.add(rbMenuItem);
            rbMenuItem.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {setPLAF(UIManager.getCrossPlatformLookAndFeelClassName( ) );}
            look_and_feelMenu.add(rbMenuItem);
            rbMenuItem = new JRadioButtonMenuItem("Windows");
            rbMenuItem.setMnemonic(KeyEvent.VK_W);
            group.add(rbMenuItem);
            rbMenuItem.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {setPLAF("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");}
            look_and_feelMenu.add(rbMenuItem);
         windowsLookAndFeelItem = rbMenuItem;
         look_and_feelMenu.setMnemonic(KeyEvent.VK_L);
         look_and_feelMenu.getAccessibleContext().setAccessibleDescription("Look&Feel");
         JMenuItem aboutItem = new JMenuItem ("About");
         aboutItem.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                   AboutDialog ad = new AboutDialog();
                   ad.show();
         othersMenu.add(look_and_feelMenu);
         othersMenu.addSeparator();
         othersMenu.add(aboutItem);
         othersMenu.addSeparator();
         othersMenu.add(closeAppItem);
         mainOutlookMenu.setMnemonic(KeyEvent.VK_A);
         mainOutlookMenu.getAccessibleContext().setAccessibleDescription("Outlook activities");
         menuBar.add(mainOutlookMenu);
         menuBar.add(othersMenu);
         mailMenu.setMnemonic(KeyEvent.VK_M);
         mailMenu.getAccessibleContext().setAccessibleDescription("Mail activities");
         chatMenu.setMnemonic(KeyEvent.VK_C);
         chatMenu.getAccessibleContext().setAccessibleDescription("Chat");
         chatMenu.setEnabled(false);
         mainOutlookMenu.add(mailMenu);
         mainOutlookMenu.addSeparator();
         mainOutlookMenu.add(chatMenu);
         //mailMenu.add(newMail);
         //mailMenu.add(reply);     //class Action has problems to catch the accelerator keys
         newMailItem.setMnemonic(KeyEvent.VK_N);
         replyItem.setMnemonic(KeyEvent.VK_R);
         mailMenu.add(newMailItem);
         mailMenu.add(replyItem);
         newMailItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
         replyItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.ALT_MASK));
         //newMail.putValue(Action.NAME, "New mail");
         //newMail.putValue(Action.SHORT_DESCRIPTION, "New mail");
         //newMail.putValue(Action.LONG_DESCRIPTION, "New mail");
         //newMail.putValue(Action.MNEMONIC_KEY, "N");  //cast an exception. why?
         //newMail.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));     
         setJMenuBar(menuBar);
       }//createMenu()
       private void createToolBar(){
         //toolBar.add(newMail);
         //toolBar.add(reply);    //does not provide texts and mnemonics
         tb1.setMnemonic(KeyEvent.VK_N);
         tb2.setMnemonic(KeyEvent.VK_R);
         toolBar.add(tb1);
         toolBar.add(tb2);
       }//createToolBar()
       private void createNodes(DefaultMutableTreeNode topNode){
         //new for dynamic processing
         DefaultMutableTreeNode
              parentNode = null,
              leaveNode  = null;
         parentNode = dyn_tree.addObject(null,new Node ("MailFolders", false, true));
         dyn_tree.addObject(parentNode,new Node ("Inbox","images/InboxIcon.gif", false, false));
         dyn_tree.addObject(parentNode,new Node ("Outbox","images/OutboxIcon.gif", false, false));
         dyn_tree.addObject(parentNode,new Node ("Sent","images/SentIcon.gif", false, false));
         dyn_tree.addObject(parentNode,new Node ("Deleted","images/DeletedIcon.gif", false, false));
         //leaveNode.setEnabled(false);  //TODO: disable "Chat"node
         dyn_tree.addObject(null,new Node ("Chat", false, false));
       }//createcreateNodes(DefaultMutableTreeNode)
       private void setTreeSettings(){
         //one selection at one time
         dyn_tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
         //connect nodes with a thin line - Java style only
         dyn_tree.putClientProperty("JTree.lineStyle","Angled");
         //collapse the root's children first
         //tree.setShowsRootHandles(false);
         //icon adjustment
         MyRenderer MyRen = new MyRenderer();
         dyn_tree.setCellRenderer(MyRen);
         //modifiable tree - by double click - allows modifying of nodes' names
         // but unfortunately also restores original icons
         //tree.setEditable(true);
       }//setTreeSettings()
       private boolean setPLAF(String LookAndFeelName){
          try{
         UIManager.setLookAndFeel(LookAndFeelName);
         SwingUtilities.updateComponentTreeUI(this);
         return true;
          } catch (Exception e) {
         //e.printStackTrace(System.err);
         return false;
       }//setPLAF(String LookAndFeelName)
       private void trytosetLookAndFeel(){
          if (setPLAF("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"))
              windowsLookAndFeelItem.setSelected(true);
       }//trytosetLookAndFeel()
       /** The applet's <I>init()</I>.
         * Calls methods to construct all visible objects.
         * Apart from that it also assigns the renderer to the tree.
       public void init(){
         sp.setOneTouchExpandable(true);
            //sp.setDividerLocation(150); - system puts the value to optimize the left part
         sp.setPreferredSize(new Dimension(450,200));
         Container cp = getContentPane();
         cp.setLayout(new FlowLayout());
            createLayout();     
         createMenu();
         createToolBar();
         createNodes(topNode);
         setTreeSettings();
         //createPopupMenu();
         assignListeners();
         cp.add(toolBar);
         cp.add(sp);
         trytosetLookAndFeel();
       }//init()
       /** If called as an application.
         * The desired Windows Look&Feel is re-set again, when the applet is running. Otherwise, it in an application
         * it tends not to work correctly.
       public static void main(String[] args) {
         OutlookClient theApplet;
         BruceEckel.Console.run(theApplet=new OutlookClient(), 500, 300);
         theApplet.trytosetLookAndFeel();
       }//main(String[])
    }///:~Take a look namely at createNodes
    Hope it helps.

  • About font of JTree

    Hi,
    Actually I want to change the font of a jTree and when I clicked save button in jDialog containing combobox for Font size ,style,name.I already mentioned in another class the default value so can u some one help me to change the font dynamically?

    actually I want to change whole JFrame font when I switch to Look and feel all cobobox containg font name ,size and style shud be disabled except java look anfd feel.ya font works

  • Exist a Jtree node.id or something like this ?

    I would want to retrieve a node using a unique 'id', for example the absolute index (into the total nodes count)
    Is there something like this ?
    Can I add a particular property to a node ? ( for example this 'id' if it does not exist )
    Another question :
    If I want to implement a search code, this 'id' can be useful, or must I transverse the whole Jtree
    Thanks

    Hello.
    Do the following:
    1. Go to the Apple Menu at the top left of the screen
    2. Select Software Update...
    3. Install any updates that are found.
    If the Amazon issue continues after these updates, then do this:
    1. Open Safari
    2. Erase any web address you have currently showing (for example www.apple.com or www.google.com)
    3. Type in www.amazon.com
    4. That should take you directly to amazon.com
    It should look like this in your Safari::

Maybe you are looking for

  • How to use if max statment in oracle

    hi can someone pls help me to transform this logic to oracle syntax: if max(person.code) = 1 then last paid date is null if max(person.code > 1) the last paid date = max(person.sdate) thanks!

  • Itunes does not start because msvcr80.dll is missing

    Having an issue since the new itunes updated to 11.1.4.62 on Windows 7x64.  After the update to 11.1.4.62, Itunes can not start because mscvr80.dll is missing. I have reinstaleed, uninstalled, reinatelled, same issue each time. When I search for mscv

  • Oci8 and oracle extensions mutually exclusive?

    Does anybody know if the following extensions are mutually exclusive. php_oci8.dll php_oracle.dll I can't getting both to load. They can be uncommented in the php.ini and loaded individually but if both are used this causes a fatal error and apache f

  • Webservice -   XI -   SAP(BAPI)

    hi i have one scenario using webservice, in this one i will post some input through  webservice  to BAPI which is in sap R/3 , and bapi output to publish using webservice,  i have no idea of webservice,  or how to use webservice in this scenario. Cou

  • Does OLAP cubes store primary fact data (10gr2)?

    Does Oracle OLAP(OLAP option of 10g database) physically store inside cube data of fact table it is based on? More detailed: 1. There are fact table F and several dimension tables around it - D1, D2, D3 2. In analytical workspace there is a cube C. C