Java/Swing Components/JGoodies Looks

Материал из Java эксперт
Версия от 06:56, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Builds the main frame in the Simple Looks Demo

/*
 * Copyright (c) 2001-2005 JGoodies Karsten Lentzsch. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions are met:
 * 
 *  o Redistributions of source code must retain the above copyright notice, 
 *    this list of conditions and the following disclaimer. 
 *     
 *  o Redistributions in binary form must reproduce the above copyright notice, 
 *    this list of conditions and the following disclaimer in the documentation 
 *    and/or other materials provided with the distribution. 
 *     
 *  o Neither the name of JGoodies Karsten Lentzsch nor the names of 
 *    its contributors may be used to endorse or promote products derived 
 *    from this software without specific prior written permission. 
 *     
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.UIResource;
import javax.swing.plaf.metal.DefaultMetalTheme;
import javax.swing.plaf.metal.MetalLookAndFeel;
import com.jgoodies.looks.LookUtils;
import com.jgoodies.looks.Options;
import com.jgoodies.looks.plastic.PlasticLookAndFeel;
import com.jgoodies.looks.windows.WindowsLookAndFeel;
/** 
 * Builds the main frame in the Simple Looks Demo. 
 * Demonstrates and tests different multi-platform issues by
 * showing a variety of Swing widgets in different configurations.
 * Also, this frame contains examples for Swing misuse,
 * that can be automatically corrected by ClearLook.<p>
 * 
 * This class provides a couple of protected methods that create
 * components or a builder. The full JGoodies Looks Demo overrides 
 * these methods to vend components or builders from the 
 * JGoodies UI framework that better handle different platforms.
 * 
 * @author Karsten Lentzsch
 * @version $Revision: 1.17 $
 */
public class DemoFrame extends JFrame {
    protected static final Dimension PREFERRED_SIZE =
        LookUtils.IS_LOW_RESOLUTION 
            ? new Dimension(650, 510) 
            : new Dimension(730, 560);
            
    private static final String COPYRIGHT = 
        "\u00a9 2001-2005 JGoodies Karsten Lentzsch. All Rights Reserved.";    
        
    
    /** Describes optional settings of the JGoodies Looks. */
    private final Settings settings;
    /**
     * Constructs a <code>DemoFrame</code>, configures the UI, 
     * and builds the content.
     */
    protected DemoFrame(Settings settings) {
        this.settings = settings;
        configureUI();
        build();
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    }
    
    public static void main(String[] args) {
        DemoFrame instance = new DemoFrame(createSettings());
        instance.setSize(PREFERRED_SIZE);
        instance.locateOnScreen(instance);
        instance.setVisible(true);
    }
    
    private static Settings createSettings() {
        Settings settings = Settings.createDefault();
        
        // Configure the settings here.
        
        return settings;
    }
    
    /**
     * Configures the user interface; requests Swing settings and 
     * jGoodies Looks options from the launcher.
     */
    private void configureUI() {
        Options.setDefaultIconSize(new Dimension(18, 18));
        // Set font options    
        UIManager.put(
            Options.USE_SYSTEM_FONTS_APP_KEY,
            settings.isUseSystemFonts());
        Options.setGlobalFontSizeHints(settings.getFontSizeHints());
        Options.setUseNarrowButtons(settings.isUseNarrowButtons());
        
        // Global options
        Options.setTabIconsEnabled(settings.isTabIconsEnabled());
        UIManager.put(Options.POPUP_DROP_SHADOW_ENABLED_KEY, 
                settings.isPopupDropShadowEnabled());
        // Swing Settings
        LookAndFeel selectedLaf = settings.getSelectedLookAndFeel();
        if (selectedLaf instanceof PlasticLookAndFeel) {
            PlasticLookAndFeel.setMyCurrentTheme(settings.getSelectedTheme());
            PlasticLookAndFeel.setTabStyle(settings.getPlasticTabStyle());
            PlasticLookAndFeel.setHighContrastFocusColorsEnabled(
                settings.isPlasticHighContrastFocusEnabled());
        } else if (selectedLaf.getClass() == MetalLookAndFeel.class) {
            MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme());
        }
        
