Adding a different tooltip for every element in my JMenuItem

Set the tooltip text for every JMenuItem.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JMenuBar menuBar = new JMenuBar();
      JMenu menu = new JMenu("menu");
      JMenuItem menuItem1 = new JMenuItem("male");
      JMenuItem menuItem2 = new JMenuItem("female");
      menuItem1.setToolTipText("The weak sex");
      menuItem2.setToolTipText("The strong sex");
      menu.add(menuItem1);
      menu.add(menuItem2);
      menuBar.add(menu);
 
      this.setJMenuBar(menuBar); 
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(400, 400);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Putting a JSlider on a null layout manager

The null layout manager gives the programmer complete control over where the components are placed. You must specify the location and size of each component using the setBounds method.

Here’s an example:

import javax.swing.plaf.metal.*;
import javax.swing.event.*;
import javax.swing.plaf.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(null);
 
      final MySlider slider = new MySlider(JSlider.HORIZONTAL, 0, 30, 15);
 
      slider.setBounds(new Rectangle(30, 30, 100, 50));
 
      getContentPane().add(slider);
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(200, 200);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

The JDK1.2.2 seems to have problems with this (you won’t see anything). I haven’t found a bug in Sun’s Bug Parade DB. It works fine using the JDK1.3. Anyone?

Changing the font color of a JLabel

Use the method setForeground.

Main.java:

import javax.swing.border.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JLabel label = new JLabel("The font and color of this JLabel have been changed!");
      getContentPane().add(label);  
      label.setFont(new Font("Tahoma", Font.ITALIC, 30));
      label.setForeground(Color.red);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Creating a multiline JTooltip

An easy way is to have your tooltip text to be HTML:

      label.setToolTipText("<html>This is a two-line<br> tooltip text!</html>");

as in following example:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame
{ 
   public Main() {
      getContentPane().setLayout(new FlowLayout());
      JLabel label = new JLabel("Mouse-over me!");
      getContentPane().add(label);
 
      label.setToolTipText("<html>This is a two-line<br> tooltip text!</html>");
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });      
   
      setSize(new Dimension(200, 200));
   } 
 
   public static void main(String[] args) throws Exception {
      Main main = new Main();
      main.setVisible(true);
   }
}

Getting rid of the top panel of a JFileChooser

Try this:

   fc.remove(1)

(where fc is a JFileChooser instance)
This example shows you also how to remove only part of the top panel:

import javax.swing.filechooser.*;
import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
 
public class Main extends JFrame {
   public Main() {
      super("JFileChooser Demonstration");
 
      getContentPane().setLayout(new FlowLayout()); 
      final JFileChooser fc = new JFileChooser();
 
      // Remove the whole top panel of JFileChooser 
      fc.remove(1);
 
      // Disable the create new folder button 
      //((JPanel)fc.getComponent(1)).getAccessibleContext()
      .getAccessibleChild(9).getAccessibleContext()
      .getAccessibleComponent().setEnabled(false);
 
      // Hide the create new folder button
      //((JPanel)fc.getComponent(1)).getAccessibleContext()
      .getAccessibleChild(9).getAccessibleContext()
      .getAccessibleComponent().setVisible(false); 
 
      JButton button = new JButton("Show JFileChooser");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            int r = fc.showOpenDialog(Main.this); 
  
            if (r == JFileChooser.APPROVE_OPTION)
               System.out.println("Selected: " + fc.getSelectedFile());
         }
      });
 
      getContentPane().add(button); 
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.pack();
      main.setVisible(true);
   }
}

Add a background image to a JTable

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;
 
public class BackgroundTable 
{ 
   public static void main(String[] args) {
      JFrame frame = new JFrame("Table Example"); 
      frame.addWindowListener( new WindowAdapter() { 
         public void windowClosing(WindowEvent e) 
         { 
            Window w = e.getWindow(); 
            w.setVisible(false); 
            w.dispose(); 
            System.exit(0); 
         } 
      }); 
 
      JTable imTable = new JTable(35, 3) { 
         public Component prepareRenderer(TableCellRenderer renderer, int row, int column) 
         { 
            Component c = super.prepareRenderer( renderer, row, column); 
            // We want renderer component to be 
            //transparent so background image is visible 
            if( c instanceof JComponent ) 
               ((JComponent)c).setOpaque(false); 
            return c; 
         }
   
         public void paint( Graphics g ) 
         { 
            ImageIcon image = new ImageIcon("FIREFALL.gif"); 
            // tile the background image 
            Dimension d = getSize(); 
            for( int x = 0; x < d.width; x += image.getIconWidth() ) 
            for( int y = 0; y < d.height; y += image.getIconHeight() ) 
            g.drawImage( image.getImage(), x, y, null, null ); 
            // Now let the paint do its usual work 
            super.paint(g); 
         } 
      }; 
 
      //make the table transparent 
      imTable.setOpaque(false); 
 
      JScrollPane jsp = new JScrollPane(imTable); 
      frame.getContentPane().add(jsp); 
 
      frame.pack(); 
      frame.show(); 
   } 
}

Freezing the first column of a JTable

