Putting a JButton inside a JComboBox

Here’s an example:

import javax.swing.plaf.basic.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
    
public class Main extends JFrame
{ 
   public Main() {
      getContentPane().setLayout(new FlowLayout());
      
      final JButton buttonOk = new JButton("OK");
      buttonOk.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println(ae.getActionCommand() + " clicked!");
         }
      });
      final JButton buttonCancel = new JButton("Cancel");
      buttonCancel.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println(ae.getActionCommand() + " clicked!");
         }
      });
 
      final JComboBox combobox = 
         new JComboBox(new Object[] {
               "Item 1",
               "Item 2",
               "Item 3",
               buttonOk,
               "Item 4",
               "Item 5",
               buttonCancel
            }
         );
 
      getContentPane().add(combobox);
      combobox.setRenderer(new ButtonComboBoxRenderer());
      combobox.addActionListener(new ButtonComboBoxListener(this, combobox));
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });      
   
      setSize(new Dimension(200, 200));
   } 
 
   public static void main(String[] args) throws Exception {
      Main main = new Main();
      main.setVisible(true);
   }
}
 
class ButtonComboBoxRenderer extends BasicComboBoxRenderer implements ListCellRenderer
{
   public ButtonComboBoxRenderer() {
      super();
   }
   
   public Component getListCellRendererComponent( JList list, 
           Object value, int index, boolean isSelected, boolean cellHasFocus) {
      if (isSelected) {
          setBackground(list.getSelectionBackground());
          setForeground(list.getSelectionForeground());
      }
      else {
          setBackground(list.getBackground());
          setForeground(list.getForeground());
      }
 
      setFont(list.getFont());
      if (value instanceof Icon) {
         setIcon((Icon)value);
      }
      if (value instanceof JButton) {
         return (Component) value;
      }
      else {
         setText((value == null) ? "" : value.toString());
      }
 
      return this;
  }  
}
 
class ButtonComboBoxListener implements ActionListener {
   JComboBox combobox;
   JFrame frame;
 
   ButtonComboBoxListener(JFrame frame, JComboBox combobox) {
      this.frame = frame;
      this.combobox = combobox;
      combobox.setSelectedIndex(0);
   }
     
   public void actionPerformed(ActionEvent e) {
      Object selectedItem = combobox.getSelectedItem();
      if (selectedItem instanceof JButton) {
         ((JButton) selectedItem).doClick();
      }
   }
}

Showing a tooltip on a individual items of JList

Override the JList method getToolTipText, determine the particular JList item the mouse is pointed on and show the appropriate text. Here’s an example:

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 FlowLayout());
 
      Vector v = new Vector();
      for (int i=0; i<50; i++) {
         v.addElement("Item #" + i);
      }
      final JList list = new JList(v) {
         public String getToolTipText(MouseEvent me) {
            int index = locationToIndex(me.getPoint());
            if (index > -1) {
               String item = (String) getModel().getElementAt(index);
               return "Tooltip for " + item;
            }
            return null;
         }
      };
 
      // necessary to activate tooltips for this JList!
      list.setToolTipText("");
 
      getContentPane().add(new JScrollPane(list));    
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(200, 230);
   }
   
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Adding a different tooltip for every element in my JMenuItem

Set the tooltip text for every JMenuItem.

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");
      JMenuItem menuItem2 = new JMenuItem("female");
      menuItem1.setToolTipText("The weak sex");
      menuItem2.setToolTipText("The strong sex");
      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();
   }
}

Creating a JLabel with the text on top of the image

You can play around with the methods setHorizontalTextAlignment and setVerticalTextAlignment as shown in the following example:

Main.java:

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("esus.com", new ImageIcon("esuslogo.gif"), JLabel.CENTER);
      label.setHorizontalTextPosition(JLabel.CENTER); 
      getContentPane().add(label);     
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Setting the selected file in a the filename textfield JFileChooser when it starts up

You just have to create a new File and set it as selectedFile before starting the FileChooser. Depending on what you want to do with the selected file you should check the file with File.canRead(), File.canWrite() or File.exists(). Here is an example:

File file = new File(date + " " + user + ".pdf");
JFileChooser fc = new JFileChooser();
fc.setSelectedFile(file);
int returnValue = fc.showSaveDialog(this);

This must be wrapped in a try-catch-block, because creating a File could throw an exception.

