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
JTextAreacomponent. - Use the
getActions()methods ofJTextAreato get a list ofActions. - Create a
JMenuBar. - Use the
addmethod ofJMenuBarto add the aboveActions. - Create several
JMenuoptions and add them to theJMenuBar.
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.

