Programmatically scroll a scrollable JTable to a specific cell or row

The scrollRectToVisible method is the magic one you need. The code fragment below assumes that selectedColumn and selectedRow indicate the cell that you want to make sure is visible. If your rows/columns are not all the same height/width you will have to change the calculations, but the concept is the same.

   table.scrollRectToVisible(
      new Rectangle(columnWidth*selectedColumn,
                    table.getRowHeight()*(selectedRow),
                    columnWidth,
                    table.getRowHeight()));

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);
   }
}

Allowing for multiple selections in a JTree

Use TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION!

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();
      final JTree tree = new JTree(root);
 
      TreeSelectionModel model = new DefaultTreeSelectionModel();
      model.setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
      tree.setSelectionModel(model);
 
      JButton button = new JButton("Display selected values on stdout");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            TreePath[] treePaths = tree.getSelectionPaths();    
            for (int i=0; i<treePaths.length; i++) {
               System.out.println(treePaths[i].getLastPathComponent());    
            }
         }
      });
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(BorderLayout.CENTER, new JScrollPane(tree));
      getContentPane().add(BorderLayout.SOUTH, button);
 
      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);
   }
}

Using an SWT Sash

Sash is the Swing equivalent of a JSplitPane. It is a widget that can be dragged to resize two areas in a GUI.

Here’s an example of a Sash in a JFace application.

Category.java:

import java.util.*;

public class Category {
   private String name;
   private Category parent;
   private ArrayList categories = new ArrayList();
   private ArrayList links = new ArrayList();
   
   public Category(String name, Category parent) {
      this.name = name;
      this.parent = parent;
   }
   
   public void addSubCategory(Category category) {
      categories.add(category);
   }
   
   public void addLink(Link link) {
      links.add(link);
   }
   
   public ArrayList getSubCategories() {
      return categories;
   }
   
   public ArrayList getLinks() {
      return links;
   }
   
   public boolean hasSubCategories() {
      return categories.size() > 0;
   }
   
   public boolean hasLinks() {
      return links.size() > 0;
   }
   
   public String getName() {
      return name;
   }
   
   public Category getParent() {
      return parent;
   }
}

Link.java:

public class Link {
   private String url;
   
   public Link(String url) {
      this.url = url;
   }
   
   public String getUrl() {
      return url;
   }
}

CategoryTreeContentProvider.java:

import org.eclipse.jface.viewers.*;
import java.util.*;

public class CategoryTreeContentProvider implements ITreeContentProvider 
{
   public Object[] getChildren(Object element) {
      Category category = (Category) element;
      System.out.println(category.getName());
      
      ArrayList children = new ArrayList();
      children.addAll(category.getSubCategories());
      children.addAll(category.getLinks());
            
      if (children.size() == 0) {
         return new Object[0];
      }
      
      return children.toArray();
   }
   
   public Object[] getElements(Object element) {
      return getChildren(element);
   }
   
   public boolean hasChildren(Object element) {
      if (element instanceof Category) {
         Category category = (Category) element;
      
         return category.hasSubCategories() || category.hasLinks();
      }
      
      return false;
   }
   
   public Object getParent(Object element) {
      if (element instanceof Category) {
         return ((Category) element).getParent();
      }
      
      return null;
   }
   
   public void dispose() {
      
   }
   
   public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
      
   }
}

CategoryTreeLabelProvider.java:

import org.eclipse.jface.viewers.*;

public class CategoryTreeLabelProvider extends LabelProvider
{
   public String getText(Object element) {
      if (element instanceof Category) {
         return ((Category) element).getName();
      }
      else if (element instanceof Link) {
         return ((Link) element).getUrl();
      }
      
      return "" + element;
   }
}

Main.java:

import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.ole.win32.OLE;
import org.eclipse.swt.ole.win32.OleAutomation;
import org.eclipse.swt.ole.win32.OleControlSite;
import org.eclipse.swt.ole.win32.OleFrame;
import org.eclipse.swt.ole.win32.Variant;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;

public class Main extends ApplicationWindow 
{
   private Category rootCategory;
   private OleAutomation automation = null;
   
