Java/Tiny Application — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 07:19, 1 июня 2010
- Browser
- Calculator
- Chat
- Database
- Download Manager
- Editor
- Forum
- Game
- Link Checker
- Servlet Application
- Web Server
Содержание
Advanced Font Chooser
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.accessibility.AccessibleContext;
import javax.accessibility.AccessibleRole;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;
import javax.swing.ToolTipManager;
import javax.swing.border.rupoundBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.MatteBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
public class AdvancedFontChooser extends JDialog {
protected int Closed_Option = JOptionPane.CLOSED_OPTION;
protected InputList fontNameInputList = new InputList(fontNames, "Name:");
protected InputList fontSizeInputList = new InputList(fontSizes, "Size:");
protected MutableAttributeSet attributes;
protected JCheckBox boldCheckBox = new JCheckBox("Bold");
protected JCheckBox italicCheckBox = new JCheckBox("Italic");
protected JCheckBox underlineCheckBox = new JCheckBox("Underline");
protected JCheckBox strikethroughCheckBox = new JCheckBox("Strikethrough");
protected JCheckBox subscriptCheckBox = new JCheckBox("Subscript");
protected JCheckBox superscriptCheckBox = new JCheckBox("Superscript");
protected ColorComboBox colorComboBox;
protected FontLabel previewLabel;
public static String[] fontNames;
public static String[] fontSizes;
public AdvancedFontChooser(JFrame owner) {
super(owner, "Font Chooser", false);
getContentPane().setLayout(
new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
JPanel p = new JPanel(new GridLayout(1, 2, 10, 2));
p.setBorder(new TitledBorder(new EtchedBorder(), "Font"));
p.add(fontNameInputList);
fontNameInputList.setDisplayedMnemonic("n");
fontNameInputList.setToolTipText("Font name");
p.add(fontSizeInputList);
fontSizeInputList.setDisplayedMnemonic("s");
fontSizeInputList.setToolTipText("Font size");
getContentPane().add(p);
p = new JPanel(new GridLayout(2, 3, 10, 5));
p.setBorder(new TitledBorder(new EtchedBorder(), "Effects"));
boldCheckBox.setMnemonic("b");
boldCheckBox.setToolTipText("Bold font");
p.add(boldCheckBox);
italicCheckBox.setMnemonic("i");
italicCheckBox.setToolTipText("Italic font");
p.add(italicCheckBox);
underlineCheckBox.setMnemonic("u");
underlineCheckBox.setToolTipText("Underline font");
p.add(underlineCheckBox);
strikethroughCheckBox.setMnemonic("r");
strikethroughCheckBox.setToolTipText("Strikethrough font");
p.add(strikethroughCheckBox);
subscriptCheckBox.setMnemonic("t");
subscriptCheckBox.setToolTipText("Subscript font");
p.add(subscriptCheckBox);
superscriptCheckBox.setMnemonic("p");
superscriptCheckBox.setToolTipText("Superscript font");
p.add(superscriptCheckBox);
getContentPane().add(p);
getContentPane().add(Box.createVerticalStrut(5));
p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
p.add(Box.createHorizontalStrut(10));
JLabel lbl = new JLabel("Color:");
lbl.setDisplayedMnemonic("c");
p.add(lbl);
p.add(Box.createHorizontalStrut(20));
colorComboBox = new ColorComboBox();
lbl.setLabelFor(colorComboBox);
colorComboBox.setToolTipText("Font color");
ToolTipManager.sharedInstance().registerComponent(colorComboBox);
p.add(colorComboBox);
p.add(Box.createHorizontalStrut(10));
getContentPane().add(p);
p = new JPanel(new BorderLayout());
p.setBorder(new TitledBorder(new EtchedBorder(), "Preview"));
previewLabel = new FontLabel("Preview Font");
p.add(previewLabel, BorderLayout.CENTER);
getContentPane().add(p);
p = new JPanel(new FlowLayout());
JPanel p1 = new JPanel(new GridLayout(1, 2, 10, 2));
JButton btOK = new JButton("OK");
btOK.setToolTipText("Save and exit");
getRootPane().setDefaultButton(btOK);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Closed_Option = JOptionPane.OK_OPTION;
dispose();
}
};
btOK.addActionListener(actionListener);
p1.add(btOK);
JButton btCancel = new JButton("Cancel");
btCancel.setToolTipText("Exit without save");
actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Closed_Option = JOptionPane.CANCEL_OPTION;
dispose();
}
};
btCancel.addActionListener(actionListener);
p1.add(btCancel);
p.add(p1);
getContentPane().add(p);
pack();
setResizable(false);
ListSelectionListener listSelectListener = new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
updatePreview();
}
};
fontNameInputList.addListSelectionListener(listSelectListener);
fontSizeInputList.addListSelectionListener(listSelectListener);
actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
updatePreview();
}
};
boldCheckBox.addActionListener(actionListener);
italicCheckBox.addActionListener(actionListener);
colorComboBox.addActionListener(actionListener);
}
public void setAttributes(AttributeSet a) {
attributes = new SimpleAttributeSet(a);
String name = StyleConstants.getFontFamily(a);
fontNameInputList.setSelected(name);
int size = StyleConstants.getFontSize(a);
fontSizeInputList.setSelectedInt(size);
boldCheckBox.setSelected(StyleConstants.isBold(a));
italicCheckBox.setSelected(StyleConstants.isItalic(a));
underlineCheckBox.setSelected(StyleConstants.isUnderline(a));
strikethroughCheckBox.setSelected(StyleConstants.isStrikeThrough(a));
subscriptCheckBox.setSelected(StyleConstants.isSubscript(a));
superscriptCheckBox.setSelected(StyleConstants.isSuperscript(a));
colorComboBox.setSelectedItem(StyleConstants.getForeground(a));
updatePreview();
}
public AttributeSet getAttributes() {
if (attributes == null)
return null;
StyleConstants.setFontFamily(attributes, fontNameInputList
.getSelected());
StyleConstants.setFontSize(attributes, fontSizeInputList
.getSelectedInt());
StyleConstants.setBold(attributes, boldCheckBox.isSelected());
StyleConstants.setItalic(attributes, italicCheckBox.isSelected());
StyleConstants.setUnderline(attributes, underlineCheckBox.isSelected());
StyleConstants.setStrikeThrough(attributes, strikethroughCheckBox
.isSelected());
StyleConstants.setSubscript(attributes, subscriptCheckBox.isSelected());
StyleConstants.setSuperscript(attributes, superscriptCheckBox
.isSelected());
StyleConstants.setForeground(attributes, (Color) colorComboBox
.getSelectedItem());
return attributes;
}
public int getOption() {
return Closed_Option;
}
protected void updatePreview() {
String name = fontNameInputList.getSelected();
int size = fontSizeInputList.getSelectedInt();
if (size <= 0)
return;
int style = Font.PLAIN;
if (boldCheckBox.isSelected())
style |= Font.BOLD;
if (italicCheckBox.isSelected())
style |= Font.ITALIC;
Font fn = new Font(name, style, size);
previewLabel.setFont(fn);
Color c = (Color) colorComboBox.getSelectedItem();
previewLabel.setForeground(c);
previewLabel.repaint();
}
public static void main(String argv[]) {
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
fontNames = ge.getAvailableFontFamilyNames();
fontSizes = new String[] { "8", "9", "10", "11", "12", "14", "16",
"18", "20", "22", "24", "26", "28", "36", "48", "72" };
AdvancedFontChooser dlg = new AdvancedFontChooser(new JFrame());
SimpleAttributeSet a = new SimpleAttributeSet();
StyleConstants.setFontFamily(a, "Monospaced");
StyleConstants.setFontSize(a, 12);
dlg.setAttributes(a);
dlg.show();
}
}
class InputList extends JPanel implements ListSelectionListener, ActionListener {
protected JLabel label = new JLabel();
protected JTextField textfield;
protected JList list;
protected JScrollPane scroll;
public InputList(String[] data, String title) {
setLayout(null);
add(label);
textfield = new OpelListText();
textfield.addActionListener(this);
label.setLabelFor(textfield);
add(textfield);
list = new OpelListList(data);
list.setVisibleRowCount(4);
list.addListSelectionListener(this);
scroll = new JScrollPane(list);
add(scroll);
}
public InputList(String title, int numCols) {
setLayout(null);
label = new OpelListLabel(title, JLabel.LEFT);
add(label);
textfield = new OpelListText(numCols);
textfield.addActionListener(this);
label.setLabelFor(textfield);
add(textfield);
list = new OpelListList();
list.setVisibleRowCount(4);
list.addListSelectionListener(this);
scroll = new JScrollPane(list);
add(scroll);
}
public void setToolTipText(String text) {
super.setToolTipText(text);
label.setToolTipText(text);
textfield.setToolTipText(text);
list.setToolTipText(text);
}
public void setDisplayedMnemonic(char ch) {
label.setDisplayedMnemonic(ch);
}
public void setSelected(String sel) {
list.setSelectedValue(sel, true);
textfield.setText(sel);
}
public String getSelected() {
return textfield.getText();
}
public void setSelectedInt(int value) {
setSelected(Integer.toString(value));
}
public int getSelectedInt() {
try {
return Integer.parseInt(getSelected());
} catch (NumberFormatException ex) {
return -1;
}
}
public void valueChanged(ListSelectionEvent e) {
Object obj = list.getSelectedValue();
if (obj != null)
textfield.setText(obj.toString());
}
public void actionPerformed(ActionEvent e) {
ListModel model = list.getModel();
String key = textfield.getText().toLowerCase();
for (int k = 0; k < model.getSize(); k++) {
String data = (String) model.getElementAt(k);
if (data.toLowerCase().startsWith(key)) {
list.setSelectedValue(data, true);
break;
}
}
}
public void addListSelectionListener(ListSelectionListener lst) {
list.addListSelectionListener(lst);
}
public Dimension getPreferredSize() {
Insets ins = getInsets();
Dimension labelSize = label.getPreferredSize();
Dimension textfieldSize = textfield.getPreferredSize();
Dimension scrollPaneSize = scroll.getPreferredSize();
int w = Math.max(Math.max(labelSize.width, textfieldSize.width),
scrollPaneSize.width);
int h = labelSize.height + textfieldSize.height + scrollPaneSize.height;
return new Dimension(w + ins.left + ins.right, h + ins.top + ins.bottom);
}
public Dimension getMaximumSize() {
return getPreferredSize();
}
public Dimension getMinimumSize() {
return getPreferredSize();
}
public void doLayout() {
Insets ins = getInsets();
Dimension size = getSize();
int x = ins.left;
int y = ins.top;
int w = size.width - ins.left - ins.right;
int h = size.height - ins.top - ins.bottom;
Dimension labelSize = label.getPreferredSize();
label.setBounds(x, y, w, labelSize.height);
y += labelSize.height;
Dimension textfieldSize = textfield.getPreferredSize();
textfield.setBounds(x, y, w, textfieldSize.height);
y += textfieldSize.height;
scroll.setBounds(x, y, w, h - y);
}
public void appendResultSet(ResultSet results, int index,
boolean toTitleCase) {
textfield.setText("");
DefaultListModel model = new DefaultListModel();
try {
while (results.next()) {
String str = results.getString(index);
if (toTitleCase) {
str = Character.toUpperCase(str.charAt(0))
+ str.substring(1);
}
model.addElement(str);
}
} catch (SQLException ex) {
System.err.println("appendResultSet: " + ex.toString());
}
list.setModel(model);
if (model.getSize() > 0)
list.setSelectedIndex(0);
}
class OpelListLabel extends JLabel {
public OpelListLabel(String text, int alignment) {
super(text, alignment);
}
public AccessibleContext getAccessibleContext() {
return InputList.this.getAccessibleContext();
}
}
class OpelListText extends JTextField {
public OpelListText() {
}
public OpelListText(int numCols) {
super(numCols);
}
public AccessibleContext getAccessibleContext() {
return InputList.this.getAccessibleContext();
}
}
class OpelListList extends JList {
public OpelListList() {
}
public OpelListList(String[] data) {
super(data);
}
public AccessibleContext getAccessibleContext() {
return InputList.this.getAccessibleContext();
}
}
// Accessibility Support
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null)
accessibleContext = new AccessibleOpenList();
return accessibleContext;
}
protected class AccessibleOpenList extends AccessibleJComponent {
public String getAccessibleName() {
System.out.println("getAccessibleName: " + accessibleName);
if (accessibleName != null)
return accessibleName;
return label.getText();
}
public AccessibleRole getAccessibleRole() {
return AccessibleRole.LIST;
}
}
}
class FontLabel extends JLabel {
public FontLabel(String text) {
super(text, JLabel.CENTER);
setBackground(Color.white);
setForeground(Color.black);
setOpaque(true);
setBorder(new LineBorder(Color.black));
setPreferredSize(new Dimension(120, 40));
}
}
class ColorComboBox extends JComboBox {
public ColorComboBox() {
int[] values = new int[] { 0, 128, 192, 255 };
for (int r = 0; r < values.length; r++)
for (int g = 0; g < values.length; g++)
for (int b = 0; b < values.length; b++) {
Color c = new Color(values[r], values[g], values[b]);
addItem(c);
}
setRenderer(new ColorComboRenderer1());
}
class ColorComboRenderer1 extends JPanel implements ListCellRenderer {
protected Color m_c = Color.black;
public ColorComboRenderer1() {
super();
setBorder(new CompoundBorder(new MatteBorder(2, 10, 2, 10,
Color.white), new LineBorder(Color.black)));
}
public Component getListCellRendererComponent(JList list, Object obj,
int row, boolean sel, boolean hasFocus) {
if (obj instanceof Color)
m_c = (Color) obj;
return this;
}
public void paint(Graphics g) {
setBackground(m_c);
super.paint(g);
}
}
}
Advanced Font Chooser revised by pole
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.font.TextAttribute;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.accessibility.AccessibleContext;
import javax.accessibility.AccessibleRole;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;
import javax.swing.ToolTipManager;
import javax.swing.border.rupoundBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.MatteBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import static java.awt.font.TextAttribute.*;
public class FontChooserWithPole extends JDialog {
protected int Closed_Option = JOptionPane.CLOSED_OPTION;
protected InputList fontNameInputList = new InputList(fontNames, "Name:");
protected InputList fontSizeInputList = new InputList(fontSizes, "Size:");
protected MutableAttributeSet attributes;
protected JCheckBox boldCheckBox = new JCheckBox("Bold");
protected JCheckBox italicCheckBox = new JCheckBox("Italic");
protected JCheckBox underlineCheckBox = new JCheckBox("Underline");
protected JCheckBox strikethroughCheckBox = new JCheckBox("Strikethrough");
protected JCheckBox subscriptCheckBox = new JCheckBox("Subscript");
protected JCheckBox superscriptCheckBox = new JCheckBox("Superscript");
protected ColorComboBox colorComboBox;
protected FontLabel previewLabel;
public static String[] fontNames;
public static String[] fontSizes;
private static final String PREVIEW_TEXT = "Preview Font";
public FontChooserWithPole(JFrame owner) {
super(owner, "Font Chooser", false);
getContentPane().setLayout(
new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
JPanel p = new JPanel(new GridLayout(1, 2, 10, 2));
p.setBorder(new TitledBorder(new EtchedBorder(), "Font"));
p.add(fontNameInputList);
fontNameInputList.setDisplayedMnemonic("n");
fontNameInputList.setToolTipText("Font name");
p.add(fontSizeInputList);
fontSizeInputList.setDisplayedMnemonic("s");
fontSizeInputList.setToolTipText("Font size");
getContentPane().add(p);
p = new JPanel(new GridLayout(2, 3, 10, 5));
p.setBorder(new TitledBorder(new EtchedBorder(), "Effects"));
boldCheckBox.setMnemonic("b");
boldCheckBox.setToolTipText("Bold font");
p.add(boldCheckBox);
italicCheckBox.setMnemonic("i");
italicCheckBox.setToolTipText("Italic font");
p.add(italicCheckBox);
underlineCheckBox.setMnemonic("u");
underlineCheckBox.setToolTipText("Underline font");
p.add(underlineCheckBox);
strikethroughCheckBox.setMnemonic("r");
strikethroughCheckBox.setToolTipText("Strikethrough font");
p.add(strikethroughCheckBox);
subscriptCheckBox.setMnemonic("t");
subscriptCheckBox.setToolTipText("Subscript font");
p.add(subscriptCheckBox);
superscriptCheckBox.setMnemonic("p");
superscriptCheckBox.setToolTipText("Superscript font");
p.add(superscriptCheckBox);
getContentPane().add(p);
getContentPane().add(Box.createVerticalStrut(5));
p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
p.add(Box.createHorizontalStrut(10));
JLabel lbl = new JLabel("Color:");
lbl.setDisplayedMnemonic("c");
p.add(lbl);
p.add(Box.createHorizontalStrut(20));
colorComboBox = new ColorComboBox();
lbl.setLabelFor(colorComboBox);
colorComboBox.setToolTipText("Font color");
ToolTipManager.sharedInstance().registerComponent(colorComboBox);
p.add(colorComboBox);
p.add(Box.createHorizontalStrut(10));
getContentPane().add(p);
p = new JPanel(new BorderLayout());
p.setBorder(new TitledBorder(new EtchedBorder(), "Preview"));
previewLabel = new FontLabel(PREVIEW_TEXT);
p.add(previewLabel, BorderLayout.CENTER);
getContentPane().add(p);
p = new JPanel(new FlowLayout());
JPanel p1 = new JPanel(new GridLayout(1, 2, 10, 2));
JButton btOK = new JButton("OK");
btOK.setToolTipText("Save and exit");
getRootPane().setDefaultButton(btOK);
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Closed_Option = JOptionPane.OK_OPTION;
dispose();
}
};
btOK.addActionListener(actionListener);
p1.add(btOK);
JButton btCancel = new JButton("Cancel");
btCancel.setToolTipText("Exit without save");
actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Closed_Option = JOptionPane.CANCEL_OPTION;
dispose();
}
};
btCancel.addActionListener(actionListener);
p1.add(btCancel);
p.add(p1);
getContentPane().add(p);
pack();
setResizable(false);
ListSelectionListener listSelectListener = new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
updatePreview();
}
}; fontNameInputList.addListSelectionListener(listSelectListener);
fontSizeInputList.addListSelectionListener(listSelectListener);
actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
updatePreview();
}
};
boldCheckBox.addActionListener(actionListener);
italicCheckBox.addActionListener(actionListener);
colorComboBox.addActionListener(actionListener);
underlineCheckBox.addActionListener(actionListener);
strikethroughCheckBox.addActionListener(actionListener);
subscriptCheckBox.addActionListener(actionListener);
superscriptCheckBox.addActionListener(actionListener);
}
public void setAttributes(AttributeSet a) {
attributes = new SimpleAttributeSet(a);
String name = StyleConstants.getFontFamily(a);
fontNameInputList.setSelected(name);
int size = StyleConstants.getFontSize(a);
fontSizeInputList.setSelectedInt(size);
boldCheckBox.setSelected(StyleConstants.isBold(a));
italicCheckBox.setSelected(StyleConstants.isItalic(a));
underlineCheckBox.setSelected(StyleConstants.isUnderline(a));
strikethroughCheckBox.setSelected(StyleConstants.isStrikeThrough(a));
subscriptCheckBox.setSelected(StyleConstants.isSubscript(a));
superscriptCheckBox.setSelected(StyleConstants.isSuperscript(a));
colorComboBox.setSelectedItem(StyleConstants.getForeground(a));
updatePreview();
}
public AttributeSet getAttributes() {
if (attributes == null)
return null;
StyleConstants.setFontFamily(attributes, fontNameInputList
.getSelected());
StyleConstants.setFontSize(attributes, fontSizeInputList
.getSelectedInt());
StyleConstants.setBold(attributes, boldCheckBox.isSelected());
StyleConstants.setItalic(attributes, italicCheckBox.isSelected());
StyleConstants.setUnderline(attributes, underlineCheckBox.isSelected());
StyleConstants.setStrikeThrough(attributes, strikethroughCheckBox
.isSelected());
StyleConstants.setSubscript(attributes, subscriptCheckBox.isSelected());
StyleConstants.setSuperscript(attributes, superscriptCheckBox
.isSelected());
StyleConstants.setForeground(attributes, (Color) colorComboBox.getSelectedItem());
return attributes;
}
public int getOption() {
return Closed_Option;
}
protected void updatePreview() {
StringBuilder previewText = new StringBuilder(PREVIEW_TEXT);
String name = fontNameInputList.getSelected();
int size = fontSizeInputList.getSelectedInt();
if (size <= 0)
return;
Map<TextAttribute, Object> attributes = new HashMap<TextAttribute, Object>();
attributes.put(FAMILY, name);
attributes.put(SIZE, (float)size);
// Using HTML to force JLabel manage natively unsupported attributes
if (underlineCheckBox.isSelected() || strikethroughCheckBox.isSelected()){
previewText.insert(0,"<html>");
previewText.append("</html>");
}
if (underlineCheckBox.isSelected()){
attributes.put(UNDERLINE, UNDERLINE_LOW_ONE_PIXEL);
previewText.insert(6,"<u>");
previewText.insert(previewText.length() - 7, "</u>");
}
if (strikethroughCheckBox.isSelected()){
attributes.put(STRIKETHROUGH, STRIKETHROUGH_ON);
previewText.insert(6,"<strike>");
previewText.insert(previewText.length() - 7, "</strike>");
}
if (boldCheckBox.isSelected())
attributes.put(WEIGHT, WEIGHT_BOLD);
if (italicCheckBox.isSelected())
attributes.put(POSTURE, POSTURE_OBLIQUE);
if (subscriptCheckBox.isSelected()){
attributes.put(SUPERSCRIPT, SUPERSCRIPT_SUB);
}
if (superscriptCheckBox.isSelected())
attributes.put(SUPERSCRIPT, SUPERSCRIPT_SUPER);
superscriptCheckBox.setEnabled(!subscriptCheckBox.isSelected());
subscriptCheckBox.setEnabled(!superscriptCheckBox.isSelected());
Font fn = new Font(attributes);
previewLabel.setText(previewText.toString());
previewLabel.setFont(fn);
Color c = (Color) colorComboBox.getSelectedItem();
previewLabel.setForeground(c);
previewLabel.repaint();
}
public static void main(String argv[]) {
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
fontNames = ge.getAvailableFontFamilyNames();
fontSizes = new String[] { "8", "9", "10", "11", "12", "14", "16",
"18", "20", "22", "24", "26", "28", "36", "48", "72" };
FontChooserWithPole dlg = new FontChooserWithPole(new JFrame());
SimpleAttributeSet a = new SimpleAttributeSet();
StyleConstants.setFontFamily(a, "Monospaced");
StyleConstants.setFontSize(a, 12);
dlg.setAttributes(a);
dlg.setVisible(true);
}
}
class InputList extends JPanel implements ListSelectionListener, ActionListener {
protected JLabel label = new JLabel();
protected JTextField textfield;
protected JList list;
protected JScrollPane scroll;
public InputList(String[] data, String title) {
setLayout(null);
add(label);
textfield = new OpelListText();
textfield.addActionListener(this);
label.setLabelFor(textfield);
add(textfield);
list = new OpelListList(data);
list.setVisibleRowCount(4);
list.addListSelectionListener(this);
scroll = new JScrollPane(list);
add(scroll);
}
public InputList(String title, int numCols) {
setLayout(null);
label = new OpelListLabel(title, JLabel.LEFT);
add(label);
textfield = new OpelListText(numCols);
textfield.addActionListener(this);
label.setLabelFor(textfield);
add(textfield);
list = new OpelListList();
list.setVisibleRowCount(4);
list.addListSelectionListener(this);
scroll = new JScrollPane(list);
add(scroll);
}
public void setToolTipText(String text) {
super.setToolTipText(text);
label.setToolTipText(text);
textfield.setToolTipText(text);
list.setToolTipText(text);
}
public void setDisplayedMnemonic(char ch) {
label.setDisplayedMnemonic(ch);
}
public void setSelected(String sel) {
list.setSelectedValue(sel, true);
textfield.setText(sel);
}
public String getSelected() {
return textfield.getText();
}
public void setSelectedInt(int value) {
setSelected(Integer.toString(value));
}
public int getSelectedInt() {
try {
return Integer.parseInt(getSelected());
} catch (NumberFormatException ex) {
return -1;
}
}
public void valueChanged(ListSelectionEvent e) {
Object obj = list.getSelectedValue();
if (obj != null)
textfield.setText(obj.toString());
}
public void actionPerformed(ActionEvent e) {
ListModel model = list.getModel();
String key = textfield.getText().toLowerCase();
for (int k = 0; k < model.getSize(); k++) {
String data = (String) model.getElementAt(k);
if (data.toLowerCase().startsWith(key)) {
list.setSelectedValue(data, true);
break;
}
}
}
public void addListSelectionListener(ListSelectionListener lst) {
list.addListSelectionListener(lst);
}
public Dimension getPreferredSize() {
Insets ins = getInsets();
Dimension labelSize = label.getPreferredSize();
Dimension textfieldSize = textfield.getPreferredSize();
Dimension scrollPaneSize = scroll.getPreferredSize();
int w = Math.max(Math.max(labelSize.width, textfieldSize.width),
scrollPaneSize.width);
int h = labelSize.height + textfieldSize.height + scrollPaneSize.height;
return new Dimension(w + ins.left + ins.right, h + ins.top + ins.bottom);
}
public Dimension getMaximumSize() {
return getPreferredSize();
}
public Dimension getMinimumSize() {
return getPreferredSize();
}
public void doLayout() {
Insets ins = getInsets();
Dimension size = getSize();
int x = ins.left;
int y = ins.top;
int w = size.width - ins.left - ins.right;
int h = size.height - ins.top - ins.bottom;
Dimension labelSize = label.getPreferredSize();
label.setBounds(x, y, w, labelSize.height);
y += labelSize.height;
Dimension textfieldSize = textfield.getPreferredSize();
textfield.setBounds(x, y, w, textfieldSize.height);
y += textfieldSize.height;
scroll.setBounds(x, y, w, h - y);
}
public void appendResultSet(ResultSet results, int index,
boolean toTitleCase) {
textfield.setText("");
DefaultListModel model = new DefaultListModel();
try {
while (results.next()) {
String str = results.getString(index);
if (toTitleCase) {
str = Character.toUpperCase(str.charAt(0))
+ str.substring(1);
}
model.addElement(str);
}
} catch (SQLException ex) {
System.err.println("appendResultSet: " + ex.toString());
}
list.setModel(model);
if (model.getSize() > 0)
list.setSelectedIndex(0);
}
class OpelListLabel extends JLabel {
public OpelListLabel(String text, int alignment) {
super(text, alignment);
}
public AccessibleContext getAccessibleContext() {
return InputList.this.getAccessibleContext();
}
}
class OpelListText extends JTextField {
public OpelListText() {
}
public OpelListText(int numCols) {
super(numCols);
}
public AccessibleContext getAccessibleContext() {
return InputList.this.getAccessibleContext();
}
}
class OpelListList extends JList {
public OpelListList() {
}
public OpelListList(String[] data) {
super(data);
}
public AccessibleContext getAccessibleContext() {
return InputList.this.getAccessibleContext();
}
}
// Accessibility Support
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null)
accessibleContext = new AccessibleOpenList();
return accessibleContext;
}
protected class AccessibleOpenList extends AccessibleJComponent {
public String getAccessibleName() {
System.out.println("getAccessibleName: " + accessibleName);
if (accessibleName != null)
return accessibleName;
return label.getText();
}
public AccessibleRole getAccessibleRole() {
return AccessibleRole.LIST;
}
}
}
class FontLabel extends JLabel {
public FontLabel(String text) {
super(text, JLabel.CENTER);
setBackground(Color.white);
setForeground(Color.black);
setOpaque(true);
setBorder(new LineBorder(Color.black));
setPreferredSize(new Dimension(120, 40));
}
}
class ColorComboBox extends JComboBox {
public ColorComboBox() {
int[] values = new int[] { 0, 128, 192, 255 };
for (int r = 0; r < values.length; r++)
for (int g = 0; g < values.length; g++)
for (int b = 0; b < values.length; b++) {
Color c = new Color(values[r], values[g], values[b]);
addItem(c);
}
setRenderer(new ColorComboRenderer1());
}
class ColorComboRenderer1 extends JPanel implements ListCellRenderer {
protected Color m_c = Color.black;
public ColorComboRenderer1() {
super();
setBorder(new CompoundBorder(new MatteBorder(2, 10, 2, 10,
Color.white), new LineBorder(Color.black)));
}
public Component getListCellRendererComponent(JList list, Object obj,
int row, boolean sel, boolean hasFocus) {
if (obj instanceof Color)
m_c = (Color) obj;
return this;
}
public void paint(Graphics g) {
setBackground(m_c);
super.paint(g);
}
}
}
A font selection dialog
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
import java.awt.BorderLayout;
import java.awt.Checkbox;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.List;
import java.awt.Panel;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
/**
* A font selection dialog.
* <p>
* Note: can take a long time to start up on systems with (literally) hundreds
* of fonts. TODO change list to JList, add a SelectionChangedListener to
* preview.
*
* @author Ian Darwin
* @version $Id: FontChooser.java,v 1.19 2004/03/20 20:44:56 ian Exp $
*/
public class FontChooser2 extends JDialog {
// Results:
/** The font the user has chosen */
protected Font resultFont;
/** The resulting font name */
protected String resultName;
/** The resulting font size */
protected int resultSize;
/** The resulting boldness */
protected boolean isBold;
/** The resulting italicness */
protected boolean isItalic;
// Working fields
/** Display text */
protected String displayText = "Qwerty Yuiop";
/** The list of Fonts */
protected String fontList[];
/** The font name chooser */
protected List fontNameChoice;
/** The font size chooser */
protected List fontSizeChoice;
/** The bold and italic choosers */
Checkbox bold, italic;
/** The list of font sizes */
protected String fontSizes[] = { "8", "10", "11", "12", "14", "16", "18",
"20", "24", "30", "36", "40", "48", "60", "72" };
/** The index of the default size (e.g., 14 point == 4) */
protected static final int DEFAULT_SIZE = 4;
/**
* The display area. Use a JLabel as the AWT label doesn"t always honor
* setFont() in a timely fashion :-)
*/
protected JLabel previewArea;
/**
* Construct a FontChooser -- Sets title and gets array of fonts on the
* system. Builds a GUI to let the user choose one font at one size.
*/
public FontChooser2(Frame f) {
super(f, "Font Chooser", true);
Container cp = getContentPane();
Panel top = new Panel();
top.setLayout(new FlowLayout());
fontNameChoice = new List(8);
top.add(fontNameChoice);
Toolkit toolkit = Toolkit.getDefaultToolkit();
// For JDK 1.1: returns about 10 names (Serif, SansSerif, etc.)
// fontList = toolkit.getFontList();
// For JDK 1.2: a much longer list; most of the names that come
// with your OS (e.g., Arial), plus the Sun/Java ones (Lucida,
// Lucida Bright, Lucida Sans...)
fontList = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getAvailableFontFamilyNames();
for (int i = 0; i < fontList.length; i++)
fontNameChoice.add(fontList[i]);
fontNameChoice.select(0);
fontSizeChoice = new List(8);
top.add(fontSizeChoice);
for (int i = 0; i < fontSizes.length; i++)
fontSizeChoice.add(fontSizes[i]);
fontSizeChoice.select(DEFAULT_SIZE);
cp.add(top, BorderLayout.NORTH);
Panel attrs = new Panel();
top.add(attrs);
attrs.setLayout(new GridLayout(0, 1));
attrs.add(bold = new Checkbox("Bold", false));
attrs.add(italic = new Checkbox("Italic", false));
previewArea = new JLabel(displayText, JLabel.CENTER);
previewArea.setSize(200, 50);
cp.add(previewArea, BorderLayout.CENTER);
Panel bot = new Panel();
JButton okButton = new JButton("Apply");
bot.add(okButton);
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
previewFont();
dispose();
setVisible(false);
}
});
JButton pvButton = new JButton("Preview");
bot.add(pvButton);
pvButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
previewFont();
}
});
JButton canButton = new JButton("Cancel");
bot.add(canButton);
canButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Set all values to null. Better: restore previous.
resultFont = null;
resultName = null;
resultSize = 0;
isBold = false;
isItalic = false;
dispose();
setVisible(false);
}
});
cp.add(bot, BorderLayout.SOUTH);
previewFont(); // ensure view is up to date!
pack();
setLocation(100, 100);
}
/**
* Called from the action handlers to get the font info, build a font, and
* set it.
*/
protected void previewFont() {
resultName = fontNameChoice.getSelectedItem();
String resultSizeName = fontSizeChoice.getSelectedItem();
int resultSize = Integer.parseInt(resultSizeName);
isBold = bold.getState();
isItalic = italic.getState();
int attrs = Font.PLAIN;
if (isBold)
attrs = Font.BOLD;
if (isItalic)
attrs |= Font.ITALIC;
resultFont = new Font(resultName, attrs, resultSize);
// System.out.println("resultName = " + resultName + "; " +
// "resultFont = " + resultFont);
previewArea.setFont(resultFont);
pack(); // ensure Dialog is big enough.
}
/** Retrieve the selected font name. */
public String getSelectedName() {
return resultName;
}
/** Retrieve the selected size */
public int getSelectedSize() {
return resultSize;
}
/** Retrieve the selected font, or null */
public Font getSelectedFont() {
return resultFont;
}
/** Simple main program to start it running */
public static void main(String[] args) {
final JFrame f = new JFrame("FontChooser Startup");
final FontChooser2 fc = new FontChooser2(f);
final Container cp = f.getContentPane();
cp.setLayout(new GridLayout(0, 1)); // one vertical column
JButton theButton = new JButton("Change font");
cp.add(theButton);
final JLabel theLabel = new JLabel("Java is great!", JLabel.CENTER);
cp.add(theLabel);
// Now that theButton and theLabel are ready, make the action listener
theButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fc.setVisible(true);
Font myNewFont = fc.getSelectedFont();
System.out.println("You chose " + myNewFont);
theLabel.setFont(myNewFont);
f.pack(); // adjust for new size
fc.dispose();
}
});
f.setSize(150, 100);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
FontChooser
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
/*
* Copyright (c) 2000 David Flanagan. All rights reserved.
* This code is from the book Java Examples in a Nutshell, 2nd Edition.
* It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
* You may study, use, and modify it for any non-commercial purpose.
* You may distribute it non-commercially as long as you retain this notice.
* For a commercial use license, or to purchase the book (recommended),
* visit http://www.davidflanagan.ru/javaexamples2.
*/
/**
* This is a JDialog subclass that allows the user to select a font, in any
* style and size, from the list of available fonts on the system. The dialog is
* modal. Display it with show(); this method does not return until the user
* dismisses the dialog. When show() returns, call getSelectedFont() to obtain
* the user"s selection. If the user clicked the dialog"s "Cancel" button,
* getSelectedFont() will return null.
*/
public class FontChooser extends JDialog {
// These fields define the component properties
String family; // The name of the font family
int style; // The font style
int size; // The font size
Font selectedFont; // The Font they correspond to
// This is the list of all font families on the system
String[] fontFamilies;
// The various Swing components used in the dialog
ItemChooser families, styles, sizes;
JTextArea preview;
JButton okay, cancel;
// The names to appear in the "Style" menu
static final String[] styleNames = new String[] { "Plain", "Italic",
"Bold", "BoldItalic" };
// The style values that correspond to those names
static final Integer[] styleValues = new Integer[] {
new Integer(Font.PLAIN), new Integer(Font.ITALIC),
new Integer(Font.BOLD), new Integer(Font.BOLD + Font.ITALIC) };
// The size "names" to appear in the size menu
static final String[] sizeNames = new String[] { "8", "10", "12", "14",
"18", "20", "24", "28", "32", "40", "48", "56", "64", "72" };
// This is the default preview string displayed in the dialog box
static final String defaultPreviewString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ\n"
+ "abcdefghijklmnopqrstuvwxyz\n"
+ "1234567890!@#$%^&*()_-=+[]{}<,.>\n"
+ "The quick brown fox jumps over the lazy dog";
/** Create a font chooser dialog for the specified frame. */
public FontChooser(Frame owner) {
super(owner, "Choose a Font"); // Set dialog frame and title
// This dialog must be used as a modal dialog. In order to be used
// as a modeless dialog, it would have to fire a PropertyChangeEvent
// whenever the selected font changed, so that applications could be
// notified of the user"s selections.
setModal(true);
// Figure out what fonts are available on the system
GraphicsEnvironment env = GraphicsEnvironment
.getLocalGraphicsEnvironment();
fontFamilies = env.getAvailableFontFamilyNames();
// Set initial values for the properties
family = fontFamilies[0];
style = Font.PLAIN;
size = 18;
selectedFont = new Font(family, style, size);
// Create ItemChooser objects that allow the user to select font
// family, style, and size.
families = new ItemChooser("Family", fontFamilies, null, 0,
ItemChooser.ruBOBOX);
styles = new ItemChooser("Style", styleNames, styleValues, 0,
ItemChooser.ruBOBOX);
sizes = new ItemChooser("Size", sizeNames, null, 4,
ItemChooser.ruBOBOX);
// Now register event listeners to handle selections
families.addItemChooserListener(new ItemChooser.Listener() {
public void itemChosen(ItemChooser.Event e) {
setFontFamily((String) e.getSelectedValue());
}
});
styles.addItemChooserListener(new ItemChooser.Listener() {
public void itemChosen(ItemChooser.Event e) {
setFontStyle(((Integer) e.getSelectedValue()).intValue());
}
});
sizes.addItemChooserListener(new ItemChooser.Listener() {
public void itemChosen(ItemChooser.Event e) {
setFontSize(Integer.parseInt((String) e.getSelectedValue()));
}
});
// Create a component to preview the font.
preview = new JTextArea(defaultPreviewString, 5, 40);
preview.setFont(selectedFont);
// Create buttons to dismiss the dialog, and set handlers on them
okay = new JButton("Okay");
cancel = new JButton("Cancel");
okay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
hide();
}
});
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectedFont = null;
hide();
}
});
// Put the ItemChoosers in a Box
Box choosersBox = Box.createHorizontalBox();
choosersBox.add(Box.createHorizontalStrut(15));
choosersBox.add(families);
choosersBox.add(Box.createHorizontalStrut(15));
choosersBox.add(styles);
choosersBox.add(Box.createHorizontalStrut(15));
choosersBox.add(sizes);
choosersBox.add(Box.createHorizontalStrut(15));
choosersBox.add(Box.createGlue());
// Put the dismiss buttons in another box
Box buttonBox = Box.createHorizontalBox();
buttonBox.add(Box.createGlue());
buttonBox.add(okay);
buttonBox.add(Box.createGlue());
buttonBox.add(cancel);
buttonBox.add(Box.createGlue());
// Put the choosers at the top, the buttons at the bottom, and
// the preview in the middle.
Container contentPane = getContentPane();
contentPane.add(new JScrollPane(preview), BorderLayout.CENTER);
contentPane.add(choosersBox, BorderLayout.NORTH);
contentPane.add(buttonBox, BorderLayout.SOUTH);
// Set the dialog size based on the component size.
pack();
}
/**
* Call this method after show() to obtain the user"s selection. If the user
* used the "Cancel" button, this will return null
*/
public Font getSelectedFont() {
return selectedFont;
}
// These are other property getter methods
public String getFontFamily() {
return family;
}
public int getFontStyle() {
return style;
}
public int getFontSize() {
return size;
}
// The property setter methods are a little more complicated.
// Note that none of these setter methods update the corresponding
// ItemChooser components as they ought to.
public void setFontFamily(String name) {
family = name;
changeFont();
}
public void setFontStyle(int style) {
this.style = style;
changeFont();
}
public void setFontSize(int size) {
this.size = size;
changeFont();
}
public void setSelectedFont(Font font) {
selectedFont = font;
family = font.getFamily();
style = font.getStyle();
size = font.getSize();
preview.setFont(font);
}
// This method is called when the family, style, or size changes
protected void changeFont() {
selectedFont = new Font(family, style, size);
preview.setFont(selectedFont);
}
// Override this inherited method to prevent anyone from making us modeless
public boolean isModal() {
return true;
}
public static void main(String[] args) {
// Create some components and a FontChooser dialog
final JFrame frame = new JFrame("demo");
final JButton button = new JButton("Push Me!");
final FontChooser chooser = new FontChooser(frame);
// Handle button clicks
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Pop up the dialog
chooser.show();
// Get the user"s selection
Font font = chooser.getSelectedFont();
// If not cancelled, set the button font
if (font != null)
button.setFont(font);
}
});
// Display the demo
frame.getContentPane().add(button);
frame.setSize(200, 100);
frame.show();
}
}
/*
* Copyright (c) 2000 David Flanagan. All rights reserved. This code is from the
* book Java Examples in a Nutshell, 2nd Edition. It is provided AS-IS, WITHOUT
* ANY WARRANTY either expressed or implied. You may study, use, and modify it
* for any non-commercial purpose. You may distribute it non-commercially as
* long as you retain this notice. For a commercial use license, or to purchase
* the book (recommended), visit http://www.davidflanagan.ru/javaexamples2.
*/
/**
* This class is a Swing component that presents a choice to the user. It allows
* the choice to be presented in a JList, in a JComboBox, or with a bordered
* group of JRadioButton components. Additionally, it displays the name of the
* choice with a JLabel. It allows an arbitrary value to be associated with each
* possible choice. Note that this component only allows one item to be selected
* at a time. Multiple selections are not supported.
*/
class ItemChooser extends JPanel {
// These fields hold property values for this component
String name; // The overall name of the choice
String[] labels; // The text for each choice option
Object[] values; // Arbitrary values associated with each option
int selection; // The selected choice
int presentation; // How the choice is presented
// These are the legal values for the presentation field
public static final int LIST = 1;
public static final int COMBOBOX = 2;
public static final int RADIOBUTTONS = 3;
// These components are used for each of the 3 possible presentations
JList list; // One type of presentation
JComboBox combobox; // Another type of presentation
JRadioButton[] radiobuttons; // Yet another type
// The list of objects that are interested in our state
ArrayList listeners = new ArrayList();
// The constructor method sets everything up
public ItemChooser(String name, String[] labels, Object[] values,
int defaultSelection, int presentation) {
// Copy the constructor arguments to instance fields
this.name = name;
this.labels = labels;
this.values = values;
this.selection = defaultSelection;
this.presentation = presentation;
// If no values were supplied, use the labels
if (values == null)
this.values = labels;
// Now create content and event handlers based on presentation type
switch (presentation) {
case LIST:
initList();
break;
case COMBOBOX:
initComboBox();
break;
case RADIOBUTTONS:
initRadioButtons();
break;
}
}
// Initialization for JList presentation
void initList() {
list = new JList(labels); // Create the list
list.setSelectedIndex(selection); // Set initial state
// Handle state changes
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
ItemChooser.this.select(list.getSelectedIndex());
}
});
// Lay out list and name label vertically
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); // vertical
this.add(new JLabel(name)); // Display choice name
this.add(new JScrollPane(list)); // Add the JList
}
// Initialization for JComboBox presentation
void initComboBox() {
combobox = new JComboBox(labels); // Create the combo box
combobox.setSelectedIndex(selection); // Set initial state
// Handle changes to the state
combobox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
ItemChooser.this.select(combobox.getSelectedIndex());
}
});
// Lay out combo box and name label horizontally
this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
this.add(new JLabel(name));
this.add(combobox);
}
// Initialization for JRadioButton presentation
void initRadioButtons() {
// Create an array of mutually exclusive radio buttons
radiobuttons = new JRadioButton[labels.length]; // the array
ButtonGroup radioButtonGroup = new ButtonGroup(); // used for exclusion
ChangeListener listener = new ChangeListener() { // A shared listener
public void stateChanged(ChangeEvent e) {
JRadioButton b = (JRadioButton) e.getSource();
if (b.isSelected()) {
// If we received this event because a button was
// selected, then loop through the list of buttons to
// figure out the index of the selected one.
for (int i = 0; i < radiobuttons.length; i++) {
if (radiobuttons[i] == b) {
ItemChooser.this.select(i);
return;
}
}
}
}
};
// Display the choice name in a border around the buttons
this.setBorder(new TitledBorder(new EtchedBorder(), name));
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
// Create the buttons, add them to the button group, and specify
// the event listener for each one.
for (int i = 0; i < labels.length; i++) {
radiobuttons[i] = new JRadioButton(labels[i]);
if (i == selection)
radiobuttons[i].setSelected(true);
radiobuttons[i].addChangeListener(listener);
radioButtonGroup.add(radiobuttons[i]);
this.add(radiobuttons[i]);
}
}
// These simple property accessor methods just return field values
// These are read-only properties. The values are set by the constructor
// and may not be changed.
public String getName() {
return name;
}
public int getPresentation() {
return presentation;
}
public String[] getLabels() {
return labels;
}
public Object[] getValues() {
return values;
}
/** Return the index of the selected item */
public int getSelectedIndex() {
return selection;
}
/** Return the object associated with the selected item */
public Object getSelectedValue() {
return values[selection];
}
/**
* Set the selected item by specifying its index. Calling this method
* changes the on-screen display but does not generate events.
*/
public void setSelectedIndex(int selection) {
switch (presentation) {
case LIST:
list.setSelectedIndex(selection);
break;
case COMBOBOX:
combobox.setSelectedIndex(selection);
break;
case RADIOBUTTONS:
radiobuttons[selection].setSelected(true);
break;
}
this.selection = selection;
}
/**
* This internal method is called when the selection changes. It stores the
* new selected index, and fires events to any registered listeners. The
* event listeners registered on the JList, JComboBox, or JRadioButtons all
* call this method.
*/
protected void select(int selection) {
this.selection = selection; // Store the new selected index
if (!listeners.isEmpty()) { // If there are any listeners registered
// Create an event object to describe the selection
ItemChooser.Event e = new ItemChooser.Event(this, selection,
values[selection]);
// Loop through the listeners using an Iterator
for (Iterator i = listeners.iterator(); i.hasNext();) {
ItemChooser.Listener l = (ItemChooser.Listener) i.next();
l.itemChosen(e); // Notify each listener of the selection
}
}
}
// These methods are for event listener registration and deregistration
public void addItemChooserListener(ItemChooser.Listener l) {
listeners.add(l);
}
public void removeItemChooserListener(ItemChooser.Listener l) {
listeners.remove(l);
}
/**
* This inner class defines the event type generated by ItemChooser objects
* The inner class name is Event, so the full name is ItemChooser.Event
*/
public static class Event extends java.util.EventObject {
int selectedIndex; // index of the selected item
Object selectedValue; // the value associated with it
public Event(ItemChooser source, int selectedIndex, Object selectedValue) {
super(source);
this.selectedIndex = selectedIndex;
this.selectedValue = selectedValue;
}
public ItemChooser getItemChooser() {
return (ItemChooser) getSource();
}
public int getSelectedIndex() {
return selectedIndex;
}
public Object getSelectedValue() {
return selectedValue;
}
}
/**
* This inner interface must be implemented by any object that wants to be
* notified when the current selection in a ItemChooser component changes.
*/
public interface Listener extends java.util.EventListener {
public void itemChosen(ItemChooser.Event e);
}
/**
* This inner class is a simple demonstration of the ItemChooser component
* It uses command-line arguments as ItemChooser labels and values.
*/
public static class Demo {
public static void main(String[] args) {
// Create a window, arrange to handle close requests
final JFrame frame = new JFrame("ItemChooser Demo");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// A "message line" to display results in
final JLabel msgline = new JLabel(" ");
// Create a panel holding three ItemChooser components
JPanel chooserPanel = new JPanel();
final ItemChooser c1 = new ItemChooser("Choice #1", args, null, 0,
ItemChooser.LIST);
final ItemChooser c2 = new ItemChooser("Choice #2", args, null, 0,
ItemChooser.ruBOBOX);
final ItemChooser c3 = new ItemChooser("Choice #3", args, null, 0,
ItemChooser.RADIOBUTTONS);
// An event listener that displays changes on the message line
ItemChooser.Listener l = new ItemChooser.Listener() {
public void itemChosen(ItemChooser.Event e) {
msgline.setText(e.getItemChooser().getName() + ": "
+ e.getSelectedIndex() + ": "
+ e.getSelectedValue());
}
};
c1.addItemChooserListener(l);
c2.addItemChooserListener(l);
c3.addItemChooserListener(l);
// Instead of tracking every change with a ItemChooser.Listener,
// applications can also just query the current state when
// they need it. Here"s a button that does that.
JButton report = new JButton("Report");
report.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Note the use of multi-line italic HTML text
// with the JOptionPane message dialog box.
String msg = "<html><i>" + c1.getName() + ": "
+ c1.getSelectedValue() + "<br>" + c2.getName()
+ ": " + c2.getSelectedValue() + "<br>"
+ c3.getName() + ": " + c3.getSelectedValue()
+ "</i>";
JOptionPane.showMessageDialog(frame, msg);
}
});
// Add the 3 ItemChooser objects, and the Button to the panel
chooserPanel.add(c1);
chooserPanel.add(c2);
chooserPanel.add(c3);
chooserPanel.add(report);
// Add the panel and the message line to the window
Container contentPane = frame.getContentPane();
contentPane.add(chooserPanel, BorderLayout.CENTER);
contentPane.add(msgline, BorderLayout.SOUTH);
// Set the window size and pop it up.
frame.pack();
frame.show();
}
}
}