GUIHelper.java
| Index Score | ||
|---|---|---|
![]() |
![]() |
org.xnap.gui.util |
![]() |
![]() |
XNap 3 |
View: Reasons, Metrics, Source Code
These are the metrics that contribute to the Enerjy Score for this file, ranked by impact. So the metrics listed at the top influence the score to a greater extent that the metrics listed at the bottom.
/*
* XNap - A P2P framework and client.
*
* See the file AUTHORS for copyright information.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.xnap.gui.util;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.StringTokenizer;
import javax.swing.*;
import javax.help.*;
import javax.swing.border.*;
import javax.swing.ActionMap;
import javax.swing.BorderFactory;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollBar;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.text.JTextComponent;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import org.xnap.XNap;
import org.xnap.gui.component.XNapBevelBorder;
import org.xnap.util.FileHelper;
import org.xnap.util.Preferences;
import org.xnap.util.SystemHelper;
import com.jgoodies.forms.factories.DefaultComponentFactory;
/**
* Helps with gui related tasks. We can not have <code>Preferences.java</code>
* depend on java.awt.
*/
public class GUIHelper
{
//--- Constant(s) ---
/**
* Kicker offset.
*/
public static final int POPUP_MENU_HEIGHT_INSET = 50;
//--- Data field(s) ---
protected static Preferences prefs = Preferences.getInstance();
//--- Constructor(s) ---
//--- Method(s) ---
/**
* Adds a mapping between the enter key and <code>action</code> to the
* input map of <code>c</code>.
*
* @return true, if successful; false, otherwise
*/
public static boolean bindEnterKey(JComponent c, Action action)
{
KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
return bindKey(c, ks, action, true);
}
/**
* Does the same as {@link #bindEnterKey(JComponent, Action)} but
* uses the default input map and not the window input map.
*
* @return true, if successful; false, otherwise */
public static boolean bindEnterKeyLocally(JComponent c, Action action)
{
KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
return bindKey(c, ks, action, false);
}
/**
* Adds a mapping between the escape key and <code>action</code> to the
* input map of <code>c</code>.
*
* @return true, if successful; false, otherwise
*/
public static boolean bindEscapeKey(JComponent c, Action action)
{
KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
return bindKey(c, ks, action, true);
}
/**
* Adds a mapping between <code>ks</code> and <code>action</code> to the
* input map of <code>c</code>.
*
* @return true, if successful; false, otherwise
*/
public static boolean bindKey(JComponent c, KeyStroke ks, Action action,
boolean whenInFocusedWindow)
{
InputMap inputMap
= (whenInFocusedWindow)
? c.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
: c.getInputMap();
ActionMap actionMap = c.getActionMap();
if (inputMap != null && actionMap != null) {
inputMap.put(ks, action);
actionMap.put(action, action);
return true;
}
return false;
}
/**
* Returns an etched default border.
*/
public static Border createDefaultBorder(String title)
{
return BorderFactory.createTitledBorder
(BorderFactory.createEtchedBorder(), " " + title + " ");
}
/**
* Returns an empty border.
*/
public static Border createEmptyBorder(int inset)
{
return BorderFactory.createEmptyBorder(inset, inset, inset, inset);
}
/**
* Returns an empty border.
*/
public static Border createEmptyBorder()
{
return createEmptyBorder(0);
}
/**
* Returns an empty border.
*/
public static Border createEtchedBorder()
{
return BorderFactory.createEtchedBorder();
}
public static Border createLoweredBorder()
{
return new XNapBevelBorder(XNapBevelBorder.LOWERED);
}
public static Border createRaisedBorder()
{
return new XNapBevelBorder(XNapBevelBorder.RAISED);
}
/**
* Creates and answers a label with separator; useful to separate
* paragraphs in a panel. This is often a better choice than
* a <code>TitledBorder</code>.
* <p>
* The current implementation doesn't support component alignments.
*
* <p>Copyright (c) 2003 JGoodies Karsten Lentzsch. All Rights Reserved.
* Modified by Steffen Pingel for XNap.
*
* @param text the title's text
* @param alignment text alignment: left, center, right
* @return a separator with title label
*/
// public JComponent createSeparator(String text, int alignment)
// {
// JPanel header = new JPanel(new GridBagLayout());
// GridBagConstraints gbc = new GridBagConstraints();
// gbc.weightx = 0.0;
// gbc.weighty = 1.0;
// gbc.anchor = GridBagConstraints.SOUTHWEST;
// gbc.fill = GridBagConstraints.BOTH;
// gbc.gridwidth = 1;
// gbc.gridheight = 3;
// if (text != null && text.length() > 0) {
// JLabel label = new TitleLabel();
// setTextAndMnemonic(label, textWithMnemonic);
// label.setVerticalAlignment(SwingConstants.CENTER);
// label.setBorder(BorderFactory.createEmptyBorder(1, 0, 1, gap));
// return label;
// header.add(createTitle(text, 4), gbc);
// }
// gbc.weightx = 1.0;
// gbc.weighty = 1.0;
// gbc.gridwidth = GridBagConstraints.REMAINDER;
// gbc.gridheight = 1;
// JSeparator separator = new JSeparator();
// header.add(Box.createGlue(), gbc);
// gbc.weighty = 0.0;
// header.add(separator, gbc);
// gbc.weighty = 1.0;
// header.add(Box.createGlue(), gbc);
// return header;
// }
public static JComponent createHeader(String title)
{
JLabel label = new JLabel(title);
Font font = UIManager.getFont("TitledBorder.font");
if (font != null) {
label.setFont(font.deriveFont(Font.BOLD));
}
Color foreground = UIManager.getColor("TitledBorder.titleColor");
if (foreground != null) {
label.setForeground(foreground);
}
return label;
}
public static JComponent createSeparator(String title)
{
// JPanel panel = new JPanel(new BorderLayout());
// panel.add(new JSeparator(), BorderLayout.CENTER);
// JLabel label = new JLabel(title);
// label.setFont(new Font("Dialog", Font.BOLD, 14));
// label.setForeground(Color.blue);
// panel.add(label, BorderLayout.EAST);
// return panel;
return DefaultComponentFactory.getInstance().createSeparator(title);
}
/**
* Returns a titled border.
*/
public static Border createTitledBorder(String title, int inset)
{
return BorderFactory.createCompoundBorder
(createDefaultBorder(title), createEmptyBorder(inset));
}
public static void expandAllNodes(JTree jt)
{
TreeModel m = jt.getModel();
for (int i = m.getChildCount(m.getRoot()) - 1; i >= 0; i--) {
Object[] path
= new Object[] { m.getRoot(), m.getChild(m.getRoot(), i) };
jt.expandPath(new TreePath(path));
}
}
public static void initialize()
{
}
public static void restrictWidth(JComponent jc)
{
jc.setMaximumSize(new Dimension(jc.getPreferredSize().width,
jc.getMaximumSize().height));
}
public static void scrollToEnd(JTextComponent jt)
{
// Element map = jt.getDocument().getDefaultRootElement();
// Element lastLine = map.getElement(map.getElementCount() - 1);
// jt.setCaretPosition(lastLine.getEndOffset() - 1);
jt.setCaretPosition(jt.getDocument().getEndPosition().getOffset() - 1);
}
/**
* Returns true, if <code>jsb</code> is at the maximum value.
*/
public static boolean shouldScroll(JScrollBar jsb)
{
int pos = jsb.getValue() + jsb.getVisibleAmount();
return (pos == jsb.getMaximum());
}
public static KeyStroke getMenuKeyStroke(int keyCode)
{
int mask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
return KeyStroke.getKeyStroke(keyCode, mask);
}
public static void setAccelerator(JMenuItem jmi, int keyCode)
{
int mask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
jmi.setAccelerator(KeyStroke.getKeyStroke(keyCode, mask));
}
public static void setMnemonics(JTabbedPane pane)
{
HashSet letters = new HashSet();
for (int i = 0; i < pane.getTabCount(); i++) {
if (pane.getMnemonicAt(i) == 0) {
pane.setMnemonicAt(i, getMnemonicForText(pane.getTitleAt(i),
letters));
}
}
}
public static void setMnemonics(Container c)
{
setMnemonics(c, null);
}
public static void setMnemonics(Container c, HashSet l)
{
HashSet letters = (l != null) ? l : new HashSet();
for (int i = 0; i < c.getComponentCount(); i++) {
Component component = c.getComponent(i);
if (component instanceof AbstractButton) {
AbstractButton ab = (AbstractButton)component;
if (ab.getMnemonic() == 0) {
setMnemonics(ab, letters);
}
else {
letters.add(new Integer(ab.getMnemonic()));
}
}
if (component instanceof JLabel) {
JLabel label = (JLabel)component;
if (label.getDisplayedMnemonic() != 0) {
letters.add(new Integer(label.getDisplayedMnemonic()));
}
if (label.getLabelFor() != null) {
setMnemonics(label, letters);
}
}
if (component instanceof JMenu) {
setMnemonics(((JMenu)component).getPopupMenu());
}
// recurse
if (component instanceof Container) {
setMnemonics((Container)component, letters);
}
}
}
private static boolean setMnemonics(JLabel label, HashSet letters)
{
if (label.getText() == null) {
return true;
}
String text = label.getText();
// try first letters of words first
StringTokenizer t = new StringTokenizer(text);
while (t.hasMoreTokens()) {
Integer character = new Integer((int)t.nextToken().charAt(0));
if (!letters.contains(character)) {
letters.add(character);
label.setDisplayedMnemonic(character.intValue());
return true;
}
}
// pick any character, start with the second one
// the first one has already been checked
for (int i = 1; i < text.length(); i++) {
Integer character = new Integer((int)text.charAt(i));
if (text.charAt(i) != ' ' && !letters.contains(character)) {
letters.add(character);
label.setDisplayedMnemonic(character.intValue());
return true;
}
}
return false;
}
private static int getMnemonicForText(String text, HashSet letters)
{
// try first letters of words first
StringTokenizer t = new StringTokenizer(text);
while (t.hasMoreTokens()) {
Integer character = new Integer((int)t.nextToken().charAt(0));
if (!letters.contains(character)) {
letters.add(character);
return character.intValue();
}
}
// pick any character, start with the second one
// the first one has already been checked
for (int i = 1; i < text.length(); i++) {
Integer character = new Integer((int)text.charAt(i));
if (text.charAt(i) != ' ' && !letters.contains(character)) {
letters.add(character);
return character.intValue();
}
}
return 0;
}
private static boolean setMnemonics(AbstractButton ab, HashSet letters)
{
if (ab.getText() == null) {
return true;
}
String text = ab.getText().toUpperCase();
// try first letters of words first
StringTokenizer t = new StringTokenizer(text);
while (t.hasMoreTokens()) {
Integer character = new Integer((int)t.nextToken().charAt(0));
if (!letters.contains(character)) {
letters.add(character);
ab.setMnemonic(character.intValue());
return true;
}
}
// pick any character, start with the second one
// the first one has already been checked
for (int i = 1; i < text.length(); i++) {
Integer character = new Integer((int)text.charAt(i));
if (text.charAt(i) != ' ' && !letters.contains(character)) {
letters.add(character);
ab.setMnemonic(character.intValue());
return true;
}
}
return false;
}
/**
* Loads text from file and sets it to <code>jta</code>.
*
* <p>If file is not found or could not be read, sets
* <code>altText</code> instead.
*/
public static void showFile(JTextComponent jta, String filename,
String altText)
{
InputStream s = FileHelper.getResourceAsStream(filename);
if (s != null) {
try {
jta.setText(FileHelper.readText(s));
jta.setCaretPosition(0);
return;
}
catch (IOException e) {
}
finally {
try {
s.close();
}
catch (IOException e) {
}
}
}
// file reading failed for some reason, fallback to altText
jta.setText(altText);
}
public static void showPopupMenu(JPopupMenu jpm, Component source,
int x, int y, int yOffset)
{
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
screen.height -= POPUP_MENU_HEIGHT_INSET;
Point origin = source.getLocationOnScreen();
origin.translate(x, y);
int height = jpm.getHeight();
if (height == 0) {
jpm.addComponentListener(new SizeListener(source, x, y));
}
int width = jpm.getWidth();
if (origin.x + width > screen.width) {
//x -= (origin.x + width) - screen.width;
// we prefer kde behaviour
x -= width;
}
if (origin.y + height > screen.height) {
// we prefer kde behaviour
//y -= (origin.y + height) - screen.height;
y -= height;
y += yOffset;
}
jpm.show(source, x, y);
}
public static void showPopupMenu(JPopupMenu jpm, Component source,
int x, int y)
{
showPopupMenu(jpm, source, x, y, 0);
}
/**
* Wraps HTML tags around <code>text</code> so the maximum width
* is limited to a senseful value.
*
* @return text, enclosed in table html tags
*/
public static String label(String text)
{
return tt(text, 500);
}
/**
* Wraps HTML tags around <code>text</code> so the maximum width
* is limited to a senseful value.
*
* @return text, enclosed in table html tags
*/
public static String tt(String text, int width)
{
StringBuffer sb = new StringBuffer(33 + text.length() + 25);
sb.append("<html>");
sb.append("<table><tr><td width=\"" + width + "\">");
if (SystemHelper.isJDK13orSmaller) {
sb.append("<font face=\"sansserif,arial,helvetica,tahoma\">");
}
sb.append(text);
if (SystemHelper.isJDK13orSmaller) {
sb.append("</font>");
}
sb.append("</td></tr></table>");
sb.append("</html>");
return sb.toString();
}
/**
* Wraps HTML tags around <code>text</code> so the maximum width
* is limited to a sensible value.
*
* @return text, enclosed in table html tags
*/
public static String tt(String text)
{
return tt(text, 300);
}
/**
* Formats key, value as a HTML table row, the key is highlighted as bold.
*/
public static String tableRow(String key, String value)
{
StringBuffer sb = new StringBuffer();
sb.append("<tr><td><b>");
sb.append(key);
sb.append("</b></td><td> ");
sb.append((value != null) ? value : XNap.tr("Unknown"));
sb.append("</td></tr>");
return sb.toString();
}
public static void limitSize(JComponent c)
{
c.setMaximumSize(new Dimension(c.getPreferredSize().width,
c.getMaximumSize().height));
}
/**
* Adds some Emacs like keybindings to a table for moving between rows.
*/
public static void bindEmacsKeysToTable(JTable jta)
{
ActionListener al =
jta.getActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN,
0));
jta.registerKeyboardAction
(al,KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK),
JComponent.WHEN_FOCUSED);
al = jta.getActionForKeyStroke(KeyStroke.getKeyStroke(KeyEvent.VK_UP,
0));
jta.registerKeyboardAction
(al, KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.CTRL_MASK),
JComponent.WHEN_FOCUSED);
al = jta.getActionForKeyStroke
(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0));
jta.registerKeyboardAction
(al, KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK),
JComponent.WHEN_FOCUSED);
al = jta.getActionForKeyStroke
(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0));
jta.registerKeyboardAction
(al, KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.ALT_MASK),
JComponent.WHEN_FOCUSED);
al = jta.getActionForKeyStroke
(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, InputEvent.CTRL_MASK));
jta.registerKeyboardAction
(al, KeyStroke.getKeyStroke(KeyEvent.VK_LESS, InputEvent.ALT_MASK),
JComponent.WHEN_FOCUSED);
al = jta.getActionForKeyStroke
(KeyStroke.getKeyStroke(KeyEvent.VK_END, InputEvent.CTRL_MASK));
jta.registerKeyboardAction
(al, KeyStroke.getKeyStroke(KeyEvent.VK_LESS, InputEvent.ALT_MASK
+ InputEvent.SHIFT_MASK),
JComponent.WHEN_FOCUSED);
}
}
The table below shows all metrics for GUIHelper.java.