Creating a JTable with fixed rows

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



FixedRowExample.java:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;

/**
 * @version 1.0 03/05/99
 */
public class FixedRowExample extends JFrame {
  Object[][] data;
  Object[] column;
  JTable fixedTable,table;
  private int FIXED_NUM = 2;

  public FixedRowExample() {
    super( "Fixed Row Example" );
    
    data =  new Object[][]{
        {      "a","","","","",""},
        {      "","b","","","",""},
        {      "","","c","","",""},
        {      "","","","d","",""},
        {      "","","","","e",""},
        {      "","","","","","f"},
        {"fixed1","","","","","","",""},
        {"fixed2","","","","","","",""}};
    column = new Object[]{"A","B","C","D","E","F"};
        
    AbstractTableModel    model = new AbstractTableModel() {
      public int getColumnCount() { return column.length; }
      public int getRowCount() { return data.length - FIXED_NUM; }
      public String getColumnName(int col) {
       return (String)column[col]; 
      }
      public Object getValueAt(int row, int col) { 
        return data[row][col]; 
      }
      public void setValueAt(Object obj, int row, int col) { 
        data[row][col] = obj; 
      }
      public boolean CellEditable(int row, int col) { 
        return true; 
      }
    };
    
    AbstractTableModel fixedModel = new AbstractTableModel() {      
      public int getColumnCount() { return column.length; }
      public int getRowCount() { return FIXED_NUM; }
      public Object getValueAt(int row, int col) { 
        return data[row + (data.length - FIXED_NUM)][col]; 
      }
    };
    
    table = new JTable( model );
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    
    fixedTable = new JTable( fixedModel );
    fixedTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    fixedTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    
    JScrollPane scroll      = new JScrollPane( table );
    scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

    
    JScrollPane fixedScroll = new JScrollPane( fixedTable ) {
      public void setColumnHeaderView(Component view) {} // work around
    };                                                   //
                                             // fixedScroll.setColumnHeader(null); 
    
    fixedScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    JScrollBar bar = fixedScroll.getVerticalScrollBar();
    JScrollBar dummyBar = new JScrollBar() {
      public void paint(Graphics g) {}
    };
    dummyBar.setPreferredSize(bar.getPreferredSize());
    fixedScroll.setVerticalScrollBar(dummyBar);
    
    final JScrollBar bar1 = scroll.getHorizontalScrollBar();
    JScrollBar bar2 = fixedScroll.getHorizontalScrollBar();
    bar2.addAdjustmentListener(new AdjustmentListener() {
      public void adjustmentValueChanged(AdjustmentEvent e) {
        bar1.setValue(e.getValue());
      }
    });
    
    
    scroll.setPreferredSize(new Dimension(400, 100));
    fixedScroll.setPreferredSize(new Dimension(400, 52));  // Hmm...
    getContentPane().add(     scroll, BorderLayout.CENTER);
    getContentPane().add(fixedScroll, BorderLayout.SOUTH);    
  }

  public static void main(String[] args) {
    FixedRowExample frame = new FixedRowExample();
    frame.addWindowListener( new WindowAdapter() {
      public void windowClosing( WindowEvent e ) {
        System.exit(0);
      }
    });
    frame.pack();
    frame.setVisible(true);
  }
}

Have a JButton cell in a JTable

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



JButtonTableExample.java:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
 
/**
 * @version 1.0 11/09/98
 */
public class JButtonTableExample extends JFrame {
 
  public JButtonTableExample(){
    super( "JButtonTable Example" );
    
    DefaultTableModel dm = new DefaultTableModel();
    dm.setDataVector(new Object[][]{{"button 1","foo"},
                                    {"button 2","bar"}},
                     new Object[]{"Button","String"});
                     
    JTable table = new JTable(dm);
    table.getColumn("Button").setCellRenderer(new ButtonRenderer());
    table.getColumn("Button").setCellEditor(new ButtonEditor(new JCheckBox()));
    JScrollPane scroll = new JScrollPane(table);
    getContentPane().add( scroll );
    setSize( 400, 100 );
    setVisible(true);
  }
 
  public static void main(String[] args) {
    JButtonTableExample frame = new JButtonTableExample();
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });
  }
}

ButtonRenderer.java:

import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
 
/**
 * @version 1.0 11/09/98
 */
