Scrolling a JScrollPane to the bottom programmatically

Call the method scrollRectToVisible of the component that is added to the JScrollPane container as shown in following example:

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() throws Exception {
      getContentPane().setLayout(new BorderLayout());
 
      final JPanel panel = createPanel(); 
      final JScrollPane scrollpane = new JScrollPane(panel);
 
      JButton button = new JButton("Scroll to bottom!");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            panel.scrollRectToVisible(
              new Rectangle(0, panel.getHeight()-1, 1, 1));
         }
      });
 
      getContentPane().add(BorderLayout.NORTH, button);
      getContentPane().add(BorderLayout.CENTER, scrollpane);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static JPanel createPanel() throws Exception {
      JPanel panel = new JPanel();
      panel.setLayout(new GridLayout(50, 20, 10, 10));
 
      for (int i=0; i<50; i++) {
         for (int j=0; j<20; j++) {
            JLabel label = new JLabel("label " + i + ", " + j);
            panel.add(label);    
         }
      }
 
      return panel;
   }
 
   public static void main(String [] args) throws Exception  {
      Main main = new Main();
      main.setSize(600, 600);
      main.setVisible(true);
   } 
} 

Making a JDesktopPane transparent

Play with setOpaque.

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();
      createInternalFrame();
      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() {
      JInternalFrame frame = new JInternalFrame("InternalFrame", 
         true,    // resizable
         true,    // closable
         true,    // maximizable
         true);   // iconifiable
      frame.setVisible(true); 
      desktop.add(frame);
      frame.setSize(300, 100);
      try {
         frame.setSelected(true);
      } catch (java.beans.PropertyVetoException e) {}
      
      desktop.putClientProperty("JDesktopPane.dragMode", "outline");
 
      JLabel label = new JLabel("Name:");
      JTextField textfield = new JTextField(20);
      JRadioButton rb1 = new JRadioButton("Male");
      JRadioButton rb2 = new JRadioButton("Female");
      ButtonGroup group = new ButtonGroup();
      group.add(rb1);
      group.add(rb2);
 
      frame.getContentPane().setLayout(new FlowLayout());
      frame.getContentPane().add(label);
      frame.getContentPane().add(textfield);
      frame.getContentPane().add(rb1);
      frame.getContentPane().add(rb2);
 
      frame.setOpaque(false);
      frame.setBackground(new Color(0,0,0,0));
      rb1.setOpaque(false);
      rb2.setOpaque(false);
   }
 
   public static void main(String []args) throws Exception {
      Main main = new Main();
      main.show();      
   }
}

Center a text over a JButton’s icon

Use the JButton’s methods setHorizontalTextPosition and setVerticalTextPosition.
Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame implements ActionListener {
   JList list; 
 
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JButton fbutton = new JButton("Text Over Image", new ImageIcon("female.gif"));
      fbutton.addActionListener(this);
      fbutton.setVerticalTextPosition(SwingConstants.CENTER);
      fbutton.setHorizontalTextPosition(SwingConstants.CENTER); 
 
      getContentPane().add(BorderLayout.CENTER, fbutton);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(400, 400);
   }
 
   public void actionPerformed(ActionEvent ae) {
      System.out.println("Your pressed the "" + ae.getActionCommand() + "" button");
   }
   
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Using a JSpinner to walk through dates

Use the SpinnerDateModel.

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);
         }
      });
 
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
      final SpinnerDateModel spinnerModel = new SpinnerDateModel();
      JSpinner spinner = new JSpinner(spinnerModel);
 
      final JTextField textfield = new JTextField(25);
      JButton button = new JButton(&quot;Get date&quot;);
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) { 
            textfield.setText(&quot;&quot;+spinnerModel.getDate());
         }
      });
 
      getContentPane().add(spinner);
      getContentPane().add(button);
      getContentPane().add(textfield);
   }
  
   public static void main(String args[])
   {
      Main main = new Main();
      main.setSize(300, 150);
      main.setVisible(true);
   }
}

Changing the background of a JLabel

Call the method setBackground on your component but don’t forget to set your component to be opaque. A component that is not opaque (default) lets whatever is behind them show through. Their backgrounds are determined by the component that is shown behind them.

Main.java:

import javax.swing.text.*;
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("Colored label");
      label.setOpaque(true);
      label.setBackground(Color.white);
 
      getContentPane().add(label);     
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(300, 100);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Creating a vertical JLabel

Code currently works only for 90 or -90 degrees only. It was written to support the answer to the question “How do I create vertically oriented JTable headers”.

Main.java:

