event

A simple text menu using TextAction example

With this tutorial we are going to show you how to create an application with a simple text menu that uses TextAction in Java. This will be particularly useful when you want to create a simple and fast menu for your GUI Application.

In order to work with TextAction in Java:

  • Create a JTextArea component.
  • Use the getActions() methods of JTextArea to get a list of Actions.
  • Create a JMenuBar.
  • Use the add method of JMenuBar to add the above Actions.
  • Create several JMenu options and add them to the JMenuBar.

Let’s take a close look at the code snippet that follows:

package com.javacodegeeks.snippets.desktop;

import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JTextArea;

public class Main {

    public static void main(String[] args) {

  JTextArea textArea = new JTextArea();

  Action[] acts = textArea.getActions();

  JMenuBar simpleMenu = new JMenuBar();

  JMenu actions = new JMenu("Options");

  simpleMenu.add(actions);

  JMenu option1 = new JMenu("Option 1");

  JMenu option2 = new JMenu("Option 2");

  actions.add(option1);

  actions.add(option2);

  int beet = acts.length / 2;

  for (int x = 0; x < beet; x++) {

option1.add(acts[x]);

  }

  for (int y = beet; y < acts.length; y++) {

option2.add(acts[y]);

  }

  JFrame jFrame = new JFrame();

  jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  jFrame.getContentPane().add(textArea);

  jFrame.setJMenuBar(simpleMenu);

  jFrame.setSize(400, 250);

  jFrame.setVisible(true);
    }
}

 
This was an example on how to create a simple text menu using TextAction in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button