Switching to another display mode

From JDK1.4, you can use the class DisplayMode. Either instantiate a DisplayMode object by specifying width, height, bitdepth and refreshrate, or get a list of available DisplayModes by calling the method getDisplayModes on the current GraphicsDevice.

When you’ve made up your mind about the display mode, call the method setFullScreenWindow to get the device into “full-screen exclusive mode” (necessary) and the method setDisplayMode to perform the display change.

Main.java:

import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame {
   DisplayMode oldDm;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment (); 
      final GraphicsDevice gd = ge.getDefaultScreenDevice ();
 
      oldDm = gd.getDisplayMode();
      final DisplayMode dm[] = gd.getDisplayModes();
 
      Vector v = getDisplayModesAsStrings(dm);
      final JComboBox cb = new JComboBox(v);
      cb.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            int selectedIndex = cb.getSelectedIndex();
            gd.setFullScreenWindow(Main.this);
        
            if (gd.isDisplayChangeSupported()) {
               try {
                  gd.setDisplayMode(dm[selectedIndex]); 
               } catch(Exception e) {
                  gd.setDisplayMode(oldDm);
               }
            }
            else {
               System.out.println("Display change not supported!");
            }            
         }
      });
 
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
      getContentPane().add(new JLabel("Change to display mode:"));
      getContentPane().add(cb);
      pack();  
   }
 
   public Vector getDisplayModesAsStrings(DisplayMode dm[]) {
      Vector v = new Vector();
 
      for (int i=0; i<dm.length; i++) {
         int width = dm[i].getWidth();
         int height = dm[i].getHeight();
         int bitDepth = dm[i].getBitDepth();
         int refreshRate = dm[i].getRefreshRate();
         v.add("" + width + "x" + height + " " + bitDepth + "bit " + 
                              (refreshRate == 0 ? "unknown" : ""+refreshRate + "hz"));
      }
 
      return v;
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.setVisible(true);
   } 
}

Get notified when the user has moved the JSplitPane divider

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.awt.*;
 
public class Main extends JFrame
{
   JSplitPane splitPane;
  
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      final JLabel label = new JLabel();
      splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, 
                                 label, new JPanel());
      splitPane.setDividerSize(20);
      splitPane.setOneTouchExpandable(true);
 
      createMainMenuBar();
 
      getContentPane().add(splitPane);
 
      addComponentListener(new ComponentAdapter() {
         public void componentShown(ComponentEvent event) {
            splitPane.setDividerLocation(0.5);  
            label.setText("Divider location: " + splitPane.getDividerLocation());
                
            removeComponentListener(this);
         }
      });
 
      splitPane.addPropertyChangeListener(new PropertyChangeListener() {
         public void propertyChange(PropertyChangeEvent pce) {
            if (pce.getPropertyName().equals(JSplitPane.DIVIDER_LOCATION_PROPERTY)) {
               label.setText("Divider location: " + splitPane.getDividerLocation());
            }
         }
      });
   }
 
   public void createMainMenuBar() {
      JMenuBar mainBar = new JMenuBar();
      JMenu menu = new JMenu("JSplitPane");
      JMenuItem item1 = new JMenuItem("HORIZONTAL_SPLIT");
      JMenuItem item2 = new JMenuItem("VERTICAL_SPLIT");
      menu.add(item1);
      menu.add(item2);
      mainBar.add(menu);
      setJMenuBar(mainBar);
 
      item1.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
         }
      });
 
      item2.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
         }
      });
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}

Changing the color of the title bar and border of a JInternalFrame

This worked for me, using the Windows Look and Feel.

To change the colors of the title bar, modify some properties:

   InternalFrame.activeTitleBackground
   InternalFrame.activeTitleForeground
   InternalFrame.inactiveTitleBackground
   InternalFrame.inactiveTitleForeground

To change the border, you can call setBorder on a JInternalFrame.

