Putting a Image on a JButton

Check out the API! You’ll see that there is a constructor taking an Icon object as parameter. Here’s an example showing two buttons with the following animated gifs on 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 FlowLayout());
 
      JButton mbutton = new JButton("female", new ImageIcon("male.gif"));
      JButton fbutton = new JButton("male", new ImageIcon("female.gif"));
      mbutton.addActionListener(this);
      fbutton.addActionListener(this);
      getContentPane().add(mbutton);
      getContentPane().add(fbutton);
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public void actionPerformed(ActionEvent ae) {
      System.out.println("Your pressed the " + ae.getActionCommand() + " button");
   }
   
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Changing the color of the check of my JCheckBox

This is all tied into the particular L and F implementation of the JCheckBox. The check color is always black (or gray, if disabled). If your background happens to be black, you can’t see the check. This is a bug (http://developer.java.sun.com/developer/bugParade/bugs/4449413.html) in progress.

This example shows you a bit of a workaround by implementing another version of CheckBoxIcon, the UI class used to paint the rectangle and the checkmark. I defined a couple new properties: MyCheckBox.checkBackground, MyCheckBox.checkClickBackground, MyCheckBox.checkForeground, MyCheckBox.checkDisabled. They all take a Color object.

Main.java:

import javax.swing.plaf.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.io.*; 
  
public class Main extends JFrame
{
   public Main() throws Exception {
      UIManager.put("CheckBox.icon", new MyCheckBoxIcon());
 
      UIManager.put("MyCheckBox.checkBackground", Color.orange); 
      UIManager.put("MyCheckBox.checkClickBackground", Color.orange); 
      UIManager.put("MyCheckBox.checkForeground", Color.red); 
      UIManager.put("MyCheckBox.checkDisabled", Color.gray); 
 
      JCheckBox cbox = new JCheckBox("This checkbox has a colored check");

      getContentPane().setLayout(null); 
      getContentPane().add(cbox);
      cbox.setBounds(10, 20, 250, 30);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String args[]) throws Exception {
      Main main = new Main();
      main.setSize(300, 100);
      main.setVisible(true);
   }
}
  
class MyCheckBoxIcon implements Icon, UIResource, Serializable {
   protected int getControlSize() { return 13; }
 
   public void paintIcon(Component c, Graphics g, int x, int y) {
      JCheckBox cb = (JCheckBox)c;
      ButtonModel model = cb.getModel();
      int controlSize = getControlSize();
 
      boolean drawCheck = model.isSelected();
 
      if (model.isEnabled()) {
         if (model.isPressed() && model.isArmed()) {
            g.setColor(UIManager.getColor("MyCheckBox.checkClickBackground"));
	    g.fillRect( x, y, controlSize-1, controlSize-1);
         } else {
            g.setColor(UIManager.getColor("MyCheckBox.checkBackground"));
            g.fillRect( x, y, controlSize-1, controlSize-1);
         }
 
         g.setColor(UIManager.getColor("MyCheckBox.checkForeground"));
 
      } else {
         g.setColor(UIManager.getColor("MyCheckBox.checkDisabled"));
         g.drawRect( x, y, controlSize-1, controlSize-1);
      }
 
      if (model.isSelected()) {
         drawCheck(c, g, x, y);
      }
   }
 
   protected void drawCheck(Component c, Graphics g, int x, int y) {
      int controlSize = getControlSize();
      g.fillRect( x+3, y+5, 2, controlSize-8 );
      g.drawLine( x+(controlSize-4), y+3, x+5, y+(controlSize-6) );
      g.drawLine( x+(controlSize-4), y+4, x+5, y+(controlSize-5) );
   }
 
   public int getIconWidth() {
      return getControlSize();
   }
       
   public int getIconHeight() {
      return getControlSize();
   }
 }

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

Detecting that the mouse enters my JTextField component

Implement a mouseListener and override the methods mouseEntered and mouseExited.
Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() {
      getContentPane().setLayout(new FlowLayout());
      JTextField textfield = new JTextField(20);
      getContentPane().add(textfield);
      final JLabel label = new JLabel();
      getContentPane().add(label);
 
      textfield.addMouseListener(new MouseAdapter() {
         public void mouseEntered(MouseEvent me) {
            label.setText("Mouse is inside JTextField!");
         }
         public void mouseExited(MouseEvent me) {
            label.setText("");
         }
      });
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String [] args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   } 
} 

Adding a border around a JLabel

Use the method setBorder.

Main.java:

import javax.swing.border.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JLabel label = new JLabel("This label should have a thick red border");
      getContentPane().add(label);     
      label.setBorder(new LineBorder(Color.red, 3)); 
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Changing the time for the JToolTip to appear

Use the Swing class ToolTipManager to change the default settings as shown in following example:

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()); 
 
      JLabel label = new JLabel("How was I?");
      label.setToolTipText("too commercial");
 
      ToolTipManager toolTipManager = ToolTipManager.sharedInstance(); 
 
      // time to wait before showing tooltip when mouse enters component
      toolTipManager.setInitialDelay(20);
 
      // time to wait before dismissing tooltip (but overridden if
      // mouse moves outside of components bounds)
      toolTipManager.setDismissDelay(1000);
 
      // time to wait before showing tooltip when mouse re-enters component
      toolTipManager.setReshowDelay(10000); 
   
      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);
   }
}

Setting the JFileChooser home directory to my current directory

Set the JFileChooser’s current directory to System.getProperty(“user.dir”) with
the method setCurrentDirectory as shown in following example. (If you set the
current directory to null, JFileChooser will use System.getProperty(“user.home”)
(the system directory, eg. C:Windows).

Main.java:

import javax.swing.filechooser.*;
import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
 
public class Main extends JFrame {
   public Main() {
      super("JFileChooser Demonstration");
 
      getContentPane().setLayout(new FlowLayout()); 
      JButton button = new JButton("Show JFileChooser");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            JFileChooser fc = new JFileChooser();
            fc.setCurrentDirectory(new File(System.getProperty("user.dir")));
            int r = fc.showOpenDialog(Main.this); 
  
            System.out.println("Selected: " + fc.getSelectedFile());
         }
      });
 
      getContentPane().add(button); 
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.pack();
      main.setVisible(true);
   }
}

Deleting all rows from a JTable

Here’s what I do:

In your JTable class, add this method:

public synchronized void clearTable()
{
   TableModel model = this.getModel(); 
   int numrows = model.getRowCount(); 
   for(int i = numrows - 1; i >=0; i--)
   {
	model.removeRow(i); 
   }
}