Changing the border of a JToolBar

ToolBarTest.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class ToolBarTest extends JFrame implements ActionListener
{
   JToolBar myToolBar = null;
 
   public ToolBarTest ()
   {
      /**
       * create the Toolbar
       */
      myToolBar = new JToolBar( JToolBar.HORIZONTAL );
      myToolBar.setFloatable( false );
 
      /**
       * first Toolbar-Button
       */
      JButton button1 = new JButton( "BevelBorder" );
      button1.addActionListener( this );
      myToolBar.add( button1 );
 
      /**
       * second Toolbar-Button
       */
      JButton button2 = new JButton( "LineBorder"  );
      button2.addActionListener( this );
      myToolBar.add( button2 );
 
      /**
       * third Toolbar-Button
       */
      JButton button3 = new JButton( "No Border"   );
      button3.addActionListener( this );
      myToolBar.add( button3 );
 
      /**
       * set BorderLayout for the contentPane and add the toolbar
       */
      getContentPane().setLayout( new BorderLayout() );
      getContentPane().add( myToolBar, BorderLayout.NORTH );
      pack();
   }
 
   public static void main ( String args[] )
   {
      /**
       * create the ToolBarTest-frame
       */
      ToolBarTest frame = new ToolBarTest();
 
      frame.addWindowListener(new WindowAdapter() {
         public void windowClosing (WindowEvent e) {
            System.exit( 0 );
         }
      });
 
      /**
       * display the frame
       */
      frame.pack();
      frame.setVisible( true );
   }
 
   public void actionPerformed ( ActionEvent e )
   {
      /**
       * set the specified Border with BorderFactory...
       */
 	 
      if ( e.getActionCommand().equals( "BevelBorder" ) )
      {
         myToolBar.setBorder( BorderFactory.createRaisedBevelBorder() );
      }
      else if ( e.getActionCommand().equals( "LineBorder" ) )
      {
         myToolBar.setBorder( BorderFactory.createLineBorder( Color.black, 2 ) );
      }
      else if ( e.getActionCommand().equals( "No Border" ) )
      {
         myToolBar.setBorder( BorderFactory.createEmptyBorder() );
      }
   }
}

Creating a JInternalFrame without a title bar

Try this:

   javax.swing.plaf.InternalFrameUI ui = frame.getUI();
   ((javax.swing.plaf.basic.BasicInternalFrameUI)ui).setNorthPane(null);

Main.java:

import java.awt.image.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
import java.awt.*;
import java.net.*;

public class Main extends JFrame
{
   JDesktopPane desktop;
 
   public Main() {
      desktop = new JDesktopPane(); 
      setContentPane(desktop);
      setBackgroundImage();
 
      // create internal frame with title bar
      createInternalFrame(true);
 
      // create internal frame without title bar
      createInternalFrame(false);
 
      setSize(new Dimension(500, 300));
      setLocation(100, 100);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0); 
         }
      });
   }
 
   protected void setBackgroundImage() {
      try {
         ImageIcon icon = new ImageIcon(new URL("http://www.esus.com/images/mong.jpg"));
         JLabel label = new JLabel(icon);
         label.setBounds(0, 0, icon.getIconWidth(), icon.getIconHeight());
  
         desktop.add(label, new Integer(Integer.MIN_VALUE));
      } catch(MalformedURLException e) {
         System.out.println(e);
      }
   }
  
   protected void createInternalFrame(boolean titlebar) {
 
      JInternalFrame frame = new JInternalFrame("InternalFrame", 
         true,    // resizable
         true,    // closable
         true,    // maximizable
         true);   // iconifiable
      if (!titlebar) {
         javax.swing.plaf.InternalFrameUI ui = frame.getUI();
            ((javax.swing.plaf.basic.BasicInternalFrameUI)ui).setNorthPane(null);
      }
 
      frame.setVisible(true); 
      desktop.add(frame);
      frame.setSize(200, 200);
      try {
         frame.setSelected(true);
      } catch (java.beans.PropertyVetoException e) {}
   }
 
   public static void main(String []args) throws Exception {
      Main main = new Main();
      main.show();      
   }
}

Detecting a state change on my JCheckBox

