Problems with Changing JTextArea font size

I am trying to prompt the user for input from a JOptionPane to change the font size of the JTextArea, shown below as, “console”.

Issue:

However, the JOptionPane is not showing when I click on the size JMenu item.

Code:

Font font = new Font("Arial", Font.PLAIN, 12);

panel = new JPanel();
panel.setLayout(new BorderLayout());
add(panel, BorderLayout.CENTER);

JTextArea console = new JTextArea();
console.setLineWrap(true);
console.setWrapStyleWord(true);
console.setEditable(false);
console.setFont(font);

JScrollPane scroll = new JScrollPane(console);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
panel.add(scroll, BorderLayout.CENTER);

JMenuBar bar = new JMenuBar();
panel.add(bar, BorderLayout.NORTH);

JMenu size = new JMenu("Size");
size.addActionListener(new ActionListener() {
    @Override public void actionPerformed(ActionEvent e) {
        String fontSize = JOptionPane.showInputDialog(panel, "New font size, 6 or larger:", "Set Font Size", JOptionPane.OK_CANCEL_OPTION);
        Font newFont = font.deriveFont(Integer.parseInt(fontSize));
        console.setFont(newFont);
    }
});

bar.add(size);

Answer

This seems to be a bug but you could use a ┬┤MenuListener┬┤ as described in this answer by @TPete

Here is the code he provided in his answer to work around the issue:

JMenu menu = new JMenu("MyMenu");
menu.addMenuListener(new MenuListener() {

    @Override
    public void menuSelected(MenuEvent e) {
        System.out.println("menuSelected");
    }

    @Override
    public void menuDeselected(MenuEvent e) {
        System.out.println("menuDeselected");
    }

    @Override
    public void menuCanceled(MenuEvent e) {
        System.out.println("menuCanceled");
    }
});

Basically he’s using a MenuListener instead of an ActionListener to catch the event successfully.

Hope this helps!

Leave a Reply

Your email address will not be published. Required fields are marked *