   public Main() {
      super(null);
      
      // statically create categories
      rootCategory = new Category("Java", null);
      Category j2seCategory = new Category("J2SE", rootCategory);
      Link link = new Link("http://java.sun.com/j2se/");
      j2seCategory.addLink(link);
      Category j2eeCategory = new Category("J2EE", rootCategory);
      link = new Link("http://java.sun.com/j2ee/");
      j2eeCategory.addLink(link);
      Category j2meCategory = new Category("J2ME", rootCategory);
      link = new Link("http://java.sun.com/j2me/");
      j2meCategory.addLink(link);
      
      rootCategory.addSubCategory(j2seCategory);
      rootCategory.addSubCategory(j2eeCategory);
      rootCategory.addSubCategory(j2meCategory);
   }
   
   protected Control createContents(Composite parent) {
      SashForm sashForm = new SashForm(parent, SWT.HORIZONTAL | SWT.NULL);
      
      TreeViewer treeViewer = new TreeViewer(sashForm);
      treeViewer.setContentProvider(new CategoryTreeContentProvider());
      treeViewer.setLabelProvider(new CategoryTreeLabelProvider());
      treeViewer.setInput(rootCategory);
      
      createIEControl(sashForm);
      
      treeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
         public void selectionChanged(SelectionChangedEvent event) {
            IStructuredSelection selection = (IStructuredSelection) event.getSelection();
            
            Object selectedObject = selection.getFirstElement();
            if (selectedObject instanceof Link) {
               goUrl(((Link) selectedObject).getUrl());  
            }
         }
      });
      
      return sashForm;
   }
   
   public static void main(String []args) {
      Main main = new Main();
      main.setBlockOnOpen(true);
      main.open();
      
      Display.getCurrent().dispose();
   }
   
   private void createIEControl(Composite parent) {     
      OleFrame frame = new OleFrame(parent, SWT.BORDER);
      FormData formData = new FormData();
      formData.top = new FormAttachment(0, 10);
      formData.left = new FormAttachment(0, 100);
      formData.right = new FormAttachment(100, 0);
      formData.bottom = new FormAttachment(100, -10);
      frame.setLayoutData(formData);
   
      OleControlSite controlSite = new OleControlSite(frame, SWT.NONE, "Shell.Explorer");
      controlSite.doVerb(OLE.OLEIVERB_SHOW);
      automation = new OleAutomation(controlSite);
      int[] rgdispid = automation.getIDsOfNames(new String[]{"GoHome"});
      int dispIdMember = rgdispid[0];
      automation.invoke(dispIdMember);
   }
   
   public void goUrl(String url) {
      int[] rgdispid = automation.getIDsOfNames(new String[]{"Navigate"});
      int dispIdMember = rgdispid[0];
      Variant[] rgvarg = new Variant[1]; // this is the URL parameter
      rgvarg[0] = new Variant(url);
      Variant pVarResult = automation.invoke(dispIdMember, rgvarg);      
   }   
}

Putting a component in a TitledBorder?

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

CompTitledPaneExample1.java:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
 
/**
 * @version 1.0 08/12/99
 */  
public class CompTitledPaneExample1 extends JFrame {
 
  String title = "<html>Title (" 
               + "<font color="#ffffff"><i>JLabel</i></font>"
               + ")";
 
  public CompTitledPaneExample1() {
    super("CompTitledPaneExample1");
    JLabel titleLabel = new JLabel(title);
    CompTitledPane p1 = new CompTitledPane(titleLabel);
    JPanel p = p1.getContentPane();
    p.setLayout(new BorderLayout());
    p.add(new SwitchPanel(p1), BorderLayout.CENTER);
    getContentPane().add(p1, BorderLayout.CENTER);
  }
  
  class SwitchPanel extends JPanel implements ActionListener {
    String[] posStr = {"", "ABOVE_TOP"   , "TOP"   , "BELOW_TOP"
                         , "ABOVE_BOTTOM", "BOTTOM", "BELOW_BOTTOM"};
    String[] jusStr = {"", "LEFT"        , "CENTER", "RIGHT"};
    TitledBorder border;
    CompTitledPane panel;
    
    SwitchPanel(CompTitledPane panel) {
      this.panel = panel;
      this.border = (TitledBorder)panel.getBorder();
      add(createPanel("Position"     ,posStr, 2));
      add(createPanel("Justification",jusStr, 1));
    }
    