Main.java:

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;
  
   public Main() {
      modifyColors();
      desktop = new JDesktopPane(); 
      setContentPane(desktop);
      setJMenuBar(createMenuBar());
      createInternalFrame(); 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   protected void modifyColors() {
      try {
         String name = UIManager.getSystemLookAndFeelClassName();
         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
         UIManager.put("InternalFrame.activeTitleBackground", Color.red);
         UIManager.put("InternalFrame.activeTitleForeground", Color.blue);
         UIManager.put("InternalFrame.inactiveTitleBackground", Color.black);
         UIManager.put("InternalFrame.inactiveTitleForeground", Color.yellow);
      }
      catch(Exception e) { 
         e.printStackTrace();
      }
   }
 
   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); 
 
      frame.setBorder(BorderFactory.createLineBorder(Color.black));
 frame.updateUI();
      desktop.add(frame);
      frame.setSize(200, 200);
      frame.setLocation(30*nframes, 30*nframes);
      try {
         frame.setSelected(true);
      } catch (java.beans.PropertyVetoException e) {}
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(500, 300);
      main.setVisible(true);
   }
}

Creating an editable JComboBox

Use the method setEditable. Here’s an example:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame
{ 
   public Main() {
      getContentPane().setLayout(new BorderLayout());
      final JComboBox combobox = new JComboBox();
      final JList list = new JList(new DefaultListModel());
 
      getContentPane().add(BorderLayout.NORTH, combobox);
      getContentPane().add(BorderLayout.CENTER, list); 
 
      combobox.setEditable(true);
      combobox.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent ie) {
            if (ie.getStateChange() == ItemEvent.SELECTED) {
               ((DefaultListModel) list.getModel()).addElement(combobox.getSelectedItem());
               combobox.insertItemAt(combobox.getSelectedItem(), 0);
            }
         }
      });
 
      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);
   }
}

Scrolling a JList to the selected item

You can use the method ensureIndexIsVisible as shown in following example:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
  
public class Main extends JFrame {
 
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      Vector v = new Vector();
      for (int i=0; i<50; i++) {
         v.addElement("Item #" + i);
      }
      final JList list = new JList(v);
 
      final JTextField textfield = new JTextField(5);
      getContentPane().add(new JLabel("Scroll to:"));
      getContentPane().add(textfield);
      JButton button = new JButton("Scroll!");
      getContentPane().add(button);
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            int n = Integer.parseInt(textfield.getText());
            list.ensureIndexIsVisible(n);
         }
      });
      getContentPane().add(new JScrollPane(list));    
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(200, 230);
   }
   
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Adding a general JComponent to a JMenu

Create your own version of the JComponent that you would like to add to your Menu and have it implement the methods of MenuElement. Here’s an example that shows a JMenu with a JTextField and a JSlider as its elements:

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("item 1");
      JMenuItem menuItem2 = new JMenuItem("item 2");
      JMenuItemTextField menuItem3 = new JMenuItemTextField(20);
      JMenuItem menuItem4 = new JMenuItem("item 4");
      JMenuItemSlider menuItem5 = new JMenuItemSlider();
      menuItem5.setMajorTickSpacing(20);
      menuItem5.setMinorTickSpacing(5);
      menuItem5.setPaintTicks(true);
      JMenuItem menuItem6 = new JMenuItem("item 6");
 
      menu.add(menuItem1);
      menu.add(menuItem2);
      menu.add(menuItem3);
      menu.add(menuItem4);
      menu.add(menuItem5);
      menu.add(menuItem6);
 
      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();
   }
}
 
class JMenuItemTextField extends JTextField implements MenuElement
{
   public JMenuItemTextField(int length) {
      super(length);
   }
 
   public Component getComponent() {
      return this;
   }
 
   public MenuElement[] getSubElements() {
      return null;
   }
 
   public void menuSelectionChanged(boolean changed) {
   }
 
   public void processKeyEvent(KeyEvent kevt, MenuElement[] me, MenuSelectionManager msm) {
   }
 
   public void processMouseEvent(MouseEvent mevt, MenuElement[] me, MenuSelectionManager msm) {
   }
}
 
class JMenuItemSlider extends JSlider implements MenuElement
{
   public JMenuItemSlider() {
      super();
   }
 
   public Component getComponent() {
      return this;
   }
 
   public MenuElement[] getSubElements() {
      return null;
   }
 
   public void menuSelectionChanged(boolean changed) {
   }
 
   public void processKeyEvent(KeyEvent kevt, MenuElement[] me, MenuSelectionManager msm) {
   }
 
   public void processMouseEvent(MouseEvent mevt, MenuElement[] me, MenuSelectionManager msm) {
   }
}

Creating a numeric-only JTextfield

Here’s the code for a Swing component that only accepts digits.

Main.java:

