Frage

I'm writing a basic notepad application on Swing. I have a Java Swing Menu. It's basically a JMenuBar with JMenus in it. One of the menus is a "Format"-menu with a "Font size" menu inside it(See image). The "font size" menu is supposed to have a list of numbers where I can choose the font size. But I can't seem to find a good solution for this.

I've tried using JComboBox and JList, but I need the GUI looking like it does in the image. In other words, it can't be a collapsed-dropdown menu, nor can it be in it's own window. Anyone have any suggestions as to how I can do this?

EDIT: Important to take notice of is that I need the values sent to an ActionListener. What you see in the image are just normal JMenuItems. But for me to send the int-values of each JMenuItem to an ActionListener I would need 3 different ActionListeners. And they would need to be hard coded.

enter image description here

War es hilfreich?

Lösung

Read the section from the Swing tutorial on How to Use Menus. It has a working example that will show you how to create sub menus.

But for me to send the int-values of each JMenuItem to an ActionListener I would need 3 different ActionListeners. And they would need to be hardcoded.

Yes, that is the way is should be done. You should have 3 separate Actions. Each Action should have a value to specify the font size.

You can also read Text Component Features for a working example of a simple editor that uses the default editor kit Actions to do the customization of the text.

The tutorial is a good place to start for all Swing basics.

Andere Tipps

You can use a loop to add the different font sizes to the Font menu, and you can add the same ActionListener to all of the items in the Font menu. When the ActionListener is called, you can get the font size by getting the text of the event's source.

Here is an example how to do it. This example adds all even font sizes from 8 to 24 as seen in the picture:

enter image description here

JFrame f = new JFrame();
ActionListener fontChangedListener = new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        int fontSize = Integer.valueOf(( (JMenuItem) e.getSource()).getText());
        System.out.println(fontSize);
    }
};

JMenuBar mb = new JMenuBar();

JMenu formatMenu = new JMenu("Format");
mb.add(formatMenu);

JMenu fontMenu = new JMenu("Font");
formatMenu.add(fontMenu);

for ( int i = 8; i <= 24; i += 2 ) {
    JMenuItem sizeMenuItem = new JMenuItem("" + i);
    sizeMenuItem.addActionListener(fontChangedListener);
    fontMenu.add(sizeMenuItem);
}

f.setJMenuBar( mb );
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top