        // Work around caching in MetalRadioButtonUI
        JRadioButton radio = new JRadioButton();
        radio.getUI().uninstallUI(radio);
        JCheckBox checkBox = new JCheckBox();
        checkBox.getUI().uninstallUI(checkBox);
        try {
            UIManager.setLookAndFeel(selectedLaf);
        } catch (Exception e) {
            System.out.println("Can"t change L&F: " + e);
        }
    }
    /**
     * Builds the <code>DemoFrame</code> using Options from the Launcher.
     */
    private void build() {
        setContentPane(buildContentPane());
        setTitle(getWindowTitle());
        setJMenuBar(
            createMenuBuilder().buildMenuBar(
                settings,
                createHelpActionListener(),
                createAboutActionListener()));
        setIconImage(readImageIcon("eye_16x16.gif").getImage());
    }
    
    
    /** 
     * Creates and returns a builder that builds the menu.
     * This method is overriden by the full JGoodies Looks Demo to use
     * a more sophisticated menu builder that uses the JGoodies
     * UI Framework.
     * 
     * @return the builder that builds the menu bar
     */
    protected MenuBuilder createMenuBuilder() {
        return new MenuBuilder();
    }
    /**
     * Builds and answers the content.
     */
    private JComponent buildContentPane() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.add(buildToolBar(), BorderLayout.NORTH);
        panel.add(buildMainPanel(), BorderLayout.CENTER);
        return panel;
    }
    // Tool Bar *************************************************************
    /**
     * Builds, configures and returns the toolbar. Requests
     * HeaderStyle, look-specific BorderStyles, and Plastic 3D Hint 
     * from Launcher.
     */
    private Component buildToolBar() {
        JToolBar toolBar = new JToolBar();
        toolBar.setFloatable(false);
        toolBar.putClientProperty("JToolBar.isRollover", Boolean.TRUE);
        // Swing
        toolBar.putClientProperty(
            Options.HEADER_STYLE_KEY,
            settings.getToolBarHeaderStyle());
        toolBar.putClientProperty(
            PlasticLookAndFeel.BORDER_STYLE_KEY,
            settings.getToolBarPlasticBorderStyle());
        toolBar.putClientProperty(
            WindowsLookAndFeel.BORDER_STYLE_KEY,
            settings.getToolBarWindowsBorderStyle());
        toolBar.putClientProperty(
            PlasticLookAndFeel.IS_3D_KEY,
            settings.getToolBar3DHint());
        AbstractButton button;
        toolBar.add(createToolBarButton("backward.gif"));
        button = createToolBarButton("forward.gif");
        button.setEnabled(false);
        toolBar.add(button);
        toolBar.add(createToolBarButton("home.gif"));
        toolBar.addSeparator();
        toolBar.add(createOpenButton());
        toolBar.add(createToolBarButton("print.gif"));
        toolBar.add(createToolBarButton("refresh.gif"));
        toolBar.addSeparator();
        ButtonGroup group = new ButtonGroup();
        button = createToolBarRadioButton("pie_mode.png");
        button.setSelectedIcon(readImageIcon("pie_mode_selected.gif"));
        group.add(button);
        button.setSelected(true);
        toolBar.add(button);
        button = createToolBarRadioButton("bar_mode.png");
        button.setSelectedIcon(readImageIcon("bar_mode_selected.gif"));
        group.add(button);
        toolBar.add(button);
        button = createToolBarRadioButton("table_mode.png");
        button.setSelectedIcon(readImageIcon("table_mode_selected.gif"));
        group.add(button);
        toolBar.add(button);
        toolBar.addSeparator();
        button = createToolBarButton("help.gif");
        button.addActionListener(createHelpActionListener());
        toolBar.add(button);
        toolBar.add(Box.createGlue());
        button = new RolloverCheckButton();
        button.setToolTipText("Shall show border when mouse is over");
        button.setMargin(new Insets(0, 0, 0, 0));
        toolBar.add(button);
        return toolBar;
    }
    private AbstractButton createOpenButton() {
        AbstractButton button = createToolBarButton("open.gif");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new JFileChooser().showOpenDialog(DemoFrame.this);
            }
        });
        return button;
    }
    /**
     * Creates and returns a <code>JButton</code> 
     * configured for use in a JToolBar.<p>
     * 
     * This is a simplified method that is overriden by the Looks Demo.
     * The full code uses the JGoodies UI framework"s ToolBarButton
     * that better handles platform differences.
     */
    protected AbstractButton createToolBarButton(String iconName) {
        JButton button = new JButton(readImageIcon(iconName));
        button.setFocusable(false);
        return button;
    }
    /**
     * Creates and returns a <code>JToggleButton</code> 
     * configured for use in a JToolBar.<p>
     * 
     * This is a simplified method that is overriden by the Looks Demo.
     * The full code uses the JGoodies UI framework"s ToolBarButton
     * that better handles platform differences.
     */
    protected AbstractButton createToolBarRadioButton(String iconName) {
        JToggleButton button = new JToggleButton(readImageIcon(iconName));
        button.setFocusable(false);
        return button;
    }
    // Tabbed Pane **********************************************************
    /**
     * Builds and answers the tabbed pane.
     */
    private Component buildMainPanel() {
        JTabbedPane tabbedPane = new JTabbedPane(SwingConstants.TOP);
        //tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        addTabs(tabbedPane);
        tabbedPane.setBorder(new EmptyBorder(10, 10, 10, 10));
        return tabbedPane;
    }
    private void addTabs(JTabbedPane tabbedPane) {
        tabbedPane.addTab("State",     new StatesTab().build());
        tabbedPane.addTab("Align",     new AlignmentTab().build());
        tabbedPane.addTab("Tab",       new TabTestTab().build());
        tabbedPane.addTab("Split",     new SplitTab().build());
        tabbedPane.addTab("HTML",      new HtmlTab().build());
        tabbedPane.addTab("Dialog",    new DialogsTab().build(tabbedPane));
        tabbedPane.addTab("Desktop",   new DesktopTab().build());
        tabbedPane.addTab("Narrow",    new NarrowTab().build());
    }
    
    protected String getWindowTitle() {
        return "Simple Looks Demo";
    }
    
    // Helper Code **********************************************************************
    /*
     * Looks up and answers an icon for the specified filename suffix.<p>
     */
    protected static ImageIcon readImageIcon(String filename) {
        URL url =
            DemoFrame.class.getClassLoader().getResource("images/" + filename);
        return new ImageIcon(url);
    }
    /**
     * Locates the given component on the screen"s center.
     */
    protected void locateOnScreen(Component component) {
        Dimension paneSize = component.getSize();
        Dimension screenSize = component.getToolkit().getScreenSize();
        component.setLocation(
            (screenSize.width  - paneSize.width)  / 2,
            (screenSize.height - paneSize.height) / 2);
    }
    /**
     * Creates and answers an ActionListener that opens the help viewer.
     */
    protected ActionListener createHelpActionListener() {
        return null;
    }
    /**
     * Creates and answers an ActionListener that opens the about dialog.
     */
    protected ActionListener createAboutActionListener() {
        return new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(
                    DemoFrame.this,
                    "The simple Looks Demo Application\n\n"
                        + COPYRIGHT + "\n\n");
            }
        };
    }
    // Checks that all tool bar buttons have a UIResource border
    private static class RolloverCheckButton extends JButton {
        private boolean checked = false;
        public void paint(Graphics g) {
            if (!checked) {
                checkAndSetResult();
            }
            super.paint(g);
        }
        private void checkAndSetResult() {
            Icon passedIcon = readImageIcon("passed.gif");
            Icon failedIcon = readImageIcon("failed.gif");
            boolean passed = allButtonBordersAreUIResources();
            setIcon(passed ? passedIcon : failedIcon);
            setText(passed ? "Can Swap L&F" : "Can"t Swap L&F");
            checked = true;
        }
        /**
         * Checks and answers whether all button borders implement UIResource.
         */
        private boolean allButtonBordersAreUIResources() {
            JToolBar bar = (JToolBar) getParent();
            for (int i = bar.getComponentCount() - 1; i >= 0; i--) {
                Component child = bar.getComponent(i);
                if (child instanceof JButton) {
                    Border b = ((JButton) child).getBorder();
                    if (!(b instanceof UIResource))
                        return false;
                }
            }
            return true;
        }
    }
}





