Changing the margins between JTable grid lines and cell data

You can do so with the JTable method setIntercellSpacing.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame 
{
   public Main() {
      super("Table example, Wines from Bordeaux");
 
      Object[][] tabledata = {
            { "Chateau Meyney, St. Estephe", 	   new Integer(1994), "$18.75"},
            { "Chateau Montrose, St. Estephe", 	   new Integer(1975), "$54.25" },
            { "Chateau Gloria, St. Julien", 	   new Integer(1993), "$22.99" },
            { "Chateau Beychevelle, St. Julien",   new Integer(1970), "$61.63" },
            { "Chateau La Tour de Mons, Margeaux", new Integer(1975), "$57.03" },
            { "Chateau Brane-Cantenac, Margeaux",  new Integer(1978), "$49.92" },
      };
 
      String columnheaders[] = { "Wine", "Vintage", "Price" };
 
      JTable table = new JTable(tabledata, columnheaders);
      table.setPreferredScrollableViewportSize(new Dimension(500, 70));
      JScrollPane scrollPane = new JScrollPane(table);
 
      table.setIntercellSpacing(new Dimension (10,20));
  
      getContentPane().add(scrollPane);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      pack();
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

Adding a background image to a JTree

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 = new DefaultMutableTreeNode("Root");
      for (int i=0; i<10; i++) {
         DefaultMutableTreeNode child = new DefaultMutableTreeNode("Child " + (i+1));
         root.add(child);
      }
      JTree tree = new JTree(root) {
         ImageIcon icon = new ImageIcon("mong.jpg");
 
         public void paint( Graphics g ) 
         { 
            // tile it
            Dimension d = this.getSize(); 
            for(int i=0; i<d.width; i+=icon.getIconWidth()) { 
               for(int j=0; j<d.height; j+=icon.getIconHeight()) { 
                  g.drawImage(icon.getImage(), i, j, null, null); 
               }
            }
 
            super.paint(g); 
         } 
      }; 
 
      tree.setOpaque( false );
  
 
      DefaultTreeCellRenderer cr = new DefaultTreeCellRenderer();
      cr.setOpaque(false);
      cr.setBackground(new Color(0, 0, 0, 0));  
      cr.setBackgroundNonSelectionColor(null);
      tree.setCellRenderer(cr);
 
      getContentPane().add(new JScrollPane(tree));
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}

Image used: http://www.esus.com/images/mong.jpg

Disabling selection in my JTable

Look at the three lines of code in this working program to find out how to disallow any selection.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame 
{
   public Main() {
      super("Table example, Wines from Bordeaux");
 
      Object[][] tabledata = {
            { "Chateau Meyney, St. Estephe", 	   new Integer(1994), "$18.75"},
            { "Chateau Montrose, St. Estephe", 	   new Integer(1975), "$54.25" },
            { "Chateau Gloria, St. Julien", 	   new Integer(1993), "$22.99" },
            { "Chateau Beychevelle, St. Julien",   new Integer(1970), "$61.63" },
            { "Chateau La Tour de Mons, Margeaux", new Integer(1975), "$57.03" },
            { "Chateau Brane-Cantenac, Margeaux",  new Integer(1978), "$49.92" },
      };
 
      String columnheaders[] = { "Wine", "Vintage", "Price" };
 
      JTable table = new JTable(tabledata, columnheaders);
      table.setPreferredScrollableViewportSize(new Dimension(500, 70));
      JScrollPane scrollPane = new JScrollPane(table);
 
      getContentPane().add(scrollPane);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      // disable selection
      table.setRowSelectionAllowed(false);
      table.setColumnSelectionAllowed(false);
      table.setCellSelectionEnabled(false);
 
      pack();
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

Have two JTrees vertically aligned in a JScrollPane

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 tree1 = new JTree(root);
      JTree tree2 = new JTree(root);
 
      tree1.addTreeSelectionListener(new TreeSelectionListener() {
         public void valueChanged(TreeSelectionEvent e) {         
            TreePath path = e.getPath();
            System.out.println(path.getLastPathComponent());     
         }
      });
 
      tree2.addTreeSelectionListener(new TreeSelectionListener() {
         public void valueChanged(TreeSelectionEvent e) {         
            TreePath path = e.getPath();
            System.out.println(path.getLastPathComponent());     
         }
      });
  
      Box box = Box.createVerticalBox();
      box.add(tree1);
      box.add(tree2);
 
      // bugparade #4833645
      tree1.setMinimumSize(tree1.getPreferredSize());
      tree1.setAlignmentX(0);
      tree2.setMinimumSize(tree2.getPreferredSize());
      tree2.setAlignmentX(0);
 
      getContentPane().setLayout(new BorderLayout());
     
      JScrollPane sp = new JScrollPane(box);
      sp.getViewport().setBackground(Color.white);
 
      getContentPane().add(BorderLayout.NORTH, sp);
 
      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);
   }
}