Add an ItemListener and put your behavior in itemStateChanged.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      final JCheckBox cb = new JCheckBox("Sample jcheckbox");
      cb.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            System.out.println("Checkbox state is now " + cb.isSelected());
         }
      });
 
      getContentPane().add(BorderLayout.NORTH, cb);
   } 
  
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(300, 100);
      main.setVisible(true);
   }
}

Detecting a selection change on a JComboBox

Use an ActionListener.

Main.java:

import java.awt.image.*;
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(1);
         }
      }); 
 
      Vector v = new Vector();
      v.add("first element");
      v.add("second element");
      v.add("third element");
      v.add("fourth element");
      v.add("fifth element");
 
      final JComboBox cb = new JComboBox(v);
      cb.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println(cb.getSelectedItem());
         }
      });
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
      getContentPane().add(new JLabel("Select element:"));
      getContentPane().add(cb);
   } 
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
      main.setSize(300, 150);
   }
}

Creating a sorted JList

This example shows you a method sortList that gets the JList data, puts them in an array, sorts them using Arrays.sort and updates the list model:

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 BorderLayout());
 
      final DefaultListModel listModel = new DefaultListModel();   
 
      // populate listmodel
      Random r = new Random();
      for (int i=0; i<50; i++) {
         listModel.addElement("list item # " + (Math.abs(r.nextInt()) % 100));
      }
 
      final JList list = new JList(listModel); 
 
      getContentPane().add(BorderLayout.CENTER, new JScrollPane(list));    
      JButton sortButton = new JButton("Sort");
      sortButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            sortList(list);
         }
      });
      getContentPane().add(BorderLayout.SOUTH, sortButton);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public void sortList(JList list) {
      ListModel model = list.getModel();
 
      int n = model.getSize();
      String[] data = new String[n]; 
 
      for (int i=0; i<n; i++) { 
         data[i] = (String) model.getElementAt(i); 
      }
 
      Arrays.sort(data); 
 
      list.setListData(data); 
   }
   
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Creating a JMenuItem with an image

Two constructors of JMenuItem take an Icon as parameters. Try the following example with these animated! GIFs:

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", new ImageIcon("male.gif"));
      JMenuItem menuItem2 = new JMenuItem("female", new ImageIcon("female.gif"));
      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();
   }
}

Using an image for the slider knob in a JSlider


You could override the default JSlider Icons that are used using UIManager.put. Just because this is what happens inside the Slider UI classes:
    Icon horizThumbIcon = UIManager.getIcon( "Slider.horizontalThumbIcon" );
    Icon vertThumbIcon = UIManager.getIcon( "Slider.verticalThumbIcon" );

This would make the image that is used as the thumb the same for all JSliders you make.

Another way is to create your own UI (and hence breaking LAF capabilities). In the following example, I override the two methods paintThumb and getThumbSize.

Main.java:

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(new FlowLayout());
  
      final JSlider hslider = new JSlider(JSlider.HORIZONTAL, 0, 30, 15);
      final JSlider vslider = new JSlider(JSlider.VERTICAL, 0, 30, 15);
      // draw the major tick marks (one for every tick label)
      hslider.setMajorTickSpacing(10);
      vslider.setMajorTickSpacing(10);
      // draw the minor tick marks (between the tick labels)
      hslider.setMinorTickSpacing(1);
      vslider.setMinorTickSpacing(1);
      // draw the tick marks
      hslider.setPaintTicks(true);
      vslider.setPaintTicks(true);
      // draw the tick mark labels
      hslider.setPaintLabels(true);
      vslider.setPaintLabels(true);
  
      getContentPane().add(hslider);
      getContentPane().add(vslider);
   
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
  
      Icon maleIcon   = new ImageIcon("male.gif");
      Icon femaleIcon = new ImageIcon("female.gif");
 
      hslider.setUI(new IconThumbSliderUI(maleIcon, femaleIcon));
      vslider.setUI(new IconThumbSliderUI(maleIcon, femaleIcon));
      pack();
   }
  
   public static void main(String[] args) {
      (new Main()).show();
   }
}
  
