001 /* $Id: SortHeader.java 108 2007-11-05 15:43:38Z ringler $
002 * This class is part of the de.mospace.swing library.
003 * Copyright (C) 2005-2006 Moritz Ringler
004 *
005 * This program is free software; you can redistribute it and/or
006 * modify it under the terms of the GNU General Public License
007 * as published by the Free Software Foundation; either version 2
008 * of the License, or (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
013 * GNU General Public License for more details.
014 *
015 * You should have received a copy of the GNU General Public License
016 * along with this program; if not, write to the Free Software
017 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
018 */
019 package de.mospace.swing.table;
020
021 import java.awt.Component;
022 import java.awt.Dimension;
023 import java.awt.GraphicsEnvironment;
024 import java.awt.Insets;
025 import java.awt.Point;
026 import java.awt.Toolkit;
027 import java.awt.event.ActionEvent;
028 import java.awt.event.MouseAdapter;
029 import java.awt.event.MouseEvent;
030 import javax.swing.AbstractAction;
031 import javax.swing.Action;
032 import javax.swing.JButton;
033 import javax.swing.JMenuItem;
034 import javax.swing.JPopupMenu;
035 import javax.swing.JSeparator;
036 import javax.swing.JTable;
037 import javax.swing.UIManager;
038 import javax.swing.plaf.TableHeaderUI;
039 import javax.swing.SwingUtilities;
040 import javax.swing.table.JTableHeader;
041 import javax.swing.table.TableCellRenderer;
042 import javax.swing.table.TableModel;
043 import de.mospace.swing.GLOBALS;
044 import de.mospace.swing.icon.BevelArrowIcon;
045 import de.mospace.swing.icon.BlankIcon;
046
047 /**
048 * A table header for sortable JTables. It displays an arrow next to the
049 * column name of the column that is currently used for sorting. Left-Clicking
050 * on the header of a column triggers sorting of the table by that column.
051 * The context menu of a column header allows sorting
052 * the table rows by the values in that column or randomizing the order of the
053 * rows. If the TableModel of the table implements
054 * the {@link de.mospace.swing.table.HeaderPopupTableModel} interface the
055 * elements of the JPopupMenu returned by its {@link
056 * de.mospace.swing.table.HeaderPopupTableModel#getHeaderPopup(MouseEvent e)
057 * getHeaderPopup} method are added to the column headers' context menus.
058 *
059 * @version $Revision: 108 $ ($Date: 2007-11-05 16:43:38 +0100 (Mo, 05 Nov 2007) $)
060 * @author Moritz Ringler
061 */
062 public class SortHeader extends JTableHeader implements TableCellRenderer {
063 private int activeColumn = -1;
064 private int popupColumn = -1;
065 private final Action sortAction;
066 private final Action randomizeAction;
067 private transient MouseEvent trigger;
068 private final JButton noneButton = new JButton();
069 private final ArrowButton arrowButton = new ArrowButton(BevelArrowIcon.DOWN);;
070
071 private static class ArrowButton extends JButton{
072 BevelArrowIcon icon, pressedIcon;
073
074 /** @param initialState one of BevelArrowIcon.UP and BevelArrowIcon.DOWN **/
075 public ArrowButton(int initialState){
076 super();
077 icon = new BevelArrowIcon(initialState, false, false);
078 pressedIcon = new BevelArrowIcon(initialState, false, true);
079 setIcon(icon);
080 setMargin(new Insets(0,0,0,0));
081 setHorizontalTextPosition(JButton.LEFT);
082 }
083
084 public void setDirection(int d){
085 icon.setDirection(d);
086 pressedIcon.setDirection(d);
087 repaint();
088 }
089 }
090
091 /** Constructs a new SortHeader associated with the specified JTable.
092 * @throws IllegalArgumentException if the TableModel of the table
093 * does not implement {@link SortableTableModel}.
094 */
095 public SortHeader(JTable table) {
096 super(table.getColumnModel());
097 setTableImpl(table);
098 MouseListener ml = new MouseListener();
099 addMouseListener(ml);
100
101 noneButton.setHorizontalTextPosition(JButton.CENTER);
102 noneButton.setIcon(new BlankIcon());
103 noneButton.setMargin(new Insets(0,0,0,0));
104
105 sortAction = new AbstractAction(GLOBALS.getString("Sort")){
106 public void actionPerformed(ActionEvent e){
107 sort(popupColumn);
108 /* repaint the header */
109 JTableHeader header = getTable().getTableHeader();
110 header.repaint();
111 }
112 };
113
114 randomizeAction = new AbstractAction(GLOBALS.getString("Randomize")){
115 public void actionPerformed(ActionEvent e){
116 randomize();
117 /* repaint the header */
118 JTableHeader header = getTable().getTableHeader();
119 header.repaint();
120 }
121 };
122 setColumnModel(table.getColumnModel());
123 setDefaultRenderer(this);
124 setReorderingAllowed(false);
125 }
126
127 /** @throws IllegalArgumentException if the TableModel of the table
128 * does not implement {@link SortableTableModel}.
129 */
130 public void setTable(JTable table){
131 setTableImpl(table);
132 }
133
134 /** must do this to avoid bug in Java 6 */
135 public void updateUI(){
136 setUI((TableHeaderUI)UIManager.getUI(this));
137 //updateUI is called by super constructor
138 //when noneButton and arrowButton have not been initialized
139 if(noneButton != null){
140 noneButton.updateUI();
141 arrowButton.updateUI();
142 }
143 }
144
145 private final void setTableImpl(JTable table){
146 if (!(table.getModel() instanceof SortableTableModel)){
147 throw new IllegalArgumentException("Table is not sortable!"+
148 "Its TableModel does not implement the" +
149 "de.mospace.swing.table.SortableTableModel interface.");
150 }
151 super.setTable(table);
152 setColumnModel(table.getColumnModel());
153 }
154
155 public Component getTableCellRendererComponent(JTable table, Object value,
156 boolean isSelected, boolean hasFocus, int row, int col) {
157 setTable(table);
158 JButton button;
159 boolean isActive = (col == activeColumn);
160 SortableTableModel model = ((SortableTableModel) table.getModel());
161 int[] sort = ((SortableTableModel) table.getModel()).getSortOrder()[0];
162 if(model.isSorted() && col == sort[0]){
163 arrowButton.setDirection(
164 (sort[1] == SortableTableModel.ASCENDING)
165 ? BevelArrowIcon.UP
166 : BevelArrowIcon.DOWN
167 );
168 button = arrowButton;
169 } else {
170 button = noneButton;
171 }
172 button.setText((value == null) ? "" : value.toString());
173 button.getModel().setPressed(isActive);
174 button.getModel().setArmed(isActive);
175 return button;
176 }
177
178 private void randomize(){
179 SortableTableModel model = (SortableTableModel) getTable().getModel();
180 model.randomize();
181 }
182
183 private void sort(int col){
184 /* Simple Left Click -> Sort by Column */
185 int sortCol = getTable().convertColumnIndexToModel(col);
186 SortableTableModel model = (SortableTableModel) getTable().getModel();
187 model.setSortBy(sortCol);
188 model.sort();
189 }
190
191 private class MouseListener extends MouseAdapter{
192 public void mousePressed(MouseEvent me) {
193 /* Left-Click: Sort or Randomize */
194 if ((me.getButton() == MouseEvent.BUTTON1)){
195 activeColumn = columnAtPoint(me.getPoint());
196 if(me.isShiftDown()){
197 randomize();
198 } else {
199 sort(activeColumn);
200 }
201 /* repaint the header */
202 JTableHeader header = getTable().getTableHeader();
203 // if (getTable().getModel() instanceof AbstractTableModel){
204 // ((AbstractTableModel) getTable().getModel()).fireTableStructureChanged();
205 // }
206 header.repaint();
207 if (header.getTable().isEditing()) {
208 header.getTable().getCellEditor().stopCellEditing();
209 }
210 /* Right-Click: Show ContextMenu */
211 } else if (me.isPopupTrigger()){
212 showPopup(me);
213 }
214 }
215
216 public void showPopup(MouseEvent me){
217 popupColumn = columnAtPoint(me.getPoint());
218 JPopupMenu popup = new JPopupMenu();
219 TableModel model = getTable().getModel();
220 if (model instanceof HeaderPopupTableModel){
221 JPopupMenu imported = ((HeaderPopupTableModel) model).getHeaderPopup(me);
222 if(imported != null){
223 Component[] importedItems = imported.getComponents();
224 for(int i=0; i<importedItems.length; i++){
225 if(importedItems[i] instanceof JMenuItem){
226 popup.add((JMenuItem) importedItems[i]);
227 } else if (importedItems[i] instanceof JSeparator){
228 popup.addSeparator();
229 }
230 }
231 popup.addSeparator();
232 }
233 }
234 popup.add(sortAction);
235 popup.add(randomizeAction);
236 popup.pack();
237 Dimension popupSize = popup.getPreferredSize();
238 Toolkit tk = Toolkit.getDefaultToolkit();
239 Dimension screen = tk.getScreenSize();
240 Insets ins = tk.getScreenInsets(
241 GraphicsEnvironment.getLocalGraphicsEnvironment()
242 .getDefaultScreenDevice().getDefaultConfiguration()
243 );
244 Point scr = new Point(screen.width-ins.right,screen.height-ins.bottom);
245 SwingUtilities.convertPointFromScreen(scr, getTable());
246 popup.show(me.getComponent(),
247 (int) Math.min(me.getX(),scr.getX()-popupSize.width),
248 (int) Math.min(me.getY(),scr.getY()-popupSize.height)
249 );
250 }
251
252 public void mouseReleased(MouseEvent me) {
253 if ((me.getButton() == MouseEvent.BUTTON1)){
254 activeColumn = -1; // clear
255 getTable().getTableHeader().repaint();
256 } else if (me.isPopupTrigger()){
257 showPopup(me);
258 }
259 }
260 }
261 }