Programmatically iconify a JInternalFrame

Use the following line of code:

   frame.getDesktopPane().getDesktopManager().iconifyFrame(frame);

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;
   Hashtable frames = new Hashtable();
 
   JMenu internalFrameMenu;
   Action iconifyAction = new IconifyAction();

   public Main() {
      desktop = new JDesktopPane(); 
      setContentPane(desktop);
      setJMenuBar(createMenuBar());
      createInternalFrame(); 
   }
 
   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);
 
      internalFrameMenu = new JMenu("Iconify");
      internalFrameMenu.setMnemonic(KeyEvent.VK_I);
  
      menuBar.add(internalFrameMenu);     
 
      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); 
      desktop.add(frame);
      frame.setSize(200, 200);
      frame.setLocation(30*nframes, 30*nframes);
      try {
         frame.setSelected(true);
      } catch (java.beans.PropertyVetoException e) {}
 
      JMenuItem menuItem = new JMenuItem(title);
      internalFrameMenu.add(menuItem);
      menuItem.addActionListener(iconifyAction);
      frames.put(title, frame);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(500, 300);
      main.setVisible(true);
   }
 
   public class IconifyAction extends AbstractAction
   {
      public IconifyAction() {
         super("Iconify Action");
      }
 
      public void actionPerformed(ActionEvent ae) {
         JInternalFrame frame = (JInternalFrame) frames.get(((JMenuItem) ae.getSource()).getText());
         frame.getDesktopPane().getDesktopManager().iconifyFrame(frame);
      }
   }
}

Handling a JButton event

Register a class that implements the ActionListener interface to your JButton and handle the event in the method actionPerformed. If you register the same ActionListener class to a number of JButtons, you can distinguish what JButton was clicked by querying the component source (getSource) or by querying the actionCommand (getActionCommand). Here’s an example:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   JTextField textfield;
   JButton button;
   JLabel label;
 
   public Main() {
      button = new JButton("Greet me!");
 
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
 
            if (ae.getSource() == button)
               label.setText("Hello " + textfield.getText());
 
            /*  OR:
            if (ae.getActionCommand().equals("Greet me!"))
               label.setText("Hello " + textfield.getText());
            */
         }
      });
 
      JPanel panel = new JPanel(new GridLayout(1, 2));
      textfield = new JTextField(20);
      panel.add(textfield);
      panel.add(button);
      getContentPane().add(BorderLayout.NORTH, panel);
      label = new JLabel();
      getContentPane().add(BorderLayout.CENTER, label);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      setSize(300, 100);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
   }
}

The previous example creates a no-name class of the interface ActionListener and directly adds the implementation of all its defined methods (actionPerformed). Note that you do not have to test for what JButton was pressed as you add the no-name ActionListener class only to this JButton.
Another option is to provide an object of a class that implements the ActionListener interface. However, in this case you would have to test for what button was clicked, that is if you have more than one button.

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame implements ActionListener
{
   JTextField textfield;
   JButton button;
   JLabel label;
 
   public Main() {
      button = new JButton("Greet me!");
 
      button.addActionListener(this);
 
      JPanel panel = new JPanel(new GridLayout(1, 2));
      textfield = new JTextField(20);
      panel.add(textfield);
      panel.add(button);
      getContentPane().add(BorderLayout.NORTH, panel);
      label = new JLabel();
      getContentPane().add(BorderLayout.CENTER, label);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      setSize(300, 100);
   }
 
   public void actionPerformed(ActionEvent ae) {
      if (ae.getSource() == button)
         label.setText("Hello " + textfield.getText());
   }
  
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
   }
}

Changing the orientation of a JSlider

You can either specify the orientation when you create your JSlider object or afterwards with the method setOrientation.

Main.java:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame implements ActionListener {
   private JSlider slider;
 
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JMenuBar menuBar = new JMenuBar();
      JMenu menu = new JMenu("JSlider Orientation");
      JMenuItem menuItem1 = new JMenuItem("HORIZONTAL");
      JMenuItem menuItem2 = new JMenuItem("VERTICAL");
      menu.add(menuItem1);
      menu.add(menuItem2);
      menuItem1.addActionListener(this);
      menuItem2.addActionListener(this);
      menuBar.add(menu); 
      setJMenuBar(menuBar);
      
      slider = new JSlider(JSlider.HORIZONTAL, 0, 30, 15);
 
      getContentPane().add(slider);

      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(400, 400);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
 
   public void actionPerformed(ActionEvent ae) {
      if (ae.getActionCommand().equals("HORIZONTAL"))
         slider.setOrientation(JSlider.HORIZONTAL);
      else if (ae.getActionCommand().equals("VERTICAL"))
         slider.setOrientation(JSlider.VERTICAL);
   }
}

