ColorChooser by clicking JMenu Item

1.6k views Asked by At

I tried codes from different site's and one from here about a color. How do I get color chooser to work with the press of a jmenu item?

I looked at ColorChooser Example and also Oracle Color Chooser Example and then implementing into the original class using the following code:

   JMenuItem clr = new JMenuItem("Font Color");
    clr.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e)
        {
            ColorChooserDemo ccd = new ColorChooserDemo();
            ccd.setVisible(true);
        }
    });

But this seems do do nothing when I press the menu item.

The class code is from the oracle webpage. These are the following class I use (shortened of course to the problem at hand). I'm making a notepad program as i'm getting back into programming and refreshing my memory of how to do things in java. Problem at hand is, I am unable to get the color chooser to come up when I click on the jmenuitem clr (which is font color) the following code show's what I have so far:

Color Chooser Class:

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

/* ColorChooserDemo.java requires no other files. */
@SuppressWarnings("serial")
public class ColorChooserDemo extends JPanel
                              implements ChangeListener {

    protected JColorChooser tcc;
    protected JLabel banner;

    public ColorChooserDemo() {
        super(new BorderLayout());

        //Set up color chooser for setting text color
        tcc = new JColorChooser();
        tcc.getSelectionModel().addChangeListener(this);
        tcc.setBorder(BorderFactory.createTitledBorder(
                                             "Choose Text Color"));

        add(tcc, BorderLayout.PAGE_END);
    }

    public void stateChanged(ChangeEvent e) {
        Color newColor = tcc.getColor();
        FirstWindow.ta1.setForeground(newColor);
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("ColorChooserDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        JComponent newContentPane = new ColorChooserDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

Main Class:

import java.awt.EventQueue;

public class Main{
    protected static Object fw;

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable(){

            @Override
            public void run() {
                // TODO Auto-generated method stub
                try
                {
                    FirstWindow fw = new FirstWindow();
                    fw.setVisible(true);
                } catch (Exception e)
                {
                    e.printStackTrace();
                }

            }

        });
    }
}

FirstWindow class:

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


public class FirstWindow extends JFrame {
    private static final long serialVersionUID = 1L;
    protected JColorChooser tcc;
    protected static JTextArea ta1;

    public FirstWindow() {
        super("Note Pad");

        Font font = new Font("Verdana", Font.BOLD, 12);

        //Setting the size of the note pad
        setSize(650, 745);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        //Create the MenuBar
        JMenuBar mb = new JMenuBar();
        setJMenuBar(mb);

        //Create the panel to hold everything in
        JPanel p = new JPanel();

        //Create the Text Area
        final JTextArea ta1 = new JTextArea();
        ta1.setFont(font);
        ta1.setMargin(new Insets(5,5,5,5));
        ta1.setLineWrap(true);
        ta1.setWrapStyleWord(true);

        //Create the Scroll Pane to hold the Text Area 
        final JScrollPane sp = new JScrollPane(ta1);
        sp.setPreferredSize(new Dimension(625,675));
        sp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);

        //Create the menu's
        JMenu format = new JMenu("Format");

            //Create menu item for picking font color
        JMenuItem clr = new JMenuItem("Font Color");
        clr.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e)
            {
                ColorChooserDemo ccd = new ColorChooserDemo();
                ccd.setVisible(true);
            }
        });

        //adding the menu items to the file menu tab

        //adding menu items to the edit tab

        //adding menu items to the format tab
        format.add(clr);

        //adding the menus to the menu bar
        mb.add(format);


        //adding the scroll pane to the panel
        p.add(sp);
        add(p, BorderLayout.CENTER);

    }
}
2

There are 2 answers

1
Gijs Overvliet On BEST ANSWER

Probably the easiest way to show the ColorChooser is the following:

In the ColorChooserDemo class, you have the method private static void createAndShowGUI(), which you should declare public.

Then, replace the ActionListener for the menu item to the following:

    clr.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e)
        {
            ColorChooserDemo.createAndShowGUI();
        }
    });

Your ColorChooserDemo class extends JPanel, not JFrame. You first need a JFrame, then add the panel, then show the JFrame. This is what happens in the createAndShowGUI() method.

Edit: I understood that you only wanted to know how to show the ColorChooserDemo when selecting a menu item.

However, to actually set the color, you might want to skip using your own ColorChooserDemo class, and replace the ActionListener code with the following:

    clr.addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent e)
        {
            Color c = JColorChooser.showDialog(ta1, "ColorChooserDemo", null);
            ta1.setForeground(c);
        }
    });
1
async On

An SSCE is easier not only for us to provide a solution, as Andrew suggested, but it may also help you figure out and understand what to do. Anyway, here's a quick example of opening a colour chooser after pressing a JMenuItem:

item.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        JColorChooser jColorChooser = new JColorChooser();

        JDialog jDialog = new JDialog();
        jDialog.setContentPane(jColorChooser);
        jDialog.pack();
        jDialog.setVisible(true);
    }
});

LE: (sorry, new to colour choosers myself) or just use JColorChooser.showDialog()