3

I want to add a vertical text into JMenu. As shown in the picture ("JTattoo"):

enter image description here

I search Google but didn't find a way to do.

Any information will be helpful to me.

Thanks in advance.

Tapas Bose
  • 28,796
  • 74
  • 215
  • 331

2 Answers2

2

Extending JMenuItem and overriding paintComponent won't work because the text spans multiple menu items.

What you want to do is add a custom border to the popup menu of the JMenu.

Here's an example:

import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.border.Border;
public class Main {

    public static void main(final String[] args) {
        final JFrame frame = new JFrame();
        final JMenu menu = new JMenu("Menu");
        menu.add("Hello");
        menu.add("World");
        menu.getPopupMenu().setBorder(new VerticalTextBorder());
        final JMenuBar menubar = new JMenuBar();
        menubar.add(menu);
        frame.setJMenuBar(menubar);
        frame.setSize(300,300);
        frame.setVisible(true);
    }

    private static class VerticalTextBorder implements Border {
        @Override
        public Insets getBorderInsets(final Component c) {
            return new Insets(0, 15, 0, 0);
        }

        @Override
        public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int width, final int height) {
            final Graphics2D g2 = (Graphics2D)g;
            final AffineTransform fontAT = new AffineTransform();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            fontAT.rotate(-Math.PI/2);
            g2.setFont(g2.getFont().deriveFont(fontAT));
            g2.drawString("Menu", 10, height);
        }

        @Override
        public boolean isBorderOpaque() {
            return false;
        }
    }
}
Reverend Gonzo
  • 39,701
  • 6
  • 59
  • 77
0

You could subclass JMenuItem and then change the way it is rendered by overriding paintComponent.

kleopatra
  • 51,061
  • 28
  • 99
  • 211
Thorn
  • 4,015
  • 4
  • 23
  • 42