diff options
author | Mark Wielaard <mark@gcc.gnu.org> | 2006-05-18 17:29:21 +0000 |
---|---|---|
committer | Mark Wielaard <mark@gcc.gnu.org> | 2006-05-18 17:29:21 +0000 |
commit | 4f9533c7722fa07511a94d005227961f4a4dec23 (patch) | |
tree | 9f9c470de62ee62fba1331a396450d728d2b1fad /libjava/classpath/examples/gnu | |
parent | eaec4980e139903ae9b274d1abcf3a13946603a8 (diff) | |
download | gcc-4f9533c7722fa07511a94d005227961f4a4dec23.zip gcc-4f9533c7722fa07511a94d005227961f4a4dec23.tar.gz gcc-4f9533c7722fa07511a94d005227961f4a4dec23.tar.bz2 |
Imported GNU Classpath 0.90
Imported GNU Classpath 0.90
* scripts/makemake.tcl: LocaleData.java moved to gnu/java/locale.
* sources.am: Regenerated.
* gcj/javaprims.h: Regenerated.
* Makefile.in: Regenerated.
* gcj/Makefile.in: Regenerated.
* include/Makefile.in: Regenerated.
* testsuite/Makefile.in: Regenerated.
* gnu/java/lang/VMInstrumentationImpl.java: New override.
* gnu/java/net/local/LocalSocketImpl.java: Likewise.
* gnu/classpath/jdwp/VMMethod.java: Likewise.
* gnu/classpath/jdwp/VMVirtualMachine.java: Update to latest
interface.
* java/lang/Thread.java: Add UncaughtExceptionHandler.
* java/lang/reflect/Method.java: Implements GenericDeclaration and
isSynthetic(),
* java/lang/reflect/Field.java: Likewise.
* java/lang/reflect/Constructor.java
* java/lang/Class.java: Implements Type, GenericDeclaration,
getSimpleName() and getEnclosing*() methods.
* java/lang/Class.h: Add new public methods.
* java/lang/Math.java: Add signum(), ulp() and log10().
* java/lang/natMath.cc (log10): New function.
* java/security/VMSecureRandom.java: New override.
* java/util/logging/Logger.java: Updated to latest classpath
version.
* java/util/logging/LogManager.java: New override.
From-SVN: r113887
Diffstat (limited to 'libjava/classpath/examples/gnu')
25 files changed, 4269 insertions, 1559 deletions
diff --git a/libjava/classpath/examples/gnu/classpath/examples/awt/AnimationApplet.java b/libjava/classpath/examples/gnu/classpath/examples/awt/AnimationApplet.java new file mode 100644 index 0000000..9d3b7ce --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/awt/AnimationApplet.java @@ -0,0 +1,233 @@ +/* AnimationApplet.java -- An example of an old-style AWT applet + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath 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; either version 2, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. */ + +package gnu.classpath.examples.awt; + +import java.awt.*; +import java.awt.event.*; +import java.applet.*; + + +/** + * AnimationApplet demonstrates the need for Xflush calls in + * GdkGraphics.c. To see how this demo can fail in their absence, + * remove the contents of schedule_flush in GdkGraphics.c. The + * animation will be so choppy that it is effectively stopped. + */ +public class AnimationApplet + extends Applet + implements Runnable +{ + boolean going = false; + Thread animThread = null; + int SPEED = 5; + int circleX = 0; + int circleY = 0; + int circleXold = 0; + int circleYold = 0; + int circleXdelta = 0; + int circleYdelta = 0; + int circleDiameter = 0; + int autoCircleX = 0; + int autoCircleY = 0; + int autoCircleXold = 0; + int autoCircleYold = 0; + int autoCircleXdelta = (int) (0.66 * SPEED); + int autoCircleYdelta = (int) (1.33 * SPEED); + int boardWidth = 0; + int boardHeight = 0; + int CIRCLE_SIZE = 5; + + private Graphics appletGraphics; + + // Update the circles' location values. + private void moveCircles() + { + circleX += circleXdelta; + if (circleX < 0) + circleX = 0; + if (circleX > boardWidth - circleDiameter) + circleX = boardWidth - circleDiameter; + + circleY += circleYdelta; + if (circleY < 0) + circleY = 0; + if (circleY > boardHeight - circleDiameter) + circleY = boardHeight - circleDiameter; + + autoCircleX += autoCircleXdelta; + if (autoCircleX < 0) + { + autoCircleX = 0; + autoCircleXdelta = -autoCircleXdelta; + } + if (autoCircleX > boardWidth - circleDiameter) + { + autoCircleX = boardWidth - circleDiameter; + autoCircleXdelta = -autoCircleXdelta; + } + + autoCircleY += autoCircleYdelta; + if (autoCircleY < 0) + { + autoCircleY = 0; + autoCircleYdelta = -autoCircleYdelta; + } + if (autoCircleY > boardHeight - circleDiameter) + { + autoCircleY = boardHeight - circleDiameter; + autoCircleYdelta = -autoCircleYdelta; + } + } + + // Clear the circle in the old location and paint a new circle + // in the new location. + private void paintCircles() + { + appletGraphics.setColor(Color.BLUE); + appletGraphics.fillOval(circleXold, circleYold, circleDiameter, + circleDiameter); + appletGraphics.setColor(Color.YELLOW); + appletGraphics.fillOval(circleX, circleY, circleDiameter, + circleDiameter); + + appletGraphics.setColor(Color.BLUE); + appletGraphics.fillOval(autoCircleXold, autoCircleYold, circleDiameter, + circleDiameter); + appletGraphics.setColor(Color.WHITE); + appletGraphics.fillOval(autoCircleX, autoCircleY, circleDiameter, + circleDiameter); + } + + // Override Applet.run. + public void run() + { + while (animThread != null) + { + circleXold = circleX; + circleYold = circleY; + autoCircleXold = autoCircleX; + autoCircleYold = autoCircleY; + + moveCircles(); + paintCircles(); + + if (animThread != null) + { + try + { + Thread.sleep(20); + } + catch (InterruptedException e) + { + } + } + } + } + + // Override Applet.paint. + public void paint(Graphics g) + { + boardWidth = this.getSize().width; + boardHeight = this.getSize().height; + g.setColor(Color.BLUE); + g.fillRect(0, 0, boardWidth, boardHeight); + if (!going) + { + FontMetrics fm = appletGraphics.getFontMetrics(); + appletGraphics.setColor(Color.WHITE); + String msg = "Click to Start"; + appletGraphics.drawString(msg, + (boardWidth >> 1) - (fm.stringWidth(msg) >> 1), + (boardHeight >> 1) - (fm.getHeight() >> 1)); + } + } + + // Override Applet.destroy. + public void destroy() + { + // animThread.stop(); + animThread = null; + } + + // Override Applet.init. + public void init() + { + boardWidth = this.getSize().width; + boardHeight = this.getSize().height; + going = false; + appletGraphics = getGraphics(); + appletGraphics.setFont(new Font(appletGraphics.getFont().getName(), + Font.BOLD, 15)); + } + + // Override Component.preferredSize for when we're run standalone. + public Dimension preferredSize () + { + return new Dimension (400, 400); + } + + // Override Applet.handleEvent, the old-style AWT-event handler. + public boolean handleEvent(Event event) + { + switch (event.id) + { + case Event.MOUSE_DOWN: + if (!going) + { + going = true; + circleDiameter = boardWidth / CIRCLE_SIZE; + circleX = (boardWidth - circleDiameter) >> 1; + circleY = (boardHeight - circleDiameter) >> 1; + circleXdelta = 0; + circleYdelta = 0; + repaint(); + animThread = new Thread(this); + animThread.start(); + } + break; + case Event.KEY_ACTION: + case Event.KEY_PRESS: + if (event.key == Event.LEFT) + circleXdelta = -SPEED; + else if (event.key == Event.RIGHT) + circleXdelta = SPEED; + else if (event.key == Event.UP) + circleYdelta = -SPEED; + else if (event.key == Event.DOWN) + circleYdelta = SPEED; + break; + case Event.KEY_ACTION_RELEASE: + case Event.KEY_RELEASE: + if (event.key == Event.LEFT && circleXdelta < 0) + circleXdelta = 0; + else if (event.key == Event.RIGHT && circleXdelta > 0) + circleXdelta = 0; + else if (event.key == Event.UP && circleYdelta < 0) + circleYdelta = 0; + else if (event.key == Event.DOWN && circleYdelta > 0) + circleYdelta = 0; + break; + default: + break; + } + return false; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/awt/Demo.java b/libjava/classpath/examples/gnu/classpath/examples/awt/Demo.java index dbb6600..64594e4 100644 --- a/libjava/classpath/examples/gnu/classpath/examples/awt/Demo.java +++ b/libjava/classpath/examples/gnu/classpath/examples/awt/Demo.java @@ -1,5 +1,5 @@ /* Demo.java -- Shows examples of AWT components - Copyright (C) 1998, 1999, 2002, 2004 Free Software Foundation, Inc. + Copyright (C) 1998, 1999, 2002, 2004, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath examples. @@ -153,7 +153,8 @@ class Demo addSubWindow ("TextField", new TextFieldWindow ()); addSubWindow ("RandomTests", new TestWindow (this)); addSubWindow ("RoundRect", new RoundRectWindow ()); - + addSubWindow ("Animation", new AnimationWindow ()); + Panel sp = new Panel(); PrettyPanel p = new PrettyPanel(); p.setLayout (new GridLayout (windows.size(), 1)); @@ -864,4 +865,35 @@ class Demo } } + static class AnimationWindow extends SubFrame + { + AnimationApplet a; + public void init () + { + initted = true; + setTitle("Animation"); + Button cb = new Button ("Close"); + cb.addActionListener(new ActionListener () { + public void actionPerformed (ActionEvent e) + { + if (a != null) + { + a.destroy(); + dispose(); + } + } + }); + a = new AnimationApplet(); + add(a, "Center"); + add(cb, "South"); + pack(); + } + + public void show() + { + super.show(); + a.init(); + a.run(); + } + } } diff --git a/libjava/classpath/examples/gnu/classpath/examples/icons/badge.png b/libjava/classpath/examples/gnu/classpath/examples/icons/badge.png Binary files differnew file mode 100644 index 0000000..2f80ad9 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/icons/badge.png diff --git a/libjava/classpath/examples/gnu/classpath/examples/print/Demo.java b/libjava/classpath/examples/gnu/classpath/examples/print/Demo.java new file mode 100644 index 0000000..0f6a5c8 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/print/Demo.java @@ -0,0 +1,391 @@ +/* Demo.java -- Simple Java Print Service Demo + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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; either version 2, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.print; + +import java.awt.BorderLayout; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.util.HashSet; +import java.util.Iterator; + +import javax.print.DocFlavor; +import javax.print.DocPrintJob; +import javax.print.PrintException; +import javax.print.PrintService; +import javax.print.PrintServiceLookup; +import javax.print.ServiceUI; +import javax.print.SimpleDoc; +import javax.print.attribute.Attribute; +import javax.print.attribute.HashPrintRequestAttributeSet; +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JFileChooser; +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.JTabbedPane; +import javax.swing.JTextField; + + +/** + * A simple demo showing the use of the Java Print Service API. + * @author Wolfgang Baer (WBaer@gmx.de) + */ +public class Demo extends JFrame + implements ActionListener +{ + // The discovered print services + private static PrintService[] services; + + // variables for the PrintPanel demo + private HashPrintRequestAttributeSet atts; + private PrintService dialogSelectedService; + private JTextField dialogSelectedService_Tf; + private JList dialogSelectedServiceAtts; + private JComboBox dialogSelectedServicedocFormat; + private JTextField selectedFileTf; + private File selectedFile; + + // variables for the PrintServicePanel demo + private JComboBox serviceBox; + private JList docFormat; + private JList attCategories; + + static + { + // lookup all services without any constraints + services = PrintServiceLookup.lookupPrintServices(null, null); + } + + /** + * Constructs the Print Demo + * @param title - the demo title. + */ + public Demo(String title) + { + super(title); + JPanel content = new JPanel(new BorderLayout()); + + JTabbedPane tabbed = new JTabbedPane(); + tabbed.addTab("Discover print services", createPrintServicePanel()); + tabbed.addTab("Print a file", createPrintPanel()); + + JPanel closePanel = new JPanel(); + JButton closeButton = new JButton("Close"); + closeButton.setActionCommand("CLOSE"); + closeButton.addActionListener(this); + closePanel.add(closeButton); + + content.add(tabbed, BorderLayout.CENTER); + content.add(closePanel, BorderLayout.SOUTH); + getContentPane().add(content); + } + + private JPanel createPrintServicePanel() + { + JPanel panel = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + + c.insets = new Insets(5,5,5,5); + c.gridx = 0; + c.gridy = 0; + c.anchor = GridBagConstraints.WEST; + c.fill = GridBagConstraints.HORIZONTAL; + JLabel serviceBoxLb = new JLabel("Available print services: "); + panel.add(serviceBoxLb, c); + + c.gridx = 1; + c.gridy = 0; + serviceBox = new JComboBox(services); + serviceBox.setActionCommand("SERVICE"); + serviceBox.addActionListener(this); + panel.add(serviceBox, c); + + c.gridx = 0; + c.gridy = 1; + JLabel docFormatLb = new JLabel("Supported DocFormat: "); + panel.add(docFormatLb, c); + + c.gridx = 1; + c.gridy = 1; + docFormat = new JList(services[0].getSupportedDocFlavors()); + docFormat.setVisibleRowCount(3); + JScrollPane scrollPane = new JScrollPane(docFormat); + panel.add(scrollPane, c); + + c.gridx = 0; + c.gridy = 2; + JLabel categoriesLb = new JLabel("Supported Attribute categories: "); + panel.add(categoriesLb, c); + + c.gridx = 1; + c.gridy = 2; + attCategories = new JList(services[0].getSupportedAttributeCategories()); + attCategories.setVisibleRowCount(3); + JScrollPane scrollPane2 = new JScrollPane(attCategories); + panel.add(scrollPane2, c); + + return panel; + } + + private JPanel createPrintPanel() + { + JPanel panel = new JPanel(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + + c.insets = new Insets(5,5,5,5); + c.gridx = 0; + c.gridy = 0; + c.gridwidth = 2; + JButton serviceBtn = new JButton("Show print dialog ..."); + serviceBtn.addActionListener(this); + panel.add(serviceBtn, c); + + c.gridx = 0; + c.gridy = 1; + c.gridwidth = 1; + c.anchor = GridBagConstraints.WEST; + c.fill = GridBagConstraints.HORIZONTAL; + JLabel selectedLb = new JLabel("Selected print service: "); + panel.add(selectedLb, c); + + c.gridx = 1; + c.gridy = 1; + dialogSelectedService_Tf = new JTextField(25); + panel.add(dialogSelectedService_Tf, c); + + c.gridx = 0; + c.gridy = 2; + JLabel selectedAttsLb = new JLabel("Selected Attributes: "); + panel.add(selectedAttsLb, c); + + c.gridx = 1; + c.gridy = 2; + c.weighty = 1.5; + c.fill = GridBagConstraints.BOTH; + dialogSelectedServiceAtts = new JList(); + dialogSelectedServiceAtts.setVisibleRowCount(3); + JScrollPane scrollPane = new JScrollPane(dialogSelectedServiceAtts); + panel.add(scrollPane, c); + + c.gridx = 0; + c.gridy = 3; + c.fill = GridBagConstraints.HORIZONTAL; + JLabel fileLb = new JLabel("File to print: "); + panel.add(fileLb, c); + + c.gridx = 1; + c.gridy = 3; + selectedFileTf = new JTextField(25); + panel.add(selectedFileTf, c); + + c.gridx = 2; + c.gridy = 3; + c.fill = GridBagConstraints.NONE; + JButton fileBt = new JButton("Choose file"); + fileBt.addActionListener(this); + panel.add(fileBt, c); + + c.gridx = 0; + c.gridy = 4; + c.fill = GridBagConstraints.HORIZONTAL; + JLabel docFormatLb = new JLabel("Document format of file: "); + panel.add(docFormatLb, c); + + c.gridx = 1; + c.gridy = 4; + dialogSelectedServicedocFormat = new JComboBox(); + panel.add(dialogSelectedServicedocFormat, c); + + c.gridx = 0; + c.gridy = 5; + c.gridwidth = 2; + c.anchor = GridBagConstraints.CENTER; + c.fill = GridBagConstraints.NONE; + JButton printBt = new JButton("Print"); + printBt.setActionCommand("PRINT"); + printBt.addActionListener(this); + panel.add(printBt, c); + + return panel; + } + + /** + * Simple action control - only one listener + * @param event + */ + public void actionPerformed(ActionEvent event) + { + if (event.getActionCommand().equals("CLOSE")) + { + System.exit(0); + } + else if (event.getActionCommand().equals("Choose file")) + { + JFileChooser chooser = new JFileChooser(); + chooser.showOpenDialog(this); + + selectedFile = chooser.getSelectedFile(); + + if (selectedFile != null) + selectedFileTf.setText(selectedFile.getName()); + else + selectedFileTf.setText("None selected"); + } + else if (event.getActionCommand().equals("Show print dialog ...")) + { + atts = new HashPrintRequestAttributeSet(); + dialogSelectedService = ServiceUI.printDialog(null, 50, 50, services, + null, null, atts); + + if (dialogSelectedService != null) + { + dialogSelectedService_Tf.setText(dialogSelectedService.getName()); + + // we do not want to have the class representation in the dialog + // as we later always use an InputStream to open the file selected + + // use set to remove duplicates + DocFlavor[] docflavors = dialogSelectedService.getSupportedDocFlavors(); + HashSet set = new HashSet(); + for (int i=0; i < docflavors.length; i++) + { + String charset = docflavors[i].getParameter("charset"); + String mimetype = docflavors[i].getMediaType() + "/" + docflavors[i].getMediaSubtype(); + if (charset != null) + mimetype += "; charset=" + charset; + set.add(mimetype); + } + + dialogSelectedServicedocFormat.removeAllItems(); + for (Iterator it = set.iterator(); it.hasNext(); ) + dialogSelectedServicedocFormat.addItem(it.next()); + } + else + dialogSelectedService_Tf.setText("None selected"); + + Attribute[] attsArray = atts.toArray(); + String[] attsSTr = new String[attsArray.length]; + for (int i = 0; i < attsSTr.length; i++) + attsSTr[i] = attsArray[i].getName() + " - " + attsArray[i].toString(); + + dialogSelectedServiceAtts.setListData(attsSTr); + + validate(); + } + else if (event.getActionCommand().equals("PRINT")) + { + if (selectedFile != null && dialogSelectedService != null) + { + DocPrintJob job = dialogSelectedService.createPrintJob(); + + // choose correct docflavor + String mimetype = (String) dialogSelectedServicedocFormat.getSelectedItem(); + + DocFlavor flavor = null; + if (mimetype.equals(DocFlavor.INPUT_STREAM.GIF.getMimeType())) + flavor = DocFlavor.INPUT_STREAM.GIF; + else if (mimetype.equals(DocFlavor.INPUT_STREAM.AUTOSENSE.getMimeType())) + flavor = DocFlavor.INPUT_STREAM.AUTOSENSE; + else if (mimetype.equals(DocFlavor.INPUT_STREAM.JPEG.getMimeType())) + flavor = DocFlavor.INPUT_STREAM.JPEG; + else if (mimetype.equals(DocFlavor.INPUT_STREAM.PCL.getMimeType())) + flavor = DocFlavor.INPUT_STREAM.PCL; + else if (mimetype.equals(DocFlavor.INPUT_STREAM.PDF.getMimeType())) + flavor = DocFlavor.INPUT_STREAM.PDF; + else if (mimetype.equals(DocFlavor.INPUT_STREAM.PNG.getMimeType())) + flavor = DocFlavor.INPUT_STREAM.PNG; + else if (mimetype.equals(DocFlavor.INPUT_STREAM.POSTSCRIPT.getMimeType())) + flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT; + else if (mimetype.equals(DocFlavor.INPUT_STREAM.TEXT_HTML_HOST.getMimeType())) + flavor = DocFlavor.INPUT_STREAM.TEXT_HTML_HOST; + else if (mimetype.equals(DocFlavor.INPUT_STREAM.TEXT_PLAIN_HOST.getMimeType())) + flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_HOST; + else + flavor = new DocFlavor(mimetype, "java.io.InputStream"); + + try + { + SimpleDoc doc = new SimpleDoc(new FileInputStream(selectedFile), flavor, null); + job.print(doc, atts); + } + catch (FileNotFoundException e) + { + JOptionPane.showMessageDialog(this, "The file was not found."); + e.printStackTrace(); + } + catch (PrintException e) + { + JOptionPane.showMessageDialog(this, e, "PrintException", JOptionPane.ERROR_MESSAGE); + e.printStackTrace(); + } + } + else + JOptionPane.showMessageDialog(this, "Please select a file to print using the FileChooser", "No file selected", JOptionPane.INFORMATION_MESSAGE); + } + else if (event.getActionCommand().equals("SERVICE")) + { // A new service was selected + PrintService selected = (PrintService) serviceBox.getSelectedItem(); + + DocFlavor[] flavors = selected.getSupportedDocFlavors(); + docFormat.setListData(flavors); + attCategories.setListData(selected.getSupportedAttributeCategories()); + } + } + + /** + * Main method. + * @param args - nothing defined. + */ + public static void main(String[] args) + { + Demo app = new Demo("GNU Classpath printing demo"); + app.pack(); + app.setVisible(true); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/ButtonDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/ButtonDemo.java index 856917f..1c6dfa0 100644 --- a/libjava/classpath/examples/gnu/classpath/examples/swing/ButtonDemo.java +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/ButtonDemo.java @@ -31,22 +31,22 @@ import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBox; +import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JToggleButton; import javax.swing.SwingConstants; +import javax.swing.SwingUtilities; import javax.swing.plaf.metal.MetalIconFactory; /** * A simple button demo showing various buttons in different states. */ public class ButtonDemo - extends JFrame + extends JPanel implements ActionListener { - - private JPanel content; private JCheckBox buttonState; private JButton button1; @@ -72,13 +72,10 @@ public class ButtonDemo /** * Creates a new demo instance. - * - * @param title the frame title. */ - public ButtonDemo(String title) + public ButtonDemo() { - super(title); - JPanel content = createContent(); + createContent(); // initFrameContent() is only called (from main) when running this app // standalone } @@ -90,15 +87,14 @@ public class ButtonDemo * only the demo content panel is used, the frame itself is never displayed, * so we can avoid this step. */ - public void initFrameContent() + void initFrameContent() { JPanel closePanel = new JPanel(); JButton closeButton = new JButton("Close"); closeButton.setActionCommand("CLOSE"); closeButton.addActionListener(this); closePanel.add(closeButton); - content.add(closePanel, BorderLayout.SOUTH); - getContentPane().add(content); + add(closePanel, BorderLayout.SOUTH); } /** @@ -108,19 +104,15 @@ public class ButtonDemo * bottom of the panel if they want to (a close button is * added if this demo is being run as a standalone demo). */ - JPanel createContent() + private void createContent() { - if (content == null) - { - content = new JPanel(new BorderLayout()); - JPanel panel = new JPanel(new GridLayout(4, 1)); - panel.add(createButtonPanel()); - panel.add(createTogglePanel()); - panel.add(createCheckBoxPanel()); - panel.add(createRadioPanel()); - content.add(panel); - } - return content; + setLayout(new BorderLayout()); + JPanel panel = new JPanel(new GridLayout(4, 1)); + panel.add(createButtonPanel()); + panel.add(createTogglePanel()); + panel.add(createCheckBoxPanel()); + panel.add(createRadioPanel()); + add(panel); } private JPanel createButtonPanel() @@ -294,10 +286,34 @@ public class ButtonDemo public static void main(String[] args) { - ButtonDemo app = new ButtonDemo("Button Demo"); - app.initFrameContent(); - app.pack(); - app.setVisible(true); + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + ButtonDemo app = new ButtonDemo(); + app.initFrameContent(); + JFrame frame = new JFrame("ButtonDemo"); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + } + }); } + /** + * Returns a DemoFactory that creates a ButtonDemo. + * + * @return a DemoFactory that creates a ButtonDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new ButtonDemo(); + } + }; + } } diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/ClasspathSwingActivityBoard.launch b/libjava/classpath/examples/gnu/classpath/examples/swing/ClasspathSwingActivityBoard.launch deleted file mode 100644 index 7d041a0..0000000 --- a/libjava/classpath/examples/gnu/classpath/examples/swing/ClasspathSwingActivityBoard.launch +++ /dev/null @@ -1,19 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<launchConfiguration type="org.eclipse.cdt.launch.localCLaunch"> -<stringAttribute key="org.eclipse.cdt.launch.DEBUGGER_ID" value="org.eclipse.cdt.debug.mi.core.CDebugger"/> -<stringAttribute key="org.eclipse.cdt.launch.protocol" value="mi"/> -<booleanAttribute key="org.eclipse.cdt.debug.mi.core.STOP_ON_SOLIB_EVENTS" value="false"/> -<stringAttribute key="org.eclipse.cdt.launch.DEBUGGER_START_MODE" value="run"/> -<listAttribute key="org.eclipse.cdt.debug.mi.core.SOLIB_PATH"/> -<booleanAttribute key="org.eclipse.debug.core.appendEnvironmentVariables" value="true"/> -<booleanAttribute key="org.eclipse.cdt.launch.ENABLE_REGISTER_BOOKKEEPING" value="false"/> -<booleanAttribute key="org.eclipse.cdt.debug.mi.core.AUTO_SOLIB" value="true"/> -<booleanAttribute key="org.eclipse.cdt.launch.DEBUGGER_STOP_AT_MAIN" value="true"/> -<booleanAttribute key="org.eclipse.cdt.launch.use_terminal" value="true"/> -<stringAttribute key="org.eclipse.cdt.launch.PROJECT_ATTR" value="jamvm"/> -<booleanAttribute key="org.eclipse.cdt.launch.ENABLE_VARIABLE_BOOKKEEPING" value="false"/> -<stringAttribute key="org.eclipse.cdt.debug.mi.core.DEBUG_NAME" value="gdb"/> -<stringAttribute key="org.eclipse.cdt.launch.PROGRAM_NAME" value="src/jamvm"/> -<stringAttribute key="org.eclipse.cdt.launch.PROGRAM_ARGUMENTS" value="-Dswing.defaultlaf=javax.swing.plaf.metal.MetalLookAndFeel gnu.classpath.examples.swing.Demo"/> -<stringAttribute key="org.eclipse.cdt.debug.mi.core.GDB_INIT" value=""/> -</launchConfiguration> diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/ComboBoxDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/ComboBoxDemo.java index 2af619c..61dee06 100644 --- a/libjava/classpath/examples/gnu/classpath/examples/swing/ComboBoxDemo.java +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/ComboBoxDemo.java @@ -37,17 +37,18 @@ import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; +import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JPanel; -import javax.swing.UIManager; +import javax.swing.SwingUtilities; import javax.swing.plaf.metal.MetalIconFactory; /** * A simple demo showing various combo boxes in different states. */ public class ComboBoxDemo - extends JFrame + extends JPanel implements ActionListener { @@ -69,7 +70,6 @@ public class ComboBoxDemo } } - private JPanel content; private JCheckBox comboState1; private JComboBox combo1; private JComboBox combo2; @@ -96,15 +96,11 @@ public class ComboBoxDemo /** * Creates a new demo instance. - * - * @param title the frame title. */ - public ComboBoxDemo(String title) + public ComboBoxDemo() { - super(title); - JPanel content = createContent(); - // initFrameContent() is only called (from main) when running this app - // standalone + super(); + createContent(); } /** @@ -114,15 +110,14 @@ public class ComboBoxDemo * only the demo content panel is used, the frame itself is never displayed, * so we can avoid this step. */ - public void initFrameContent() + void initFrameContent() { JPanel closePanel = new JPanel(); JButton closeButton = new JButton("Close"); closeButton.setActionCommand("CLOSE"); closeButton.addActionListener(this); closePanel.add(closeButton); - content.add(closePanel, BorderLayout.SOUTH); - getContentPane().add(content); + add(closePanel, BorderLayout.SOUTH); } /** @@ -132,21 +127,17 @@ public class ComboBoxDemo * bottom of the panel if they want to (a close button is * added if this demo is being run as a standalone demo). */ - JPanel createContent() + private void createContent() { - if (content == null) - { - content = new JPanel(new BorderLayout()); - JPanel panel = new JPanel(new GridLayout(6, 1)); - panel.add(createPanel1()); - panel.add(createPanel2()); - panel.add(createPanel3()); - panel.add(createPanel4()); - panel.add(createPanel5()); - panel.add(createPanel6()); - content.add(panel); - } - return content; + setLayout(new BorderLayout()); + JPanel panel = new JPanel(new GridLayout(6, 1)); + panel.add(createPanel1()); + panel.add(createPanel2()); + panel.add(createPanel3()); + panel.add(createPanel4()); + panel.add(createPanel5()); + panel.add(createPanel6()); + add(panel); } private JPanel createPanel1() @@ -362,17 +353,34 @@ public class ComboBoxDemo public static void main(String[] args) { - try - { - UIManager.setLookAndFeel(new javax.swing.plaf.metal.MetalLookAndFeel()); - } - catch (Exception e) { - e.printStackTrace(); - } - ComboBoxDemo app = new ComboBoxDemo("ComboBox Demo"); - app.initFrameContent(); - app.pack(); - app.setVisible(true); + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + ComboBoxDemo app = new ComboBoxDemo(); + app.initFrameContent(); + JFrame frame = new JFrame(); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + } + }); } + /** + * Returns a DemoFactory that creates a ComboBoxDemo. + * + * @return a DemoFactory that creates a ComboBoxDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new ComboBoxDemo(); + } + }; + } } diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/Demo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/Demo.java index 7cb7226..0f0b355 100644 --- a/libjava/classpath/examples/gnu/classpath/examples/swing/Demo.java +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/Demo.java @@ -27,74 +27,34 @@ import java.awt.event.*; import javax.swing.*; import javax.swing.tree.*; -import javax.swing.border.*; import javax.swing.plaf.metal.DefaultMetalTheme; import javax.swing.plaf.metal.MetalLookAndFeel; +import javax.swing.plaf.metal.MetalTheme; import javax.swing.plaf.metal.OceanTheme; +import java.lang.reflect.Method; import java.net.URL; public class Demo { JFrame frame; - static Color blueGray = new Color(0xdc, 0xda, 0xd5); - static - { - try - { - if (System.getProperty("swing.defaultlaf") == null) - { - StringBuffer text = new StringBuffer(); - text.append("You may change the Look and Feel of this\n"); - text.append("Demo by setting the system property\n"); - text.append("-Dswing.defaultlaf=<LAFClassName>\n"); - text.append("\n"); - text.append("Possible values for <LAFClassName> are:\n"); - text.append("\n"); - text.append("* javax.swing.plaf.metal.MetalLookAndFeel\n"); - text.append(" the default GNU Classpath L&F\n"); - text.append("\n"); - text.append("* gnu.classpath.examples.swing.GNULookAndFeel\n"); - text.append(" the GNU Look and Feel\n"); - text.append(" (derived from javax.swing.plaf.basic.BasicLookAndFeel)\n"); - text.append("\n"); - text.append("MetalLookAndFeel supports different Themes.\n"); - text.append("DefaultMetalTheme (the default) and OceanTheme (in development)\n"); - - final String DEFAULT = "MetalLookAndFeel (default)"; - final String OCEAN = "MetalLookAndFeel (Ocean)"; - final String GNU = "GNULookAndFeel"; - final String[] lafs = new String[] { DEFAULT, OCEAN, GNU }; - - int laf = JOptionPane.showOptionDialog(null, text /* textPane */, - "Look and Feel choice", - JOptionPane.OK_OPTION, - JOptionPane.QUESTION_MESSAGE, - null, lafs, DEFAULT); - if (laf == 0) - { - MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme()); - UIManager.setLookAndFeel(new MetalLookAndFeel()); - } - if (laf == 1) - { - MetalLookAndFeel.setCurrentTheme(new OceanTheme()); - UIManager.setLookAndFeel(new MetalLookAndFeel()); - } - else if (laf == 2) - UIManager.setLookAndFeel(new GNULookAndFeel()); - } - } - catch (UnsupportedLookAndFeelException e) - { - System.err.println("Cannot install GNULookAndFeel, exiting"); - System.exit(1); - } - } + /** + * The main desktop. This is package private to avoid synthetic accessor + * method. + */ + JDesktopPane desktop; + + /** + * The themes menu. This is implemented as a field so that the L&F switcher + * can disable the menu when a non-Metal L&F is selected. + */ + JMenu themesMenu; + + static Color blueGray = new Color(0xdc, 0xda, 0xd5); - static Icon stockIcon(String s) + private static Icon stockIcon(String s) { return getIcon("/gnu/classpath/examples/icons/stock-" + s + ".png", s); } @@ -104,14 +64,14 @@ public class Demo return getIcon("/gnu/classpath/examples/icons/big-" + s + ".png", s); } - static Icon getIcon(String location, String name) + private static Icon getIcon(String location, String name) { URL url = Demo.class.getResource(location); if (url == null) System.err.println("WARNING " + location + " not found."); return new ImageIcon(url, name); } - static JMenuBar mkMenuBar() + private JMenuBar mkMenuBar() { JMenuBar bar = new JMenuBar(); @@ -160,90 +120,135 @@ public class Demo edit.add(preferences); JMenu examples = new JMenu("Examples"); - new PopUpAction("Buttons", - (new ButtonDemo("Button Demo")).createContent(), - examples); - - new PopUpAction("Slider", - (new SliderDemo("Slider Demo")).createContent(), - examples); - - new PopUpAction("ProgressBar", - ProgressBarDemo.createContent(), - examples); - - new PopUpAction("List", - mkListPanel(new String[] { "hello", - "this", - "is", - "a", - "list", - "that", - "wraps", - "over"}), - examples); - - new PopUpAction("Scrollbar", - (new ScrollBarDemo("ScrollBarDemo")).createContent(), - examples); - - new PopUpAction("Viewport", - mkViewportBox(mkBigButton("View Me!")), - examples); - - new PopUpAction("ScrollPane", - mkScrollPane(mkBigButton("Scroll Me!")), - examples); - - new PopUpAction("TabPane", - mkTabs(new String[] {"happy", - "sad", - "indifferent"}), - examples); - - new PopUpAction("Spinner", - new SpinnerDemo("Spinner Demo").createContent(), examples); - - new PopUpAction("TextField", - (new TextFieldDemo("TextField Demo")).createContent(), - examples); - - new PopUpAction("FileChooser", - (new FileChooserDemo("FileChooser Demo")).createContent(), - examples); - - new PopUpAction("ColorChooser", - mkColorChooser(), - examples); - - new PopUpAction("ComboBox", - (new ComboBoxDemo("ComboBox Demo")).createContent(), - examples); - - new PopUpAction("Editor", - mkEditorPane(), - examples); + examples.add(new JMenuItem(new PopupAction("Buttons", + ButtonDemo.createDemoFactory()))); + examples.add(new JMenuItem(new PopupAction("Slider", + SliderDemo.createDemoFactory()))); + examples.add(new JMenuItem(new PopupAction("ProgressBar", + ProgressBarDemo.createDemoFactory()))); + examples.add(new JMenuItem(new PopupAction("Scrollbar", + ScrollBarDemo.createDemoFactory()))); + examples.add(new JMenuItem(new PopupAction("Spinner", + SpinnerDemo.createDemoFactory()))); + examples.add(new JMenuItem(new PopupAction("TextField", + TextFieldDemo.createDemoFactory()))); + examples.add(new JMenuItem(new PopupAction("TextArea", + TextAreaDemo.createDemoFactory()))); + examples.add(new JMenuItem(new PopupAction("FileChooser", + FileChooserDemo.createDemoFactory()))); + + examples.add(new JMenuItem(new PopupAction("ComboBox", + ComboBoxDemo.createDemoFactory()))); + + examples.add(new JMenuItem(new PopupAction("Table", + TableDemo.createDemoFactory()))); + examples.add(new JMenuItem(new PopupAction("List", + ListDemo.createDemoFactory()))); + examples.add(new JMenuItem(new PopupAction("TabbedPane", + TabbedPaneDemo.createDemoFactory()))); + examples.add(new JMenuItem(new PopupAction("Tree", + TreeDemo.createDemoFactory()))); + examples.add(new JMenuItem(new PopupAction("Theme Editor", + MetalThemeEditor.createDemoFactory()))); + + examples.add(new JMenuItem(new PopupAction("DocumentFilter", + DocumentFilterDemo.createDemoFactory()))); + + examples.add(new JMenuItem(new PopupAction("NavigationFilter", + NavigationFilterDemo.createDemoFactory()))); + + final JMenuItem vmMenu; - new PopUpAction("Tree", - mkTree(), - examples); - - new PopUpAction("Table", - mkTable(), - examples); - help.add(new JMenuItem("just play with the widgets")); help.add(new JMenuItem("and enjoy the sensation of")); help.add(new JMenuItem("your neural connections growing")); + help.add(new JSeparator()); + help.add(vmMenu = new JMenuItem("Really, which VM is this running on?")); + vmMenu.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent ae) + { + String message = "This is " + + System.getProperty("java.vm.name") + + " Version " + + System.getProperty("java.vm.version") + + " distributed by " + + System.getProperty("java.vm.vendor") + + "."; + + String gnuClasspath = System.getProperty("gnu.classpath.version"); + if(gnuClasspath != null) + message += "\nThe runtime's libraries are " + + "kindly provided by the " + + "members of GNU Classpath and are in version " + + gnuClasspath + "."; + + JOptionPane.showMessageDialog(vmMenu, message); + } + }); + + // Create L&F menu. + JMenu lafMenu = new JMenu("Look and Feel"); + ButtonGroup lafGroup = new ButtonGroup(); + UIManager.LookAndFeelInfo[] lafs = UIManager.getInstalledLookAndFeels(); + String currentLaf = UIManager.getLookAndFeel().getClass().getName(); + for (int i = 0; i < lafs.length; ++i) + { + UIManager.LookAndFeelInfo laf = lafs[i]; + ChangeLAFAction action = new ChangeLAFAction(laf); + JRadioButtonMenuItem lafItem = new JRadioButtonMenuItem(action); + boolean selected = laf.getClassName().equals(currentLaf); + lafItem.setSelected(selected); + lafMenu.add(lafItem); + } + + // Create themes menu. + themesMenu = new JMenu("Themes"); + ButtonGroup themesGroup = new ButtonGroup(); + // In order to make the demo runable on a 1.4 type VM we have to avoid calling + // MetalLookAndFeel.getCurrentTheme(). We simply check whether this method exists + // and is public. + Method m = null; + try + { + m = MetalLookAndFeel.class.getMethod("getCurrentTheme", null); + } + catch (NoSuchMethodException nsme) + { + // Ignore it. + } + + if (m != null) + { + JRadioButtonMenuItem ocean = + new JRadioButtonMenuItem(new ChangeThemeAction(new OceanTheme())); + ocean.setSelected(MetalLookAndFeel.getCurrentTheme() instanceof OceanTheme); + themesMenu.add(ocean); + themesGroup.add(ocean); + + JRadioButtonMenuItem steel = + new JRadioButtonMenuItem(new ChangeThemeAction(new DefaultMetalTheme())); + ocean.setSelected(MetalLookAndFeel.getCurrentTheme() + instanceof DefaultMetalTheme); + themesMenu.add(steel); + themesGroup.add(steel); + } + else + { + themesMenu.setEnabled(false); + } + bar.add(file); bar.add(edit); bar.add(examples); + bar.add(lafMenu); + bar.add(themesMenu); bar.add(help); return bar; } - static void triggerDialog(final JButton but, final String dir) + private static void triggerDialog(final JButton but, final String dir) { but.addActionListener(new ActionListener() { @@ -277,7 +282,7 @@ public class Demo return bar; } - static String valign2str(int a) + private static String valign2str(int a) { switch (a) { @@ -307,9 +312,9 @@ public class Demo } } - static JButton mkButton(String title, Icon icon, - int hAlign, int vAlign, - int hPos, int vPos) + private static JButton mkButton(String title, Icon icon, + int hAlign, int vAlign, + int hPos, int vPos) { JButton b; if (icon == null) @@ -338,93 +343,7 @@ public class Demo } - static JPanel mkButtonWorld() - { - Icon ii = bigStockIcon("home"); - int CENTER = SwingConstants.CENTER; - int TOP = SwingConstants.TOP; - int BOTTOM = SwingConstants.BOTTOM; - - int[] valigns = new int[] {SwingConstants.CENTER, - SwingConstants.TOP, - SwingConstants.BOTTOM}; - - int[] haligns = new int[] {SwingConstants.CENTER, - SwingConstants.RIGHT, - SwingConstants.LEFT}; - - Border[] borders = new Border[] { - new SoftBevelBorder(BevelBorder.RAISED), - new SoftBevelBorder(BevelBorder.LOWERED), - new BevelBorder(BevelBorder.RAISED), - - LineBorder.createBlackLineBorder(), - new MatteBorder(2, 2, 2, 2, Color.GREEN), - LineBorder.createGrayLineBorder(), - - new BevelBorder(BevelBorder.LOWERED), - new EtchedBorder(EtchedBorder.RAISED), - new EtchedBorder(EtchedBorder.LOWERED) - }; - - JComponent[] comps = new JComponent[3*3]; - - int q = 0; - - JPanel panel = new JPanel(); - panel.setLayout(new GridLayout(3, 3)); - - for (int i = 0; i < 3; ++i) - for (int j = 0; j < 3; ++j) - { - JButton b = mkButton(halign2str(haligns[i]) - + valign2str(valigns[j]), - ii, - -1, -1, haligns[i], valigns[j]); - b.setBorder(borders[q++]); - JPanel tmp = new JPanel(); - tmp.setBorder(new MatteBorder(5, 5, 5, 5, blueGray)); - tmp.add(b); - panel.add(tmp); - } - - return panel; - } - - private static class CheckCellRenderer - extends JCheckBox implements ListCellRenderer - { - public Component getListCellRendererComponent(JList list, - Object value, - int index, - boolean isSelected, - boolean cellHasFocus) - { - setSelected(isSelected); - setText(value.toString()); - - return this; - } - } - - private static class LabelCellRenderer - extends DefaultListCellRenderer - { - public Component getListCellRendererComponent(JList list, - Object value, - int index, - boolean isSelected, - boolean cellHasFocus) - { - Component c = super.getListCellRendererComponent(list, value, index, - isSelected, - cellHasFocus); - - return c; - } - } - - public static JScrollPane mkScrollPane(JComponent inner) + private static JScrollPane mkScrollPane(JComponent inner) { JScrollPane jsp; jsp = new JScrollPane(inner, @@ -434,275 +353,24 @@ public class Demo return jsp; } - private static JPanel mkTreeWorld() - { - // non-leafs - DefaultMutableTreeNode root = new DefaultMutableTreeNode("Exotic Subsistence"); - DefaultMutableTreeNode fruit = new DefaultMutableTreeNode("Interesting Fruit"); - DefaultMutableTreeNode veg = new DefaultMutableTreeNode("Extraordinary Vegetables"); - DefaultMutableTreeNode liq = new DefaultMutableTreeNode("Peculiar Liquids"); - - // leafs - DefaultMutableTreeNode f1 = new DefaultMutableTreeNode("Abiu"); - DefaultMutableTreeNode f2 = new DefaultMutableTreeNode("Bamboo Shoots"); - DefaultMutableTreeNode f3 = new DefaultMutableTreeNode("Breadfruit"); - DefaultMutableTreeNode f4 = new DefaultMutableTreeNode("Canistel"); - DefaultMutableTreeNode f5 = new DefaultMutableTreeNode("Duku"); - DefaultMutableTreeNode f6 = new DefaultMutableTreeNode("Guava"); - DefaultMutableTreeNode f7 = new DefaultMutableTreeNode("Jakfruit"); - DefaultMutableTreeNode f8 = new DefaultMutableTreeNode("Quaribea"); - - DefaultMutableTreeNode v1 = new DefaultMutableTreeNode("Amaranth"); - DefaultMutableTreeNode v2 = new DefaultMutableTreeNode("Kiwano"); - DefaultMutableTreeNode v3 = new DefaultMutableTreeNode("Leeks"); - DefaultMutableTreeNode v4 = new DefaultMutableTreeNode("Luffa"); - DefaultMutableTreeNode v5 = new DefaultMutableTreeNode("Chayote"); - DefaultMutableTreeNode v6 = new DefaultMutableTreeNode("Jicama"); - DefaultMutableTreeNode v7 = new DefaultMutableTreeNode("Okra"); - - DefaultMutableTreeNode l1 = new DefaultMutableTreeNode("Alcoholic"); - DefaultMutableTreeNode l11 = new DefaultMutableTreeNode("Caipirinha"); - DefaultMutableTreeNode l21 = new DefaultMutableTreeNode("Mojito"); - DefaultMutableTreeNode l31 = new DefaultMutableTreeNode("Margarita"); - DefaultMutableTreeNode l41 = new DefaultMutableTreeNode("Martini"); - DefaultMutableTreeNode l5 = new DefaultMutableTreeNode("Non Alcoholic"); - DefaultMutableTreeNode l55 = new DefaultMutableTreeNode("Babaji"); - DefaultMutableTreeNode l65 = new DefaultMutableTreeNode("Chikita"); - - root.add(fruit); - root.add(veg); - root.add(liq); - fruit.add(f1); - fruit.add(f2); - fruit.add(f3); - fruit.add(f4); - fruit.add(f5); - fruit.add(f6); - fruit.add(f7); - fruit.add(f8); - veg.add(v1); - veg.add(v2); - veg.add(v3); - veg.add(v4); - veg.add(v5); - veg.add(v6); - veg.add(v7); - liq.add(l1); - l1.add(l11); - l1.add(l21); - l1.add(l31); - l1.add(l41); - liq.add(l5); - l5.add(l55); - l5.add(l65); - - final JTree tree = new JTree(root); - tree.setLargeModel(true); - tree.setEditable(true); - DefaultTreeSelectionModel dtsm = new DefaultTreeSelectionModel(); - dtsm.setSelectionMode(DefaultTreeSelectionModel.SINGLE_TREE_SELECTION); - tree.setSelectionModel(dtsm); - - // buttons to add and delete - JButton add = mkButton("add element"); - add.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent e) - { - for (int i = 0; i < tree.getRowCount(); i++) - { - if (tree.isRowSelected(i)) - { - TreePath p = tree.getPathForRow(i); - DefaultMutableTreeNode n = (DefaultMutableTreeNode) p. - getLastPathComponent(); - n.add(new DefaultMutableTreeNode("New Element")); - tree.repaint(); - break; - } - } - } - }); - - - JPanel p1 = new JPanel(); - p1.setLayout(new BorderLayout()); - - JPanel p2 = new JPanel(); - p2.add(add); - - p1.add(p2, BorderLayout.NORTH); - p1.add(mkScrollPane(tree), BorderLayout.CENTER); - - return p1; - } - - public static JPanel mkListWorld() - { - - String foo[] = new String[] { - "non alcoholic ", - "carbonated ", - "malted ", - "fresh squeezed ", - "imported ", - "high fructose ", - "enriched " - }; - - String bar[] = new String[] { - "orange juice", - "ginger beer", - "yak milk", - "corn syrup", - "herbal remedy" - }; - - final DefaultListModel mod = new DefaultListModel(); - final JList list1 = new JList(mod); - final JList list2 = new JList(mod); - - list2.setSelectionModel(list1.getSelectionModel()); - for (int i = 0; i < bar.length; ++i) - for (int j = 0; j < foo.length; ++j) - mod.addElement(foo[j] + bar[i]); - - list1.setCellRenderer(new LabelCellRenderer()); - list2.setCellRenderer(new CheckCellRenderer()); - - JButton add = mkButton("add element"); - add.addActionListener(new ActionListener() - { - int i = 0; - public void actionPerformed(ActionEvent e) - { - mod.addElement("new element " + i); - ++i; - } - }); - - JButton del = mkButton("delete selected"); - del.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent e) - { - for (int i = 0; i < mod.getSize(); ++i) - if (list1.isSelectedIndex(i)) - mod.remove(i); - } - }); - - - JSplitPane splitter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); - splitter.add(mkScrollPane(list1), JSplitPane.LEFT); - splitter.add(mkScrollPane(list2), JSplitPane.RIGHT); - - JPanel p1 = new JPanel(); - p1.setLayout(new BorderLayout()); - - JPanel p2 = new JPanel(); - p2.setLayout(new GridLayout(1, 2)); - p2.add(add); - p2.add(del); - - p1.add(p2, BorderLayout.NORTH); - p1.add(splitter, BorderLayout.CENTER); - return p1; - } - - - static JPanel mkDesktopWorld() - { - - final JDesktopPane desk = new JDesktopPane(); - desk.setDesktopManager(new DefaultDesktopManager()); - desk.setPreferredSize(new Dimension(300,300)); - desk.setMinimumSize(new Dimension(300,300)); - JButton but = mkButton("add frame"); - but.addActionListener(new ActionListener() - { - int i = 10; - public void actionPerformed(ActionEvent e) - { - JInternalFrame f; - f = new JInternalFrame("internal", true, true, true, true); - f.getContentPane().setLayout(new BorderLayout()); - f.getContentPane().add(mkToolBar(), BorderLayout.NORTH); - f.getContentPane().add(mkButton(bigStockIcon("fullscreen")), - BorderLayout.CENTER); - desk.add(f); - f.setBounds(i, i, 250, 200); - f.setVisible(true); - i += 30; - } - }); - - JPanel panel = new JPanel(); - panel.setLayout(new BorderLayout()); - panel.add(desk, BorderLayout.CENTER); - panel.add(but, BorderLayout.NORTH); - but.doClick(); - but.doClick(); - JInternalFrame palette = new JInternalFrame("Palette", true, true, true, - true); - palette.putClientProperty("JInternalFrame.isPalette", Boolean.TRUE); - desk.add(palette, JDesktopPane.PALETTE_LAYER); - JLabel label = new JLabel("This is a floating palette!"); - palette.getContentPane().add(label); - palette.pack(); - palette.setVisible(true); - return panel; - } - - static JPanel mkTabWorld() - { - JPanel panel = new JPanel(new GridLayout(2, 2)); - panel.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); - JTabbedPane tabs1 = new JTabbedPane(SwingConstants.TOP); - tabs1.add("Top Item 1", new JButton("Button")); - tabs1.add("Top Item 2", new JButton("Button")); - JTabbedPane tabs2 = new JTabbedPane(SwingConstants.LEFT); - tabs2.add("Left Item 1", new JButton("Button")); - tabs2.add("Left Item 2", new JButton("Button")); - JTabbedPane tabs3 = new JTabbedPane(SwingConstants.BOTTOM); - tabs3.add("Bottom Item 1", new JButton("Button")); - tabs3.add("Bottom Item 2", new JButton("Button")); - JTabbedPane tabs4 = new JTabbedPane(SwingConstants.RIGHT); - tabs4.add("Right Item 1", new JButton("Button")); - tabs4.add("Right Item 2", new JButton("Button")); - panel.add(tabs1); - panel.add(tabs2); - panel.add(tabs3); - panel.add(tabs4); - return panel; - } - - static JTabbedPane mkTabbedPane() - { - JTabbedPane tabs = new JTabbedPane(); - - tabs.add("Button world!", mkButtonWorld()); - tabs.add("List world!", mkListWorld()); - tabs.add("Desktop world!", mkDesktopWorld()); - tabs.add("Tree world!", mkTreeWorld()); - tabs.add("Tab world!", mkTabWorld()); - return tabs; - } - public Demo() { frame = new JFrame("Swing Activity Board"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setJMenuBar(mkMenuBar()); JComponent component = (JComponent) frame.getContentPane(); component.setLayout(new BorderLayout()); component.add(mkToolBar(), BorderLayout.NORTH); JPanel main = new JPanel(); main.setLayout(new BoxLayout(main, BoxLayout.Y_AXIS)); - main.add(mkTabbedPane()); + desktop = createDesktop(); + + // Put the desktop in a scrollpane. The scrollbars may show then + // up when the them or LaF is changed. + main.add(new JScrollPane(desktop)); main.add(mkButtonBar()); component.add(main, BorderLayout.CENTER); frame.pack(); - frame.setSize(800, 600); frame.show(); } @@ -720,38 +388,14 @@ public class Demo SwingUtilities.invokeLater(new LaterMain()); } - public static JList mkList(Object[] elts) - { - JList list = new JList(elts); - list.setFont(new Font("Luxi", Font.PLAIN, 14)); - return list; - } - - public static JTabbedPane mkTabs(String[] names) - { - JTabbedPane tabs = new JTabbedPane(); - for (int i = 0; i < names.length; ++i) - { - tabs.addTab(names[i], mkButton(names[i])); - } - return tabs; - } - - public static JComboBox mkComboBox(String[] names) - { - JComboBox box = new JComboBox(names); - return box; - } - - public static JButton mkBigButton(String title) + private static JButton mkBigButton(String title) { JButton b = new JButton(title); b.setMargin(new Insets(5,5,5,5)); - //b.setFont(new Font("Luxi", Font.PLAIN, 14)); return b; } - public static JPanel mkPanel(JComponent[] inners) + private static JPanel mkPanel(JComponent[] inners) { JPanel p = new JPanel(); for (int i = 0; i < inners.length; ++i) @@ -761,85 +405,7 @@ public class Demo return p; } - public static JScrollBar mkScrollBar() - { - JScrollBar scrollbar = new JScrollBar(); - return scrollbar; - } - - public static JPanel mkViewportBox(final JComponent inner) - { - final JViewport port = new JViewport(); - port.setView(inner); - JButton left = mkBigButton("left"); - JButton right = mkBigButton("right"); - - left.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent e) - { - Point p = port.getViewPosition(); - port.setViewPosition(new Point(p.x - 10, p.y)); - } - }); - - right.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent e) - { - Point p = port.getViewPosition(); - port.setViewPosition(new Point(p.x + 10, p.y)); - } - }); - - return mkPanel(new JComponent[] {port, left, right}); - } - - public static JPanel mkListPanel(Object[] elts) - { - final DefaultListModel mod = new DefaultListModel(); - final JList list1 = new JList(mod); - list1.setLayoutOrientation(JList.VERTICAL_WRAP); - list1.setVisibleRowCount(4); - final JList list2 = new JList(mod); - list2.setLayoutOrientation(JList.VERTICAL_WRAP); - list2.setVisibleRowCount(4); - - list2.setSelectionModel(list1.getSelectionModel()); - for (int i = 0; i < elts.length; ++i) - mod.addElement(elts[i]); - list1.setCellRenderer(new LabelCellRenderer()); - list2.setCellRenderer(new CheckCellRenderer()); - - JButton add = mkBigButton("add element"); - add.addActionListener(new ActionListener() - { - int i = 0; - public void actionPerformed(ActionEvent e) - { - mod.addElement("new element " + i); - ++i; - } - }); - - JButton del = mkBigButton("delete selected"); - del.addActionListener(new ActionListener() - { - public void actionPerformed(ActionEvent e) - { - for (int i = 0; i < mod.getSize(); ++i) - if (list1.isSelectedIndex(i)) - mod.remove(i); - } - }); - - return mkPanel(new JComponent[] {list1, //mkScrollPane(list1), - list2, //mkScrollPane(list2), - mkPanel(new JComponent[] {add, del})}); - } - - - public static JButton mkDisposerButton(final JFrame c) + static JButton mkDisposerButton(final JFrame c) { JButton close = mkBigButton("Close"); close.addActionListener(new ActionListener() @@ -857,50 +423,50 @@ public class Demo return new JColorChooser(); } - private static class PopUpAction - implements ActionListener - { - private JComponent inner; - private String name; - - PopUpAction(String n, JComponent i, JMenu m) - { - name = n; - inner = i; - - JMenuItem item = new JMenuItem(name); - item.addActionListener(this); - m.add(item); - } - - PopUpAction(String n, JComponent i, JPanel p) + /** + * This action brings up a new Window with the specified content. + */ + private class PopupAction + extends AbstractAction + { + /** + * The component to be shown. + */ + private DemoFactory demoFactory; + + /** + * Creates a new PopupAction with the specified name and showing the + * component created by the specified DemoFactory when activated. + * + * @param n the name of the action + * @param factory the demo factory + */ + PopupAction(String n, DemoFactory factory) { - name = n; - inner = i; - - JButton b = mkBigButton(name); - b.addActionListener(this); - p.add(b); + putValue(NAME, n); + demoFactory = factory; } + /** + * Brings up the new window showing the component stored in the + * constructor. + * + * @param e the action event that triggered the action + */ public void actionPerformed(ActionEvent e) { - JFrame frame = new JFrame(name); - frame.getContentPane().setLayout(new BorderLayout()); - frame.getContentPane().add(inner, BorderLayout.CENTER); - frame.getContentPane().add(mkDisposerButton(frame), BorderLayout.SOUTH); + JInternalFrame frame = new JInternalFrame((String) getValue(NAME)); + frame.setClosable(true); + frame.setIconifiable(true); + frame.setMaximizable(true); + frame.setResizable(true); + frame.setContentPane(demoFactory.createDemo()); frame.pack(); - frame.show(); + desktop.add(frame); + frame.setVisible(true); } } - private static JEditorPane mkEditorPane() - { - JEditorPane editorPane = new JEditorPane(); - editorPane.setEditable(true); - return editorPane; - } - /** * Create the tree. * @@ -947,93 +513,42 @@ public class Demo } } - /** - * Make a sample table component. - */ - private static JPanel mkTable() - { - return new TableDemo("Table demo, double click to edit") - .createContent(); - } - private JPanel mkButtonBar() { - JPanel panel = new JPanel(new FlowLayout()); - new PopUpAction("Buttons", - (new ButtonDemo("Button Demo")).createContent(), - panel); - - new PopUpAction("Slider", - (new SliderDemo("Slider Demo")).createContent(), - panel); - - new PopUpAction("ProgressBar", - ProgressBarDemo.createContent(), - panel); - - - new PopUpAction("List", - mkListPanel(new String[] { "hello", - "this", - "is", - "a", - "list", - "that", - "wraps", - "over"}), - panel); - - new PopUpAction("Scrollbar", - (new ScrollBarDemo("ScrollBar Demo")).createContent(), - panel); - - new PopUpAction("Viewport", - mkViewportBox(mkBigButton("View Me!")), - panel); - - new PopUpAction("ScrollPane", - mkScrollPane(mkBigButton("Scroll Me!")), - panel); - - new PopUpAction("TabPane", - mkTabs(new String[] {"happy", - "sad", - "indifferent"}), - panel); - - new PopUpAction("Spinner", - new SpinnerDemo("Spinner Demo").createContent(), panel); - - new PopUpAction("TextField", - (new TextFieldDemo("TextField Demo")).createContent(), - panel); - - new PopUpAction("FileChooser", - (new FileChooserDemo("FileChooser Demo")).createContent(), - panel); - - new PopUpAction("ColorChooser", - mkColorChooser(), - panel); - - new PopUpAction("ComboBox", - (new ComboBoxDemo("ComboBox Demo")).createContent(), - panel); - - new PopUpAction("Editor", - mkEditorPane(), - panel); - - new PopUpAction("Tree", - mkTree(), - panel); - - new PopUpAction("Table", - mkTable(), - panel); - + JPanel panel = new JPanel(new GridLayout(3, 1, 5, 5)); + panel.add(new JButton(new PopupAction("Buttons", + ButtonDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("Slider", + SliderDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("ProgressBar", + ProgressBarDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("ScrollBar", + ScrollBarDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("Spinner", + SpinnerDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("TextField", + TextFieldDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("TextArea", + TextAreaDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("FileChooser", + FileChooserDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("ComboBox", + ComboBoxDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("Table", + TableDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("List", + ListDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("TabbedPane", + TabbedPaneDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("Tree", + TreeDemo.createDemoFactory()))); + panel.add(new JButton(new PopupAction("Theme Editor", + MetalThemeEditor.createDemoFactory()))); JButton exitDisposer = mkDisposerButton(frame); panel.add(exitDisposer); + + panel.setMaximumSize(new Dimension(Integer.MAX_VALUE, + panel.getPreferredSize().height)); exitDisposer.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) @@ -1043,4 +558,104 @@ public class Demo }); return panel; } + + /** + * Creates and returns the main desktop. + * + * @return the main desktop + */ + private JDesktopPane createDesktop() + { + JDesktopPane d = new DemoDesktop(); + d.setPreferredSize(new Dimension(900, 500)); + return d; + } + + /** + * This Action is used to switch Metal themes. + */ + class ChangeThemeAction extends AbstractAction + { + /** + * The theme to switch to. + */ + MetalTheme theme; + + /** + * Creates a new ChangeThemeAction for the specified theme. + * + * @param t the theme to switch to + */ + ChangeThemeAction(MetalTheme t) + { + theme = t; + putValue(NAME, t.getName()); + } + + /** + * Changes the theme to the one specified in the constructor. + * + * @param event the action event that triggered this action + */ + public void actionPerformed(ActionEvent event) + { + MetalLookAndFeel.setCurrentTheme(theme); + try + { + // Only switch theme if we have a metal L&F. It is still necessary + // to install a new MetalLookAndFeel instance. + if (UIManager.getLookAndFeel() instanceof MetalLookAndFeel) + UIManager.setLookAndFeel(new MetalLookAndFeel()); + } + catch (UnsupportedLookAndFeelException ex) + { + ex.printStackTrace(); + } + SwingUtilities.updateComponentTreeUI(frame); + } + + } + + /** + * This Action is used to switch Metal themes. + */ + class ChangeLAFAction extends AbstractAction + { + /** + * The theme to switch to. + */ + private UIManager.LookAndFeelInfo laf; + + /** + * Creates a new ChangeLAFAction for the specified L&F. + * + * @param l the L&F to switch to + */ + ChangeLAFAction(UIManager.LookAndFeelInfo l) + { + laf = l; + putValue(NAME, laf.getName()); + } + + /** + * Changes the theme to the one specified in the constructor. + * + * @param event the action event that triggered this action + */ + public void actionPerformed(ActionEvent event) + { + try + { + UIManager.setLookAndFeel(laf.getClassName()); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + SwingUtilities.updateComponentTreeUI(frame); + themesMenu.setEnabled(laf.getClassName() + .equals("javax.swing.plaf.metal.MetalLookAndFeel")); + } + + } } diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/DemoDesktop.java b/libjava/classpath/examples/gnu/classpath/examples/swing/DemoDesktop.java new file mode 100644 index 0000000..edfaf36 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/DemoDesktop.java @@ -0,0 +1,82 @@ +/* DemoDesktop.java -- A custom desktop for the demo + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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; either version 2, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.swing; + +import java.awt.Graphics; + +import javax.swing.ImageIcon; +import javax.swing.JDesktopPane; + +/** + * A customized Desktop for the GNU Classpath Swing demo that paints the + * GNU Classpath Icon in the middle of the desktop. + * + * @author Roman Kennke (kennke@aicas.com) + */ +public class DemoDesktop + extends JDesktopPane +{ + + /** + * The icon that's painted centered on the desktop. + */ + private ImageIcon image; + + /** + * Creates a new desktop. + */ + DemoDesktop() + { + super(); + String badge = "/gnu/classpath/examples/icons/badge.png"; + image = new ImageIcon(getClass().getResource(badge)); + } + + /** + * Paints the desktop including the icon. + * + * @param g the graphics to use for painting + */ + protected void paintComponent(Graphics g) + { + super.paintComponent(g); + image.paintIcon(this, g, (getWidth() - image.getIconWidth()) / 2, + (getHeight() - image.getIconHeight()) / 2); + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/DemoFactory.java b/libjava/classpath/examples/gnu/classpath/examples/swing/DemoFactory.java new file mode 100644 index 0000000..0320f31 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/DemoFactory.java @@ -0,0 +1,57 @@ +/* DemoFactory.java -- Creates components used as separate Swing demos + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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; either version 2, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.swing; + +import javax.swing.JComponent; + +/** + * Creates components used in the Swing demo as separate demos. + * + * @author Roman Kennke (kennke@aicas.de) + */ +public interface DemoFactory +{ + + /** + * Creates the component that should be as demo application. + * + * @return the component that should be as demo application + */ + JComponent createDemo(); +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/DocumentFilterDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/DocumentFilterDemo.java new file mode 100644 index 0000000..28dce1c --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/DocumentFilterDemo.java @@ -0,0 +1,289 @@ +/* DpocumentFilterDemo.java -- An example for the DocumentFilter class. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath 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; either version 2, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. +*/ + + +package gnu.classpath.examples.swing; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.GridLayout; +import java.awt.Toolkit; +import java.awt.datatransfer.Clipboard; +import java.awt.datatransfer.StringSelection; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JTextField; +import javax.swing.SwingUtilities; +import javax.swing.text.AbstractDocument; +import javax.swing.text.AttributeSet; +import javax.swing.text.BadLocationException; +import javax.swing.text.DocumentFilter; +import javax.swing.text.TextAction; + +/** + * A demonstration of the <code>javax.swing.text.DocumentFilter</code> class. + * + * <p>Similar to a dialog in a popular programming IDE the user can insert + * a CVS URL into a textfield and the filter will split the components apart + * and will put them into the right textfields saving the user a lot of + * typing time.</p> + * + * @author Robert Schuster + */ +public class DocumentFilterDemo + extends JPanel + implements ActionListener +{ + JTextField target; + + JTextField host; + JTextField repositoryPath; + JTextField user; + JTextField password; + JComboBox connectionType; + + /** + * Creates a new demo instance. + */ + public DocumentFilterDemo() + { + createContent(); + // initFrameContent() is only called (from main) when running this app + // standalone + } + + /** + * When the demo is run independently, the frame is displayed, so we should + * initialise the content panel (including the demo content and a close + * button). But when the demo is run as part of the Swing activity board, + * only the demo content panel is used, the frame itself is never displayed, + * so we can avoid this step. + */ + void initFrameContent() + { + JPanel closePanel = new JPanel(); + JButton closeButton = new JButton("Close"); + closeButton.setActionCommand("CLOSE"); + closeButton.addActionListener(this); + closePanel.add(closeButton); + add(closePanel, BorderLayout.SOUTH); + } + + private void createContent() + { + setLayout(new BorderLayout()); + + JPanel panel = new JPanel(new GridLayout(7, 2)); + panel.add(new JLabel("CVS URL:")); + panel.add(target = new JTextField(20)); + target.setBackground(Color.RED); + + panel.add(new JLabel("Host:")); + panel.add(host = new JTextField(20)); + + panel.add(new JLabel("Repository Path:")); + panel.add(repositoryPath = new JTextField(20)); + + panel.add(new JLabel("Username:")); + panel.add(user = new JTextField(20)); + + panel.add(new JLabel("Password:")); + panel.add(password = new JTextField(20)); + + panel.add(new JLabel("Connection Type:")); + panel.add(connectionType = new JComboBox()); + + JButton helpButton = new JButton("Help"); + panel.add(helpButton); + + helpButton.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent ae) + { + JOptionPane.showMessageDialog(DocumentFilterDemo.this, + "Paste a CVS URL into the red " + + "textfield.\nIf you do not want to " + + "look up a CVS URL yourself click " + + "on the 'provide me an example' " + + "button.\nThis will paste a proper " + + "string into your clipboard."); + } + }); + + JButton exampleButton = new JButton("Provide me an example!"); + panel.add(exampleButton); + exampleButton.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent ae) + { + try + { + Toolkit tk = Toolkit.getDefaultToolkit(); + Clipboard cb = tk.getSystemSelection(); + StringSelection selection + = new StringSelection(":extssh:gnu@cvs.savannah.gnu.org:" + + "/cvs/example/project"); + + cb.setContents(selection, selection); + + // Confirm success with a beep. + tk.beep(); + } + catch (IllegalStateException ise) + { + JOptionPane.showMessageDialog(DocumentFilterDemo.this, + "Clipboard is currently" + + " unavailable.", + "Error", + JOptionPane.ERROR_MESSAGE); + } + } + }); + + connectionType.addItem("pserver"); + connectionType.addItem("ext"); + connectionType.addItem("extssh"); + + add(panel); + + AbstractDocument doc = (AbstractDocument) target.getDocument(); + doc.setDocumentFilter(new CVSFilter()); + } + + public void actionPerformed(ActionEvent e) + { + if (e.getActionCommand().equals("CLOSE")) + System.exit(0); + + } + + public static void main(String[] args) + { + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + DocumentFilterDemo app = new DocumentFilterDemo(); + app.initFrameContent(); + JFrame frame = new JFrame("DocumentFilterDemo"); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + } + }); + } + + /** + * Returns a DemoFactory that creates a DocumentFilterDemo. + * + * @return a DemoFactory that creates a DocumentFilterDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new DocumentFilterDemo(); + } + }; + } + + class CVSFilter extends DocumentFilter + { + // example: pserver:anonymous@cvs.sourceforge.net:/cvsroot/fmj + String cvsPattern = ":?(pserver|ext|extssh):(\\w)+(:(\\w)+)?@(\\w|\\.)+:/(\\w|/)*"; + + public void insertString(DocumentFilter.FilterBypass fb, + int offset, String string, + AttributeSet attr) + throws BadLocationException + { + filterString(fb, offset, 0, string, attr, true); + } + + public void replace(DocumentFilter.FilterBypass fb, + int offset, int length, + String string, + AttributeSet attr) + throws BadLocationException + { + filterString(fb, offset, length, string, attr, false); + } + + public void filterString(DocumentFilter.FilterBypass fb, + int offset, int length, String string, + AttributeSet attr, boolean insertion) + throws BadLocationException + { + if(string.matches(cvsPattern)) + { + // Split off the connection type part. + String[] result = string.split(":", 2); + + // If the string contained a leading colon, result[0] + // will be empty at that point. We simply repeat the split + // operation on the remaining string and continue. + if(result[0].equals("")) + result = result[1].split(":", 2); + + connectionType.setSelectedItem(result[0]); + + // Split off the username and password part + result = result[1].split("@", 2); + + // Break username and password in half + String[] userCredentials = result[0].split(":"); + user.setText(userCredentials[0]); + + // If the result has two entries the second one will + // be the password. + if (userCredentials.length == 2) + password.setText(userCredentials[1]); + + // Now break the host part apart. + result = result[1].split(":"); + + host.setText(result[0]); + + repositoryPath.setText(result[1]); + } + + // The unmodified string is put into the document. + if (insertion) + fb.insertString(offset, string, attr); + else + fb.replace(offset, length, string, attr); + } + + } + +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/FileChooserDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/FileChooserDemo.java index de86d23..86cc015 100644 --- a/libjava/classpath/examples/gnu/classpath/examples/swing/FileChooserDemo.java +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/FileChooserDemo.java @@ -30,19 +30,23 @@ import java.io.File; import javax.swing.BorderFactory; import javax.swing.DefaultListModel; import javax.swing.JButton; +import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; +import javax.swing.SwingUtilities; import javax.swing.filechooser.FileFilter; /** * A simple demo showing the {@link JFileChooser} component used in different * ways. */ -public class FileChooserDemo extends JFrame implements ActionListener +public class FileChooserDemo + extends JPanel + implements ActionListener { /** * A file filter for Java source files. @@ -64,8 +68,6 @@ public class FileChooserDemo extends JFrame implements ActionListener } } - private JPanel content; - /** A label to display the selected file. */ JLabel selectedFileLabel; @@ -80,15 +82,11 @@ public class FileChooserDemo extends JFrame implements ActionListener /** * Creates a new demo instance. - * - * @param frameTitle the frame title. */ - public FileChooserDemo(String frameTitle) + public FileChooserDemo() { - super(frameTitle); - JPanel content = createContent(); - // initFrameContent() is only called (from main) when running this app - // standalone + super(); + createContent(); } /** @@ -98,15 +96,14 @@ public class FileChooserDemo extends JFrame implements ActionListener * only the demo content panel is used, the frame itself is never displayed, * so we can avoid this step. */ - public void initFrameContent() + void initFrameContent() { JPanel closePanel = new JPanel(); JButton closeButton = new JButton("Close"); closeButton.setActionCommand("CLOSE"); closeButton.addActionListener(this); closePanel.add(closeButton); - content.add(closePanel, BorderLayout.SOUTH); - getContentPane().add(content); + add(closePanel, BorderLayout.SOUTH); } /** @@ -116,57 +113,52 @@ public class FileChooserDemo extends JFrame implements ActionListener * bottom of the panel if they want to (a close button is * added if this demo is being run as a standalone demo). */ - JPanel createContent() + private void createContent() { - if (content == null) - { - JPanel panel = new JPanel(new BorderLayout()); + setLayout(new BorderLayout()); - // create a panel of buttons to select the different styles of file - // chooser... - JPanel buttonPanel = new JPanel(new GridLayout(5, 1)); - JButton openButton = new JButton("Open..."); - openButton.setActionCommand("OPEN"); - openButton.addActionListener(this); - buttonPanel.add(openButton); - JButton saveButton = new JButton("Save..."); - saveButton.setActionCommand("SAVE"); - saveButton.addActionListener(this); - buttonPanel.add(saveButton); - JButton queryButton = new JButton("Select Directory..."); - queryButton.setActionCommand("SELECT_DIRECTORY"); - queryButton.addActionListener(this); - buttonPanel.add(queryButton); - JButton openJavaButton = new JButton("Open Java file..."); - openJavaButton.setActionCommand("OPEN_JAVA"); - openJavaButton.addActionListener(this); - buttonPanel.add(openJavaButton); - JButton openMultiButton = new JButton("Open multiple files..."); - openMultiButton.setActionCommand("OPEN_MULTI"); - openMultiButton.addActionListener(this); - buttonPanel.add(openMultiButton); - panel.add(buttonPanel, BorderLayout.WEST); + // create a panel of buttons to select the different styles of file + // chooser... + JPanel buttonPanel = new JPanel(new GridLayout(5, 1)); + JButton openButton = new JButton("Open..."); + openButton.setActionCommand("OPEN"); + openButton.addActionListener(this); + buttonPanel.add(openButton); + JButton saveButton = new JButton("Save..."); + saveButton.setActionCommand("SAVE"); + saveButton.addActionListener(this); + buttonPanel.add(saveButton); + JButton queryButton = new JButton("Select Directory..."); + queryButton.setActionCommand("SELECT_DIRECTORY"); + queryButton.addActionListener(this); + buttonPanel.add(queryButton); + JButton openJavaButton = new JButton("Open Java file..."); + openJavaButton.setActionCommand("OPEN_JAVA"); + openJavaButton.addActionListener(this); + buttonPanel.add(openJavaButton); + JButton openMultiButton = new JButton("Open multiple files..."); + openMultiButton.setActionCommand("OPEN_MULTI"); + openMultiButton.addActionListener(this); + buttonPanel.add(openMultiButton); + add(buttonPanel, BorderLayout.WEST); - // create a panel to display the selected file(s) and the return code - JPanel displayPanel = new JPanel(new BorderLayout()); + // create a panel to display the selected file(s) and the return code + JPanel displayPanel = new JPanel(new BorderLayout()); - selectedFileLabel = new JLabel("-"); - selectedFileLabel.setBorder(BorderFactory.createTitledBorder("Selected File/Directory: ")); - displayPanel.add(selectedFileLabel, BorderLayout.NORTH); + selectedFileLabel = new JLabel("-"); + selectedFileLabel.setBorder(BorderFactory.createTitledBorder("Selected File/Directory: ")); + displayPanel.add(selectedFileLabel, BorderLayout.NORTH); - selectedFilesList = new JList(); - JScrollPane sp = new JScrollPane(selectedFilesList); - sp.setBorder(BorderFactory.createTitledBorder("Selected Files: ")); - displayPanel.add(sp); + selectedFilesList = new JList(); + JScrollPane sp = new JScrollPane(selectedFilesList); + sp.setBorder(BorderFactory.createTitledBorder("Selected Files: ")); + displayPanel.add(sp); - returnCodeLabel = new JLabel("0"); - returnCodeLabel.setBorder(BorderFactory.createTitledBorder("Return Code:")); - displayPanel.add(returnCodeLabel, BorderLayout.SOUTH); + returnCodeLabel = new JLabel("0"); + returnCodeLabel.setBorder(BorderFactory.createTitledBorder("Return Code:")); + displayPanel.add(returnCodeLabel, BorderLayout.SOUTH); - panel.add(displayPanel); - content = panel; - } - return content; + add(displayPanel); } /** @@ -239,10 +231,34 @@ public class FileChooserDemo extends JFrame implements ActionListener public static void main(String[] args) { - FileChooserDemo app = new FileChooserDemo("File Chooser Demo"); - app.initFrameContent(); - app.pack(); - app.setVisible(true); + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + FileChooserDemo app = new FileChooserDemo(); + app.initFrameContent(); + JFrame frame = new JFrame("FileChooser Demo"); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + } + }); } + /** + * Returns a DemoFactory that creates a FileChooserDemo. + * + * @return a DemoFactory that creates a FileChooserDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new FileChooserDemo(); + } + }; + } } diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/GNULookAndFeel.java b/libjava/classpath/examples/gnu/classpath/examples/swing/GNULookAndFeel.java deleted file mode 100644 index c8fd09d..0000000 --- a/libjava/classpath/examples/gnu/classpath/examples/swing/GNULookAndFeel.java +++ /dev/null @@ -1,265 +0,0 @@ -/* GNULookAndFeel.java -- An example of using the javax.swing UI. - Copyright (C) 2005 Free Software Foundation, Inc. - -This file is part of GNU Classpath examples. - -GNU Classpath 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; either version 2, or (at your option) -any later version. - -GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the -Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA -02110-1301 USA. -*/ - -package gnu.classpath.examples.swing; - -import java.awt.Color; -import java.awt.Component; -import java.awt.Graphics; - -import javax.swing.Icon; -import javax.swing.ImageIcon; -import javax.swing.JCheckBox; -import javax.swing.JRadioButton; -import javax.swing.UIDefaults; -import javax.swing.plaf.ColorUIResource; -import javax.swing.plaf.IconUIResource; -import javax.swing.plaf.basic.BasicLookAndFeel; - -public class GNULookAndFeel extends BasicLookAndFeel -{ - - static Color blueGray = new Color(0xdc, 0xda, 0xd5); - - public boolean isNativeLookAndFeel() { return true; } - public boolean isSupportedLookAndFeel() { return true; } - public String getDescription() { return "GNU Look and Feel"; } - public String getID() { return "GNULookAndFeel"; } - public String getName() { return "GNU"; } - - static UIDefaults LAF_defaults; - - private final static String iconspath = "/gnu/javax/swing/plaf/gtk/icons/"; - - public UIDefaults getDefaults() - { - if (LAF_defaults == null) - { - LAF_defaults = super.getDefaults(); - Object[] myDefaults = new Object[] { - "Button.background", new ColorUIResource(blueGray), - "CheckBox.background", new ColorUIResource(blueGray), - "CheckBoxMenuItem.background", new ColorUIResource(blueGray), - "ToolBar.background", new ColorUIResource(blueGray), - "Panel.background", new ColorUIResource(blueGray), - "Slider.background", new ColorUIResource(blueGray), - "OptionPane.background", new ColorUIResource(blueGray), - "ProgressBar.background", new ColorUIResource(blueGray), - "TabbedPane.background", new ColorUIResource(blueGray), - "Label.background", new ColorUIResource(blueGray), - "Menu.background", new ColorUIResource(blueGray), - "MenuBar.background", new ColorUIResource(blueGray), - "MenuItem.background", new ColorUIResource(blueGray), - "ScrollBar.background", new ColorUIResource(blueGray), - "CheckBox.icon", new CheckBoxIcon(), - "RadioButton.icon", new RadioButtonIcon(), - - "Tree.closedIcon", - new IconUIResource(new ImageIcon - (getClass().getResource - (iconspath + "TreeClosed.png"))), - "Tree.leafIcon", - new IconUIResource(new ImageIcon - (getClass().getResource - (iconspath + "TreeLeaf.png"))), - "Tree.openIcon", - new IconUIResource(new ImageIcon - (getClass().getResource - (iconspath + "TreeOpen.png"))), - }; - LAF_defaults.putDefaults(myDefaults); - } - return LAF_defaults; - } - - /** - * The icon used for CheckBoxes in the BasicLookAndFeel. This is an empty - * icon with a size of 13x13 pixels. - */ - static class CheckBoxIcon - implements Icon - { - /** - * Returns the height of the icon. The BasicLookAndFeel CheckBox icon - * has a height of 13 pixels. - * - * @return the height of the icon - */ - public int getIconHeight() - { - return 13; - } - - /** - * Returns the width of the icon. The BasicLookAndFeel CheckBox icon - * has a width of 13 pixels. - * - * @return the height of the icon - */ - public int getIconWidth() - { - return 13; - } - - /** - * Paints the icon. The BasicLookAndFeel CheckBox icon is empty and does - * not need to be painted. - * - * @param c the component to be painted - * @param g the Graphics context to be painted with - * @param x the x position of the icon - * @param y the y position of the icon - */ - public void paintIcon(Component c, Graphics g, int x, int y) - { - Color save = g.getColor(); - g.setColor(c.getForeground()); - g.drawRect(x, y, getIconWidth(), getIconHeight()); - - JCheckBox item = (JCheckBox) c; - if (item.isSelected()) - { - g.drawLine(3 + x, 5 + y, 3 + x, 9 + y); - g.drawLine(4 + x, 5 + y, 4 + x, 9 + y); - g.drawLine(5 + x, 7 + y, 9 + x, 3 + y); - g.drawLine(5 + x, 8 + y, 9 + x, 4 + y); - } - - g.setColor(save); - } - } - - /** - * The icon used for RadioButtons in the GNULookAndFeel. This is an empty - * icon with a size of 13x13 pixels. - */ - static class RadioButtonIcon - implements Icon - { - /** - * Returns the height of the icon. The GNULookAndFeel RadioButton icon - * has a height of 13 pixels. - * - * @return the height of the icon - */ - public int getIconHeight() - { - return 13; - } - - /** - * Returns the width of the icon. The GNULookAndFeel RadioButton icon - * has a width of 13 pixels. - * - * @return the height of the icon - */ - public int getIconWidth() - { - return 13; - } - - /** - * Paints the icon. The GNULookAndFeel RadioButton icon is empty and does - * not need to be painted. - * - * @param c the component to be painted - * @param g the Graphics context to be painted with - * @param x the x position of the icon - * @param y the y position of the icon - */ - public void paintIcon(Component c, Graphics g, int x, int y) - { - Color savedColor = g.getColor(); - JRadioButton b = (JRadioButton) c; - - // draw outer circle - if (b.isEnabled()) - g.setColor(Color.GRAY); - else - g.setColor(Color.GRAY); - g.drawLine(x + 2, y + 1, x + 3, y + 1); - g.drawLine(x + 4, y, x + 7, y); - g.drawLine(x + 8, y + 1, x + 9, y + 1); - g.drawLine(x + 10, y + 2, x + 10, y + 3); - g.drawLine(x + 11, y + 4, x + 11, y + 7); - g.drawLine(x + 10, y + 8, x + 10, y + 9); - g.drawLine(x + 8, y + 10, x + 9, y + 10); - g.drawLine(x + 4, y + 11, x + 7, y + 11); - g.drawLine(x + 2, y + 10, x + 3, y + 10); - g.drawLine(x + 1, y + 9, x + 1, y + 8); - g.drawLine(x, y + 7, x, y + 4); - g.drawLine(x + 1, y + 2, x + 1, y + 3); - - if (b.getModel().isArmed()) - { - g.setColor(Color.GRAY); - g.drawLine(x + 4, y + 1, x + 7, y + 1); - g.drawLine(x + 4, y + 10, x + 7, y + 10); - g.drawLine(x + 1, y + 4, x + 1, y + 7); - g.drawLine(x + 10, y + 4, x + 10, y + 7); - g.fillRect(x + 2, y + 2, 8, 8); - } - else - { - // only draw inner highlight if not filled - if (b.isEnabled()) - { - g.setColor(Color.WHITE); - - g.drawLine(x + 2, y + 8, x + 2, y + 9); - g.drawLine(x + 1, y + 4, x + 1, y + 7); - g.drawLine(x + 2, y + 2, x + 2, y + 3); - g.drawLine(x + 3, y + 2, x + 3, y + 2); - g.drawLine(x + 4, y + 1, x + 7, y + 1); - g.drawLine(x + 8, y + 2, x + 9, y + 2); - } - } - - // draw outer highlight - if (b.isEnabled()) - { - g.setColor(Color.WHITE); - - // outer - g.drawLine(x + 10, y + 1, x + 10, y + 1); - g.drawLine(x + 11, y + 2, x + 11, y + 3); - g.drawLine(x + 12, y + 4, x + 12, y + 7); - g.drawLine(x + 11, y + 8, x + 11, y + 9); - g.drawLine(x + 10, y + 10, x + 10, y + 10); - g.drawLine(x + 8, y + 11, x + 9, y + 11); - g.drawLine(x + 4, y + 12, x + 7, y + 12); - g.drawLine(x + 2, y + 11, x + 3, y + 11); - } - - if (b.isSelected()) - { - if (b.isEnabled()) - g.setColor(Color.BLACK); - else - g.setColor(Color.GRAY); - g.drawLine(x + 4, y + 3, x + 7, y + 3); - g.fillRect(x + 3, y + 4, 6, 4); - g.drawLine(x + 4, y + 8, x + 7, y + 8); - } - g.setColor(savedColor); - } - } -} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/ListDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/ListDemo.java new file mode 100644 index 0000000..7ed15be --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/ListDemo.java @@ -0,0 +1,231 @@ +/* ListDemo.java -- Demostrates JList + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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; either version 2, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.swing; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.DefaultListCellRenderer; +import javax.swing.DefaultListModel; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import javax.swing.ListCellRenderer; +import javax.swing.SwingUtilities; + +public class ListDemo + extends JPanel + implements ActionListener +{ + + private static class LabelCellRenderer + extends DefaultListCellRenderer + { + public Component getListCellRendererComponent(JList list, + Object value, + int index, + boolean isSelected, + boolean cellHasFocus) + { + Component c = super.getListCellRendererComponent(list, value, index, + isSelected, + cellHasFocus); + return c; + } + } + + private static class CheckCellRenderer + extends JCheckBox + implements ListCellRenderer + { + public Component getListCellRendererComponent(JList list, + Object value, + int index, + boolean isSelected, + boolean cellHasFocus) + { + setSelected(isSelected); + setText(value.toString()); + + return this; + } + } + + ListDemo() + { + super(); + createContent(); + } + + private void createContent() + { + + String foo[] = new String[] { + "non alcoholic ", + "carbonated ", + "malted ", + "fresh squeezed ", + "imported ", + "high fructose ", + "enriched " + }; + + String bar[] = new String[] { + "orange juice", + "ginger beer", + "yak milk", + "corn syrup", + "herbal remedy" + }; + + final DefaultListModel mod = new DefaultListModel(); + final JList list1 = new JList(mod); + final JList list2 = new JList(mod); + + list2.setSelectionModel(list1.getSelectionModel()); + for (int i = 0; i < bar.length; ++i) + for (int j = 0; j < foo.length; ++j) + mod.addElement(foo[j] + bar[i]); + + list1.setCellRenderer(new LabelCellRenderer()); + list2.setCellRenderer(new CheckCellRenderer()); + + JButton add = new JButton("add element"); + add.addActionListener(new ActionListener() + { + int i = 0; + public void actionPerformed(ActionEvent e) + { + mod.addElement("new element " + i); + ++i; + } + }); + + JButton del = new JButton("delete selected"); + del.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + for (int i = 0; i < mod.getSize(); ++i) + if (list1.isSelectedIndex(i)) + mod.remove(i); + } + }); + + + JSplitPane splitter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); + splitter.add(new JScrollPane(list1), JSplitPane.LEFT); + splitter.add(new JScrollPane(list2), JSplitPane.RIGHT); + + setLayout(new BorderLayout()); + JPanel p2 = new JPanel(); + p2.setLayout(new GridLayout(1, 2)); + p2.add(add); + p2.add(del); + + add(p2, BorderLayout.NORTH); + add(splitter, BorderLayout.CENTER); + } + + public void actionPerformed(ActionEvent e) + { + if (e.getActionCommand().equals("CLOSE")) + { + System.exit(0); + } + } + + /** + * When the demo is run independently, the frame is displayed, so we should + * initialise the content panel (including the demo content and a close + * button). But when the demo is run as part of the Swing activity board, + * only the demo content panel is used, the frame itself is never displayed, + * so we can avoid this step. + */ + void initFrameContent() + { + JPanel closePanel = new JPanel(); + JButton closeButton = new JButton("Close"); + closeButton.setActionCommand("CLOSE"); + closeButton.addActionListener(this); + closePanel.add(closeButton); + add(closePanel, BorderLayout.SOUTH); + } + + public static void main(String[] args) + { + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + ListDemo app = new ListDemo(); + app.initFrameContent(); + JFrame frame = new JFrame("List Demo"); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + } + }); + } + + /** + * Returns a DemoFactory that creates a ListDemo. + * + * @return a DemoFactory that creates a ListDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new ListDemo(); + } + }; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/MetalThemeEditor.java b/libjava/classpath/examples/gnu/classpath/examples/swing/MetalThemeEditor.java new file mode 100644 index 0000000..d3be0b8 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/MetalThemeEditor.java @@ -0,0 +1,585 @@ +/* MetalThemeEditor.java -- Edit themes using this application + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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; either version 2, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.swing; + +import gnu.javax.swing.plaf.metal.CustomizableTheme; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Graphics; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.Window; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JColorChooser; +import javax.swing.JComponent; +import javax.swing.JFileChooser; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.plaf.metal.MetalLookAndFeel; + +/** + * This application serves two purposes: 1. demonstrate the color chooser + * component, 2. make creating new Metal themes as easy as possible. + * + * @author Roman Kennke (kennke@aicas.com) + */ +public class MetalThemeEditor + extends JPanel +{ + /** + * An icon to display a chosen color in a button. + */ + private class ColorIcon implements Icon + { + /** + * The color to be shown on the icon. + */ + Color color; + + /** + * Creates a new ColorIcon. + * + * @param c the color to be displayed + */ + ColorIcon(Color c) + { + color = c; + } + + /** + * Returns the icon height, which is 10. + * + * @return 10 + */ + public int getIconHeight() + { + return 10; + } + + /** + * Returns the icon width, which is 30. + * + * @return 30 + */ + public int getIconWidth() + { + return 30; + } + + /** + * Paints the icon. + * + * @param c the component to paint on + * @param g the graphics to use + * @param x the x location + * @param y the y location + */ + public void paintIcon(Component c, Graphics g, int x, int y) + { + g.setColor(color); + g.fillRect(x, y, 30, 10); + } + + } + + /** + * Opens up a color chooser and lets the user select a color for the theme. + */ + private class ChooseColorAction implements ActionListener + { + + /** + * The button that will get updated when a new color is selected. + */ + private JButton button; + + /** + * Specifies which color of the theme should be updated. See constants in + * the MetalThemeEditor class. + */ + private int colorType; + + /** + * Creates a new ChooseColorAction. The specified button will have its + * icon updated to the new color if appropriate. + * + * @param b the button to update + * @param type the color type to update + */ + ChooseColorAction(JButton b, int type) + { + button = b; + colorType = type; + } + + /** + * Opens a color chooser and lets the user select a color. + */ + public void actionPerformed(ActionEvent event) + { + Color c = JColorChooser.showDialog(button, "Choose a color", + getColor(colorType)); + if (c != null) + { + setColor(colorType, c); + button.setIcon(new ColorIcon(c)); + } + } + } + + /** + * Denotes the primary1 color of the theme. + */ + private static final int PRIMARY1 = 0; + + /** + * Denotes the primary2 color of the theme. + */ + private static final int PRIMARY2 = 1; + + /** + * Denotes the primary3 color of the theme. + */ + private static final int PRIMARY3 = 2; + + /** + * Denotes the secondary1 color of the theme. + */ + private static final int SECONDARY1 = 3; + + /** + * Denotes the secondary2 color of the theme. + */ + private static final int SECONDARY2 = 4; + + /** + * Denotes the secondary3 color of the theme. + */ + private static final int SECONDARY3 = 5; + + /** + * The theme that is edited. + */ + CustomizableTheme theme; + + /** + * Creates a new instance of the MetalThemeEditor. + */ + MetalThemeEditor() + { + theme = new CustomizableTheme(); + setBorder(BorderFactory.createEmptyBorder(12, 12, 11, 11)); + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); + add(createConfigurationPanel()); + add(Box.createVerticalStrut(17)); + add(createButtonPanel()); + } + + /** + * Creates the main panel of the MetalThemeEditor. This is the upper + * area where the colors can be selected. + * + * @return the main panel + */ + private JPanel createConfigurationPanel() + { + JPanel p = new JPanel(); + p.setLayout(new GridBagLayout()); + GridBagConstraints c = new GridBagConstraints(); + c.weightx = 1; + c.weighty = 0; + c.fill = GridBagConstraints.HORIZONTAL; + Insets labelInsets = new Insets(0, 0, 11, 6); + Insets buttonInsets = new Insets(0, 0, 11, 0); + + // Primary 1 + JLabel primary1Label = new JLabel("Primary 1:"); + c.gridx = 0; + c.gridy = 0; + c.insets = labelInsets; + p.add(primary1Label, c); + + Icon p1Icon = new ColorIcon(theme.getPrimary1()); + JButton primary1Button = new JButton(p1Icon); + primary1Button.addActionListener(new ChooseColorAction(primary1Button, + PRIMARY1)); + //c.weightx = 0; + c.gridx = 1; + c.insets = buttonInsets; + p.add(primary1Button, c); + primary1Label.setLabelFor(primary1Button); + + // Primary 2 + JLabel primary2Label = new JLabel("Primary 2:"); + c.gridx = 0; + c.gridy = 1; + c.insets = labelInsets; + p.add(primary2Label, c); + + Icon p2Icon = new ColorIcon(theme.getPrimary2()); + JButton primary2Button = new JButton(p2Icon); + primary2Button.addActionListener(new ChooseColorAction(primary2Button, + PRIMARY2)); + c.gridx = 1; + c.insets = buttonInsets; + p.add(primary2Button, c); + primary2Label.setLabelFor(primary2Button); + + // Primary 3 + JLabel primary3Label = new JLabel("Primary 3:"); + c.gridx = 0; + c.gridy = 2; + c.insets = labelInsets; + p.add(primary3Label, c); + + Icon p3Icon = new ColorIcon(theme.getPrimary3()); + JButton primary3Button = new JButton(p3Icon); + primary3Button.addActionListener(new ChooseColorAction(primary3Button, + PRIMARY3)); + c.gridx = 1; + c.insets = buttonInsets; + p.add(primary3Button, c); + primary3Label.setLabelFor(primary3Button); + + // Secondary 1 + JLabel secondary1Label = new JLabel("Secondary 1:"); + c.gridx = 0; + c.gridy = 3; + c.insets = labelInsets; + p.add(secondary1Label, c); + + Icon s1Icon = new ColorIcon(theme.getSecondary1()); + JButton secondary1Button = new JButton(s1Icon); + secondary1Button.addActionListener(new ChooseColorAction(secondary1Button, + SECONDARY1)); + c.gridx = 1; + c.insets = buttonInsets; + p.add(secondary1Button, c); + secondary1Label.setLabelFor(secondary1Button); + + // Secondary 2 + JLabel secondary2Label = new JLabel("Secondary 2:"); + c.gridx = 0; + c.gridy = 4; + c.insets = labelInsets; + p.add(secondary2Label, c); + + Icon s2Icon = new ColorIcon(theme.getSecondary2()); + JButton secondary2Button = new JButton(s2Icon); + secondary2Button.addActionListener(new ChooseColorAction(secondary2Button, + SECONDARY2)); + c.gridx = 1; + c.insets = buttonInsets; + p.add(secondary2Button, c); + secondary2Label.setLabelFor(secondary2Button); + + // Secondary 3 + JLabel secondary3Label = new JLabel("Secondary 3:"); + c.gridx = 0; + c.gridy = 5; + c.insets = labelInsets; + p.add(secondary3Label, c); + + Icon s3Icon = new ColorIcon(theme.getSecondary3()); + JButton secondary3Button = new JButton(s3Icon); + secondary3Button.addActionListener(new ChooseColorAction(secondary3Button, + SECONDARY3)); + c.gridx = 1; + c.insets = buttonInsets; + p.add(secondary3Button, c); + secondary3Label.setLabelFor(secondary3Button); + + return p; + } + + /** + * Creates the button panel at the bottom of the MetalThemeEditor. + * + * @return the button panel + */ + private JPanel createButtonPanel() + { + JPanel p = new JPanel(); + p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS)); + p.add(Box.createHorizontalGlue()); + + JButton applyButton = new JButton("Apply"); + applyButton.addActionListener + (new ActionListener() + { + public void actionPerformed(ActionEvent ev) + { + try + { + CustomizableTheme copy = (CustomizableTheme) theme.clone(); + MetalLookAndFeel.setCurrentTheme(copy); + UIManager.setLookAndFeel(new MetalLookAndFeel()); + Window w = SwingUtilities.getWindowAncestor(MetalThemeEditor.this); + SwingUtilities.updateComponentTreeUI(w); + } + catch (Exception ex) + { + ex.printStackTrace(); + } + } + }); + p.add(applyButton); + + p.add(Box.createHorizontalStrut(5)); + + JButton exportButton = new JButton("Export as Java File"); + exportButton.addActionListener + (new ActionListener() + { + public void actionPerformed(ActionEvent ev) + { + export(); + } + }); + p.add(exportButton); + + return p; + } + + /** + * Exports the current theme as Java source file. This will prompt the user + * to choose a filename. + */ + void export() + { + JFileChooser chooser = new JFileChooser(); + int confirm = chooser.showSaveDialog(this); + if (confirm == JFileChooser.APPROVE_OPTION) + exportToFile(chooser.getSelectedFile()); + } + + /** + * Writes out the current configured Metal theme as Java source file. + * + * @param file the file to write into + */ + void exportToFile(File file) + { + String fileName = file.getName(); + if (! fileName.endsWith(".java")) + { + JOptionPane.showMessageDialog(this, + "Filename does not denote a Java source file", + "Invalid filename", + JOptionPane.ERROR_MESSAGE); + return; + } + + String className = fileName.substring(0, fileName.length() - 5); + Color p1 = theme.getPrimary1(); + Color p2 = theme.getPrimary2(); + Color p3 = theme.getPrimary3(); + Color s1 = theme.getSecondary1(); + Color s2 = theme.getSecondary2(); + Color s3 = theme.getSecondary3(); + + try + { + FileOutputStream out = new FileOutputStream(file); + Writer writer = new OutputStreamWriter(out); + writer.write("import javax.swing.plaf.ColorUIResource;\n"); + writer.write("import javax.swing.plaf.metal.DefaultMetalTheme;\n"); + writer.write("public class " + className + " extends DefaultMetalTheme\n"); + writer.write("{\n"); + writer.write(" protected ColorUIResource getPrimary1()\n"); + writer.write(" {\n"); + writer.write(" return new ColorUIResource(" + p1.getRGB() + ");\n"); + writer.write(" }\n"); + writer.write(" protected ColorUIResource getPrimary2()\n"); + writer.write(" {\n"); + writer.write(" return new ColorUIResource(" + p2.getRGB() + ");\n"); + writer.write(" }\n"); + writer.write(" protected ColorUIResource getPrimary3()\n"); + writer.write(" {\n"); + writer.write(" return new ColorUIResource(" + p3.getRGB() + ");\n"); + writer.write(" }\n"); + writer.write(" protected ColorUIResource getSecondary1()\n"); + writer.write(" {\n"); + writer.write(" return new ColorUIResource(" + s1.getRGB() + ");\n"); + writer.write(" }\n"); + writer.write(" protected ColorUIResource getSecondary2()\n"); + writer.write(" {\n"); + writer.write(" return new ColorUIResource(" + s2.getRGB() + ");\n"); + writer.write(" }\n"); + writer.write(" protected ColorUIResource getSecondary3()\n"); + writer.write(" {\n"); + writer.write(" return new ColorUIResource(" + s3.getRGB() + ");\n"); + writer.write(" }\n"); + writer.write("}\n"); + writer.close(); + out.close(); + } + catch (FileNotFoundException ex) + { + ex.printStackTrace(); + } + catch (IOException ex) + { + ex.printStackTrace(); + } + + } + + /** + * Returns the color of the theme with the specified type. For the possible + * types see the constants of this class. + * + * @param colorType the color type to fetch from the theme + * + * @return the current color of the specified type + * + * @throws IllegalArgumentException for illegal color types + */ + Color getColor(int colorType) + { + Color color = null; + switch (colorType) + { + case PRIMARY1: + color = theme.getPrimary1(); + break; + case PRIMARY2: + color = theme.getPrimary2(); + break; + case PRIMARY3: + color = theme.getPrimary3(); + break; + case SECONDARY1: + color = theme.getSecondary1(); + break; + case SECONDARY2: + color = theme.getSecondary2(); + break; + case SECONDARY3: + color = theme.getSecondary3(); + break; + default: + throw new IllegalArgumentException("Unknown color type: " + colorType); + } + return color; + } + + /** + * Sets the color of the specified type in the current theme. + * + * @param colorType the color type + * @param color the color to set + * + * @throws IllegalArgumentException for illegal color types + */ + void setColor(int colorType, Color color) + { + switch (colorType) + { + case PRIMARY1: + theme.setPrimary1(color); + break; + case PRIMARY2: + theme.setPrimary2(color); + break; + case PRIMARY3: + theme.setPrimary3(color); + break; + case SECONDARY1: + theme.setSecondary1(color); + break; + case SECONDARY2: + theme.setSecondary2(color); + break; + case SECONDARY3: + theme.setSecondary3(color); + break; + default: + throw new IllegalArgumentException("Illegal color type: " + colorType); + } + } + + /** + * The entry point to the application. + * + * @param args ignored + */ + public static void main(String[] args) + { + JFrame f = new JFrame("MetalThemeEditor"); + f.setContentPane(new MetalThemeEditor()); + f.pack(); + f.setVisible(true); + } + + /** + * Returns a DemoFactory that creates a MetalThemeEditor. + * + * @return a DemoFactory that creates a MetalThemeEditor + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new MetalThemeEditor(); + } + }; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/NavigationFilterDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/NavigationFilterDemo.java new file mode 100644 index 0000000..6c1be74 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/NavigationFilterDemo.java @@ -0,0 +1,206 @@ +/* NavigationFilterDemo.java -- An example for the NavigationFilter class. + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath examples. + +GNU Classpath 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; either version 2, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. +*/ + + +package gnu.classpath.examples.swing; + +import java.awt.BorderLayout; +import java.awt.Point; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JTextArea; +import javax.swing.SwingConstants; +import javax.swing.SwingUtilities; +import javax.swing.text.BadLocationException; +import javax.swing.text.JTextComponent; +import javax.swing.text.NavigationFilter; +import javax.swing.text.Position; +import javax.swing.text.Utilities; + +/** + * A demonstration of the <code>javax.swing.text.NavigationFilter</code> class. + * + * <p>It shows a NavigationFilter which lets you walk word-wise + * through a text.</p> + * + * @author Robert Schuster + */ +public class NavigationFilterDemo + extends JPanel + implements ActionListener +{ + + JTextArea textArea; + + /** + * Creates a new demo instance. + */ + public NavigationFilterDemo() + { + createContent(); + // initFrameContent() is only called (from main) when running this app + // standalone + } + + /** + * When the demo is run independently, the frame is displayed, so we should + * initialise the content panel (including the demo content and a close + * button). But when the demo is run as part of the Swing activity board, + * only the demo content panel is used, the frame itself is never displayed, + * so we can avoid this step. + */ + void initFrameContent() + { + JPanel closePanel = new JPanel(); + JButton closeButton = new JButton("Close"); + closeButton.setActionCommand("CLOSE"); + closeButton.addActionListener(this); + closePanel.add(closeButton); + add(closePanel, BorderLayout.SOUTH); + } + + private void createContent() + { + setLayout(new BorderLayout()); + + add(textArea = new JTextArea(10, 20)); + + textArea.setWrapStyleWord(true); + + textArea.setLineWrap(true); + + textArea.setNavigationFilter(new WordFilter()); + + textArea.setText("GNU Classpath, Essential Libraries for Java, " + + "is a GNU project to create free core class " + + "libraries for use with virtual machines and " + + "compilers for the java programming language."); + } + + public void actionPerformed(ActionEvent e) + { + if (e.getActionCommand().equals("CLOSE")) + System.exit(0); + + } + + public static void main(String[] args) + { + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + NavigationFilterDemo app = new NavigationFilterDemo(); + app.initFrameContent(); + JFrame frame = new JFrame("NavigationFilterDemo"); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + } + }); + } + + /** + * Returns a DemoFactory that creates a NavigationFilterDemo. + * + * @return a DemoFactory that creates a NavigationFilterDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new NavigationFilterDemo(); + } + }; + } + + class WordFilter extends NavigationFilter + { + public int getNextVisualPositionFrom(JTextComponent text, + int pos, + Position.Bias bias, + int direction, + Position.Bias[] biasRet) + throws BadLocationException + { + Point pt; + + int newpos = pos; + switch (direction) + { + case SwingConstants.NORTH: + // Find out where the caret want to be positioned ideally. + pt = text.getCaret().getMagicCaretPosition(); + + // Calculate its position above. + newpos = Utilities.getPositionAbove(text, pos, pt.x); + + // If we have a valid position, then calculate the next word start + // from there. + if (newpos != -1) + return Utilities.getWordStart(text, newpos); + else + return pos; + case SwingConstants.SOUTH: + // Find out where the caret want to be positioned ideally. + pt = text.getCaret().getMagicCaretPosition(); + + // Calculate its position below. + newpos = Utilities.getPositionBelow(text, pos, pt.x); + + // If we have a valid position, then calculate the next word start + // from there. + if (newpos != -1) + return Utilities.getWordStart(text, newpos); + else + return pos; + case SwingConstants.WEST: + // Calculate the next word start. + newpos = Utilities.getWordStart(text, newpos);; + + // If that means that the caret will not move, return + // the start of the previous word. + if (newpos != pos) + return newpos; + else + return Utilities.getPreviousWord(text, newpos); + case SwingConstants.EAST: + // Simply calculate the next word's start offset. + return Utilities.getNextWord(text, newpos); + default: + // Do whatever the super implementation did. + return super.getNextVisualPositionFrom(text, pos, bias, + direction, biasRet); + } + } + + } + +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/ProgressBarDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/ProgressBarDemo.java index d62175b..1391a00 100644 --- a/libjava/classpath/examples/gnu/classpath/examples/swing/ProgressBarDemo.java +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/ProgressBarDemo.java @@ -38,13 +38,13 @@ exception statement from your version. */ package gnu.classpath.examples.swing; -import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; +import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JProgressBar; @@ -54,38 +54,37 @@ import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class ProgressBarDemo - extends JFrame + extends JPanel implements ActionListener { /** * Creates a new ProgressBarDemo window with the specified title. - * - * @param title the title of the program window */ - ProgressBarDemo(String title) + ProgressBarDemo() + { + super(); + createContent(); + } + + void initFrameContent() { - super(title); - JPanel content = createContent(); JPanel closePanel = new JPanel(); JButton closeButton = new JButton("Close"); closeButton.setActionCommand("CLOSE"); closeButton.addActionListener(this); closePanel.add(closeButton); - getContentPane().add(content); - getContentPane().add(closePanel, BorderLayout.SOUTH); + add(closePanel); } - static JPanel createContent() + private void createContent() { - JPanel content = new JPanel(); - content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS)); + setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); JPanel horizontalProgressBar = createHorizontalProgressBar(); - content.add(horizontalProgressBar); - content.add(Box.createVerticalStrut(10)); + add(horizontalProgressBar); + add(Box.createVerticalStrut(10)); JPanel verticalProgressBar = createVerticalProgressBar(); - content.add(verticalProgressBar); - return content; + add(verticalProgressBar); } private static JPanel createHorizontalProgressBar() @@ -194,8 +193,10 @@ public class ProgressBarDemo public void actionPerformed(ActionEvent event) { - // TODO Auto-generated method stub - + if (event.getActionCommand().equals("CLOSE")) + { + System.exit(0); + } } /** @@ -210,10 +211,29 @@ public class ProgressBarDemo { public void run() { - ProgressBarDemo app = new ProgressBarDemo("ProgressBar Demo"); - app.pack(); - app.setVisible(true); + ProgressBarDemo app = new ProgressBarDemo(); + app.initFrameContent(); + JFrame frame = new JFrame("ProgressBar Demo"); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); } }); } + + /** + * Returns a DemoFactory that creates a ProgressBarDemo. + * + * @return a DemoFactory that creates a ProgressBarDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new ProgressBarDemo(); + } + }; + } } diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/ScrollBarDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/ScrollBarDemo.java index f90ffd4..505991e 100644 --- a/libjava/classpath/examples/gnu/classpath/examples/swing/ScrollBarDemo.java +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/ScrollBarDemo.java @@ -28,31 +28,27 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; +import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollBar; +import javax.swing.SwingUtilities; /** * A simple scroll bar demo showing various scroll bars in different states. */ public class ScrollBarDemo - extends JFrame + extends JPanel implements ActionListener { - private JPanel content; - /** * Creates a new demo instance. - * - * @param title the frame title. */ - public ScrollBarDemo(String title) + public ScrollBarDemo() { - super(title); - JPanel content = createContent(); - // initFrameContent() is only called (from main) when running this app - // standalone + super(); + createContent(); } /** @@ -62,15 +58,14 @@ public class ScrollBarDemo * only the demo content panel is used, the frame itself is never displayed, * so we can avoid this step. */ - public void initFrameContent() + void initFrameContent() { JPanel closePanel = new JPanel(); JButton closeButton = new JButton("Close"); closeButton.setActionCommand("CLOSE"); closeButton.addActionListener(this); closePanel.add(closeButton); - content.add(closePanel, BorderLayout.SOUTH); - getContentPane().add(content); + add(closePanel, BorderLayout.SOUTH); } /** @@ -80,15 +75,11 @@ public class ScrollBarDemo * bottom of the panel if they want to (a close button is * added if this demo is being run as a standalone demo). */ - JPanel createContent() + private void createContent() { - if (content == null) - { - content = new JPanel(new BorderLayout()); - JPanel panel = createScrollBarPanel(); - content.add(panel); - } - return content; + setLayout(new BorderLayout()); + JPanel panel = createScrollBarPanel(); + add(panel); } private JPanel createScrollBarPanel() @@ -151,10 +142,33 @@ public class ScrollBarDemo public static void main(String[] args) { - ScrollBarDemo app = new ScrollBarDemo("ScrollBar Demo"); - app.initFrameContent(); - app.pack(); - app.setVisible(true); - } + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + ScrollBarDemo app = new ScrollBarDemo(); + app.initFrameContent(); + JFrame frame = new JFrame("ScrollBar Demo"); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + }}); + } + /** + * Returns a DemoFactory that creates a ScrollBarDemo. + * + * @return a DemoFactory that creates a ScrollBarDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new ScrollBarDemo(); + } + }; + } } diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/SliderDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/SliderDemo.java index 2bc5107..df84cc6 100644 --- a/libjava/classpath/examples/gnu/classpath/examples/swing/SliderDemo.java +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/SliderDemo.java @@ -29,15 +29,17 @@ import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JCheckBox; +import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JSlider; +import javax.swing.SwingUtilities; -public class SliderDemo extends JFrame implements ActionListener +public class SliderDemo + extends JPanel + implements ActionListener { - private JPanel content; - JSlider hslider1; JSlider hslider2; JSlider hslider3; @@ -58,12 +60,9 @@ public class SliderDemo extends JFrame implements ActionListener JCheckBox enabledCheckBox; - public SliderDemo(String frameTitle) + public SliderDemo() { - super(frameTitle); - content = createContent(); - // initFrameContent() is only called (from main) when running this app - // standalone + createContent(); } /** @@ -73,15 +72,14 @@ public class SliderDemo extends JFrame implements ActionListener * only the demo content panel is used, the frame itself is never displayed, * so we can avoid this step. */ - public void initFrameContent() + void initFrameContent() { JPanel closePanel = new JPanel(); JButton closeButton = new JButton("Close"); closeButton.setActionCommand("CLOSE"); closeButton.addActionListener(this); closePanel.add(closeButton); - content.add(closePanel, BorderLayout.SOUTH); - getContentPane().add(content); + add(closePanel, BorderLayout.SOUTH); } /** @@ -91,26 +89,22 @@ public class SliderDemo extends JFrame implements ActionListener * bottom of the panel if they want to (a close button is * added if this demo is being run as a standalone demo). */ - JPanel createContent() + private void createContent() { - if (content == null) - { - content = new JPanel(new BorderLayout()); - JPanel panel = new JPanel(new GridLayout(1, 2)); - panel.add(createHorizontalPanel()); - panel.add(createVerticalPanel()); - enabledCheckBox = new JCheckBox("Enabled"); - enabledCheckBox.setSelected(true); - enabledCheckBox.setActionCommand("TOGGLE_ENABLED"); - enabledCheckBox.addActionListener(this); - JPanel checkBoxPanel = new JPanel(); - checkBoxPanel.add(enabledCheckBox); - JPanel panel2 = new JPanel(new BorderLayout()); - panel2.add(panel); - panel2.add(checkBoxPanel, BorderLayout.SOUTH); - content.add(panel2); - } - return content; + setLayout(new BorderLayout()); + JPanel panel = new JPanel(new GridLayout(1, 2)); + panel.add(createHorizontalPanel()); + panel.add(createVerticalPanel()); + enabledCheckBox = new JCheckBox("Enabled"); + enabledCheckBox.setSelected(true); + enabledCheckBox.setActionCommand("TOGGLE_ENABLED"); + enabledCheckBox.addActionListener(this); + JPanel checkBoxPanel = new JPanel(); + checkBoxPanel.add(enabledCheckBox); + JPanel panel2 = new JPanel(new BorderLayout()); + panel2.add(panel); + panel2.add(checkBoxPanel, BorderLayout.SOUTH); + add(panel2); } private JPanel createHorizontalPanel() @@ -259,10 +253,35 @@ public class SliderDemo extends JFrame implements ActionListener } public static void main(String[] args) { - SliderDemo app = new SliderDemo("Slider Demo"); - app.initFrameContent(); - app.pack(); - app.setVisible(true); + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + SliderDemo app = new SliderDemo(); + app.initFrameContent(); + JFrame frame = new JFrame("Slider Demo"); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + } + }); } + + /** + * Returns a DemoFactory that creates a SliderDemo. + * + * @return a DemoFactory that creates a SliderDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new SliderDemo(); + } + }; + } } diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/SpinnerDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/SpinnerDemo.java index 4a05bc4..d0edd96 100644 --- a/libjava/classpath/examples/gnu/classpath/examples/swing/SpinnerDemo.java +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/SpinnerDemo.java @@ -33,24 +33,22 @@ import java.util.Date; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; +import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.SpinnerDateModel; import javax.swing.SpinnerListModel; import javax.swing.SpinnerNumberModel; -import javax.swing.UIManager; -import javax.swing.plaf.metal.DefaultMetalTheme; -import javax.swing.plaf.metal.MetalLookAndFeel; +import javax.swing.SwingUtilities; /** * A simple demo showing various spinners in different states. */ public class SpinnerDemo - extends JFrame + extends JPanel implements ActionListener { - private JPanel content; private JCheckBox spinnerState1; private JSpinner spinner1; private JSpinner spinner2; @@ -65,15 +63,11 @@ public class SpinnerDemo /** * Creates a new demo instance. - * - * @param title the frame title. */ - public SpinnerDemo(String title) + public SpinnerDemo() { - super(title); - JPanel content = createContent(); - // initFrameContent() is only called (from main) when running this app - // standalone + super(); + createContent(); } /** @@ -83,15 +77,14 @@ public class SpinnerDemo * only the demo content panel is used, the frame itself is never displayed, * so we can avoid this step. */ - public void initFrameContent() + void initFrameContent() { JPanel closePanel = new JPanel(); JButton closeButton = new JButton("Close"); closeButton.setActionCommand("CLOSE"); closeButton.addActionListener(this); closePanel.add(closeButton); - content.add(closePanel, BorderLayout.SOUTH); - getContentPane().add(content); + add(closePanel, BorderLayout.SOUTH); } /** @@ -101,18 +94,14 @@ public class SpinnerDemo * bottom of the panel if they want to (a close button is * added if this demo is being run as a standalone demo). */ - JPanel createContent() + private void createContent() { - if (content == null) - { - content = new JPanel(new BorderLayout()); - JPanel panel = new JPanel(new GridLayout(3, 1)); - panel.add(createPanel1()); - panel.add(createPanel2()); - panel.add(createPanel3()); - content.add(panel); - } - return content; + setLayout(new BorderLayout()); + JPanel panel = new JPanel(new GridLayout(3, 1)); + panel.add(createPanel1()); + panel.add(createPanel2()); + panel.add(createPanel3()); + add(panel); } private JPanel createPanel1() @@ -213,18 +202,34 @@ public class SpinnerDemo public static void main(String[] args) { - try - { - MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme()); - UIManager.setLookAndFeel(new javax.swing.plaf.metal.MetalLookAndFeel()); - } - catch (Exception e) { - e.printStackTrace(); - } - SpinnerDemo app = new SpinnerDemo("Spinner Demo"); - app.initFrameContent(); - app.pack(); - app.setVisible(true); + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + SpinnerDemo app = new SpinnerDemo(); + app.initFrameContent(); + JFrame frame = new JFrame("Spinner Demo"); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + } + }); } + /** + * Returns a DemoFactory that creates a SpinnerDemo. + * + * @return a DemoFactory that creates a SpinnerDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new SpinnerDemo(); + } + }; + } } diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/TabbedPaneDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/TabbedPaneDemo.java new file mode 100644 index 0000000..9d797d2 --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/TabbedPaneDemo.java @@ -0,0 +1,145 @@ +/* TabbedPaneDemo.java -- Demonstrates JTabbedPane + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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; either version 2, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.swing; + +import java.awt.BorderLayout; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JTabbedPane; +import javax.swing.SwingConstants; +import javax.swing.SwingUtilities; + +public class TabbedPaneDemo + extends JPanel + implements ActionListener +{ + TabbedPaneDemo() + { + super(); + createContent(); + } + + private void createContent() + { + JPanel p = new JPanel(); + p.setLayout(new GridLayout(2, 2)); + JTabbedPane tabs1 = new JTabbedPane(SwingConstants.TOP); + tabs1.add("Top Item 1", new JButton("Button")); + tabs1.add("Top Item 2", new JButton("Button")); + JTabbedPane tabs2 = new JTabbedPane(SwingConstants.LEFT); + tabs2.add("Left Item 1", new JButton("Button")); + tabs2.add("Left Item 2", new JButton("Button")); + JTabbedPane tabs3 = new JTabbedPane(SwingConstants.BOTTOM); + tabs3.add("Bottom Item 1", new JButton("Button")); + tabs3.add("Bottom Item 2", new JButton("Button")); + JTabbedPane tabs4 = new JTabbedPane(SwingConstants.RIGHT); + tabs4.add("Right Item 1", new JButton("Button")); + tabs4.add("Right Item 2", new JButton("Button")); + p.add(tabs1); + p.add(tabs2); + p.add(tabs3); + p.add(tabs4); + setLayout(new BorderLayout()); + add(p, BorderLayout.CENTER); + } + + public void actionPerformed(ActionEvent e) + { + if (e.getActionCommand().equals("CLOSE")) + { + System.exit(0); + } + } + + /** + * When the demo is run independently, the frame is displayed, so we should + * initialise the content panel (including the demo content and a close + * button). But when the demo is run as part of the Swing activity board, + * only the demo content panel is used, the frame itself is never displayed, + * so we can avoid this step. + */ + void initFrameContent() + { + JPanel closePanel = new JPanel(); + JButton closeButton = new JButton("Close"); + closeButton.setActionCommand("CLOSE"); + closeButton.addActionListener(this); + closePanel.add(closeButton); + add(closePanel, BorderLayout.SOUTH); + } + + public static void main(String[] args) + { + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + TabbedPaneDemo app = new TabbedPaneDemo(); + app.initFrameContent(); + JFrame frame = new JFrame("TabbedPane Demo"); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + } + }); + } + + /** + * Returns a DemoFactory that creates a TabbedPaneDemo. + * + * @return a DemoFactory that creates a TabbedPaneDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new TabbedPaneDemo(); + } + }; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/TableDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/TableDemo.java index 1fbf2de..e661ee3 100644 --- a/libjava/classpath/examples/gnu/classpath/examples/swing/TableDemo.java +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/TableDemo.java @@ -41,10 +41,14 @@ package gnu.classpath.examples.swing; import java.awt.BorderLayout; import java.awt.Dimension; +import javax.swing.Icon; +import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; +import javax.swing.SwingUtilities; +import javax.swing.plaf.metal.MetalIconFactory; import javax.swing.table.DefaultTableColumnModel; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; @@ -54,7 +58,7 @@ import javax.swing.table.TableColumn; * * @author Audrius Meskauskas (audriusa@bioinformatics.org) */ -public class TableDemo extends JFrame +public class TableDemo extends JPanel { /** * The initial row count for this table. @@ -74,11 +78,12 @@ public class TableDemo extends JFrame { /** - * Return true if the cell is editable. All cells are editable. + * Return true if the cell is editable. + * Icons are not editable, other cells are editable. */ - public boolean isCellEditable(int parm1, int parm2) + public boolean isCellEditable(int row, int column) { - return true; + return column!=1; } /** @@ -124,19 +129,20 @@ public class TableDemo extends JFrame } /** - * The first column contains booleans, others - default class. + * The first column contains booleans, the second - icons, + * others - default class. */ public Class getColumnClass(int column) { if (column == 0) return Boolean.class; + else if (column == 1) + return Icon.class; else return super.getColumnClass(column); } } - private JPanel content; - /** * The table being displayed. */ @@ -154,13 +160,11 @@ public class TableDemo extends JFrame /** * Create the table demo with the given titel. - * - * @param title the frame title. */ - public TableDemo(String title) + public TableDemo() { - super(title); - getContentPane().add(createContent(), BorderLayout.CENTER); + super(); + createContent(); } /** @@ -169,55 +173,59 @@ public class TableDemo extends JFrame * the bottom of the panel if they want to (a close button is added if this * demo is being run as a standalone demo). */ - JPanel createContent() + private void createContent() { - if (content == null) + setLayout(new BorderLayout()); + values = new Object[rows][]; + + // The icons that appear in the icon column. + Icon[] icons = new Icon[] + { + MetalIconFactory.getTreeComputerIcon(), + MetalIconFactory.getTreeHardDriveIcon(), + MetalIconFactory.getTreeFolderIcon(), + }; + + for (int i = 0; i < values.length; i++) { - JPanel p = new JPanel(); - p.setLayout(new BorderLayout()); - values = new Object[rows][]; - for (int i = 0; i < values.length; i++) + values[i] = new Object[cols]; + for (int j = 2; j < cols; j++) { - values[i] = new Object[cols]; - for (int j = 1; j < cols; j++) - { - values[i][j] = "" + ((char) ('a' + j)) + i; - } - values [i][0] = i % 2 == 0? Boolean.TRUE : Boolean.FALSE; + values[i][j] = "" + ((char) ('a' + j)) + i; } + values [i][0] = i % 2 == 0? Boolean.TRUE : Boolean.FALSE; + values [i][1] = icons [ i % icons.length ]; + } - table.setModel(model); + table.setModel(model); - // Make the columns with gradually increasing width: - DefaultTableColumnModel cm = new DefaultTableColumnModel(); - for (int i = 0; i < cols; i++) - { - TableColumn column = new TableColumn(i); + // Make the columns with gradually increasing width: + DefaultTableColumnModel cm = new DefaultTableColumnModel(); + for (int i = 0; i < cols; i++) + { + TableColumn column = new TableColumn(i); - // Showing the variable width columns. - int width = 100+20*i; - column.setPreferredWidth(width); + // Showing the variable width columns. + int width = 100+10*i; + column.setPreferredWidth(width); - // If we do not set the header value here, the value, returned - // by model, is used. - column.setHeaderValue("Width +"+(20*i)); + // If we do not set the header value here, the value, returned + // by model, is used. + column.setHeaderValue("Width +"+(20*i)); - cm.addColumn(column); - } + cm.addColumn(column); + } - table.setColumnModel(cm); + table.setColumnModel(cm); - // Create the table, place it into scroll pane and place - // the pane into this frame. - JScrollPane scroll = new JScrollPane(); + // Create the table, place it into scroll pane and place + // the pane into this frame. + JScrollPane scroll = new JScrollPane(); - // The horizontal scroll bar is never needed. - scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); - scroll.getViewport().add(table); - p.add(scroll, BorderLayout.CENTER); - content = p; - } - return content; + // The horizontal scroll bar is never needed. + scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + scroll.getViewport().add(table); + add(scroll, BorderLayout.CENTER); } /** @@ -228,9 +236,33 @@ public class TableDemo extends JFrame */ public static void main(String[] args) { - TableDemo frame = new TableDemo("Table double click on the cell to edit."); - frame.setSize(new Dimension(640, 100)); - frame.validate(); - frame.setVisible(true); + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + TableDemo demo = new TableDemo(); + JFrame frame = new JFrame(); + frame.getContentPane().add(demo); + frame.setSize(new Dimension(640, 100)); + frame.setVisible(true); + } + }); + } + + /** + * Returns a DemoFactory that creates a TableDemo. + * + * @return a DemoFactory that creates a TableDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new TableDemo(); + } + }; } } diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/TextAreaDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/TextAreaDemo.java new file mode 100644 index 0000000..b72997c --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/TextAreaDemo.java @@ -0,0 +1,620 @@ +/* TextAreaDemo.java -- An example showing various textareas in Swing. + Copyright (C) 2005, 2006 Free Software Foundation, Inc. + + This file is part of GNU Classpath examples. + + GNU Classpath 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; either version 2, or (at your option) + any later version. + + GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + */ + + +package gnu.classpath.examples.swing; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.GridLayout; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Shape; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.BorderFactory; +import javax.swing.Box; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTabbedPane; +import javax.swing.JTextArea; +import javax.swing.SwingUtilities; +import javax.swing.text.BadLocationException; +import javax.swing.text.DefaultCaret; +import javax.swing.text.Highlighter; +import javax.swing.text.JTextComponent; +import javax.swing.text.View; +import javax.swing.text.LayeredHighlighter.LayerPainter; + +/** + * A simple textare demo showing various textareas in different states. + */ +public class TextAreaDemo + extends JPanel + implements ActionListener +{ + + /** + * A custom caret for demonstration purposes. This class is inspired by the + * CornerCaret from the OReilly Swing book. + * + * @author Roman Kennke (kennke@aicas.com) + */ + static class CornerCaret + extends DefaultCaret + { + public CornerCaret() + { + super(); + setBlinkRate(500); + } + + protected synchronized void damage(Rectangle r) + { + if (r == null) + return; + x = r.x; + y = r.y + (r.height * 4 / 5 - 3); + width = 5; + height = 5; + repaint(); + } + + public void paint(Graphics g) + { + JTextComponent comp = getComponent(); + if (comp == null) + return; + int dot = getDot(); + Rectangle r = null; + try + { + r = comp.modelToView(dot); + } + catch (BadLocationException e) + { + return; + } + if (r == null) + return; + int dist = r.height * 4 / 5 - 3; + if ((x != r.x) || (y != r.y + dist)) + { + repaint(); + x = r.x; + y = r.y + dist; + width = 5; + height = 5; + } + if (isVisible()) + { + g.drawLine(r.x, r.y + dist, r.x, r.y + dist + 4); + g.drawLine(r.x, r.y + dist + 4, r.x + 4, r.y + dist + 4); + } + } + } + + static class DemoHighlightPainter + extends LayerPainter + { + static DemoHighlightPainter INSTANCE = new DemoHighlightPainter(); + + static Color[] colors = { Color.BLUE, Color.CYAN, Color.GRAY, Color.GREEN, + Color.MAGENTA, Color.ORANGE, Color.PINK, + Color.ORANGE, Color.RED, Color.BLUE, Color.YELLOW }; + + public DemoHighlightPainter() + { + super(); + } + + private void paintHighlight(Graphics g, Rectangle rect) + { + g.fillRect(rect.x, rect.y, rect.width, rect.height); + } + + public void paint(Graphics g, int p0, int p1, Shape bounds, JTextComponent t) + { + try + { + + for (int i = p0; i < p1; i++) + { + Rectangle r = t.modelToView(i); + Point l1 = t.modelToView(i + 1).getLocation(); + + g.setColor(colors[(int) (Math.random() * colors.length)]); + g.fillOval(r.x, r.y, l1.x - r.x, r.height); + } + } + catch (BadLocationException ble) + { + } + + } + + public Shape paintLayer(Graphics g, int p0, int p1, Shape bounds, + JTextComponent c, View view) + { + paint(g, p0, p1, bounds, c); + + return bounds; + } + } + + /** + * The non wrapping text areas and state buttons. + */ + JTextArea textarea1; + + JTextArea textarea2; + + JTextArea textarea3; + + JCheckBox enabled1; + + JCheckBox editable1; + + JPanel panel1; + + /** + * The char wrapping textareas and state buttons. + */ + JTextArea textarea4; + + JTextArea textarea5; + + JTextArea textarea6; + + JCheckBox enabled2; + + JCheckBox editable2; + + /** + * The word wrapping textareas and state buttons. + */ + JTextArea textarea7; + + JTextArea textarea8; + + JTextArea textarea9; + + JCheckBox enabled3; + + JCheckBox editable3; + + /** + * The custom colored textareas and state buttons. + */ + JTextArea textarea10; + + JTextArea textarea11; + + JTextArea textarea12; + + JTextArea textarea13; + + JTextArea textarea14; + + JTextArea textarea14b; + + JCheckBox enabled4; + + JCheckBox editable4; + + /** + * Some miscellaneous textarea demos. + */ + JTextArea textarea15; + + JTextArea textarea16; + + JTextArea textarea17; + + JCheckBox enabled5; + + JCheckBox editable5; + + /** + * Creates a new demo instance. + */ + public TextAreaDemo() + { + super(); + createContent(); + } + + /** + * When the demo is run independently, the frame is displayed, so we should + * initialise the content panel (including the demo content and a close + * button). But when the demo is run as part of the Swing activity board, only + * the demo content panel is used, the frame itself is never displayed, so we + * can avoid this step. + */ + void initFrameContent() + { + JPanel closePanel = new JPanel(); + JButton closeButton = new JButton("Close"); + closeButton.setActionCommand("CLOSE"); + closeButton.addActionListener(this); + closePanel.add(closeButton); + add(closePanel, BorderLayout.SOUTH); + } + + /** + * Returns a panel with the demo content. The panel uses a BorderLayout(), and + * the BorderLayout.SOUTH area is empty, to allow callers to add controls to + * the bottom of the panel if they want to (a close button is added if this + * demo is being run as a standalone demo). + */ + private void createContent() + { + setLayout(new BorderLayout()); + JTabbedPane tabPane = new JTabbedPane(); + tabPane.addTab("Non-wrap", createNonWrapPanel()); + tabPane.addTab("Char-wrap", createCharWrapPanel()); + tabPane.addTab("Word-wrap", createWordWrapPanel()); + tabPane.addTab("Custom colors", createCustomColoredPanel()); + tabPane.addTab("Misc", createMiscPanel()); + add(tabPane); + } + + private JPanel createNonWrapPanel() + { + JPanel panel = new JPanel(new BorderLayout()); + panel.setBorder(BorderFactory.createTitledBorder("Not wrapping")); + + panel1 = new JPanel(new GridLayout(2, 2)); + + textarea1 = new JTextArea("Hello World!"); + textarea1.setFont(new Font("Dialog", Font.PLAIN, 8)); + panel1.add(new JScrollPane(textarea1)); + + textarea2 = new JTextArea("Hello World!"); + textarea2.setFont(new Font("Dialog", Font.ITALIC, 12)); + panel1.add(new JScrollPane(textarea2)); + + textarea3 = new JTextArea("Hello World!"); + textarea3.setFont(new Font("Dialog", Font.BOLD, 14)); + panel1.add(new JScrollPane(textarea3)); + + panel.add(panel1); + + JPanel statePanel = new JPanel(); + statePanel.setLayout(new BoxLayout(statePanel, BoxLayout.Y_AXIS)); + statePanel.add(Box.createVerticalGlue()); + enabled1 = new JCheckBox("enabled"); + enabled1.setSelected(true); + enabled1.addActionListener(this); + enabled1.setActionCommand("ENABLED1"); + statePanel.add(enabled1); + editable1 = new JCheckBox("editable"); + editable1.setSelected(true); + editable1.addActionListener(this); + editable1.setActionCommand("EDITABLE1"); + statePanel.add(editable1); + statePanel.add(Box.createVerticalGlue()); + panel.add(statePanel, BorderLayout.EAST); + + return panel; + } + + private JPanel createCharWrapPanel() + { + JPanel panel = new JPanel(new BorderLayout()); + panel.setBorder(BorderFactory.createTitledBorder("Wrap at char bounds")); + + JPanel innerPanel = new JPanel(new GridLayout(2, 2)); + + textarea4 = new JTextArea("Hello World!"); + textarea4.setLineWrap(true); + textarea4.setFont(new Font("Dialog", Font.PLAIN, 8)); + innerPanel.add(new JScrollPane(textarea4)); + + textarea5 = new JTextArea("Hello World!"); + textarea5.setLineWrap(true); + textarea5.setFont(new Font("Dialog", Font.ITALIC, 12)); + innerPanel.add(new JScrollPane(textarea5)); + + textarea6 = new JTextArea("Hello World!"); + textarea6.setLineWrap(true); + textarea6.setFont(new Font("Dialog", Font.BOLD, 14)); + innerPanel.add(new JScrollPane(textarea6)); + + panel.add(innerPanel); + + JPanel statePanel = new JPanel(); + statePanel.setLayout(new BoxLayout(statePanel, BoxLayout.Y_AXIS)); + statePanel.add(Box.createVerticalGlue()); + enabled2 = new JCheckBox("enabled"); + enabled2.setSelected(true); + enabled2.addActionListener(this); + enabled2.setActionCommand("ENABLED2"); + statePanel.add(enabled2); + editable2 = new JCheckBox("editable"); + editable2.setSelected(true); + editable2.addActionListener(this); + editable2.setActionCommand("EDITABLE2"); + statePanel.add(editable2); + statePanel.add(Box.createVerticalGlue()); + panel.add(statePanel, BorderLayout.EAST); + + return panel; + } + + private JPanel createWordWrapPanel() + { + JPanel panel = new JPanel(new BorderLayout()); + panel.setBorder(BorderFactory.createTitledBorder("Wrap at word bounds")); + + JPanel innerPanel = new JPanel(new GridLayout(2, 2)); + + textarea7 = new JTextArea("Hello World!"); + textarea7.setWrapStyleWord(true); + textarea7.setLineWrap(true); + textarea7.setFont(new Font("Dialog", Font.PLAIN, 8)); + innerPanel.add(new JScrollPane(textarea7)); + + textarea8 = new JTextArea("Hello World!"); + textarea8.setWrapStyleWord(true); + textarea8.setLineWrap(true); + textarea8.setFont(new Font("Dialog", Font.ITALIC, 12)); + innerPanel.add(new JScrollPane(textarea8)); + + textarea9 = new JTextArea("Hello World!"); + textarea9.setWrapStyleWord(true); + textarea9.setLineWrap(true); + textarea9.setFont(new Font("Dialog", Font.BOLD, 14)); + innerPanel.add(new JScrollPane(textarea9)); + + panel.add(innerPanel); + + JPanel statePanel = new JPanel(); + statePanel.setLayout(new BoxLayout(statePanel, BoxLayout.Y_AXIS)); + statePanel.add(Box.createVerticalGlue()); + enabled3 = new JCheckBox("enabled"); + enabled3.setSelected(true); + enabled3.addActionListener(this); + enabled3.setActionCommand("ENABLED3"); + statePanel.add(enabled3); + editable3 = new JCheckBox("editable"); + editable3.setSelected(true); + editable3.addActionListener(this); + editable3.setActionCommand("EDITABLE3"); + statePanel.add(editable3); + statePanel.add(Box.createVerticalGlue()); + panel.add(statePanel, BorderLayout.EAST); + + return panel; + } + + private JPanel createCustomColoredPanel() + { + JPanel panel = new JPanel(new BorderLayout()); + + JPanel innerPanel = new JPanel(new GridLayout(3, 2)); + panel.setBorder(BorderFactory.createTitledBorder("Custom colors")); + + textarea10 = new JTextArea("custom foreground", 10, 15); + textarea10.setForeground(Color.GREEN); + innerPanel.add(new JScrollPane(textarea10)); + + textarea11 = new JTextArea("custom background", 10, 15); + textarea11.setBackground(Color.YELLOW); + innerPanel.add(new JScrollPane(textarea11)); + + textarea12 = new JTextArea("custom disabled textcolor", 10, 15); + textarea12.setDisabledTextColor(Color.BLUE); + innerPanel.add(new JScrollPane(textarea12)); + + textarea13 = new JTextArea("custom selected text color", 10, 15); + textarea13.setSelectedTextColor(Color.RED); + innerPanel.add(new JScrollPane(textarea13)); + + textarea14 = new JTextArea("custom selection color", 10, 15); + textarea14.setSelectionColor(Color.RED); + innerPanel.add(new JScrollPane(textarea14)); + + textarea14b = new JTextArea("custom selection and selected text color", 10, 15); + textarea14b.setSelectedTextColor(Color.WHITE); + textarea14b.setSelectionColor(Color.BLACK); + innerPanel.add(new JScrollPane(textarea14b)); + + panel.add(innerPanel); + + JPanel statePanel = new JPanel(); + statePanel.setLayout(new BoxLayout(statePanel, BoxLayout.Y_AXIS)); + statePanel.add(Box.createVerticalGlue()); + enabled4 = new JCheckBox("enabled"); + enabled4.setSelected(true); + enabled4.addActionListener(this); + enabled4.setActionCommand("ENABLED4"); + statePanel.add(enabled4); + editable4 = new JCheckBox("editable"); + editable4.setSelected(true); + editable4.addActionListener(this); + editable4.setActionCommand("EDITABLE4"); + statePanel.add(editable4); + statePanel.add(Box.createVerticalGlue()); + panel.add(statePanel, BorderLayout.EAST); + + return panel; + } + + private JPanel createMiscPanel() + { + JPanel panel = new JPanel(new BorderLayout()); + panel.setBorder(BorderFactory.createTitledBorder("Miscellaneous")); + + JPanel innerPanel = new JPanel(new GridLayout(2, 2)); + + textarea15 = new JTextArea("Custom Caret"); + textarea15.setCaret(new CornerCaret()); + innerPanel.add(new JScrollPane(textarea15)); + + textarea16 = new JTextArea("Custom Caret color"); + textarea16.setCaretColor(Color.MAGENTA); + innerPanel.add(new JScrollPane(textarea16)); + + textarea16 = new JTextArea("Custom Selection painter"); + textarea16.setFont(new Font("Dialog", Font.PLAIN, 24)); + textarea16.setCaret(new DefaultCaret() + { + public Highlighter.HighlightPainter getSelectionPainter() + { + return DemoHighlightPainter.INSTANCE; + } + }); + + innerPanel.add(new JScrollPane(textarea16)); + + panel.add(innerPanel); + + JPanel statePanel = new JPanel(); + statePanel.setLayout(new BoxLayout(statePanel, BoxLayout.Y_AXIS)); + statePanel.add(Box.createVerticalGlue()); + enabled5 = new JCheckBox("enabled"); + enabled5.setSelected(true); + enabled5.addActionListener(this); + enabled5.setActionCommand("ENABLED5"); + statePanel.add(enabled5); + editable5 = new JCheckBox("editable"); + editable5.setSelected(true); + editable5.addActionListener(this); + editable5.setActionCommand("EDITABLE5"); + statePanel.add(editable5); + statePanel.add(Box.createVerticalGlue()); + panel.add(statePanel, BorderLayout.EAST); + + return panel; + } + + public void actionPerformed(ActionEvent e) + { + if (e.getActionCommand().equals("CLOSE")) + { + System.exit(0); + } + else if (e.getActionCommand().equals("ENABLED1")) + { + boolean enabled = enabled1.isSelected(); + textarea1.setEnabled(enabled); + textarea2.setEnabled(enabled); + textarea3.setEnabled(enabled); + } + else if (e.getActionCommand().equals("EDITABLE1")) + { + boolean editable = editable1.isSelected(); + textarea1.setEditable(editable); + textarea2.setEditable(editable); + textarea3.setEditable(editable); + } + else if (e.getActionCommand().equals("ENABLED2")) + { + boolean enabled = enabled2.isSelected(); + textarea4.setEnabled(enabled); + textarea5.setEnabled(enabled); + textarea6.setEnabled(enabled); + } + else if (e.getActionCommand().equals("EDITABLE2")) + { + boolean editable = editable2.isSelected(); + textarea4.setEditable(editable); + textarea5.setEditable(editable); + textarea6.setEditable(editable); + } + else if (e.getActionCommand().equals("ENABLED3")) + { + boolean enabled = enabled3.isSelected(); + textarea7.setEnabled(enabled); + textarea8.setEnabled(enabled); + textarea9.setEnabled(enabled); + } + else if (e.getActionCommand().equals("EDITABLE3")) + { + boolean editable = editable3.isSelected(); + textarea7.setEditable(editable); + textarea8.setEditable(editable); + textarea9.setEditable(editable); + } + else if (e.getActionCommand().equals("ENABLED4")) + { + boolean enabled = enabled4.isSelected(); + textarea10.setEnabled(enabled); + textarea11.setEnabled(enabled); + textarea12.setEnabled(enabled); + textarea13.setEnabled(enabled); + textarea14.setEnabled(enabled); + textarea14b.setEnabled(enabled); + } + else if (e.getActionCommand().equals("EDITABLE4")) + { + boolean editable = editable4.isSelected(); + textarea10.setEditable(editable); + textarea11.setEditable(editable); + textarea12.setEditable(editable); + textarea13.setEditable(editable); + textarea14.setEditable(editable); + textarea14b.setEditable(editable); + } + } + + public static void main(String[] args) + { + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + TextAreaDemo app = new TextAreaDemo(); + app.initFrameContent(); + JFrame frame = new JFrame(); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + } + }); + } + + /** + * Returns a DemoFactory that creates a TextAreaDemo. + * + * @return a DemoFactory that creates a TextAreaDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new TextAreaDemo(); + } + }; + } +} diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/TextFieldDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/TextFieldDemo.java index 6eda469..ba0fefa 100644 --- a/libjava/classpath/examples/gnu/classpath/examples/swing/TextFieldDemo.java +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/TextFieldDemo.java @@ -1,5 +1,5 @@ /* TextFieldDemo.java -- An example showing various textfields in Swing. - Copyright (C) 2005, 2006, Free Software Foundation, Inc. + Copyright (C) 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Classpath examples. @@ -27,7 +27,9 @@ import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.GridLayout; +import java.awt.Point; import java.awt.Rectangle; +import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -36,18 +38,28 @@ import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JCheckBox; +import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; +import javax.swing.JScrollPane; import javax.swing.JTextField; +import javax.swing.SwingUtilities; +import javax.swing.border.CompoundBorder; +import javax.swing.border.EmptyBorder; +import javax.swing.border.LineBorder; +import javax.swing.border.TitledBorder; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultCaret; +import javax.swing.text.Highlighter; import javax.swing.text.JTextComponent; +import javax.swing.text.View; +import javax.swing.text.LayeredHighlighter.LayerPainter; /** * A simple textfield demo showing various textfields in different states. */ public class TextFieldDemo - extends JFrame + extends JPanel implements ActionListener { @@ -106,66 +118,96 @@ public class TextFieldDemo } } } + + static class DemoHighlightPainter + extends LayerPainter + { + + static DemoHighlightPainter INSTANCE = new DemoHighlightPainter(); + - private JPanel content; + static Color[] colors = { Color.BLUE, Color.CYAN, Color.GRAY, Color.GREEN, + Color.MAGENTA, Color.ORANGE, Color.PINK, + Color.ORANGE, Color.RED, Color.BLUE, Color.YELLOW }; + + + public DemoHighlightPainter() + { + super(); + } + + private void paintHighlight(Graphics g, Rectangle rect) + { + g.fillRect(rect.x, rect.y, rect.width, rect.height); + } + + public void paint(Graphics g, int p0, int p1, Shape bounds, JTextComponent t) + { + try + { + + for (int i = p0; i < p1; i++) + { + Rectangle r = t.modelToView(i); + Point l1 = t.modelToView(i + 1).getLocation(); + + g.setColor(colors[(int) (Math.random() * colors.length)]); + g.fillOval(r.x, r.y, l1.x - r.x, r.height); + } + } + catch (BadLocationException ble) + { + } + } + + public Shape paintLayer(Graphics g, int p0, int p1, Shape bounds, + JTextComponent c, View view) + { + paint(g, p0, p1, bounds, c); + + return bounds; + } + + } /** * The left aligned textfields and state buttons. */ - JTextField textfield1; - JTextField textfield2; - JTextField textfield3; - JCheckBox enabled1; - JCheckBox editable1; - JPanel textFieldPanel1; + Compound compound1; + /** * The right aligned textfields and state buttons. */ - JTextField textfield4; - JTextField textfield5; - JTextField textfield6; - JCheckBox enabled2; - JCheckBox editable2; + Compound compound2; /** * The centered textfields and state buttons. */ - JTextField textfield7; - JTextField textfield8; - JTextField textfield9; - JCheckBox enabled3; - JCheckBox editable3; + Compound compound3; /** * The custom colored textfields and state buttons. */ - JTextField textfield10; - JTextField textfield11; - JTextField textfield12; - JTextField textfield13; - JTextField textfield14; - JCheckBox enabled4; - JCheckBox editable4; + Compound compound4; + Compound compound5; /** - * Some miscallenous textfield demos. + * Some miscellaneous textfield demos. */ - JTextField textfield15; - JTextField textfield16; - JCheckBox enabled5; - JCheckBox editable5; + Compound compound6; + + /** + * Some textfields with custom borders. + */ + Compound compound7; /** * Creates a new demo instance. - * - * @param title the frame title. */ - public TextFieldDemo(String title) + public TextFieldDemo() { - super(title); - JPanel content = createContent(); - // initFrameContent() is only called (from main) when running this app - // standalone + super(); + createContent(); } /** @@ -175,15 +217,14 @@ public class TextFieldDemo * only the demo content panel is used, the frame itself is never displayed, * so we can avoid this step. */ - public void initFrameContent() + void initFrameContent() { JPanel closePanel = new JPanel(); JButton closeButton = new JButton("Close"); closeButton.setActionCommand("CLOSE"); closeButton.addActionListener(this); closePanel.add(closeButton); - content.add(closePanel, BorderLayout.SOUTH); - getContentPane().add(content); + add(closePanel, BorderLayout.SOUTH); } /** @@ -193,239 +234,185 @@ public class TextFieldDemo * bottom of the panel if they want to (a close button is * added if this demo is being run as a standalone demo). */ - JPanel createContent() + private void createContent() { - if (content == null) - { - content = new JPanel(new BorderLayout()); - JPanel panel = new JPanel(new GridLayout(5, 1)); - panel.add(createLeftAlignedPanel()); - panel.add(createRightAlignedPanel()); - panel.add(createCenteredPanel()); - panel.add(createCustomColoredPanel()); - panel.add(createMiscPanel()); - content.add(panel); - //content.setPreferredSize(new Dimension(400, 300)); - } - return content; + setLayout(new BorderLayout()); + JPanel panel = new JPanel(new GridLayout(7, 1)); + panel.add(createLeftAlignedPanel()); + panel.add(createRightAlignedPanel()); + panel.add(createCenteredPanel()); + panel.add(createCustomColorPanel1()); + panel.add(createCustomColorPanel2()); + panel.add(createCustomBordersPanel()); + panel.add(createMiscPanel()); + + // Put everything in a scroll pane to make it neccessary + // to reach the bottom inner panels if the screen is to small. + add(new JScrollPane(panel)); } private JPanel createLeftAlignedPanel() { - JPanel panel = new JPanel(new BorderLayout()); - panel.setBorder(BorderFactory.createTitledBorder("Left aligned")); + compound1 = createTextFieldCompound("Left aligned", 1); + + compound1.setupTextfields("Hello World!", + JTextField.LEFT, + new Font[] { new Font("Dialog", Font.PLAIN, 8), + new Font("Dialog", Font.ITALIC, 12), + new Font("Dialog", Font.BOLD, 14) + }); - textFieldPanel1 = new JPanel(); - textFieldPanel1.setLayout(new BoxLayout(textFieldPanel1, BoxLayout.X_AXIS)); - - textfield1 = new JTextField("Hello World!"); - textfield1.setHorizontalAlignment(JTextField.LEFT); - textfield1.setFont(new Font("Dialog", Font.PLAIN, 8)); - textFieldPanel1.add(textfield1); - - textfield2 = new JTextField("Hello World!"); - textfield2.setHorizontalAlignment(JTextField.LEFT); - textfield2.setFont(new Font("Dialog", Font.ITALIC, 12)); - textFieldPanel1.add(textfield2); - - textfield3 = new JTextField("Hello World!"); - textfield3.setHorizontalAlignment(JTextField.LEFT); - textfield3.setFont(new Font("Dialog", Font.BOLD, 14)); - textFieldPanel1.add(textfield3); + return compound1.panel; + } + + private Compound createTextFieldCompound(String title, int actionCommandNo) + { + Compound compound = new Compound(); + compound.panel = new JPanel(new BorderLayout()); + compound.panel.setBorder(BorderFactory.createTitledBorder(title)); + + compound.textFieldPanel = new JPanel(); + compound.textFieldPanel.setLayout(new BoxLayout(compound.textFieldPanel, BoxLayout.X_AXIS)); - panel.add(textFieldPanel1); + compound.panel.add(compound.textFieldPanel); JPanel statePanel = new JPanel(); statePanel.setLayout(new BoxLayout(statePanel, BoxLayout.Y_AXIS)); statePanel.add(Box.createVerticalGlue()); - enabled1 = new JCheckBox("enabled"); - enabled1.setSelected(true); - enabled1.addActionListener(this); - enabled1.setActionCommand("ENABLED1"); - statePanel.add(enabled1); - editable1 = new JCheckBox("editable"); - editable1.setSelected(true); - editable1.addActionListener(this); - editable1.setActionCommand("EDITABLE1"); - statePanel.add(editable1); + compound.enabled = new JCheckBox("enabled"); + compound.enabled.setSelected(true); + compound.enabled.addActionListener(this); + compound.enabled.setActionCommand("ENABLED" + actionCommandNo); + statePanel.add(compound.enabled); + compound.editable = new JCheckBox("editable"); + compound.editable.setSelected(true); + compound.editable.addActionListener(this); + compound.editable.setActionCommand("EDITABLE" + actionCommandNo); + statePanel.add(compound.editable); statePanel.add(Box.createVerticalGlue()); - panel.add(statePanel, BorderLayout.EAST); + compound.panel.add(statePanel, BorderLayout.EAST); - return panel; + return compound; } private JPanel createRightAlignedPanel() { - JPanel panel = new JPanel(new BorderLayout()); - panel.setBorder(BorderFactory.createTitledBorder("Right aligned")); + compound2 = createTextFieldCompound("Right aligned", 2); + + compound2.setupTextfields("Hello World!", + JTextField.RIGHT, + new Font[] { new Font("Dialog", Font.PLAIN, 8), + new Font("Dialog", Font.ITALIC, 12), + new Font("Dialog", Font.BOLD, 14) + }); - JPanel textFieldPanel = new JPanel(); - textFieldPanel.setLayout(new BoxLayout(textFieldPanel, BoxLayout.X_AXIS)); - - textfield4 = new JTextField("Hello World!"); - textfield4.setHorizontalAlignment(JTextField.RIGHT); - textfield4.setFont(new Font("Dialog", Font.PLAIN, 8)); - textFieldPanel.add(textfield4); - - textfield5 = new JTextField("Hello World!"); - textfield5.setHorizontalAlignment(JTextField.RIGHT); - textfield5.setFont(new Font("Dialog", Font.ITALIC, 12)); - textFieldPanel.add(textfield5); - - textfield6 = new JTextField("Hello World!"); - textfield6.setHorizontalAlignment(JTextField.RIGHT); - textfield6.setFont(new Font("Dialog", Font.BOLD, 14)); - textFieldPanel.add(textfield6); - - panel.add(textFieldPanel); - - JPanel statePanel = new JPanel(); - statePanel.setLayout(new BoxLayout(statePanel, BoxLayout.Y_AXIS)); - statePanel.add(Box.createVerticalGlue()); - enabled2 = new JCheckBox("enabled"); - enabled2.setSelected(true); - enabled2.addActionListener(this); - enabled2.setActionCommand("ENABLED2"); - statePanel.add(enabled2); - editable2 = new JCheckBox("editable"); - editable2.setSelected(true); - editable2.addActionListener(this); - editable2.setActionCommand("EDITABLE2"); - statePanel.add(editable2); - statePanel.add(Box.createVerticalGlue()); - panel.add(statePanel, BorderLayout.EAST); - - return panel; + return compound2.panel; } private JPanel createCenteredPanel() { - JPanel panel = new JPanel(new BorderLayout()); - panel.setBorder(BorderFactory.createTitledBorder("Centered")); - - JPanel textFieldPanel = new JPanel(); - textFieldPanel.setLayout(new BoxLayout(textFieldPanel, BoxLayout.X_AXIS)); - - textfield7 = new JTextField("Hello World!"); - textfield7.setHorizontalAlignment(JTextField.CENTER); - textfield7.setFont(new Font("Dialog", Font.PLAIN, 8)); - textFieldPanel.add(textfield7); - - textfield8 = new JTextField("Hello World!"); - textfield8.setHorizontalAlignment(JTextField.CENTER); - textfield8.setFont(new Font("Dialog", Font.ITALIC, 12)); - textFieldPanel.add(textfield8); - - textfield9 = new JTextField("Hello World!"); - textfield9.setHorizontalAlignment(JTextField.CENTER); - textfield9.setFont(new Font("Dialog", Font.BOLD, 14)); - textFieldPanel.add(textfield9); - - panel.add(textFieldPanel); - - JPanel statePanel = new JPanel(); - statePanel.setLayout(new BoxLayout(statePanel, BoxLayout.Y_AXIS)); - statePanel.add(Box.createVerticalGlue()); - enabled3 = new JCheckBox("enabled"); - enabled3.setSelected(true); - enabled3.addActionListener(this); - enabled3.setActionCommand("ENABLED3"); - statePanel.add(enabled3); - editable3 = new JCheckBox("editable"); - editable3.setSelected(true); - editable3.addActionListener(this); - editable3.setActionCommand("EDITABLE3"); - statePanel.add(editable3); - statePanel.add(Box.createVerticalGlue()); - panel.add(statePanel, BorderLayout.EAST); - - return panel; + compound3 = createTextFieldCompound("Centered", 3); + + compound3.setupTextfields("Hello World!", + JTextField.CENTER, + new Font[] { new Font("Dialog", Font.PLAIN, 8), + new Font("Dialog", Font.ITALIC, 12), + new Font("Dialog", Font.BOLD, 14) + }); + + return compound3.panel; } - private JPanel createCustomColoredPanel() + private JPanel createCustomColorPanel1() { - JPanel panel = new JPanel(new BorderLayout()); - - JPanel textFieldPanel = new JPanel(); - panel.setBorder(BorderFactory.createTitledBorder("Custom colors")); - textFieldPanel.setLayout(new BoxLayout(textFieldPanel, BoxLayout.X_AXIS)); + compound4 = createTextFieldCompound("Custom colors I", 4); - textfield10 = new JTextField("custom foreground"); - textfield10.setForeground(Color.GREEN); - textFieldPanel.add(textfield10); + compound4.textfield1 = new JTextField("custom foreground"); + compound4.textfield1.setForeground(Color.RED); + compound4.textFieldPanel.add(compound4.textfield1); - textfield11 = new JTextField("custom background"); - textfield11.setForeground(Color.YELLOW); - textFieldPanel.add(textfield11); + compound4.textfield2 = new JTextField("custom background"); + compound4.textfield2.setBackground(Color.YELLOW); + compound4.textFieldPanel.add(compound4.textfield2); - textfield12 = new JTextField("custom disabled textcolor"); - textfield12.setDisabledTextColor(Color.BLUE); - textFieldPanel.add(textfield12); - - textfield13 = new JTextField("custom selected text color"); - textfield13.setSelectedTextColor(Color.RED); - textFieldPanel.add(textfield13); + compound4.textfield3 = new JTextField("custom foreground and background"); + compound4.textfield3.setForeground(Color.RED); + compound4.textfield3.setBackground(Color.YELLOW); + compound4.textFieldPanel.add(compound4.textfield3); + + return compound4.panel; + + } + + private JPanel createCustomColorPanel2() + { + compound5 = createTextFieldCompound("Custom colors II", 5); - textfield14 = new JTextField("custom selection color"); - textfield14.setSelectionColor(Color.CYAN); - textFieldPanel.add(textfield14); + compound5.textfield1 = new JTextField("custom disabled textcolor"); + compound5.textfield1.setDisabledTextColor(Color.BLUE); + compound5.textFieldPanel.add(compound5.textfield1); - panel.add(textFieldPanel); + compound5.textfield2 = new JTextField("custom selected text color"); + compound5.textfield2.setSelectedTextColor(Color.RED); + compound5.textFieldPanel.add(compound5.textfield2); - JPanel statePanel = new JPanel(); - statePanel.setLayout(new BoxLayout(statePanel, BoxLayout.Y_AXIS)); - statePanel.add(Box.createVerticalGlue()); - enabled4 = new JCheckBox("enabled"); - enabled4.setSelected(true); - enabled4.addActionListener(this); - enabled4.setActionCommand("ENABLED4"); - statePanel.add(enabled4); - editable4 = new JCheckBox("editable"); - editable4.setSelected(true); - editable4.addActionListener(this); - editable4.setActionCommand("EDITABLE4"); - statePanel.add(editable4); - statePanel.add(Box.createVerticalGlue()); - panel.add(statePanel, BorderLayout.EAST); - - return panel; + compound5.textfield3 = new JTextField("custom selection color"); + compound5.textfield3.setSelectionColor(Color.BLACK); + compound5.textFieldPanel.add(compound5.textfield3); + + return compound5.panel; + } private JPanel createMiscPanel() { - JPanel panel = new JPanel(new BorderLayout()); - panel.setBorder(BorderFactory.createTitledBorder("Miscallenous")); - - JPanel textFieldPanel = new JPanel(); - textFieldPanel.setLayout(new BoxLayout(textFieldPanel, BoxLayout.X_AXIS)); + compound6 = createTextFieldCompound("Miscellaneous", 6); + + compound6.textfield1 = new JTextField("Custom Caret"); + compound6.textfield1.setCaret(new CornerCaret()); + compound6.textFieldPanel.add(compound6.textfield1); + + compound6.textfield2 = new JTextField("Custom Caret color"); + compound6.textfield2.setForeground(Color.LIGHT_GRAY); + compound6.textfield2.setBackground(Color.BLACK); + compound6.textfield2.setSelectedTextColor(Color.BLACK); + compound6.textfield2.setCaretColor(Color.WHITE); + compound6.textfield2.setSelectionColor(Color.DARK_GRAY); + compound6.textFieldPanel.add(compound6.textfield2); + + compound6.textfield3 = new JTextField("Custom highlighter"); + compound6.textfield3.setCaret(new DefaultCaret() + { + public Highlighter.HighlightPainter getSelectionPainter() + { + return DemoHighlightPainter.INSTANCE; + } + }); + compound6.textFieldPanel.add(compound6.textfield3); - textfield15 = new JTextField("Custom Caret"); - textfield15.setCaret(new CornerCaret()); - textFieldPanel.add(textfield15); + return compound6.panel; + } + + private JPanel createCustomBordersPanel() + { + compound7 = createTextFieldCompound("Custom borders", 7); - textfield16 = new JTextField("Custom Caret color"); - textfield16.setCaretColor(Color.MAGENTA); - textFieldPanel.add(textfield16); + compound7.textfield1 = new JTextField("red 5 pixel lineborder"); + compound7.textfield1.setBorder(new LineBorder(Color.RED, 5)); + compound7.textFieldPanel.add(compound7.textfield1); - panel.add(textFieldPanel); + compound7.textfield2 = new JTextField("complex irregular border"); - JPanel statePanel = new JPanel(); - statePanel.setLayout(new BoxLayout(statePanel, BoxLayout.Y_AXIS)); - statePanel.add(Box.createVerticalGlue()); - enabled5 = new JCheckBox("enabled"); - enabled5.setSelected(true); - enabled5.addActionListener(this); - enabled5.setActionCommand("ENABLED5"); - statePanel.add(enabled5); - editable5 = new JCheckBox("editable"); - editable5.setSelected(true); - editable5.addActionListener(this); - editable5.setActionCommand("EDITABLE5"); - statePanel.add(editable5); - statePanel.add(Box.createVerticalGlue()); - panel.add(statePanel, BorderLayout.EAST); + CompoundBorder innerCompound = new CompoundBorder(new EmptyBorder(5, 40, 15, 10), new LineBorder(Color.BLACK)); + CompoundBorder outerCompound = new CompoundBorder(new LineBorder(Color.BLACK), innerCompound); + compound7.textfield2.setBorder(outerCompound); + compound7.textFieldPanel.add(compound7.textfield2); + + compound7.textfield3 = new JTextField("a titled border", 10); + compound7.textfield3.setBorder(new TitledBorder(null, "Freak Out Border", TitledBorder.CENTER, TitledBorder.LEFT)); + compound7.textFieldPanel.add(compound7.textfield3); - return panel; + return compound7.panel; } public void actionPerformed(ActionEvent e) @@ -436,72 +423,172 @@ public class TextFieldDemo } else if (e.getActionCommand().equals("ENABLED1")) { - boolean enabled = enabled1.isSelected(); - textfield1.setEnabled(enabled); - textfield2.setEnabled(enabled); - textfield3.setEnabled(enabled); + boolean enabled = compound1.enabled.isSelected(); + compound1.textfield1.setEnabled(enabled); + compound1.textfield2.setEnabled(enabled); + compound1.textfield3.setEnabled(enabled); } else if (e.getActionCommand().equals("EDITABLE1")) { - boolean editable = editable1.isSelected(); - textfield1.setEditable(editable); - textfield2.setEditable(editable); - textfield3.setEditable(editable); + boolean editable = compound1.editable.isSelected(); + compound1.textfield1.setEditable(editable); + compound1.textfield2.setEditable(editable); + compound1.textfield3.setEditable(editable); } else if (e.getActionCommand().equals("ENABLED2")) { - boolean enabled = enabled2.isSelected(); - textfield4.setEnabled(enabled); - textfield5.setEnabled(enabled); - textfield6.setEnabled(enabled); + boolean enabled = compound2.enabled.isSelected(); + compound2.textfield1.setEnabled(enabled); + compound2.textfield2.setEnabled(enabled); + compound2.textfield3.setEnabled(enabled); } else if (e.getActionCommand().equals("EDITABLE2")) { - boolean editable = editable2.isSelected(); - textfield4.setEditable(editable); - textfield5.setEditable(editable); - textfield6.setEditable(editable); + boolean editable = compound2.editable.isSelected(); + compound2.textfield1.setEditable(editable); + compound2.textfield2.setEditable(editable); + compound2.textfield3.setEditable(editable); } else if (e.getActionCommand().equals("ENABLED3")) { - boolean enabled = enabled3.isSelected(); - textfield7.setEnabled(enabled); - textfield8.setEnabled(enabled); - textfield9.setEnabled(enabled); + boolean enabled = compound3.enabled.isSelected(); + compound3.textfield1.setEnabled(enabled); + compound3.textfield2.setEnabled(enabled); + compound3.textfield3.setEnabled(enabled); } else if (e.getActionCommand().equals("EDITABLE3")) { - boolean editable = editable3.isSelected(); - textfield7.setEditable(editable); - textfield8.setEditable(editable); - textfield9.setEditable(editable); + boolean editable = compound3.editable.isSelected(); + compound3.textfield1.setEditable(editable); + compound3.textfield2.setEditable(editable); + compound3.textfield3.setEditable(editable); } else if (e.getActionCommand().equals("ENABLED4")) { - boolean enabled = enabled4.isSelected(); - textfield10.setEnabled(enabled); - textfield11.setEnabled(enabled); - textfield12.setEnabled(enabled); - textfield13.setEnabled(enabled); - textfield14.setEnabled(enabled); + boolean enabled = compound4.enabled.isSelected(); + compound4.textfield1.setEnabled(enabled); + compound4.textfield2.setEnabled(enabled); + compound4.textfield3.setEnabled(enabled); } else if (e.getActionCommand().equals("EDITABLE4")) { - boolean editable = editable4.isSelected(); - textfield10.setEditable(editable); - textfield11.setEditable(editable); - textfield12.setEditable(editable); - textfield13.setEditable(editable); - textfield14.setEditable(editable); + boolean editable = compound4.editable.isSelected(); + compound4.textfield1.setEditable(editable); + compound4.textfield2.setEditable(editable); + compound4.textfield3.setEditable(editable); + } + else if (e.getActionCommand().equals("ENABLED5")) + { + boolean enabled = compound5.enabled.isSelected(); + compound5.textfield1.setEnabled(enabled); + compound5.textfield2.setEnabled(enabled); + compound5.textfield3.setEnabled(enabled); + } + else if (e.getActionCommand().equals("EDITABLE5")) + { + boolean editable = compound5.editable.isSelected(); + compound5.textfield1.setEditable(editable); + compound5.textfield2.setEditable(editable); + compound5.textfield3.setEditable(editable); + } + else if (e.getActionCommand().equals("ENABLED6")) + { + boolean enabled = compound6.enabled.isSelected(); + compound6.textfield1.setEnabled(enabled); + compound6.textfield2.setEnabled(enabled); + compound6.textfield3.setEnabled(enabled); + } + else if (e.getActionCommand().equals("EDITABLE6")) + { + boolean editable = compound6.editable.isSelected(); + compound6.textfield1.setEditable(editable); + compound6.textfield2.setEditable(editable); + compound6.textfield3.setEditable(editable); + } + else if (e.getActionCommand().equals("ENABLED7")) + { + boolean enabled = compound7.enabled.isSelected(); + compound7.textfield1.setEnabled(enabled); + compound7.textfield2.setEnabled(enabled); + compound7.textfield3.setEnabled(enabled); + } + else if (e.getActionCommand().equals("EDITABLE7")) + { + boolean editable = compound7.editable.isSelected(); + compound7.textfield1.setEditable(editable); + compound7.textfield2.setEditable(editable); + compound7.textfield3.setEditable(editable); } } public static void main(String[] args) { - TextFieldDemo app = new TextFieldDemo("TextField Demo"); - app.initFrameContent(); - app.pack(); - app.setVisible(true); + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + TextFieldDemo app = new TextFieldDemo(); + app.initFrameContent(); + JFrame frame = new JFrame("TextField demo"); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + } + }); } + /** + * Returns a DemoFactory that creates a TextFieldDemo. + * + * @return a DemoFactory that creates a TextFieldDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new TextFieldDemo(); + } + }; + } + + static class Compound + { + JTextField textfield1; + JTextField textfield2; + JTextField textfield3; + JCheckBox enabled; + JCheckBox editable; + JPanel textFieldPanel; + JPanel panel; + + /** Creates and initializes the textfields with the same text and + * alignment but with a different font. + * + * @param title The text for the textfields. + * @param align The alignment for the textfields. + * @param fonts The fonts to be used for the textfields. + */ + void setupTextfields(String title, int align, Font[] fonts) + { + textfield1 = new JTextField(title); + textfield1.setHorizontalAlignment(align); + textfield1.setFont(fonts[0]); + textFieldPanel.add(textfield1); + + textfield2 = new JTextField(title); + textfield2.setHorizontalAlignment(align); + textfield2.setFont(fonts[1]); + textFieldPanel.add(textfield2); + + textfield3 = new JTextField(title); + textfield3.setHorizontalAlignment(align); + textfield3.setFont(fonts[2]); + textFieldPanel.add(textfield3); + } + + } + } diff --git a/libjava/classpath/examples/gnu/classpath/examples/swing/TreeDemo.java b/libjava/classpath/examples/gnu/classpath/examples/swing/TreeDemo.java new file mode 100644 index 0000000..32f765f --- /dev/null +++ b/libjava/classpath/examples/gnu/classpath/examples/swing/TreeDemo.java @@ -0,0 +1,291 @@ +/* TreeDemo.java -- Demostrates JTree + Copyright (C) 2006 Free Software Foundation, Inc. + +This file is part of GNU Classpath. + +GNU Classpath 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; either version 2, or (at your option) +any later version. + +GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the +Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +02110-1301 USA. + +Linking this library statically or dynamically with other modules is +making a combined work based on this library. Thus, the terms and +conditions of the GNU General Public License cover the whole +combination. + +As a special exception, the copyright holders of this library give you +permission to link this library with independent modules to produce an +executable, regardless of the license terms of these independent +modules, and to copy and distribute the resulting executable under +terms of your choice, provided that you also meet, for each linked +independent module, the terms and conditions of the license of that +module. An independent module is a module which is not derived from +or based on this library. If you modify this library, you may extend +this exception to your version of the library, but you are not +obligated to do so. If you do not wish to do so, delete this +exception statement from your version. */ + + +package gnu.classpath.examples.swing; + +import java.awt.BorderLayout; +import java.awt.JobAttributes.DefaultSelectionType; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.DebugGraphics; +import javax.swing.JButton; +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTree; +import javax.swing.SwingUtilities; +import javax.swing.event.TreeSelectionEvent; +import javax.swing.event.TreeSelectionListener; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeModel; +import javax.swing.tree.DefaultTreeSelectionModel; +import javax.swing.tree.TreePath; +import javax.swing.tree.TreeSelectionModel; + +public class TreeDemo + extends JPanel + implements ActionListener +{ + + TreeDemo() + { + super(); + createContent(); + } + + private void createContent() + { + // non-leafs + DefaultMutableTreeNode root = new DefaultMutableTreeNode("Exotic Subsistence"); + DefaultMutableTreeNode fruit = new DefaultMutableTreeNode("Interesting Fruit"); + DefaultMutableTreeNode veg = new DefaultMutableTreeNode("Extraordinary Vegetables"); + DefaultMutableTreeNode liq = new DefaultMutableTreeNode("Peculiar Liquids"); + + // leafs + DefaultMutableTreeNode f1 = new DefaultMutableTreeNode("Abiu"); + DefaultMutableTreeNode f2 = new DefaultMutableTreeNode("Bamboo Shoots"); + DefaultMutableTreeNode f3 = new DefaultMutableTreeNode("Breadfruit"); + DefaultMutableTreeNode f4 = new DefaultMutableTreeNode("Canistel"); + DefaultMutableTreeNode f5 = new DefaultMutableTreeNode("Duku"); + DefaultMutableTreeNode f6 = new DefaultMutableTreeNode("Guava"); + DefaultMutableTreeNode f7 = new DefaultMutableTreeNode("Jakfruit"); + DefaultMutableTreeNode f8 = new DefaultMutableTreeNode("Quaribea"); + + DefaultMutableTreeNode v1 = new DefaultMutableTreeNode("Amaranth"); + DefaultMutableTreeNode v2 = new DefaultMutableTreeNode("Kiwano"); + DefaultMutableTreeNode v3 = new DefaultMutableTreeNode("Leeks"); + DefaultMutableTreeNode v4 = new DefaultMutableTreeNode("Luffa"); + DefaultMutableTreeNode v5 = new DefaultMutableTreeNode("Chayote"); + DefaultMutableTreeNode v6 = new DefaultMutableTreeNode("Jicama"); + DefaultMutableTreeNode v7 = new DefaultMutableTreeNode("Okra"); + + DefaultMutableTreeNode l1 = new DefaultMutableTreeNode("Alcoholic"); + DefaultMutableTreeNode l11 = new DefaultMutableTreeNode("Caipirinha"); + DefaultMutableTreeNode l21 = new DefaultMutableTreeNode("Mojito"); + DefaultMutableTreeNode l31 = new DefaultMutableTreeNode("Margarita"); + DefaultMutableTreeNode l41 = new DefaultMutableTreeNode("Martini"); + DefaultMutableTreeNode l5 = new DefaultMutableTreeNode("Non Alcoholic"); + DefaultMutableTreeNode l55 = new DefaultMutableTreeNode("Babaji"); + DefaultMutableTreeNode l65 = new DefaultMutableTreeNode("Chikita"); + + root.add(fruit); + root.add(veg); + root.add(liq); + fruit.add(f1); + fruit.add(f2); + fruit.add(f3); + fruit.add(f4); + fruit.add(f5); + fruit.add(f6); + fruit.add(f7); + fruit.add(f8); + veg.add(v1); + veg.add(v2); + veg.add(v3); + veg.add(v4); + veg.add(v5); + veg.add(v6); + veg.add(v7); + liq.add(l1); + l1.add(l11); + l1.add(l21); + l1.add(l31); + l1.add(l41); + liq.add(l5); + l5.add(l55); + l5.add(l65); + + final JTree tree = new JTree(root); + tree.setLargeModel(true); + tree.setEditable(true); + final DefaultTreeSelectionModel selModel = new DefaultTreeSelectionModel(); + selModel.setSelectionMode( + DefaultTreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); + tree.setSelectionModel(selModel); + + // buttons to add and delete + JButton add = new JButton("add element"); + add.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + for (int i = 0; i < tree.getRowCount(); i++) + { + if (tree.isRowSelected(i)) + { + TreePath p = tree.getPathForRow(i); + DefaultMutableTreeNode n = (DefaultMutableTreeNode) p. + getLastPathComponent(); + n.add(new DefaultMutableTreeNode("New Element")); + + // The expansion state of the parent node does not change + // by default. We will expand it manually, to ensure that the + // added node is immediately visible. + tree.expandPath(p); + + // Refresh the tree (.repaint would be not enough both in + // Classpath and Sun implementations). + DefaultTreeModel model = (DefaultTreeModel) tree.getModel(); + model.reload(n); + break; + } + } + } + }); + + // Demonstration of the various selection modes + final JCheckBox cbSingle = new JCheckBox("single selection"); + cbSingle.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + if (cbSingle.isSelected()) + selModel.setSelectionMode( + DefaultTreeSelectionModel.SINGLE_TREE_SELECTION); + else + selModel.setSelectionMode( + DefaultTreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); + } + }); + + // Demonstration of the root visibility changes + final JCheckBox cbRoot = new JCheckBox("root"); + cbRoot.addActionListener(new ActionListener() + { + public void actionPerformed(ActionEvent e) + { + tree.setRootVisible(cbRoot.isSelected()); + } + }); + cbRoot.setSelected(true); + + // Demonstration of the tree selection listener. + final JLabel choice = new JLabel("Make a choice"); + tree.getSelectionModel().addTreeSelectionListener( + new TreeSelectionListener() + { + public void valueChanged(TreeSelectionEvent event) + { + TreePath was = event.getOldLeadSelectionPath(); + TreePath now = event.getNewLeadSelectionPath(); + String swas = + was == null ? "none":was.getLastPathComponent().toString(); + String snow = + now == null ? "none":now.getLastPathComponent().toString(); + choice.setText("From "+swas+" to "+snow); + } + } + ); + + setLayout(new BorderLayout()); + + JPanel p2 = new JPanel(); + p2.add(add); + p2.add(cbSingle); + p2.add(cbRoot); + + tree.getSelectionModel(). + setSelectionMode(DefaultTreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); + + add(p2, BorderLayout.NORTH); + add(new JScrollPane(tree), BorderLayout.CENTER); + add(choice, BorderLayout.SOUTH); + } + + public void actionPerformed(ActionEvent e) + { + if (e.getActionCommand().equals("CLOSE")) + { + System.exit(0); + } + } + + /** + * When the demo is run independently, the frame is displayed, so we should + * initialise the content panel (including the demo content and a close + * button). But when the demo is run as part of the Swing activity board, + * only the demo content panel is used, the frame itself is never displayed, + * so we can avoid this step. + */ + void initFrameContent() + { + JPanel closePanel = new JPanel(); + JButton closeButton = new JButton("Close"); + closeButton.setActionCommand("CLOSE"); + closeButton.addActionListener(this); + closePanel.add(closeButton); + add(closePanel, BorderLayout.SOUTH); + } + + public static void main(String[] args) + { + SwingUtilities.invokeLater + (new Runnable() + { + public void run() + { + TreeDemo app = new TreeDemo(); + app.initFrameContent(); + JFrame frame = new JFrame("Tree Demo"); + frame.getContentPane().add(app); + frame.pack(); + frame.setVisible(true); + } + }); + } + + /** + * Returns a DemoFactory that creates a TreeDemo. + * + * @return a DemoFactory that creates a TreeDemo + */ + public static DemoFactory createDemoFactory() + { + return new DemoFactory() + { + public JComponent createDemo() + { + return new TreeDemo(); + } + }; + } +} |