import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new GridLayout(2, 1));
 
      final JPasswordField passwordField = new JPasswordField(20);
      final JTextField textField = new JTextField(20);
      getContentPane().add(new NumberTextField(5));
      getContentPane().add(new NumberTextField(123, 7));
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}
 
class NumberTextField extends JTextField
{
   private NumberFormat nf;
 
   public NumberTextField(int cols) {
      super(cols);
      nf = NumberFormat.getNumberInstance();
   }
 
   public NumberTextField(int value, int cols) {
      this(cols);
      setValue(value);
   }
 
   public int getValue() {
      int n = 0;
      try {
         n = nf.parse(getText()).intValue();
      }
      catch(ParseException e) { }
      return n;
   }
 
   public void setValue(int value) {
      setText(nf.format(value));
   }
 
   protected Document createDefaultModel() {
      return new NumberDocument();
   }
 
   protected class NumberDocument extends PlainDocument {
      public void insertString(int offset, String string, AttributeSet as) 
            throws BadLocationException  {
         char [] src = string.toCharArray();
         char [] dest = new char[src.length];
         int count=0;
         for (int i=0; i < src.length; i++) {
            if (Character.isDigit(src[i])) 
               dest[count++] = src[i];
         }
         super.insertString(offset, new String(dest, 0, count), as);
      }
   }
}

Creating a multi-line text tooltip for a JLabel

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

Get started with a simple JTable

Using a simple Swing table in your GUI apps doesn’t require a lot of code. Create a one-dimensional containing the table headers and a two-dimensional array that represents the contents. Create a JTable with those two arrays and add it to the container. This is the simpliest example. All cells are editable and column widths can be adjusted.
If you want to have more control over your JTables, you can create your own TableModel, CellRenderer and CellEditor.

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);
         }
      });
 
      pack();
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

Creating a JTable with multiline cells

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



MultiLineCellExample.java:

import javax.swing.*;
import javax.swing.table.*;
import javax.swing.border.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
 
/**
 * @version 1.0 11/09/98
 */
public class MultiLineCellExample extends JFrame {
  MultiLineCellExample() {
    super( &quot;Multi-Line Cell Example&quot; );
 
    DefaultTableModel dm = new DefaultTableModel() {
      public Class getColumnClass(int columnIndex) {
        return String.class;
      }
    };
    dm.setDataVector(new Object[][]{{&quot;ana&quot;,&quot;bnb&quot;,&quot;cnc&quot;},
                                    {&quot;AnA&quot;,&quot;BnB&quot;,&quot;CnC&quot;}},
                     new Object[]{&quot;1&quot;,&quot;2&quot;,&quot;3&quot;});
 
    JTable table = new JTable( dm );
    
    int lines = 2;
    table.setRowHeight( table.getRowHeight() * lines);
    
    //
    // table.setRowHeight(0);
    //
    // I got &quot;java.lang.IllegalArgumentException: New row height less than 1&quot;
    //
    table.setDefaultRenderer(String.class, new MultiLineCellRenderer());
    JScrollPane scroll = new JScrollPane( table );
    getContentPane().add( scroll );
    setSize( 400, 130 );
    setVisible(true);
  }
 
  public static void main(String[] args) {
    MultiLineCellExample frame = new MultiLineCellExample();
    frame.addWindowListener( new WindowAdapter() {
      public void windowClosing( WindowEvent e ) {
        System.exit(0);
      }
    });
  }
}
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.border.*;
import java.awt.*;
 
/**
 * @version 1.0 11/09/98
 */
 
public class MultiLineCellRenderer extends JTextArea implements TableCellRenderer {
 
  public MultiLineCellRenderer() {
    setLineWrap(true);
    setWrapStyleWord(true);
    setOpaque(true);
  }
 
  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());
    }
    setFont(table.getFont());
    if (hasFocus) {
      setBorder( UIManager.getBorder(&quot;Table.focusCellHighlightBorder&quot;) );
      if (table.isCellEditable(row, column)) {
        setForeground( UIManager.getColor(&quot;Table.focusCellForeground&quot;) );
        setBackground( UIManager.getColor(&quot;Table.focusCellBackground&quot;) );
      }
    } else {
      setBorder(new EmptyBorder(1, 2, 1, 2));
    }
    setText((value == null) ? &quot;&quot; : value.toString());
    return this;
  }
}