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

Setting the width of a JTable column

you should do something like this:

   TableColumn column=jTable1.getColumnModel().getColumn(1);
   column.setMinWidth(0);
   column.setMaxWidth(300);
   column.setPreferredWidth(15);

Setting

column.setMinWidth(0);
column.setMaxWidth(300);

is not nessesary, but you’ll be sure that desired width fits in this range.

Creating a JTable with row headers

Courtesy of Nobuo Tamemasa (http://www2.gol.com/users/tame/swing/examples/JTableExamples1.html)



import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
 
 
/**
 * @version 1.0 11/09/98
 */
  
class RowHeaderRenderer extends JLabel implements ListCellRenderer {
   
  RowHeaderRenderer(JTable table) {
    JTableHeader header = table.getTableHeader();
    setOpaque(true);
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    setHorizontalAlignment(CENTER);
    setForeground(header.getForeground());
    setBackground(header.getBackground());
    setFont(header.getFont());
  }
  
  public Component getListCellRendererComponent( JList list, 
         Object value, int index, boolean isSelected, boolean cellHasFocus) {
    setText((value == null) ? "" : value.toString());
    return this;
  }
}
 
public class RowHeaderExample extends JFrame {
 
  public RowHeaderExample() {
    super( "Row Header Example" );
    setSize( 300, 150 );
        
    ListModel lm = new AbstractListModel() {
      String headers[] = {"a", "b", "c", "d", "e", "f", "g", "h", "i"};
      public int getSize() { return headers.length; }
      public Object getElementAt(int index) {
        return headers[index];
      }
    };
 
    DefaultTableModel dm = new DefaultTableModel(lm.getSize(),10);
    JTable table = new JTable( dm );
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    
    JList rowHeader = new JList(lm);    
    rowHeader.setFixedCellWidth(50);
    
    rowHeader.setFixedCellHeight(table.getRowHeight()
                               + table.getRowMargin());
//                             + table.getIntercellSpacing().height);
    rowHeader.setCellRenderer(new RowHeaderRenderer(table));
 
    JScrollPane scroll = new JScrollPane( table );
    scroll.setRowHeaderView(rowHeader);
    getContentPane().add(scroll, BorderLayout.CENTER);
  }
 
  public static void main(String[] args) {
    RowHeaderExample frame = new RowHeaderExample();
    frame.addWindowListener( new WindowAdapter() {
      public void windowClosing( WindowEvent e ) {
        System.exit(0);
      }
    });
    frame.setVisible(true);
  }
}