Force the JScrollPane to scroll to the next JTextField when I press the TAB-Key

There are three steps to this:

1. Listen for focus events coming from the components that you want to scroll to. (This works for most component classes, not just JTextField.)

2. In the event listener, find the location of the component that now has focus with getBounds().

3. Ask the scrolled component to make that location visible with scrollRectToVisible(). NOTE! The obvious thing to call scrollRectToVisible on is the JScrollPane, which will compile fine but won’t do what you want. You must call scrollRectToVisible on the object contained in viewport of the scrollpane.

This Forte-generated example shows how this works for a simple panel containing a number of JTextFields. Notice that scrollRectToVisible is called on the JPanel containing the text fields.

TestFocus.java:

public class TestFocus extends javax.swing.JFrame {
 
    /** Creates new form TestFocus */
    public TestFocus() {
        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.
     */
    private void initComponents() {
        scrollPane = new javax.swing.JScrollPane();
        panel = new javax.swing.JPanel();
        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jTextField4 = new javax.swing.JTextField();
         
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });
        
        scrollPane.setPreferredSize(new java.awt.Dimension(120, 80));
        panel.setLayout(new java.awt.GridLayout(0, 1, 0, 15));
        
        jTextField1.setFont(new java.awt.Font("Dialog", 0, 18));
        jTextField1.setText("jTextField1");
        jTextField1.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jTextFieldFocusGained(evt);
            }
        });
         
        panel.add(jTextField1);
        
        jTextField2.setFont(new java.awt.Font("Dialog", 0, 18));
        jTextField2.setText("jTextField2");
        jTextField2.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jTextFieldFocusGained(evt);
            }
        });
        
        panel.add(jTextField2);
        
        jTextField3.setFont(new java.awt.Font("Dialog", 0, 18));
        jTextField3.setText("jTextField3");
        jTextField3.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jTextFieldFocusGained(evt);
            }
        });
        
        panel.add(jTextField3);
        
        jTextField4.setFont(new java.awt.Font("Dialog", 0, 18));
        jTextField4.setText("jTextField4");
        jTextField4.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jTextFieldFocusGained(evt);
            }
        });
        
        panel.add(jTextField4);
        
        scrollPane.setViewportView(panel);
        
        getContentPane().add(scrollPane, java.awt.BorderLayout.CENTER);
        
        pack();
    }
 
    private void jTextFieldFocusGained(java.awt.event.FocusEvent evt) {
        java.awt.Component focusedComponent = evt.getComponent();
        panel.scrollRectToVisible(focusedComponent.getBounds(null));
        repaint();
    }
 
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {
        System.exit(0);
    }
 
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        new TestFocus().show();
    }
 
    // Variables declaration - do not modify
    private javax.swing.JScrollPane scrollPane;
    private javax.swing.JPanel panel;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    // End of variables declaration

}

If your panel of components contains a JTextArea, or another JTextComponent subclass, then be aware that those components will absorb TABs into themselves instead of allowing the TAB to change focus. You can disable this behavior by creating a subclass that overrides isManagingFocus() to always return false.

Preventing a JInternalFrame from being moved

You can subclass the protected class BorderListener that is defined in BasicInternalFrameUI and provide an empty implementation for mouseDragged. In the following example, it is done so for the Metal look and feel.

Main.java:

import javax.swing.plaf.basic.*;
import javax.swing.plaf.metal.*;
import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.net.*;
 
public class Main extends JFrame {
   JDesktopPane desktop;
   int nframes = 0;
 
   JMenu internalFrameMenu;
 
   public Main() {
      desktop = new JDesktopPane(); 
      setContentPane(desktop);
      setJMenuBar(createMenuBar());
      createInternalFrame(); 
   }
 
