Setting the JSplitPane divider location

Use the method setDividerLocation to set the divider. You can either set the new position by pixel or specify a percentage:

   // sets the divider at pixel 100
   splitPane.setDividerLocation(100);
   // sets the divider in the middle
   splitPane.setDividerLocation(.5);

The JSplitPane MUST be visible invoking this method
otherwise it will not have the desired effect. Here’s an example on how to set the divider location the moment when the JFrame becomes visible:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   JSplitPane splitPane;
  
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, 
                                 new JPanel(), new JPanel());
 
      createMainMenuBar();
 
      getContentPane().add(splitPane);
 
      addComponentListener(new ComponentAdapter() {
         public void componentShown(ComponentEvent event) {
            splitPane.setDividerLocation(0.5); 
                
            removeComponentListener(this);
         }
      });
   }
 
   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);
   }
}

Number of rows the JTabbedPane is using to display its tabs

According to the javax.swing.JTabbedPane.getTabRunCount() API documentation:

Returns the number of tab runs currently used to display the tabs.

Returns:

an integer giving the number of rows if the tabPlacement is TOP or BOTTOM and the number of columns if tabPlacement is LEFT or RIGHT, or 0 if there is no UI set on this tabbedpane

This is basically a convenience method for javax.swing.plaf.TabbedPaneUI.getTabRunCount(), which has no API documentation.