    JPanel createPanel(String str, String[] strs, int selectPos) {
      JPanel p = new JPanel();
      p.setLayout(new GridLayout(strs.length, 1));
      p.add(new JLabel(str));
      ButtonGroup g = new ButtonGroup();
      for (int i=1;i<strs.length;i++) {
        JRadioButton b = new JRadioButton(strs[i]);
        if (i == selectPos) {
          b.setSelected(true);
        }
        p.add( b );
        g.add( b );
        b.addActionListener(this);
      }
      return p;
    }
    
    public void actionPerformed(ActionEvent e) {
      JRadioButton b = (JRadioButton)e.getSource();
      String label = b.getText();
      for (int i=1; i<posStr.length; i++) {
        if (label.equals(posStr[i])) {
          border.setTitlePosition(i);
          panel.revalidate();
          panel.repaint();
          return;
        }    
      }
      for (int i=1; i<jusStr.length; i++) {
        if (label.equals(jusStr[i])) {
          border.setTitleJustification(i);
          panel.revalidate();
          panel.repaint();
          return;
        }    
      }
    }   
  }
 
  public static void main (String args[]) {
    CompTitledPaneExample1 frame = new CompTitledPaneExample1();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
	System.exit(0);
      }
    });
    frame.setSize(280, 230);
    frame.setVisible(true);
  }
}

CompTitledPane.java:

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
    
/**
 * @version 1.0 08/12/99
 */
public class CompTitledPane extends JPanel {
  protected CompTitledBorder border;
  protected JComponent component;
  protected JPanel panel;
  protected boolean transmittingAllowed;
  protected StateTransmitter transmitter;
  
  public CompTitledPane() {
    this(new JLabel("Title"));
    // debug
    // JLabel label = (JLabel)getTitleComponent();
    // label.setOpaque(true);
    // label.setBackground(Color.yellow);
  }
  
  public CompTitledPane(JComponent component) {
    this.component = component;
    border = new CompTitledBorder(component);
    setBorder(border);
    panel = new JPanel();
    setLayout(null);
    add(component);
    add(panel); 
    transmittingAllowed = false;
    transmitter = null;
  }
  
  public JComponent getTitleComponent() {
    return component;
  }
  
  public void setTitleComponent(JComponent newComponent) {
    remove(component);
    add(newComponent);
    border.setTitleComponent(newComponent);
    component = newComponent;
  }
  
  public JPanel getContentPane() {
    return panel;
  }
  
  public void doLayout() {
    Insets insets = getInsets();
    Rectangle rect = getBounds();
    rect.x = 0;
    rect.y = 0;
 
    Rectangle compR = border.getComponentRect(rect,insets);
    component.setBounds(compR);
    rect.x += insets.left;
    rect.y += insets.top;
    rect.width  -= insets.left + insets.right;
    rect.height -= insets.top  + insets.bottom;
    panel.setBounds(rect);   
  }
   
  public void setTransmittingAllowed(boolean enable) {
    transmittingAllowed = enable;
  }
  
  public boolean getTransmittingAllowed() {
    return transmittingAllowed;
  }
  
  public void setTransmitter(StateTransmitter transmitter) {
    this.transmitter = transmitter;
  }
  
  public StateTransmitter getTransmitter() {
    return transmitter;
  }
  
  public void setEnabled(boolean enable) {
    super.setEnabled(enable);
    if (transmittingAllowed && transmitter != null) {
      transmitter.setChildrenEnabled(enable);
    }
  } 
    
}

StateTransmitter.java:

/**
 * @version 1.0 08/12/99
 */
public interface StateTransmitter {

  public void setChildrenEnabled(boolean enable);
  
}

// sample
//
//  public void setChildrenEnabled(boolean enable) {
//    
//    Component[] children = panel.getComponents();
//    for(int i=0; i<children.length; i++) { 
//      System.out.println(" " + i + 
//                         " " + children[i].getClass().getName() +
//                         " " + enable);
//      children[i].setEnabled(enable); 
//    }
//  }
//

CompTitledBorder.java:

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
  
/**
 * @version 1.0 08/12/99
 */
public class CompTitledBorder extends TitledBorder { 
  protected JComponent component;
  
  public CompTitledBorder(JComponent component) {
    this(null, component, LEFT, TOP);
  }
  