The main class of the JGoodies Tiny application

/*
 * Copyright (c) 2001-2005 JGoodies Karsten Lentzsch. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without 
 * modification, are permitted provided that the following conditions are met:
 * 
 *  o Redistributions of source code must retain the above copyright notice, 
 *    this list of conditions and the following disclaimer. 
 *     
 *  o Redistributions in binary form must reproduce the above copyright notice, 
 *    this list of conditions and the following disclaimer in the documentation 
 *    and/or other materials provided with the distribution. 
 *     
 *  o Neither the name of JGoodies Karsten Lentzsch nor the names of 
 *    its contributors may be used to endorse or promote products derived 
 *    from this software without specific prior written permission. 
 *     
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */
import java.awt.BorderLayout;
import java.awt.ruponent;
import java.awt.Dimension;
import java.awt.Frame;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import com.jgoodies.looks.FontSizeHints;
import com.jgoodies.looks.LookUtils;
import com.jgoodies.looks.Options;

/**
 * The main class of the JGoodies Tiny application. 
 * It configures the UI, builds the main frame and opens it.
 * <p>
 * The JGoodies Looks Professional comes with Skeleton, a much better sample
 * application that separates concerns and uses a scalable architecture.
 *
 * @author Karsten Lentzsch
 */
public class Tiny {
    /**
     * Configures the UI, then builds and opens the UI.
     */
    public static void main(String[] args) {
        Tiny instance = new Tiny();
        instance.configureUI();
        instance.buildInterface();
    }
    /**
     * Configures the UI; tries to set the system look on Mac, 
     * <code>WindowsLookAndFeel</code> on general Windows, and
     * <code>Plastic3DLookAndFeel</code> on Windows XP and all other OS.<p>
     * 
     * The JGoodies Swing Suite"s <code>ApplicationStarter</code>,
     * <code>ExtUIManager</code>, and <code>LookChoiceStrategies</code>
     * classes provide a much more fine grained algorithm to choose and
     * restore a look and theme.
     */
    private void configureUI() {
        UIManager.put(Options.USE_SYSTEM_FONTS_APP_KEY, Boolean.TRUE);
        Options.setGlobalFontSizeHints(FontSizeHints.MIXED);
        Options.setDefaultIconSize(new Dimension(18, 18));
        String lafName =
            LookUtils.IS_OS_WINDOWS_XP
                ? Options.getCrossPlatformLookAndFeelClassName()
                : Options.getSystemLookAndFeelClassName();
        try {
            UIManager.setLookAndFeel(lafName);
        } catch (Exception e) {
            System.err.println("Can"t set look & feel:" + e);
        }
    }
    /**
     * Creates and configures a frame, builds the menu bar, builds the
     * content, locates the frame on the screen, and finally shows the frame.
     */
    private void buildInterface() {
        JFrame frame = new JFrame();
        frame.setJMenuBar(buildMenuBar());
        frame.setContentPane(buildContentPane());
        frame.setSize(600, 400);
        locateOnScreen(frame);
        frame.setTitle("JGoodies :: Tiny");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
    /**
     * Locates the frame on the screen center.
     */
    private void locateOnScreen(Frame frame) {
        Dimension paneSize   = frame.getSize();
        Dimension screenSize = frame.getToolkit().getScreenSize();
        frame.setLocation(
            (screenSize.width  - paneSize.width)  / 2,
            (screenSize.height - paneSize.height) / 2);
    }
    /**
     * Builds and answers the menu bar.
     */
    private JMenuBar buildMenuBar() {
        JMenu menu;
        JMenuBar menuBar = new JMenuBar();
        menuBar.putClientProperty(Options.HEADER_STYLE_KEY, Boolean.TRUE);
        menu = new JMenu("File");
        menu.add(new JMenuItem("New..."));
        menu.add(new JMenuItem("Open..."));
        menu.add(new JMenuItem("Save"));
        menu.addSeparator();
        menu.add(new JMenuItem("Print..."));
        menuBar.add(menu);
        menu = new JMenu("Edit");
        menu.add(new JMenuItem("Cut"));
        menu.add(new JMenuItem("Copy"));
        menu.add(new JMenuItem("Paste"));
        menuBar.add(menu);
        return menuBar;
    }
    /**
     * Builds and answers the content pane.
     */
    private JComponent buildContentPane() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.add(buildToolBar(), BorderLayout.NORTH);
        panel.add(buildSplitPane(), BorderLayout.CENTER);
        panel.add(buildStatusBar(), BorderLayout.SOUTH);
        return panel;
    }
    /**
     * Builds and answers the tool bar.
     */
    private Component buildToolBar() {
        JToolBar toolBar = new JToolBar();
        toolBar.putClientProperty(Options.HEADER_STYLE_KEY, Boolean.TRUE);
        
        toolBar.add(createCenteredLabel("Tool Bar"));
        return toolBar;
    }
    /**
     * Builds and answers the split panel.
     */
    private Component buildSplitPane() {
        JSplitPane splitPane =
            new JSplitPane(
                JSplitPane.HORIZONTAL_SPLIT,
                buildSideBar(),
                buildMainPanel());
        return splitPane;
    }
    /**
     * Builds and answers the side bar.
     */
    private Component buildSideBar() {
        return createStrippedScrollPane(new JTree());
    }
    /**
     * Builds and answers the main panel.
     */
    private Component buildMainPanel() {
        JEditorPane editor = new JEditorPane();
        editor.setText(
            "This is a minimal Swing application, that demos,\n" +
            "how to install and use a JGoodies look&feel\n" +
            "in a Swing application.");
        return createStrippedScrollPane(editor);
    }
    /**
     * Builds and answers the tool bar.
     */
    private Component buildStatusBar() {
        JPanel statusBar = new JPanel(new BorderLayout());
        statusBar.add(createCenteredLabel("Status Bar"));
        return statusBar;
    }
    // Helper Code ********************************************************
    /**
     * Creates and answers a <code>JScrollpane</code> that has no border.
     */
    private JScrollPane createStrippedScrollPane(Component c) {
        JScrollPane scrollPane = new JScrollPane(c);
        scrollPane.setBorder(null);
        return scrollPane;
    }
    /**
     * Creates and answers a <code>JLabel</code> that has the text
     * centered and that is wrapped with an empty border.
     */
    private Component createCenteredLabel(String text) {
        JLabel label = new JLabel(text);
        label.setHorizontalAlignment(SwingConstants.CENTER);
        label.setBorder(new EmptyBorder(3, 3, 3, 3));
        return label;
    }
}