public class ButtonRenderer extends JButton implements TableCellRenderer {
 
  public ButtonRenderer() {
    setOpaque(true);
  }
  
  public Component getTableCellRendererComponent(JTable table, Object value,
                   boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected) {
      setForeground(table.getSelectionForeground());
      setBackground(table.getSelectionBackground());
    } else{
      setForeground(table.getForeground());
      setBackground(UIManager.getColor("Button.background"));
    }
    setText( (value ==null) ? "" : value.toString() );
    return this;
  }
}

ButtonEditor.java:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
 
/**
 * @version 1.0 11/09/98
 */
public class ButtonEditor extends DefaultCellEditor {
  protected JButton button;
  private String    label;
  private boolean   isPushed;
 
  public ButtonEditor(JCheckBox checkBox) {
    super(checkBox);
    button = new JButton();
    button.setOpaque(true);
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        fireEditingStopped();
      }
    });
  }
 
  public Component getTableCellEditorComponent(JTable table, Object value,
                   boolean isSelected, int row, int column) {
    if (isSelected) {
      button.setForeground(table.getSelectionForeground());
      button.setBackground(table.getSelectionBackground());
    } else{
      button.setForeground(table.getForeground());
      button.setBackground(table.getBackground());
    }
    label = (value ==null) ? "" : value.toString();
    button.setText( label );
    isPushed = true;
    return button;
  }
 
  public Object getCellEditorValue() {
    if (isPushed)  {
      // 
      // 
      JOptionPane.showMessageDialog(button ,label + ": Ouch!");
      // System.out.println(label + ": Ouch!");
    }
    isPushed = false;
    return new String( label ) ;
  }
   
  public boolean stopCellEditing() {
    isPushed = false;
    return super.stopCellEditing();
  }
 
  protected void fireEditingStopped() {
    super.fireEditingStopped();
  }
}

Change the row height of a JTable that resides in a JFrame automatically when that frame is resized

Maybe this code gives you some ideas.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame 
{
   public Main() {
      super("Table example, Wines from Bordeaux");
 
      Object[][] tabledata = {
            { "Chateau Meyney, St. Estephe", 	   new Integer(1994), "$18.75"},
            { "Chateau Montrose, St. Estephe", 	   new Integer(1975), "$54.25" },
            { "Chateau Gloria, St. Julien", 	   new Integer(1993), "$22.99" },
            { "Chateau Beychevelle, St. Julien",   new Integer(1970), "$61.63" },
            { "Chateau La Tour de Mons, Margeaux", new Integer(1975), "$57.03" },
            { "Chateau Brane-Cantenac, Margeaux",  new Integer(1978), "$49.92" },
            { "Chateau Meyney, St. Estephe", 	   new Integer(1994), "$18.75"},
            { "Chateau Montrose, St. Estephe", 	   new Integer(1975), "$54.25" },
            { "Chateau Gloria, St. Julien", 	   new Integer(1993), "$22.99" },
            { "Chateau Beychevelle, St. Julien",   new Integer(1970), "$61.63" },
            { "Chateau La Tour de Mons, Margeaux", new Integer(1975), "$57.03" },
            { "Chateau Brane-Cantenac, Margeaux",  new Integer(1978), "$49.92" },
      };
 
      String columnheaders[] = { "Wine", "Vintage", "Price" };
 
      final JTable table = new JTable(tabledata, columnheaders);
      table.setPreferredScrollableViewportSize(new Dimension(500, 70));
      JScrollPane scrollPane = new JScrollPane(table);
 
      // initial height
      table.setRowHeight(20);
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(scrollPane);
 
      addComponentListener(new ComponentAdapter() {
         int oldHeight;
 
         public void componentResized(ComponentEvent e) {
            if (oldHeight > 0) {
               int newRowHeight = ( table.getRowHeight() * getHeight() ) / oldHeight;
               table.setRowHeight(newRowHeight);
            }
  
            oldHeight = getHeight();
         }
      });
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      pack();
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

Have dotted lines in a JTree

That appends on your Look & Feel – you can use three lineStyle’s:

// show hierarchy-lines
JTree#putClientProperty(“JTree.lineStyle”, “Angled”);

// show horizontal lines
JTree#putClientProperty( “JTree.lineStyle”, “Horitontal” );

// do not show any lines
JTree#putClientProperty(“JTree.lineStyle”, “None”);