import javax.swing.plaf.basic.*;
import javax.swing.border.*;
import javax.swing.text.*;
import java.awt.event.*;
import java.awt.font.*;
import java.awt.geom.*;
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(0);
         }
      });
 
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
 
      JLabel normalLabel = new JLabel(&quot;Normal JLabel&quot;);
      normalLabel.setBorder(LineBorder.createBlackLineBorder());
 
      JLabel verticalLabel1 = new JLabel(&quot;Vertical JLabel, 90 degrees&quot;);
      verticalLabel1.setUI(new VerticalLabelUI(90));
      verticalLabel1.setBorder(LineBorder.createBlackLineBorder());
 
      JLabel verticalLabel2 = new JLabel(&quot;Vertical JLabel, -90 degrees&quot;);
      verticalLabel2.setUI(new VerticalLabelUI(-90));
      verticalLabel2.setBorder(LineBorder.createBlackLineBorder());
 
      getContentPane().add(normalLabel);
      getContentPane().add(verticalLabel1);
      getContentPane().add(verticalLabel2);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.pack();
      main.setVisible(true);
   }
}
 
class VerticalLabelUI extends BasicLabelUI
{
   protected float degrees;
   private static Rectangle paintIconR = new Rectangle();
   private static Rectangle paintTextR = new Rectangle();
   private static Rectangle paintViewR = new Rectangle();
   private static Insets paintViewInsets = new Insets(0, 0, 0, 0);
 
   VerticalLabelUI(float degrees) {
      this.degrees = degrees;
   }
 
   public Dimension getPreferredSize(JComponent c) {
      Dimension dim = super.getPreferredSize(c);
      return new Dimension( dim.height, dim.width );
   }
 
   public void paint(Graphics g, JComponent c) {
      JLabel label = (JLabel)c;
      String text = label.getText();
      Icon icon = (label.isEnabled()) ? label.getIcon() : label.getDisabledIcon();
 
      if ((icon == null) &amp;&amp; (text == null)) {
         return;
      }
 
      FontMetrics fm = g.getFontMetrics();
      paintViewInsets = c.getInsets(paintViewInsets);
 
      paintViewR.x = paintViewInsets.left;
      paintViewR.y = paintViewInsets.top;    	
      paintViewR.height = c.getWidth() - (paintViewInsets.left + paintViewInsets.right);
      paintViewR.width = c.getHeight() - (paintViewInsets.top + paintViewInsets.bottom);
 
      paintIconR.x = paintIconR.y = paintIconR.width = paintIconR.height = 0;
      paintTextR.x = paintTextR.y = paintTextR.width = paintTextR.height = 0;
 
      String clippedText = 
            layoutCL(label, fm, text, icon, paintViewR, paintIconR, paintTextR);
 
      Graphics2D g2d = (Graphics2D) g;
      // save old value
      AffineTransform affineTransformOld = g2d.getTransform();
 
      double radians = degrees * (Math.PI / 180); 
      g2d.rotate(radians);
      Dimension d = getPreferredSize(c);      
      if (degrees == 90) {
         g2d.translate(0,-d.width);
      } 
      else {
         g2d.translate(-d.height, 0);
      }
 
      if (icon != null) {
         icon.paintIcon(c, g, paintIconR.x, paintIconR.y);
      }
 
      if (text != null) {
         View v = (View) c.getClientProperty(BasicHTML.propertyKey);
         if (v != null) {
            v.paint(g, paintTextR);
         }
         else {
            int textX = paintTextR.x;
            int textY = paintTextR.y + fm.getAscent();
 
            if (label.isEnabled()) {
               paintEnabledText(label, g, clippedText, textX, textY);
            }
            else {
               paintDisabledText(label, g, clippedText, textX, textY);
            }
         }
      } 	
    	
      g2d.setTransform(affineTransformOld);
   }
}

Add a background image to a JTable

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;
 
public class BackgroundTable 
{ 
   public static void main(String[] args) {
      JFrame frame = new JFrame("Table Example"); 
      frame.addWindowListener( new WindowAdapter() { 
         public void windowClosing(WindowEvent e) 
         { 
            Window w = e.getWindow(); 
            w.setVisible(false); 
            w.dispose(); 
            System.exit(0); 
         } 
      }); 
 
      JTable imTable = new JTable(35, 3) { 
         public Component prepareRenderer(TableCellRenderer renderer, int row, int column) 
         { 
            Component c = super.prepareRenderer( renderer, row, column); 
            // We want renderer component to be 
            //transparent so background image is visible 
            if( c instanceof JComponent ) 
               ((JComponent)c).setOpaque(false); 
            return c; 
         }
   
         public void paint( Graphics g ) 
         { 
            ImageIcon image = new ImageIcon("FIREFALL.gif"); 
            // tile the background image 
            Dimension d = getSize(); 
            for( int x = 0; x < d.width; x += image.getIconWidth() ) 
            for( int y = 0; y < d.height; y += image.getIconHeight() ) 
            g.drawImage( image.getImage(), x, y, null, null ); 
            // Now let the paint do its usual work 
            super.paint(g); 
         } 
      }; 
 
      //make the table transparent 
      imTable.setOpaque(false); 
 
      JScrollPane jsp = new JScrollPane(imTable); 
      frame.getContentPane().add(jsp); 
 
      frame.pack(); 
      frame.show(); 
   } 
}

Freezing the first column of a JTable

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



RowHeaderRenderer.java:

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