class IconThumbSliderUI extends MetalSliderUI {
    protected Icon hThumbIcon = null;
    protected Icon vThumbIcon = null;
  
    public IconThumbSliderUI(Icon hThumbIcon, Icon vThumbIcon) {
        setHorizontalThumbIcon(hThumbIcon);
        setVerticalThumbIcon(vThumbIcon);
    }
  
    public void setHorizontalThumbIcon(Icon hThumbIcon) {
       if (hThumbIcon == null) this.hThumbIcon = horizThumbIcon;
       else                    this.hThumbIcon = hThumbIcon;
    }
 
    public void setVerticalThumbIcon(Icon vThumbIcon) {
       if (vThumbIcon == null) this.vThumbIcon = vertThumbIcon;
       else                    this.vThumbIcon = vThumbIcon;
 
    }
 
    public void paintThumb(Graphics g)  {
        Rectangle knobBounds = thumbRect;
 
        g.translate( knobBounds.x, knobBounds.y );
 
        if ( slider.getOrientation() == JSlider.HORIZONTAL ) {
            hThumbIcon.paintIcon( slider, g, 0, 0 );
        }
        else {
            vThumbIcon.paintIcon( slider, g, 0, 0 );
        }
  
        g.translate( -knobBounds.x, -knobBounds.y );
    }
 
    protected Dimension getThumbSize() {
        Dimension size = new Dimension();
 
        if ( slider.getOrientation() == JSlider.VERTICAL ) {
	    size.width = vThumbIcon.getIconWidth();
	    size.height = vThumbIcon.getIconHeight();
	}
	else {
	    size.width = hThumbIcon.getIconWidth();
	    size.height = hThumbIcon.getIconHeight();
	}
 
	return size;
    }
}

Images used in this example:

Enabling a component depending on the text entered in a JTextField

Add a document listener to the JTextField and listen to the characters that are inserted and removed.

Main.java:

import javax.swing.event.*;
import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame implements DocumentListener
{
   private JTextField tf; 
   private JButton button;
 
   public Main() {           
      getContentPane().setLayout(new BorderLayout());
      JPanel northPanel = new JPanel(new GridLayout(1, 2));
      northPanel.add(new JLabel("Enter an integer: "));
      tf = new JTextField();
      northPanel.add(tf);
      getContentPane().add(BorderLayout.NORTH, northPanel);
      button = new JButton("OK"); 
      getContentPane().add(BorderLayout.SOUTH, button);
      // Add a document listener to the textfield
      Document document = tf.getDocument();
      document.addDocumentListener(this);
 
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.exit(1);
         }
      });
      button.setEnabled(false);
 
      pack();
   }
 
   public void insertUpdate(DocumentEvent evt) {
      String s = tf.getText();
 
      try {
         int v = Integer.parseInt(s);
         button.setEnabled(true);
      }
      catch(NumberFormatException e) {
         button.setEnabled(false);
      }
   }
 
   public void removeUpdate(DocumentEvent evt) {
      if (tf.getText().length() == 0) {
         button.setEnabled(false);
      }
      else {
         insertUpdate(evt);
      }
   }
 
   public void changedUpdate(DocumentEvent evt) {
   }
 
   public static void main(String args[]) {
      Main main = new Main();
      main.setVisible(true);
   }
}

Change the color of a JToolTip

To change the color of a tooltip, create a JToolTip instance and use the methods setForeground and setBackground to change its appearance. Then override the method createToolTip on the component where this tooltip applies to and return your own JToolTip instance.

(btw. to change the colors of all your tooltips, use the class UIManager and change the keys ToolTip.background and ToolTip.foreground.)

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame {
   public Main() {
      super("JToolTip Delay Demonstration");
 
      getContentPane().setLayout(new FlowLayout()); 
   
      final JToolTip tooltip = new JToolTip();
      tooltip.setBackground(Color.red);
      tooltip.setForeground(Color.yellow);
 
      JLabel label = new JLabel("How was I?") {
         public JToolTip createToolTip() {
            return tooltip;
         }
      };
 
      label.setToolTipText("too commercial");
    
      getContentPane().add(label);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
 
      setSize(400, 300);
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.setVisible(true);
   }
}