Adding a background image to my JTextField

How do I add a background image to my JTextField?

Make sure the opaqueness property of your JTextField component is false. You can then override the paintComponent method that draws the background image and calls super.paintComponent. Here’s an example:

import javax.swing.*;
import java.awt.*;
 
public class Main {
   public static void main(String args[]) {
      JFrame frame = new JFrame("JTextField Background Demonstration");
      final ImageIcon imageIcon = new ImageIcon("bluebg.jpg");
 
      JTextField textField = new JTextField() {
         Image image = imageIcon.getImage();
         { 
            setOpaque(false);
         }
         public void paintComponent (Graphics g) {
            g.drawImage(image, 0, 0, this);
            setForeground(Color.yellow);
            super.paintComponent(g);
         }
      };
      textField.setFont(new Font("Helvetica", Font.BOLD, 16));
 
      frame.getContentPane().add(BorderLayout.CENTER, textField);
      frame.setDefaultCloseOperation(3);
      frame.setSize(200, 50);
      frame.setVisible(true);
      frame.setResizable(false);
   }
}

Embedding a clickable HTML image in a JLabel

A JLabel is able to render HTML but it does not respond to clicks on anchor tags. You could do something simple like add a MouseListener to your JLabel and respond to mouse events like a normal browser would.

Main.java:

import java.awt.event.*;
import java.awt.font.*; 
import javax.swing.*;
import java.util.*;
import java.text.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      final JLabel label = new JLabel("<html><a href="dummy"><img src="file:c:\esuslogo.gif"></a></html>");
      getContentPane().add(label);
 
      label.addMouseListener(new MouseAdapter() {
         public void mouseEntered(MouseEvent me) {
            label.setCursor(new Cursor(Cursor.HAND_CURSOR));
         }
         public void mouseExited(MouseEvent me) {
            label.setCursor(Cursor.getDefaultCursor());
         }
         public void mouseClicked(MouseEvent me) {
            System.out.println("Clicked on JLabel image");
         }
      });
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Setting the JProgressBar colors

You can set the progress rectangle color and remaining area color with setForeground and setBackground.
To set the color of the string drawn inside the progress bar, you have two choices (there is no trivial API method to set these colors, look at bug http://developer.java.sun.com/developer/bugParade/bugs/4226498.html.

  • Set the UIManager property values ProgressBar.selectionForeground and ProgressBar.selectionBackground before creating the JProgressBar. Beware that all your JProgressBar components will take on this color.
  • Extend the JProgressBar UI class to provide a method setSelectionForeground and setSelectionBackground

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame {
   public Main() {
      super("JProgressBar Color Demonstration");
 
      // sets the color of the string painted inside the progressbar
      // selectionForeground is the color of the string that appears
      //    in the rectangle that shows the progress
      // selectionBackground is the color of the string that appears
      //    in the rectangle that shows the remaining area
      UIManager.put("ProgressBar.selectionForeground", Color.red);
      UIManager.put("ProgressBar.selectionBackground", Color.green);
 
      JProgressBar pb = new JProgressBar(0, 100);
      pb.setValue(50); 
      pb.setStringPainted(true);
 
      // sets the foreground color, but only the 
      // rectangle that shows the progress, not the text  
      pb.setForeground(Color.green);
 
      // sets the background color, the rectangle that  
      // shows the remaining area
      pb.setBackground(Color.red);
 
      // add the scroll pane to this window.
      getContentPane().add(pb);
 
      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);
   }
}

Creating a directory chooser

Set the file selection mode in JFileChooser to JFileChooser.DIRECTORIES_ONLY. A directory
can then be selected by not navigating into the directory but by selecting it when you’re a level
higher.

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 Directory Chooser Demonstration");
 
      getContentPane().setLayout(new FlowLayout()); 
      JButton button = new JButton("Show JFileChooser and select directory");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            JFileChooser fc = new JFileChooser();
            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int r = fc.showOpenDialog(Main.this); 
            while (r != JFileChooser.APPROVE_OPTION) {
               JOptionPane.showMessageDialog(Main.this,"Try again, select a directory.", 
                  "ERROR", JOptionPane.ERROR_MESSAGE); 
               r = fc.showOpenDialog(Main.this); 
            }
  
            System.out.println("Selected directory: " + 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);
   }
}