Setting the decoration style of a JFrame

(JDK1.4+!)

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
class Main extends JFrame {
    public Main() {
        setUndecorated(true);
        getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Decoration example");
        setSize(400, 400);
        Object[] options = { "COLOR_CHOOSER_DIALOG",
                             "ERROR_DIALOG",
                             "FILE_CHOOSER_DIALOG", 
                             "FRAME",
                             "INFORMATION_DIALOG",
                             "NONE",
                             "PLAIN_DIALOG", 
                             "QUESTION_DIALOG",
                             "WARNING_DIALOG" };
        final JComboBox combobox = new JComboBox(options);
        combobox.setSelectedItem("FRAME");
        getContentPane().setLayout(new FlowLayout());
        getContentPane().add(combobox);
 
        combobox.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent ae) {
              String selected = (String) combobox.getSelectedItem();
              if (selected.equals("COLOR_CHOOSER_DIALOG"))
                 setDecorationStyle(JRootPane.COLOR_CHOOSER_DIALOG);
              else if (selected.equals("ERROR_DIALOG"))
                 setDecorationStyle(JRootPane.ERROR_DIALOG);
              else if (selected.equals("FILE_CHOOSER_DIALOG"))
                 setDecorationStyle(JRootPane.FILE_CHOOSER_DIALOG);
              else if (selected.equals("FRAME"))
                 setDecorationStyle(JRootPane.FRAME);
              else if (selected.equals("INFORMATION_DIALOG"))
                 setDecorationStyle(JRootPane.INFORMATION_DIALOG);
              else if (selected.equals("NONE"))
                 setDecorationStyle(JRootPane.NONE);
              else if (selected.equals("PLAIN_DIALOG"))
                 setDecorationStyle(JRootPane.PLAIN_DIALOG);
              else if (selected.equals("QUESTION_DIALOG"))
                 setDecorationStyle(JRootPane.QUESTION_DIALOG);
              else if (selected.equals("WARNING_DIALOG"))
                 setDecorationStyle(JRootPane.WARNING_DIALOG);
           }
        });
    }
 
    public void setDecorationStyle(int decorationStyle) {
       setVisible(false);
       getRootPane().setWindowDecorationStyle(decorationStyle);
       setVisible(true);
    }
 
    public static void main(String[] args) {
        new Main().setVisible(true);
    }
}

Catching an event when a JTabbedPane tab is selected

You can add a ChangeListener to your JTabbedPane component to catch the events. The first example shows you how. The event will be raised after the change has already occurred. If you want to catch the event before the change occurs, ie. to disallow a user from selecting a tab, you have to override the setSelectedIndex method. The second example shows how to prevent users from selecting tabs with odd index numbers.
First example:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame implements ActionListener {
   JTabbedPane tabbedPane;
   int ntabs = 0;
 
   public Main() {
      getContentPane().setLayout(new BorderLayout());
      tabbedPane = new JTabbedPane();
      createTab();
 
      getContentPane().add(BorderLayout.CENTER, tabbedPane);
      setJMenuBar(createMenuBar());
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      tabbedPane.addChangeListener(new ChangeListener() {
         public void stateChanged(ChangeEvent ce) {
            System.out.println("Tab " + (tabbedPane.getSelectedIndex() + 1) + " is selected");
         }
      });
  
      setTitle("JTabbedPane Orientation Demonstration");
      setSize(new Dimension(400, 400));
   }
 
   protected JMenuBar createMenuBar() {
      JMenuBar menuBar = new JMenuBar();
 
      JMenu menu = new JMenu("JTabbedPane");
      JMenuItem menuItem1 = new JMenuItem("Create new tab");
      menuItem1.addActionListener(this);
      menu.add(menuItem1);
      menuBar.add(menu);
 
      return menuBar;
   }
  
   public void actionPerformed(ActionEvent e) {
      if (e.getActionCommand().equals("Create new tab")) {
         createTab();
      }
   }
 
   protected void createTab() {
      ntabs++;
      tabbedPane.addTab("Tab #" + ntabs, new JLabel("Tab #" + ntabs));
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

Second example:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame implements ActionListener {
   JTabbedPane tabbedPane;
   int ntabs = 0;
 
   public Main() {
      getContentPane().setLayout(new BorderLayout());
      tabbedPane = new JTabbedPane() {
         public void setSelectedIndex(int index) {
            System.out.println("index selected: " + index);
            if (index % 2 == 0) {
               System.out.println("allowed");
               super.setSelectedIndex(index);
            }
            else {
               System.out.println("not allowed");
            }
         }
      };
      createTab();
 
      getContentPane().add(BorderLayout.CENTER, tabbedPane);
      setJMenuBar(createMenuBar());
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      setTitle("JTabbedPane Selection Demonstration");
      setSize(new Dimension(400, 400));
   }
 
   protected JMenuBar createMenuBar() {
      JMenuBar menuBar = new JMenuBar();
 
      JMenu menu = new JMenu("JTabbedPane");
      JMenuItem menuItem1 = new JMenuItem("Create new tab");
      menuItem1.addActionListener(this);
      menu.add(menuItem1);
      menuBar.add(menu);
 
      return menuBar;
   }
  
   public void actionPerformed(ActionEvent e) {
      if (e.getActionCommand().equals("Create new tab")) {
         createTab();
      }
   }
 
   protected void createTab() {
      tabbedPane.addTab("Tab #" + ntabs, new JLabel("Tab #" + ntabs));
      ntabs++;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

Changing the margins of a JToolBar

Set an empty border on your JToolBar object.

Main.java:

import javax.swing.border.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
  
public class Main extends JFrame {
   public Main() {
      super("JToolBar example");
 
      final JTextArea textArea = new JTextArea(5, 30);
      JToolBar toolBar = new JToolBar();
 
      JButton gifButton = new JButton(new ImageIcon("gifIcon.gif"));
      JButton jpgButton = new JButton(new ImageIcon("jpgIcon.gif"));
      JButton tiffButton = new JButton(new ImageIcon("tiffIcon.gif"));
 
      gifButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textArea.append("gifButton clicked!n");
         }
      });
 
      jpgButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textArea.append("jpgButton clicked!n");
         }
      });
        
      tiffButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textArea.append("tiffButton clicked!n");
         }
      });
 
      toolBar.add(gifButton);
      toolBar.add(jpgButton);
      toolBar.add(tiffButton);
 
      toolBar.setBorder(new EmptyBorder(new Insets(10,10,10,10)));
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(BorderLayout.NORTH, toolBar);
      getContentPane().add(BorderLayout.CENTER, new JScrollPane(textArea));
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}