   protected JMenuBar createMenuBar() {
      JMenuBar menuBar = new JMenuBar();
 
      JMenu createMenu = new JMenu("Create");
      createMenu.setMnemonic(KeyEvent.VK_C);
      JMenuItem newMenuItem = new JMenuItem("New");
      newMenuItem.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            createInternalFrame();
         }
      }); 
      newMenuItem.setMnemonic(KeyEvent.VK_N);
      createMenu.add(newMenuItem);
      menuBar.add(createMenu);
  
      return menuBar;
   }
 
   protected void createInternalFrame() {
      nframes++;
      String title = "JInternalFrame #" + nframes;
      JInternalFrame frame = new JInternalFrame(title,
         true,    // resizable
         true,    // closable
         true,    // maximizable
         true);   // iconifiable
      frame.setVisible(true); 
      desktop.add(frame);
      frame.setSize(200, 200);
      frame.setLocation(30*nframes, 30*nframes);
      try {
         frame.setSelected(true);
      } catch (java.beans.PropertyVetoException e) {}
 
      frame.setUI(new MyMetalInternalFrameUI(frame));
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(500, 300);
      main.setVisible(true);
   }
}
 
class MyMetalInternalFrameUI extends MetalInternalFrameUI {
   public MyMetalInternalFrameUI(JInternalFrame b) { super(b); }
 
   protected MouseInputAdapter createBorderListener(JInternalFrame w) {
      return new MyBorderListener();
   }
 
   protected class MyBorderListener extends BasicInternalFrameUI.BorderListener {
      public void mouseDragged(MouseEvent e) {  }
   }
}

Implementing a mouseover effect with a JButton

Add a MouseListener to your JButton and code the desired behaviour in mouseEntered and mouseExited.
This example makes the JButton’s label red when mouse-moving over it.

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 JButton button = new JButton(&quot;OK!&quot;);
      button.addMouseListener(new MouseAdapter() {
         Color oldcolor = button.getForeground();
         public void mouseEntered(MouseEvent me) {
            oldcolor = button.getForeground();
            button.setForeground(Color.red); 
         }
         public void mouseExited(MouseEvent me) {
            button.setForeground(oldcolor);
         }
      });
 
      getContentPane().add(button);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(400, 400);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Refreshing the contents of a JList

JListExample.java:

 
// Created with JBuilder (c) Philip Craiger
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
/**
 * Title:        A JList Programming Example
 * Description:
 * Copyright:    Copyright (c) 2001
 * Company:
 * @author Dr. Philip Craiger
 * @version 1.0
 */
 
public class JListExample extends JFrame {
  private JButton btnMove = new JButton();
  private JButton bthRemove = new JButton();
 
  // Model View Controller: We change contents of the JList through
  // manipulation of a MODEL, not the actual JList.
  
 
  private DefaultListModel model_1 = new DefaultListModel();
  private DefaultListModel model_2 = new DefaultListModel();
 
  private JList jList1 = new JList(model_2);
  private JList jList2 = new JList(model_1);
  
  // JLists do not scroll by default.  We need to add them to
  // an encompassing JScrollPane
  private JScrollPane jScrollPane1 = new JScrollPane();
  private JScrollPane jScrollPane2 = new JScrollPane();
 
  public JListExample() {     // our constructor
    super("A JList Example"); // call to super constructor
    try {
      jbInit();
    }
    catch(Exception e) {
      e.printStackTrace();
    }
  }
 
  public static void main(String[] args) {
    JListExample foo = new JListExample();
    foo.setSize(new Dimension(450,200));
    foo.show();
  }
 