  public CompTitledBorder(Border border) {
    this(border, null, LEFT, TOP);
  }
  
  public CompTitledBorder(Border border, JComponent component) {
    this(border, component, LEFT, TOP);
  }
    
  public CompTitledBorder(Border     border,
                          JComponent component,
                          int        titleJustification,
                          int        titlePosition)      {
    super(border, null, titleJustification,
                        titlePosition, null, null);
    this.component = component;
    if (border == null) {
      this.border = super.getBorder();
    }
  }
  
  
  public void paintBorder(Component c, Graphics g,
                          int x, int y, int width, int height) {
    Rectangle borderR = new Rectangle(x      +  EDGE_SPACING,
                                      y      +  EDGE_SPACING,
                                      width  - (EDGE_SPACING * 2),
                                      height - (EDGE_SPACING * 2));
    Insets borderInsets;
    if (border != null) {
      borderInsets = border.getBorderInsets(c);
    } else {
      borderInsets = new Insets(0, 0, 0, 0);
    }
    
    Rectangle rect = new Rectangle(x,y,width,height);
    Insets insets = getBorderInsets(c);
    Rectangle compR = getComponentRect(rect, insets);
    int diff;
    switch (titlePosition) {
      case ABOVE_TOP:
        diff = compR.height + TEXT_SPACING;
        borderR.y += diff;
        borderR.height -= diff;
        break;
      case TOP:
      case DEFAULT_POSITION:
        diff = insets.top/2 - borderInsets.top - EDGE_SPACING;
        borderR.y += diff;
        borderR.height -= diff;
        break;
      case BELOW_TOP:
      case ABOVE_BOTTOM:
        break;
      case BOTTOM:
        diff = insets.bottom/2 - borderInsets.bottom - EDGE_SPACING;
        borderR.height -= diff;
        break;
      case BELOW_BOTTOM:
        diff = compR.height + TEXT_SPACING;
        borderR.height -= diff;
        break;
    }
    border.paintBorder(c, g, borderR.x,     borderR.y, 
                             borderR.width, borderR.height);    
    Color col = g.getColor();
    g.setColor(c.getBackground());
    g.fillRect(compR.x, compR.y, compR.width, compR.height);
    g.setColor(col);
    component.repaint();
  }
   
  public Insets getBorderInsets(Component c, Insets insets) {
    Insets borderInsets;
    if (border != null) {
      borderInsets  = border.getBorderInsets(c);
    } else {
      borderInsets  = new Insets(0,0,0,0);
    }
    insets.top    = EDGE_SPACING + TEXT_SPACING + borderInsets.top;
    insets.right  = EDGE_SPACING + TEXT_SPACING + borderInsets.right;
    insets.bottom = EDGE_SPACING + TEXT_SPACING + borderInsets.bottom;
    insets.left   = EDGE_SPACING + TEXT_SPACING + borderInsets.left;
 
    if (c == null || component == null) {
      return insets;
    }
 
    int compHeight = 0;
    if (component != null) {
      compHeight = component.getPreferredSize().height;
    }
 
    switch (titlePosition) {
      case ABOVE_TOP:
        insets.top    += compHeight + TEXT_SPACING;
        break;
      case TOP:
      case DEFAULT_POSITION:
        insets.top    += Math.max(compHeight,borderInsets.top) - borderInsets.top;
        break;
      case BELOW_TOP:
        insets.top    += compHeight + TEXT_SPACING;
        break;
      case ABOVE_BOTTOM:
        insets.bottom += compHeight + TEXT_SPACING;
        break;
      case BOTTOM:
        insets.bottom += Math.max(compHeight,borderInsets.bottom) - borderInsets.bottom;
        break;
      case BELOW_BOTTOM:
        insets.bottom += compHeight + TEXT_SPACING;
        break;
    }
    return insets;
  }
  
  public JComponent getTitleComponent() {
    return component;
  }
  