images used:


Setting the top-left icon of a JInternalFrame

Use setFrameIcon():

JInternalFrame frame = new JInternalFrame("Test",false,false,false,false);

try {
  URL url = new URL("http://localhost/images/icon.gif");
  ImageIcon icon = new ImageIcon(url);
  frame.setFrameIcon(icon);
} catch (MalformedURLException me) {}

...

Creating a JCheckBoxGroup


JCheckBoxGroup.java:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
 
public class JCheckBoxGroup extends JFrame{
   private ButtonGroup checkBoxGroup;
   private JCheckBox check1, check2, check3;
   private JPanel panel;
 
   public JCheckBoxGroup() {
      super("JCheckBoxGroup Example");
      panel = new JPanel(new GridLayout(3,0));
      check1 = new JCheckBox("1", true);
      check2 = new JCheckBox("2", false);
      check3 = new JCheckBox("3", false);
      checkBoxGroup = new ButtonGroup();
 
      //add CheckBoxes to ButtonGroup
      checkBoxGroup.add(check1);
      checkBoxGroup.add(check2);
      checkBoxGroup.add(check3);
  		
      panel.add(check1);
      panel.add(check2);
      panel.add(check3);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            dispose();
            System.exit(0);
         }
      });
   
      setContentPane(panel);
      setSize(250,150);
      setVisible(true);
   }
 
   public static void main(String args[]) {
      JCheckBoxGroup j = new JCheckBoxGroup();
   }
}

Putting a JButton inside a JComboBox

Here’s an example:

import javax.swing.plaf.basic.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
    
public class Main extends JFrame
{ 
   public Main() {
      getContentPane().setLayout(new FlowLayout());
      
      final JButton buttonOk = new JButton("OK");
      buttonOk.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println(ae.getActionCommand() + " clicked!");
         }
      });
      final JButton buttonCancel = new JButton("Cancel");
      buttonCancel.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println(ae.getActionCommand() + " clicked!");
         }
      });
 
      final JComboBox combobox = 
         new JComboBox(new Object[] {
               "Item 1",
               "Item 2",
               "Item 3",
               buttonOk,
               "Item 4",
               "Item 5",
               buttonCancel
            }
         );
 
      getContentPane().add(combobox);
      combobox.setRenderer(new ButtonComboBoxRenderer());
      combobox.addActionListener(new ButtonComboBoxListener(this, combobox));
  
      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);
   }
}
 
class ButtonComboBoxRenderer extends BasicComboBoxRenderer implements ListCellRenderer
{
   public ButtonComboBoxRenderer() {
      super();
   }
   
   public Component getListCellRendererComponent( JList list, 
           Object value, int index, boolean isSelected, boolean cellHasFocus) {
      if (isSelected) {
          setBackground(list.getSelectionBackground());
          setForeground(list.getSelectionForeground());
      }
      else {
          setBackground(list.getBackground());
          setForeground(list.getForeground());
      }
 
      setFont(list.getFont());
      if (value instanceof Icon) {
         setIcon((Icon)value);
      }
      if (value instanceof JButton) {
         return (Component) value;
      }
      else {
         setText((value == null) ? "" : value.toString());
      }
 
      return this;
  }  
}
 
class ButtonComboBoxListener implements ActionListener {
   JComboBox combobox;
   JFrame frame;
 
   ButtonComboBoxListener(JFrame frame, JComboBox combobox) {
      this.frame = frame;
      this.combobox = combobox;
      combobox.setSelectedIndex(0);
   }
     
   public void actionPerformed(ActionEvent e) {
      Object selectedItem = combobox.getSelectedItem();
      if (selectedItem instanceof JButton) {
         ((JButton) selectedItem).doClick();
      }
   }
}

Showing a tooltip on a individual items of JList

Override the JList method getToolTipText, determine the particular JList item the mouse is pointed on and show the appropriate text. Here’s an 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) {
         public String getToolTipText(MouseEvent me) {
            int index = locationToIndex(me.getPoint());
            if (index > -1) {
               String item = (String) getModel().getElementAt(index);
               return "Tooltip for " + item;
            }
            return null;
         }
      };
 
      // necessary to activate tooltips for this JList!
      list.setToolTipText("");
 
      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 different tooltip for every element in my JMenuItem

Set the tooltip text for every JMenuItem.

Main.java:

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

Putting a JSlider on a null layout manager

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

Here’s an example:

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

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