Friday, August 15, 2014

Using HTML on Swing Components [Java][Swing]

This program has a JMenuBar (contains a JMenu (containing a JMenuItem)), a JButton that opens up a JDialog that has a tabbed pane with a label in it, a JRadioButton and a JCheckBox ; all showing the usage of HTML on them.


Source:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class opener extends JDialog {

    JTabbedPane pane = new JTabbedPane(1);

    public opener(JFrame parent) {
        /*<html> tag should be the first text in the component name string*/
        
        super(parent, "Showing HTML on tabbed panes", false);
        setLayout(new FlowLayout());
        add(pane);
        pane.addTab("<html><font color = \"green\">Tab", new JLabel("This is a pane"));
    }
}

class Parent extends JFrame {

    JButton tabbedPaneOpener = new JButton("<html>Open a Dialog With a <center><font color = \"blue\">" + "tabbed pane" + "</font>");
    JMenuBar menuBar = new JMenuBar();
    JMenu file = new JMenu("<html><font color = \"red\" size= +20>File");
    JMenuItem menuItem = new JMenuItem("Open");
    JRadioButton radioButton = new JRadioButton("<html><font color = \"green\" size= +20>" + "Push </font> me or don't!");
    JCheckBox checkBox = new JCheckBox("<html><font size = +5>" + "Check </font>" + " me or uncheck me!");

    {
        tabbedPaneOpener.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                opener op = new opener(Parent.this);
                op.setVisible(true);
                op.setSize(400, 200);
                setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            }

        });
    }

    Parent() {
        Panel p = new Panel();
        add(p);
        p.setLayout(new GridLayout(2, 2));
        menuBar.add(file);
        file.add(menuItem);

        add(menuBar, BorderLayout.NORTH);
        tabbedPaneOpener.setToolTipText("Open a dialog");
        p.add(tabbedPaneOpener);
        p.add(radioButton);
        p.add(checkBox);

        setSize(400, 250);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

public class HTMLonComponents {

    public static void main(String[] args) {
        try {
            for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (Exception e) {
            // If Nimbus is not available, you can set the GUI to another look and feel.
        }
        new Parent();
    }
}

No comments:

Post a Comment