  private void jbInit() throws Exception {
 
  // Note we are adding and removing JList items from the MODEL
  // NOT directly from the JList.  Because JList is associated with the
  // model, the JList contents are updated automatically
 
    model_1.addElement("Java");
    model_1.addElement("Visual Basic");
    model_1.addElement("C++");
    model_1.addElement("C");
    model_1.addElement("Common LISP");
    model_1.addElement("Fortran");
    model_1.addElement("Pascal");
    model_1.addElement("Python");
    this.getContentPane().setLayout(null);
 
    btnMove.setText("Move >>");
    btnMove.setBounds(new Rectangle(150, 35, 98, 36));
    btnMove.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(ActionEvent e) {
        btnMove_actionPerformed(e);
      }
    });
 
    bthRemove.setText("<< Remove");
    bthRemove.setBounds(new Rectangle(152, 87, 97, 36));
    bthRemove.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(ActionEvent e) {
        bthRemove_actionPerformed(e);
      }
    });
 
    jScrollPane1.setBounds(new Rectangle(286, 15, 109, 133));
    jScrollPane2.setBounds(new Rectangle(14, 15, 106, 136));
 
    // Allow user to select a single item from JList
    jList1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    jList2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
 
    this.getContentPane().add(jScrollPane2, null);
    jScrollPane2.getViewport().add(jList2, null); // Must add JList
    this.getContentPane().add(jScrollPane1, null); // to a JScrollPane
    this.getContentPane().add(btnMove, null);
    this.getContentPane().add(bthRemove, null);
    jScrollPane1.getViewport().add(jList1, null); // JList to JScrollPane
    jList2.setSelectedIndex(0);
  }
 
  void btnMove_actionPerformed(ActionEvent e) {
    model_2.addElement(jList2.getSelectedValue());  // change the MODEL
    model_1.removeElement(jList2.getSelectedValue());  // change the MODEL
    jList2.setSelectedIndex(0);       // Highlight first item in JList
  }
 
  void bthRemove_actionPerformed(ActionEvent e) {
    model_1.addElement(jList1.getSelectedValue());  // change the MODEL
    model_2.removeElement(jList1.getSelectedValue()); // change the MODEL
    jList2.setSelectedIndex(0);       // Highlight first item in JList
  }
}

Catching the event when a JMenuItem has been selected

Add an ActionListener object. Here’s an example:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame implements ActionListener {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JMenuBar menuBar = new JMenuBar();
      JMenu menu = new JMenu(&quot;menu&quot;);
      JMenuItem menuItem1 = new JMenuItem(&quot;option 1&quot;);
      JMenuItem menuItem2 = new JMenuItem(&quot;option 2&quot;);
      JMenuItem menuItem3 = new JMenuItem(&quot;option 3&quot;);
      menuItem1.addActionListener(this);
      menuItem2.addActionListener(this);
      menuItem3.addActionListener(this);
      menu.add(menuItem1);
      menu.add(menuItem2);
      menu.add(new JSeparator());
      menu.add(menuItem3);
      menuBar.add(menu);
 
      this.setJMenuBar(menuBar); 
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(400, 400);
   }

   public void actionPerformed(ActionEvent ae) {
      System.out.println(ae.getActionCommand() + &quot; selected!&quot;);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Embedding a JSpinner inside a JTable cell

Main.java:

import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
  
public class JSpinnerTableExample extends JFrame {
 
  public JSpinnerTableExample(){
    super( &amp;amp;quot;JSpinnerTable Example&amp;amp;quot; );
    
    SpinnerNumberModel spinnerModel1 = new SpinnerNumberModel(10.0, -500.0, 500.0, .5);
    SpinnerDateModel spinnerModel2 = new SpinnerDateModel();
 
    DefaultTableModel dtm = new DefaultTableModel();
    dtm.setDataVector(new Object[][]{{ spinnerModel1, &amp;amp;quot;JSpinner1&amp;amp;quot; },
                                     { spinnerModel2, &amp;amp;quot;JSpinner2&amp;amp;quot; }},
                      new Object[]{&amp;amp;quot;JSpinner&amp;amp;quot;,&amp;amp;quot;String&amp;amp;quot;});
                     
    JTable table = new JTable(dtm);
    table.getColumn(&amp;amp;quot;JSpinner&amp;amp;quot;).setCellRenderer(new SpinnerRenderer());
    table.getColumn(&amp;amp;quot;JSpinner&amp;amp;quot;).setCellEditor(new SpinnerEditor());
 
    table.setRowHeight(20);
    JScrollPane scroll = new JScrollPane(table);
    getContentPane().add(scroll);
 
    setSize( 400, 100 );
    setVisible(true);
  }
 
  public static void main(String[] args) {
    JSpinnerTableExample frame = new JSpinnerTableExample();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
  }
}
 
class SpinnerRenderer extends JSpinner implements TableCellRenderer {
   public SpinnerRenderer() {
      setOpaque(true);
   }
  
   public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int row, int column) {
      setModel((SpinnerModel) value);
  
      return this;
   }
}
  
class SpinnerEditor extends AbstractCellEditor implements TableCellEditor {
   protected JSpinner spinner;
  
   public SpinnerEditor() {
      spinner = new JSpinner();
   }
 
   public Component getTableCellEditorComponent(JTable table, Object value,
                    boolean isSelected, int row, int column) {
      spinner.setModel((SpinnerModel) value);
 
      return spinner;
   }
 
   public Object getCellEditorValue() {
      SpinnerModel sm = spinner.getModel();
      return sm;
   }
}