The code for TabRunTest takes the following command line params:

  1. TOP (default) | BOTTOM (1) | LEFT (2) | RIGHT (3)

  • creates the specified number of tabs or 10 (if not specified or negative).

    There is a Get Info button at the bottom of the window to display the tab count and tab run count

    TabRowTest.java:

    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
     
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTabbedPane;
     
    /**
     *@author     Administrator
     *@created    February 4, 2002
     */
    public class TabRowTest extends JPanel {
     
       public static void main(String[] args) {
          JFrame frame = new JFrame("Multiple Colors...");
     
          java.awt.Container contentPane = frame.getContentPane();
          contentPane.setLayout(new BorderLayout());
     
          int tabPlacement = JTabbedPane.TOP;
          if (args.length > 0) {
             try {
                int temp = Integer.parseInt(args[0]);
                switch (temp) {
                   case 1:
                      tabPlacement = JTabbedPane.BOTTOM;
                      break;
                   case 2:
                      tabPlacement = JTabbedPane.LEFT;
                      break;
                   case 3:
                      tabPlacement = JTabbedPane.RIGHT;
                      break;
                }
             } catch (Exception ex) {
                ex.printStackTrace();
                System.out.println();
                System.out.println("------------------CONTINUING--------------------");
                System.out.println();
             }
          }
     
          int numberOfTabs = 10;
          if (args.length > 1) {
             try {
                numberOfTabs = Integer.parseInt(args[1]);
                if (numberOfTabs < 0) {
                   numberOfTabs = 10;
                }
             } catch (Exception ex) {
                ex.printStackTrace();
                System.out.println();
                System.out.println("------------------CONTINUING--------------------");
                System.out.println();
             }
          }
     
          contentPane.add(new TabRowTest(tabPlacement, numberOfTabs));
     
          frame.setSize(800, 600);
     
          frame.addWindowListener(
             new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent ev) {
                   System.exit(0);
                }
             });
     
          frame.show();
       }
       // main
     
       public TabRowTest(int tabPlacement, int numberOfTabs) {
          super(new BorderLayout());
     
          final JTabbedPane tabbedPane = new JTabbedPane(tabPlacement);
          add(tabbedPane, BorderLayout.CENTER);
     
          for (int idx = 1; idx < (numberOfTabs + 1); idx++) {
             tabbedPane.addTab("Tab #" + idx, new JLabel("Tab #" + idx + " stuff"));
          }
     
          JPanel infopanel = new JPanel(new GridLayout(1, 0));
          add(infopanel, BorderLayout.SOUTH);
     
          final JLabel tabCountLabel = new JLabel("<tab count>");
          final JLabel runCountLabel = new JLabel("<run count>");
     
          JButton button = new JButton("Get Info");
          infopanel.add(button);
          infopanel.add(new JLabel("# Tabs:"));
          infopanel.add(tabCountLabel);
          infopanel.add(new JLabel("Run Count:"));
          infopanel.add(runCountLabel);
     
          button.addActionListener(
             new ActionListener() {
                public void actionPerformed(ActionEvent ev) {
                   int tabCount = tabbedPane.getTabCount();
                   int runCount = tabbedPane.getTabRunCount();
                   tabCountLabel.setText("" + tabCount);
                   runCountLabel.setText("" + runCount);
                }
             });
       }
       // TabRowTest
    }
    

  • Creating a scrollable JInternalFrame

    Main.java:

    import javax.swing.border.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    import java.net.*;
     
    public class Main extends JFrame {
       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("Transparent JInternalFrame Demonstration");
          setSize(new Dimension(400, 400));
       }
     
       protected JMenuBar createMenuBar() {
          JMenuBar menuBar = new JMenuBar();
     
          JMenu menu = new JMenu("JDesktopPane");
          JMenuItem menuItem1 = new JMenuItem("Create new JInternalFrame");
          menuItem1.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent ae) {
                createInternalFrame();
             }
          });
          menu.add(menuItem1);
          menuBar.add(menu);
     
          return menuBar;
       }
     
       protected void createInternalFrame() {
          JInternalFrame frame = new JInternalFrame("InternalFrame", 
             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++;
          frame.setContentPane(new JScrollPane(new MyPanel(new ImageIcon("mong.jpg"))));
     
          try {
             frame.setSelected(true);
          } catch (java.beans.PropertyVetoException e) {}
       }
     
       public static void main(String []args) {
          Main main = new Main();
          main.show();
       }
    }
     
    class MyPanel extends JPanel
    {
       private ImageIcon bgImage;
     
       public MyPanel(ImageIcon bgImage) {
          setLayout(new GridLayout(20, 1));
          setBorder(new EmptyBorder(10, 10, 10, 10));
          for (int i=0; i<10; i++) {    
             add(new JLabel("JLabel #" + i));
             add(new JTextField(10));
          }
     
          this.bgImage = bgImage;
       }
     
       public void paintComponent(Graphics g) {    
          Dimension d = getSize();      
          g.drawImage(bgImage.getImage(), 0, 0, (int)d.getWidth(), (int)d.getHeight() , this);          
       }
    }
    

    Changing the mouse pointer to a hand cursor when the mouse moves over a JButton

    Main.java:

    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
     
    public class Main extends JFrame
    {
       private Cursor handCursor = new Cursor(Cursor.HAND_CURSOR);
       private Cursor defaultCursor = new Cursor(Cursor.DEFAULT_CURSOR);
     
       public static void main(String []args) {
          Main main = new Main();
          main.show();
       }
     
       public Main() {
          JButton button = new JButton("Move mouse over this button!");
          button.addMouseListener(new MouseAdapter() {
             public void mouseEntered(MouseEvent me) {
                setCursor(handCursor);
             }
             public void mouseExited(MouseEvent me) {
                setCursor(defaultCursor);
             }
          });
      
          getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER));
          getContentPane().add(button);
     
          addWindowListener(new WindowAdapter() {
             public void windowClosing(WindowEvent e) {
                System.exit(0);
             }
          });
     
          setSize(300, 100);
       }  
    }
    

    Getting the selected item(s) from a JList

    There are several functions to determine the selected value(s) of a JList:

    • getSelectedIndex() returns the first selected index
    • getSelectedIndices() returns all of the selected indices
    • getSelectedValue() returns the first selected value
    • getSelectedValues() returns all of the selected values

    Here’s an example:

    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<20; i++) {
             v.addElement("Item #" + i);
          }
     
          final JList list = new JList(v);
          getContentPane().add(new JScrollPane(list));
          JButton button = new JButton("Show selected items");
          getContentPane().add(button);
          button.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent ae) { 
                System.out.println("Selected values:");
                Object[] oarr = list.getSelectedValues();
                for (int i=0; i<oarr.length; i++) {
                   System.out.println(oarr[i]);
                }
     
                System.out.println("Selected indices:");
                int[] iarr = list.getSelectedIndices();
                for (int i=0; i<iarr.length; i++) {
                   System.out.println(iarr[i]);
                }
             }
          });
     
          addWindowListener(new WindowAdapter() {
             public void windowClosing(WindowEvent event) {
                System.exit(0);   
             }      
          });
     
          setSize(200, 250);
       }
       
       public static void main(String[] args) {
          (new Main()).show();
       }
    }
    

    Allowing multiple selections in a JList

    A JList has three different selection modes:

    1) SINGLE_SELECTION: allows only one item to be selected at a time

    2) SINGLE_INTERVAL_SELECTION: allows contiguous items to be selected at a time

    3) MULTIPLE_INTERVAL_SELECTION: (default) allows any combination of items to be selected at a time

    Following example shows you how to apply them
    Main.java:

    import javax.swing.event.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.awt.*;
      
    public class Main extends JFrame implements ActionListener {
       JList list; 
     
       public Main() {
          getContentPane().setLayout(new BorderLayout());
     
          final DefaultListModel listModel = new DefaultListModel();   
     
          // populate listmodel
          for (int i=0; i<10; i++) {
             listModel.addElement("list item #" + i);
          }
     
          list = new JList(listModel); 
          getContentPane().add(BorderLayout.CENTER, new JScrollPane(list));    
     
          JPanel panel = new JPanel(new GridLayout(3, 1));
          JRadioButton rb1 = new JRadioButton("SINGLE_SELECTION");
          rb1.addActionListener(this);
          JRadioButton rb2 = new JRadioButton("SINGLE_INTERVAL_SELECTION");
          rb2.addActionListener(this);
          JRadioButton rb3 = new JRadioButton("MULTIPLE_INTERVAL_SELECTION");
          rb3.addActionListener(this);
          ButtonGroup bg = new ButtonGroup();
          bg.add(rb1);
          bg.add(rb2);
          bg.add(rb3);
          panel.add(rb1);
          panel.add(rb2);
          panel.add(rb3);
          getContentPane().add(BorderLayout.EAST, panel);
      
          addWindowListener(new WindowAdapter() {
             public void windowClosing(WindowEvent event) {
                System.exit(0);   
             }      
          });
     
          pack();
       }
     
       public void actionPerformed(ActionEvent ae) {
          if (ae.getActionCommand().equals("SINGLE_SELECTION"))
             list.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
          else if (ae.getActionCommand().equals("SINGLE_INTERVAL_SELECTION"))
             list.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
          else if (ae.getActionCommand().equals("MULTIPLE_INTERVAL_SELECTION"))
             list.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
       }
       
       public static void main(String[] args) {
          (new Main()).show();
       }
    }
    

    Detecting a value change of my JSlider

    Add a ChangeListener and add behavior to its method stateChanged.

    Main.java:

    import javax.swing.event.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
      
    public class Main extends JFrame { 
       JSlider slider;
     
       public Main() {
          addWindowListener(new WindowAdapter() {
             public void windowClosing(WindowEvent we) {
                System.exit(1);
             }
          });   
     
          slider = new JSlider(JSlider.HORIZONTAL, 0, 20, 1);
          slider.addChangeListener(new ChangeListener() {
             public void stateChanged(ChangeEvent ce) {
                repaint();
             }
          });
     
          slider.setMajorTickSpacing(1);
          slider.setPaintTicks(true);
          slider.setPaintLabels(true);
     
          getContentPane().setLayout(new BorderLayout());
          getContentPane().add(BorderLayout.NORTH, slider);
       } 
     
       public void paint(Graphics g) {
          super.paint(g);
      
          Graphics2D g2d = (Graphics2D) g;
     
          g2d.setFont(new Font("Serif", Font.BOLD, 36));
          g2d.drawString(""+slider.getValue(), 200, 130);
       }
     
       public static void main(String []args) {
          Main main = new Main();
          main.setSize(400, 150);
          main.setVisible(true);
       }
    }

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