  public void setTitleComponent(JComponent component) {
    this.component = component;
  }
  
  
  public Rectangle getComponentRect(Rectangle rect,Insets borderInsets) {
    Dimension compD = component.getPreferredSize();
    Rectangle compR = new Rectangle(0,0,compD.width,compD.height);
    switch (titlePosition) {
      case ABOVE_TOP:
        compR.y = EDGE_SPACING;
        break;
      case TOP:
      case DEFAULT_POSITION:
        compR.y = EDGE_SPACING + 
                 (borderInsets.top -EDGE_SPACING -TEXT_SPACING -compD.height)/2;
        break;
      case BELOW_TOP:
        compR.y = borderInsets.top - compD.height - TEXT_SPACING;
        break;
      case ABOVE_BOTTOM:
        compR.y = rect.height - borderInsets.bottom + TEXT_SPACING;
        break;
      case BOTTOM:
        compR.y = rect.height - borderInsets.bottom + TEXT_SPACING +
                 (borderInsets.bottom -EDGE_SPACING -TEXT_SPACING -compD.height)/2;
        break;
      case BELOW_BOTTOM:
        compR.y = rect.height - compD.height - EDGE_SPACING;
        break;
    }
    switch (titleJustification) {
      case LEFT:
      case DEFAULT_JUSTIFICATION:
        compR.x = TEXT_INSET_H + borderInsets.left;
        break;
      case RIGHT:
        compR.x = rect.width - borderInsets.right -TEXT_INSET_H -compR.width;
        break;
      case CENTER:
        compR.x = (rect.width - compR.width) / 2;
        break;
    }
    return compR;
  }
 
}

Perform outline-dragging with JInternalFrame

Outline dragging is a JDesktopPane client property that provides the user with a outline rectangle when JInternalFrames are dragged instead of displaying the full contents of the JInternalFrame, making dragging internal frames a lot more performant. To perform outline dragging, set the property JDesktopPane.dragMode to outline. Swing 1.1.1 had added fast implementation for fast dragging. Put the client property to “faster”.
Here’s an example:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.net.*;
 
public class Main extends JFrame implements ActionListener {
   JDesktopPane desktop;
   int nframes = 0;
 
   public Main() {
      getContentPane().setLayout(new BorderLayout());
      desktop = new JDesktopPane(); 
      createInternalFrame();
      getContentPane().add(BorderLayout.CENTER, desktop);
      setJMenuBar(createMenuBar());
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   
      setTitle(&quot;Outline Dragging Demonstration&quot;);
      setSize(new Dimension(400, 400));
   }
 
   protected JMenuBar createMenuBar() {
      JMenuBar menuBar = new JMenuBar();

      JMenu menu = new JMenu(&quot;JDesktopPane&quot;);
      JMenuItem menuItem1 = new JMenuItem(&quot;Create new JInternalFrame&quot;);
      menuItem1.addActionListener(this);
      menu.add(menuItem1);
      menu.add(new JSeparator());
      JMenuItem menuItem2 = new JMenuItem(&quot;Outline dragging normal&quot;);
      menuItem2.addActionListener(this);
      menu.add(menuItem2);
      JMenuItem menuItem3 = new JMenuItem(&quot;Outline dragging on&quot;);
      menuItem3.addActionListener(this);
      menu.add(menuItem3);
      JMenuItem menuItem4 = new JMenuItem(&quot;Fast dragging&quot;);
      menuItem4.addActionListener(this);
      menu.add(menuItem4);
      menuBar.add(menu);

      return menuBar;
   }
 
   public void actionPerformed(ActionEvent e) {
      if (e.getActionCommand().equals(&quot;Create new JInternalFrame&quot;)) {
         createInternalFrame();
      }
      else if (e.getActionCommand().equals(&quot;Outline dragging normal&quot;)) {
         desktop.putClientProperty(&quot;JDesktopPane.dragMode&quot;, &quot;normal&quot;);
      }
      else if (e.getActionCommand().equals(&quot;Outline dragging on&quot;)) {
         // Make dragging faster
         desktop.putClientProperty(&quot;JDesktopPane.dragMode&quot;, &quot;outline&quot;);
      }
      else if (e.getActionCommand().equals(&quot;Fast dragging&quot;)) {
         desktop.putClientProperty(&quot;JDesktopPane.dragMode&quot;, &quot;faster&quot;);
      }
   }
 