Courtesy of Nobuo Tamemasa (http://www2.gol.com/users/tame/swing/examples/JTableExamples1.html)



RowHeaderRenderer.java:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
 
/**
 * @version 1.0 11/09/98
 */
 
class RowHeaderRenderer extends JLabel implements ListCellRenderer {
  
  RowHeaderRenderer(JTable table) {
    JTableHeader header = table.getTableHeader();
    setOpaque(true);
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    setHorizontalAlignment(CENTER);
    setForeground(header.getForeground());
    setBackground(header.getBackground());
    setFont(header.getFont());
  }
  
  public Component getListCellRendererComponent( JList list, 
         Object value, int index, boolean isSelected, boolean cellHasFocus) {
    setText((value == null) ? "" : value.toString());
    return this;
  }
}
 
public class RowHeaderExample extends JFrame {
 
  public RowHeaderExample() {
    super( "Row Header Example" );
    setSize( 300, 150 );
         
    ListModel lm = new AbstractListModel() {
      String headers[] = {"a", "b", "c", "d", "e", "f", "g", "h", "i"};
      public int getSize() { return headers.length; }
      public Object getElementAt(int index) {
        return headers[index];
      }
    };
 
    DefaultTableModel dm = new DefaultTableModel(lm.getSize(),10);
    JTable table = new JTable( dm );
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    
    JList rowHeader = new JList(lm);    
    rowHeader.setFixedCellWidth(50);
    
    rowHeader.setFixedCellHeight(table.getRowHeight()
                               + table.getRowMargin());
//                             + table.getIntercellSpacing().height);
    rowHeader.setCellRenderer(new RowHeaderRenderer(table));
 
    JScrollPane scroll = new JScrollPane( table );
    scroll.setRowHeaderView(rowHeader);
    getContentPane().add(scroll, BorderLayout.CENTER);
  }
 
  public static void main(String[] args) {
    RowHeaderExample frame = new RowHeaderExample();
    frame.addWindowListener( new WindowAdapter() {
      public void windowClosing( WindowEvent e ) {
        System.exit(0);
      }
    });
    frame.setVisible(true);
  }
}

Making a JSlider cell editor for my JTable


Note: in JDK1.4, you don’t need to do the setSize() and updateUI in the SliderRenderer.

Main.java:

import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
  
public class JSliderTableExample extends JFrame {
 
  public JSliderTableExample() {
    super( "JSliderTableExample Example" );
 
    DefaultTableModel dtm = new DefaultTableModel();
    dtm.setDataVector(new Object[][]{{ "JSlider1", new Integer(10) },
                                     { "JSlider2", new Integer(12) }},
                      new Object[]{ "String","JSlider"});
                     
    JTable table = new JTable(dtm);
    table.getColumn("JSlider").setCellRenderer(new SliderRenderer(JSlider.HORIZONTAL, 0, 20, 10));
    table.getColumn("JSlider").setCellEditor(new SliderEditor(JSlider.HORIZONTAL, 0, 20, 10));
 
    table.setRowHeight(20);
    JScrollPane scroll = new JScrollPane(table);
    getContentPane().add(scroll);
 
    setSize( 400, 100 );
    setVisible(true);
  }
 
  public static void main(String[] args) {
    JSliderTableExample frame = new JSliderTableExample();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
  }
}
  
class SliderRenderer extends JSlider implements TableCellRenderer
{
   public SliderRenderer(int orientation, int min, int max, int value) {
      super(orientation, min, max, value);
   }
 
   public Component getTableCellRendererComponent(JTable table, Object value,
                                  boolean isSelected, boolean hasFocus,
                                  int row, int column)
   {
      if (isSelected) {
         setForeground(table.getSelectionForeground());
         setBackground(table.getSelectionBackground());
      } else {
         setForeground(table.getForeground());
         setBackground(table.getBackground());
      }
 
      TableColumnModel columnModel = table.getColumnModel();      
      TableColumn selectedColumn = columnModel.getColumn(column);      
      int columnWidth = selectedColumn.getWidth();
      int columnHeight = table.getRowHeight();
      setSize(new Dimension(columnWidth, columnHeight));
 
      setValue(((Integer)value).intValue());
      updateUI();
      return this;
   }
}
 
class SliderEditor extends DefaultCellEditor {
   protected JSlider slider;
 
   public SliderEditor(int orientation, int min, int max, int value) {
      super(new JCheckBox());
      slider = new JSlider(orientation, min, max, value);      
      slider.setOpaque(true);      
   }
 
   public Component getTableCellEditorComponent(JTable table, Object value,
                                   boolean isSelected, int row, int column) {
      if (isSelected) {
         slider.setForeground(table.getSelectionForeground());
         slider.setBackground(table.getSelectionBackground());
      } else {
         slider.setForeground(table.getForeground());
         slider.setBackground(table.getBackground());
      }
      slider.setValue(((Integer) value).intValue());
 
      return slider;
   }
 
   public Object getCellEditorValue() {
      return new Integer(slider.getValue());
   }
 
   public boolean stopCellEditing() {
      return super.stopCellEditing();
   }
 
   protected void fireEditingStopped() {
      super.fireEditingStopped();
   }
}

Get started with a JTree

These sample codes will just teach you how to create a simple JTree, without worrying about how the tree is displayed. For detailed information about this, look at the other examples in this category.

DefaultMutableTreeNode

You create the simpliest JTree by constructing the hierarchy using the class DefaultMutableTreeNode. With its add method, children (of type DefaultMutableTreeNode) can be added. A child can have children as well.

Then, pass the root element to a JTree instance.

This simple example shows you how to.

Main.java:

import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
 
public class Main extends JFrame
{
   public Main() {
      DefaultMutableTreeNode root = createNodes();
      JTree tree = new JTree(root);
 
      getContentPane().add(new JScrollPane(tree));
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static DefaultMutableTreeNode createNodes() {
      DefaultMutableTreeNode root = new DefaultMutableTreeNode("Java");
      
      DefaultMutableTreeNode j2se = new DefaultMutableTreeNode("J2SE");
      DefaultMutableTreeNode j2ee = new DefaultMutableTreeNode("J2EE");
      DefaultMutableTreeNode j2me = new DefaultMutableTreeNode("J2ME");
 
      j2se.add(new DefaultMutableTreeNode("http://java.sun.com/j2se/"));
      j2ee.add(new DefaultMutableTreeNode("http://java.sun.com/j2ee/"));
      j2me.add(new DefaultMutableTreeNode("http://java.sun.com/j2me/"));
 
      root.add(j2se);
      root.add(j2ee);
      root.add(j2me);
 
      return root;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}

Extending TreeModel

But if you already have an existing tree-based model, you want to use it directly (and not create a mirror that is a set of DefaultMutableTreeNodes). This way, your view stays in sync with your existing model.

You can reuse your tree-based datastructure by creating your own class that implements TreeModel as shown in the following example. The custom datastructure Category contains the data and a CategoryTreeModel passes it on to the view.

Category.java:

import java.util.*;
 
public class Category
{
   private String name;
   private Vector subCategories = new Vector();
   private Vector links = new Vector();
 
   public Category(String name) {
      this.name = name;
   }
 
   public void addSubCategory(Category category) {
      subCategories.addElement(category);
   }
 
   public void addLink(String link) {
      links.addElement(link);
   }
 
   public Vector getSubCategories() {
      return subCategories;
   }
 
   public Vector getLinks() {
      return links;
   } 
 
   public String toString() {
      return name;
   }
}

CategoryTree.java:

import javax.swing.*;
import javax.swing.tree.*;
 
public class CategoryTree extends JTree {
    CategoryTreeModel model;
 
    public CategoryTree(Category category) {
        super(new CategoryTreeModel(category));
    }
}

CategoryTreeModel.java:

import javax.swing.event.*;
import javax.swing.tree.*;
import java.util.*;
 
public class CategoryTreeModel implements TreeModel {
   private Category rootCategory;
   private Vector listeners = new Vector();
 
   public CategoryTreeModel(Category rootCategory) {
      this.rootCategory = rootCategory;
   }
 
   public Object getChild(Object parent, int index) {
      Category category = (Category) parent;
  
      // if the index falls in the subcategories vector
      if (index < category.getSubCategories().size()) {
         return category.getSubCategories().elementAt(index);
      }
 
      // else if the index falls in the links vector
      index -= category.getSubCategories().size();
      return category.getLinks().elementAt(index);
   }
 
   public int getChildCount(Object parent) {
      Category category = (Category) parent;
 
      return category.getSubCategories().size() +
             category.getLinks().size();
   }
 
   public int getIndexOfChild(Object parent, Object child) {
      Category category = (Category) parent;
 
      if (child instanceof Category) {
         return category.getSubCategories().indexOf(child);
      }
      else {
         return category.getLinks().indexOf(child);
      }
   }
 
   public Object getRoot() {
      return rootCategory;
   }
 
   public boolean isLeaf(Object node) {
      return node instanceof String;
   }
 
   public void addTreeModelListener(TreeModelListener l) {
      listeners.addElement(l);
   } 
 
   public void removeTreeModelListener(TreeModelListener l) {
      listeners.removeElement(l);
   }
 
   public void valueForPathChanged(TreePath path, Object newValue) {
      System.out.println("Value for path changed, " + newValue);
   }  
}

Main.java:

import java.net.*;
import java.awt.event.*;
  
public class Main extends JFrame
{
   public Main() {
      Category category = createCategory();
 
      CategoryTree tree = new CategoryTree(category);
  
      getContentPane().add(new JScrollPane(tree));
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static Category createCategory() {
      Category category = new Category("Java");
 
      Category j2se = new Category("j2se");
      j2se.addLink("http://java.sun.com/j2se/");
 
      Category j2ee = new Category("j2ee");
      j2ee.addLink("http://java.sun.com/j2ee/");
 
      Category j2me = new Category("j2me");
      j2me.addLink("http://java.sun.com/j2me/");
 
      category.addSubCategory(j2se);
      category.addSubCategory(j2ee);
      category.addSubCategory(j2me);
 
      return category;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}