   protected void createInternalFrame() {
      JInternalFrame frame = new JInternalFrame(&quot;InternalFrame&quot;, 
         true,    // resizable
         true,    // closable
         true,    // maximizable
         true);   // iconifiable
      frame.setVisible(true); 
      desktop.add(frame);
      frame.setSize(200, 200);
      frame.setLocation(30*nframes, 30*nframes);
      nframes++;
      try {
         frame.setSelected(true);
      } catch (java.beans.PropertyVetoException e) {}
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

Changing a JButton’s label

Use the method setText.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame {
   JList list; 
 
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      // following objects are final because they are used
      // in a inner class
      final JTextField textfield = new JTextField(20); 
      final JButton button = new JButton("initial label");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            if (!textfield.getText().equals(""))
               button.setText(textfield.getText());
         }
      });
 
      getContentPane().add(textfield);
      getContentPane().add(button);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Dynamically changing the font size of a JComboBox

Main.java:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      Vector v = new Vector();
      for (int i=10; i<100; i+=5) {
         v.addElement(""+i);
      }
 
      final JComboBox combobox = new JComboBox(v);
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
      getContentPane().add(new JLabel("Select font size:"));
      getContentPane().add(combobox);
 
      Font f = combobox.getFont();
      combobox.setFont(f.deriveFont(10.0f));
  
      combobox.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            Font f = combobox.getFont();
            combobox.setFont(f.deriveFont(
                                new Float(""+combobox.getSelectedItem()).
                                          floatValue()));
         }
      });
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(200, 200);
      main.setVisible(true);
   }
}

Adding a border to each element in a JList

Change the default cell renderer as in following example:

import javax.swing.border.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main {
   public static void main(String args[]) {
      JFrame frame = new JFrame("JList Background Demonstration");
      final ImageIcon imageIcon = new ImageIcon("bg1.jpg");
 
      Vector v = new Vector();
      for (int i=0; i<10; i++) {
         v.addElement("Item #" + i);
      }
 
      JList list = new JList(v);
 
      list.setCellRenderer(new BorderCellRenderer(new BevelBorder(BevelBorder.LOWERED)));
//      list.setCellRenderer(new BorderCellRenderer(new BevelBorder(BevelBorder.RAISED)));
//      list.setCellRenderer(new BorderCellRenderer(new EtchedBorder(EtchedBorder.LOWERED)));
//      list.setCellRenderer(new BorderCellRenderer(new EtchedBorder(EtchedBorder.RAISED)));
      
      frame.getContentPane().add(BorderLayout.CENTER, list); //new JScrollPane(list));
      frame.setDefaultCloseOperation(3);
      frame.pack();
      frame.setVisible(true);
   }
}
 
class BorderCellRenderer extends DefaultListCellRenderer implements ListCellRenderer {
   AbstractBorder border;
 
   public BorderCellRenderer(AbstractBorder border) {
      this.border = border;
   }
 
   public Component getListCellRendererComponent(
      JList list,
      Object value,            // value to display
      int index,               // cell index
      boolean isSelected,      // is the cell selected
      boolean cellHasFocus)    // the list and the cell have the focus
   {
      Component c = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
 
      ((JComponent) c).setBorder(border);
 
      return c;
   }
}

Changing the colors of my JMenu and JMenuItems

Use setForeground and setBackground. You can change the default selection colors using the UIManager.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
    
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
  
      // change default selection colors
      UIManager.put("Menu.selectionBackground", 
             new javax.swing.plaf.ColorUIResource(Color.blue));
      UIManager.put("MenuItem.selectionBackground", 
             new javax.swing.plaf.ColorUIResource(Color.green));
 
      JMenuBar menuBar = new JMenuBar();
      JMenu menu = new JMenu("Sex");
      JMenuItem menuItem1 = new JMenuItem("male");
      JMenuItem menuItem2 = new JMenuItem("female");
      JMenuItem menuItem3 = new JMenuItem("androgyne");
 
      menuItem1.setBackground(Color.red);
      menuItem1.setForeground(Color.yellow);
      menuItem2.setBackground(Color.red);
      menuItem2.setForeground(Color.yellow);
      menuItem3.setBackground(Color.red);
      menuItem3.setForeground(Color.yellow);
  
      menu.setBackground(Color.white);
      menu.setForeground(Color.blue);
 
      // add the MenuItems to the Menu 
      menu.add(menuItem1);
      menu.add(menuItem2);
      menu.add(menuItem3);
  
      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();
   }
}