Java text box in GUI(Text Based Game) - java

I'm making a program for school, which it's supposed to be a GUI, but I wanted to make it more interesting. So I decided to make it a Text Based Game. Only problem is that I don't know how to add a text box to the screen and have it display text for different things that happen within the users options.
The code is right here, and I want a text box to appear during battles, or going to the shop. If you could help that would be nice!
package src.main.derp.skdlfja;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.ScrollPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Menu extends Char{
public boolean atk = false;
public boolean talk = false;
public boolean item = false;
public boolean surrender = false;
public boolean spare = false;
public boolean atkScreen = false;
JTextArea output;
JScrollPane scrollPane;
protected JTextField textField;
protected JTextArea textArea;
private final static String newline = "\n";
public JMenuBar createMenuBar() {
JMenuBar menuBar;
JMenu menu, submenu;
JMenuItem menuItem;
JRadioButtonMenuItem rbMenuItem;
JCheckBoxMenuItem cbMenuItem;
menuBar = new JMenuBar();
menu = new JMenu("Action Menu");
menu.setMnemonic(KeyEvent.VK_A);
menu.getAccessibleContext().setAccessibleDescription("Fighing Actions");
menuBar.add(menu);
menuItem = new JMenuItem("Attack", KeyEvent.VK_T);
menu.add(menuItem);
submenu = new JMenu("Talk");
submenu.setMnemonic(KeyEvent.VK_S);
menuItem = new JMenuItem("Check");
submenu.add(menuItem);
menuItem = new JMenuItem("Say Hi");
submenu.add(menuItem);
menuItem = new JMenuItem("");
submenu.add(menuItem);
menuItem = new JMenuItem("");
submenu.add(menuItem);
menu.add(submenu);
submenu = new JMenu("Item");
submenu.setMnemonic(KeyEvent.VK_S);
menuItem = new JMenuItem("Health Bottle");
submenu.add(menuItem);
menuItem = new JMenuItem("Smoke Bomb");
submenu.add(menuItem);
menu.add(submenu);
submenu = new JMenu("Spare/Flee");
submenu.setMnemonic(KeyEvent.VK_S);
menuItem = new JMenuItem("Spare");
submenu.add(menuItem);
menuItem = new JMenuItem("Flee");
submenu.add(menuItem);
menu.add(submenu);
menu = new JMenu("Shop");
menu.setMnemonic(KeyEvent.VK_N);
submenu = new JMenu("Buy");
submenu.setMnemonic(KeyEvent.VK_S);
menuItem = new JMenuItem("Health Potion");
submenu.add(menuItem);
menuItem = new JMenuItem("Smoke Bomb");
submenu.add(menuItem);
menuItem = new JMenuItem("New Book");
submenu.add(menuItem);
menuItem = new JMenuItem("Old Shoes");
submenu.add(menuItem);
menu.add(submenu);
menuItem = new JMenuItem("Kill",
KeyEvent.VK_T);
menu.add(menuItem);
submenu = new JMenu("Talk");
submenu.setMnemonic(KeyEvent.VK_S);
menuItem = new JMenuItem("Hello, who are you?");
submenu.add(menuItem);
menuItem = new JMenuItem("How long have you been set shop here?");
submenu.add(menuItem);
menuItem = new JMenuItem("What is this place?");
submenu.add(menuItem);
menuItem = new JMenuItem("Why am I here?");
submenu.add(menuItem);
menu.add(submenu);
menuBar.add(menu);
return menuBar;
}
public Container createContentPane() {
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setOpaque(false);
output = new JTextArea(5, 30);
output.setEditable(false);
scrollPane = new JScrollPane(output);
contentPane.add(scrollPane, BorderLayout.CENTER);
return contentPane;
}
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = Menu.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("TBGRPG");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Menu demo = new Menu();
frame.setJMenuBar(demo.createMenuBar());
frame.setContentPane(demo.createContentPane());
frame.setSize(450, 260);
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

use JOptionPane
JOptionPane.showMessageDialog(null,"whatever text you want to show");

Related

Java GUI - Menu Bar and Split Pane

I know how to code Java but I'm having a lot of trouble with this. I've made a menubar but I want to put a split pane underneath it. The menubar is fine but the split pane is giving me a lot of errors and I don't know how to fix it.
Any help would be much appreciated.
package getcodinggui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
import javax.swing.JSplitPane;
import javax.swing.SwingUtilities;
public class GetCodingGUI {
JTextArea output;
JScrollPane scrollPane;
public JMenuBar createMenuBar() {
JMenuBar menuBar;
JMenu menu;
menuBar = new JMenuBar();
menu = new JMenu("Home");
menu.setMnemonic(KeyEvent.VK_A);
menu.getAccessibleContext().setAccessibleDescription(
"File Menu Items");
menuBar.add(menu);
menu = new JMenu("About");
menu.setMnemonic(KeyEvent.VK_N);
menu.getAccessibleContext().setAccessibleDescription(
"Edit Menu Items");
menuBar.add(menu);
menu = new JMenu("Contact Us");
menu.setMnemonic(KeyEvent.VK_N);
menu.getAccessibleContext().setAccessibleDescription(
"Edit Menu Items");
menuBar.add(menu);
menu = new JMenu("FAQ");
menu.setMnemonic(KeyEvent.VK_N);
menu.getAccessibleContext().setAccessibleDescription(
"Edit Menu Items");
menuBar.add(menu);
menu = new JMenu("Log In");
menu.setMnemonic(KeyEvent.VK_N);
menu.getAccessibleContext().setAccessibleDescription(
"Edit Menu Items");
menuBar.add(menu);
return menuBar;
}
public Container createContentPane() {
//Create the content-pane-to-be.
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setOpaque(true);
//Create a scrolled text area.
output = new JTextArea(5, 30);
output.setEditable(false);
scrollPane = new JScrollPane(output);
//Add the text area to the content pane.
contentPane.add(scrollPane, BorderLayout.CENTER);
return contentPane;
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
public static class MyJFrameWin extends JFrame{
JSplitPane jSplitPane, jSplitPane2;
JPanel jPanel1, jPanel2a, jPanel2b;
jPanel1 = new JPanel();
jPanel2a = new JPanel();
jPanel2b = new JPanel();
jSplitPane2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
jPanel2a, jPanel2b);
jSplitPane2.setOneTouchExpandable(true);
jSplitPane2.setDividerLocation(100);
jSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
jPanel1, jSplitPane2);
jSplitPane.setOneTouchExpandable(true);
jSplitPane.setDividerLocation(150);
getContentPane().add(jSplitPane);
}
}
//Create and set up the content pane.
GetCodingGUI demo = new GetCodingGUI();
frame.setJMenuBar(demo.createMenuBar());
frame.setContentPane(demo.createContentPane());
//Display the window.
frame.setSize(1280, 720);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(runJSplitPaneLater);
}
javax.swing.SwingUtilities.invokeLater(new Runnable, runJSplitPaneLater()
{
static Runnable runJSplitPaneLater = new Runnable(){
#Override
public void run() {
MyJFrameWin myJFrameWin = new MyJFrameWin();
myJFrameWin.setVisible(true);
createAndShowGUI();
}
});
}
}
I had to clean up 20 compile errors.
Here's the GUI I created.
Here are the changes I made.
I rearranged all of your code. Code is much easier to understand when it reads from top to bottom.
Since the SwingUtilities invokeLater method requires a Runnable, I made your GUI view class implement Runnable.
I put your content pane in one of the JSplitPanes. I just guessed which pane.
I put the outer JSplitPane into the JFrame.
I fixed your menu alt keys.
I returned a JPanel from your createContentPane method.
I formatted your code.
I reduced the size of your JFrame so it would fit on my screen.
Here's the code:
package com.ggl.testing;
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class GetCodingGUI implements Runnable {
private JTextArea output;
private JScrollPane scrollPane;
public static void main(String[] args) {
SwingUtilities.invokeLater(new GetCodingGUI());
}
#Override
public void run() {
// Create and set up the window.
JFrame frame = new JFrame("Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JSplitPane jSplitPane, jSplitPane2;
JPanel jPanel1, jPanel2a, jPanel2b;
jPanel1 = new JPanel();
jPanel2a = new JPanel();
jPanel2b = createContentPane();
jSplitPane2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, jPanel2a,
jPanel2b);
jSplitPane2.setOneTouchExpandable(true);
jSplitPane2.setDividerLocation(100);
jSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, jPanel1,
jSplitPane2);
jSplitPane.setOneTouchExpandable(true);
jSplitPane.setDividerLocation(150);
frame.add(jSplitPane);
frame.setJMenuBar(createMenuBar());
// Display the window.
frame.setSize(800, 600);
frame.setVisible(true);
}
public JMenuBar createMenuBar() {
JMenuBar menuBar;
JMenu menu;
menuBar = new JMenuBar();
menu = new JMenu("Home");
menu.setMnemonic(KeyEvent.VK_H);
menu.getAccessibleContext().setAccessibleDescription("File Menu Items");
menuBar.add(menu);
menu = new JMenu("About");
menu.setMnemonic(KeyEvent.VK_A);
menu.getAccessibleContext().setAccessibleDescription("Edit Menu Items");
menuBar.add(menu);
menu = new JMenu("Contact Us");
menu.setMnemonic(KeyEvent.VK_C);
menu.getAccessibleContext().setAccessibleDescription("Edit Menu Items");
menuBar.add(menu);
menu = new JMenu("FAQ");
menu.setMnemonic(KeyEvent.VK_F);
menu.getAccessibleContext().setAccessibleDescription("Edit Menu Items");
menuBar.add(menu);
menu = new JMenu("Log In");
menu.setMnemonic(KeyEvent.VK_L);
menu.getAccessibleContext().setAccessibleDescription("Edit Menu Items");
menuBar.add(menu);
return menuBar;
}
public JPanel createContentPane() {
// Create the content-pane-to-be.
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setOpaque(true);
// Create a scrolled text area.
output = new JTextArea(5, 30);
output.setEditable(false);
scrollPane = new JScrollPane(output);
// Add the text area to the content pane.
contentPane.add(scrollPane, BorderLayout.CENTER);
return contentPane;
}
}

How to add JScrollPane on the JTextArea?

Here, if i was using constructor then it does not do anything & i don't want to add my scrollpane with setBounds() so can anyone help me to get out of this problem...
My Code is...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyMenu implements ActionListener
{
JTextField tf=new JTextField();
JFrame jf=new JFrame("My Menu");
JMenuBar menubar;
JMenu menu,SubMenu;
JMenuItem menuItem,exit;
JScrollPane jp;
JRadioButtonMenuItem rbMenuItem;
JCheckBoxMenuItem cbMenuItem;
MyMenu()
{
jf.add(tf);
menubar=new JMenuBar();
menu=new JMenu("First Menu");
menu.setMnemonic(KeyEvent.VK_F);
menubar.add(menu);
jp=new JScrollPane()
jf.add(jp);
menuItem=new JMenuItem("Ank");
//menuItem.setActionCommand("Ank");
menuItem.addActionListener(this);
KeyStroke i=KeyStroke.getKeyStroke(KeyEvent.VK_1,ActionEvent.CTRL_MASK);
menuItem.setAccelerator(i);
menu.add(menuItem);
//a grp of radioButton menu items
ButtonGroup group=new ButtonGroup();
rbMenuItem =new JRadioButtonMenuItem("Radio Button menu item");
rbMenuItem.setSelected(true);
rbMenuItem.setMnemonic(KeyEvent.VK_R);
group.add(rbMenuItem);
rbMenuItem=new JRadioButtonMenuItem("Another one");
rbMenuItem.setMnemonic(KeyEvent.VK_O);
group.add(rbMenuItem);
menu.addSeparator();
cbMenuItem=new JCheckBoxMenuItem("A check box menu item");
cbMenuItem.setMnemonic(KeyEvent.VK_C);
menu.add(cbMenuItem);
cbMenuItem=new JCheckBoxMenuItem("ANother1");
cbMenuItem.setMnemonic(KeyEvent.VK_H);
menu.add(cbMenuItem);
//a submenu
menu.addSeparator();
SubMenu=new JMenu("A SUbmenu");
SubMenu.setMnemonic(KeyEvent.VK_S);
menuItem=new JMenuItem(" Item q");
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2,ActionEvent.ALT_MASK));
SubMenu.add(menuItem);
menuItem=new JMenuItem("Another q");
SubMenu.add(menuItem);
menu.add(SubMenu);
exit=new JMenuItem("EXIT");
exit.addActionListener(this);
menu.add(exit);
//..Build a second menu.
menu =new JMenu("another Menu");
menu.setMnemonic(KeyEvent.VK_N);
menubar.add(menu);
jf.setJMenuBar(menubar);
jf.setSize(300,400);
jf.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("EXIT"))
{
System.exit(0);
}
if(e.getActionCommand().equals("Ank1"))
{
tf.setText("helloo");
}
}
public static void main(String... c)
{
new MyMenu();
}
}
Also, if i using a constructor and pass the JTextField into it, then nothing happens.
Seems to work okay for me...
Changed...
jf.add(tf);
to
jf.add(tf, BorderLayout.NORTH);
and
jp = new JScrollPane();
to
jp = new JScrollPane(new JTextArea(10, 20));
Runnable example...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
class MyMenu implements ActionListener {
JTextField tf = new JTextField();
JFrame jf = new JFrame("My Menu");
JMenuBar menubar;
JMenu menu, SubMenu;
JMenuItem menuItem, exit;
JScrollPane jp;
JRadioButtonMenuItem rbMenuItem;
JCheckBoxMenuItem cbMenuItem;
MyMenu() {
jf.add(tf, BorderLayout.NORTH);
menubar = new JMenuBar();
menu = new JMenu("First Menu");
menu.setMnemonic(KeyEvent.VK_F);
menubar.add(menu);
jp = new JScrollPane(new JTextArea(10, 20));
jf.add(jp);
menuItem = new JMenuItem("Ank");
//menuItem.setActionCommand("Ank");
menuItem.addActionListener(this);
KeyStroke i = KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.CTRL_MASK);
menuItem.setAccelerator(i);
menu.add(menuItem);
//a grp of radioButton menu items
ButtonGroup group = new ButtonGroup();
rbMenuItem = new JRadioButtonMenuItem("Radio Button menu item");
rbMenuItem.setSelected(true);
rbMenuItem.setMnemonic(KeyEvent.VK_R);
group.add(rbMenuItem);
rbMenuItem = new JRadioButtonMenuItem("Another one");
rbMenuItem.setMnemonic(KeyEvent.VK_O);
group.add(rbMenuItem);
menu.addSeparator();
cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
cbMenuItem.setMnemonic(KeyEvent.VK_C);
menu.add(cbMenuItem);
cbMenuItem = new JCheckBoxMenuItem("ANother1");
cbMenuItem.setMnemonic(KeyEvent.VK_H);
menu.add(cbMenuItem);
//a submenu
menu.addSeparator();
SubMenu = new JMenu("A SUbmenu");
SubMenu.setMnemonic(KeyEvent.VK_S);
menuItem = new JMenuItem(" Item q");
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ActionEvent.ALT_MASK));
SubMenu.add(menuItem);
menuItem = new JMenuItem("Another q");
SubMenu.add(menuItem);
menu.add(SubMenu);
exit = new JMenuItem("EXIT");
exit.addActionListener(this);
menu.add(exit);
//..Build a second menu.
menu = new JMenu("another Menu");
menu.setMnemonic(KeyEvent.VK_N);
menubar.add(menu);
jf.setJMenuBar(menubar);
jf.pack();
jf.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("EXIT")) {
System.exit(0);
}
if (e.getActionCommand().equals("Ank1")) {
tf.setText("helloo");
}
}
public static void main(String... c) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
new MyMenu();
}
});
}
}
Take a closer look at How to Use Scroll Panes and How to Use BorderLayout for more details
Try the following:
JTextArea tf = new JTextArea(10, 20);
JScrollPane scrollBar = new JScrollPane(tf);
You will only need to add the scroll bar to the JFrame.

How to get the currently selected Menu or MenuItem

How can I retrieve the currently selected menu or menu item when clicked on it and the subsequent path will be printed on console. In this code I have done the menus and sub menus up to 4 levels. And want to print the path of selected menus and submenus when clicked on. I am using swing concept for this program. Please help. Thanks in advance.
import java.awt.Component;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.MenuElement;
import javax.swing.MenuSelectionManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Menu {
public static void main(final String args[]) {
JFrame frame = new JFrame("MenuSample Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
JMenu worldMenu = new JMenu("world");
menuBar.add(worldMenu);
JMenu indMenu = new JMenu("India");
worldMenu.add(indMenu);
/* creates menu */
JMenu odMenu = new JMenu("Odisha");
indMenu.add(odMenu);
JMenu delhiMenu = new JMenu("Delhi");
indMenu.add(delhiMenu);
JMenu upMenu = new JMenu("Uttar Pradesh");
indMenu.add(upMenu);
JMenu mpMenu = new JMenu("Madhya Pradesh");
indMenu.add(mpMenu);
JMenu ausMenu = new JMenu("Australia");
worldMenu.add(ausMenu);
JMenu AmericaMenu = new JMenu("America");
worldMenu.add(AmericaMenu);
/* creates submenu */
JMenu bbMenu = new JMenu("Bhubaneswar");
odMenu.add(bbMenu);
JMenu bmMenu = new JMenu("Berhampur");
odMenu.add(bmMenu);
/*creates sub sub menu */
JMenuItem rjMenuItem = new JMenuItem("Raj Mahal");
bbMenu.add(rjMenuItem);
JMenuItem abMenuItem = new JMenuItem("Acharya Bihar");
bbMenu.add(abMenuItem);
JMenuItem bnMenuItem = new JMenuItem("Bani Bihar");
bbMenu.add(bnMenuItem);
/* retrieving path */
MenuSelectionManager.defaultManager().addChangeListener(
new ChangeListener() {
public void stateChanged(ChangeEvent evt) {
MenuElement[] path = MenuSelectionManager.defaultManager()
.getSelectedPath();
//
int s=0;
for (int i = 0; i < path.length; i++) {
Component c = path[i].getComponent();
if (c instanceof JMenuItem) {
JMenuItem mi = (JMenuItem) c;
String label = mi.getText();
System.out.println("LEVEL----" + s);
System.out.println("you hv selected:"+label);
s++;
}
}
}
});
//
frame.setJMenuBar(menuBar);
frame.setSize(350, 250);
frame.setVisible(true);
}
}
How to get the currently selected
Menu - A parent JMenu cannot be selected. Why would you want to know
if the mouse is over it?
MenuItem - Embrace the Action interface
It is an all too common oversight to not use the Action interface. When developing with Swing make Action your friend, it will treat you well. You went down the wrong path with MenuSelectionManager.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class MenuExample {
private JFrame frame;
private JLabel choiceIndicator;
MenuExample create() {
frame = createFrame();
choiceIndicator = new JLabel();
frame.setJMenuBar(createMenuBar());
frame.getContentPane().add(createContent());
return this;
}
private Component createContent() {
JPanel panel = new JPanel();
panel.add(new JLabel("Last menu item choice:"));
panel.add(choiceIndicator);
return panel;
}
private JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
menuBar.add(createWorld());
return menuBar;
}
private JMenu createWorld() {
JMenu worldMenu = new JMenu("World");
worldMenu.add(createIndia());
worldMenu.add(new JMenu("Australia"));
worldMenu.add(new JMenu("America"));
return worldMenu;
}
private JMenu createIndia() {
JMenu india = new JMenu("India");
india.add(createOdisha());
india.add(new JMenu("Delhi"));
india.add(new JMenu("Uttar Pradesh"));
india.add(new JMenu("Madhya Pradesh"));
return india;
}
private JMenuItem createOdisha() {
JMenu menu = new JMenu("Odisha");
menu.add(createBhubaneswar());
menu.add(new JMenu("Berhampur"));
return menu;
}
private JMenuItem createBhubaneswar() {
JMenu menu = new JMenu("Bhubaneswar");
menu.add(choiceItem("Raj Mahal"));
menu.add(choiceItem("Acharya Bihar"));
menu.add(choiceItem("Bani Bihar"));
return menu;
}
private JMenuItem choiceItem(String text) {
return new JMenuItem(new Choice(text, choiceIndicator));
}
private JFrame createFrame() {
JFrame frame = new JFrame(getClass().getSimpleName());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
return frame;
}
void show() {
frame.setSize(350, 250);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MenuExample().create().show();
}
});
}
class Choice extends AbstractAction {
private final JLabel choiceIndicator;
public Choice(String text, JLabel choiceIndicator) {
this(text, null, null, null, choiceIndicator);
}
public Choice(String text, ImageIcon icon, String desc, Integer mnemonic, JLabel choiceIndicator) {
super(text, icon);
putValue(SHORT_DESCRIPTION, desc);
putValue(MNEMONIC_KEY, mnemonic);
this.choiceIndicator = choiceIndicator;
}
public void actionPerformed(ActionEvent e) {
choiceIndicator.setText(e.getActionCommand());
}
}
}

Adding a checkbox group to a java menu

Im trying to add a checkboxgroup to my menu but keep getting a "Cannot find symbol" error.
MenuBar mb = new MenuBar();
Menu file = new Menu("File");
Menu colorM = new Menu("Color");
MenuItem quitM = new MenuItem("Quit", new MenuShortcut(KeyEvent.VK_Q));
CheckboxGroup cbg = new CheckboxGroup();
Checkbox cb1 = new Checkbox("Black",cbg,true);
Checkbox cb2 = new Checkbox("Red",cbg,false);
Checkbox cb3 = new Checkbox("Blue",cbg,false);
Checkbox cb4 = new Checkbox("Green",cbg,false);
Then in my initialization i have
chatF.setMenuBar(mb);
mb.add(file);
mb.add(colorM);
file.add(quitM);
colorM.add(cbg);
I tried adding a MenuItem and putting the cbg in there but same problem
CheckboxGroup is not a Component (or, more specifically, a MenuItem), so you can't add it to the menu. Instead, you can create a CheckboxMenuItem, but I think CheckboxGroup only works with instances of Checkbox so you'll have to write your own code to enforce single-selection.
If Swing is an option, you can instead use JRadioButtonMenuItem and ButtonGroup:
package com.example.checkboxmenu;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
public class CheckboxMenu extends JFrame {
public CheckboxMenu() {
JMenuBar mb = new JMenuBar();
JMenu file = new JMenu("File"); //$NON-NLS-1$
JMenu colorM = new JMenu("Color");
JMenuItem quitM = new JMenuItem("Quit", KeyEvent.VK_Q);
JRadioButtonMenuItem cb1 = new JRadioButtonMenuItem("Black", true);
JRadioButtonMenuItem cb2 = new JRadioButtonMenuItem("Red", true);
JRadioButtonMenuItem cb3 = new JRadioButtonMenuItem("Blue", true);
JRadioButtonMenuItem cb4 = new JRadioButtonMenuItem("Green", true);
ButtonGroup group = new ButtonGroup();
group.add(cb1);
group.add(cb2);
group.add(cb3);
group.add(cb4);
setJMenuBar(mb);
mb.add(file);
mb.add(colorM);
file.add(quitM);
colorM.add(cb1);
colorM.add(cb2);
colorM.add(cb3);
colorM.add(cb4);
quitM.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400,300);
setVisible(true);
}
/**
* #param args
*/
public static void main(String[] args) {
new CheckboxMenu();
}
}
You can't add a CheckboxGroup to a Menu... you can only add MenuItem instances. You can add a CheckboxMenuItem, but this doesn't understand CheckboxGroup either.
So you need to change the CheckBoxs to CheckboxMenuItems, add them individually to the menu, roll your own CheckboxMenuItemGroup class and use it to bind the CheckboxMenuItems together.
Something like the following should work:
public class CheckboxMenuItemGroup implements ItemListener {
private Set<CheckboxMenuItem> items = new HashSet<CheckboxMenuItem>();
public void add(CheckboxMenuItem cbmi) {
cbmi.addItemListener(this);
cbmi.setState(false);
items.add(cbmi);
}
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
String itemAffected = (String) e.getItem();
for (CheckboxMenuItem item : items) {
// Use this line to allow user to toggle the selected item off
if (!item.getLabel().equals(itemAffected)) item.setState(false);
// Use this line to force one of the items to always be selected
// item.setState(item.getLabel().equals(itemAffected));
}
}
}
public void selectItem(CheckboxMenuItem itemToSelect) {
for (CheckboxMenuItem item : items) {
item.setState(item == itemToSelect);
}
}
public CheckboxMenuItem getSelectedItem() {
for (CheckboxMenuItem item : items) {
if (item.getState()) return item;
}
return null;
}
}
This should work because ItemListeners don't get called when code calls item.setState(), only when the user clicks on the item in the menu. Just make sure you only set the state of the items with the CheckboxMenuItemGroup.selectItem() call, otherwise you could end up with more than one item selected.
Then you just need to build your menu like this:
public static void main(String[] args) {
final Frame f = new Frame("Test CheckboxMenuItemGroup");
MenuBar mb = new MenuBar();
Menu menu = new Menu("Menu");
CheckboxMenuItem cb1 = new CheckboxMenuItem("Black");
CheckboxMenuItem cb2 = new CheckboxMenuItem("Red");
CheckboxMenuItem cb3 = new CheckboxMenuItem("Blue");
CheckboxMenuItem cb4 = new CheckboxMenuItem("Green");
CheckboxMenuItemGroup mig = new CheckboxMenuItemGroup();
mig.add(cb1);
mig.add(cb2);
mig.add(cb3);
mig.add(cb4);
mig.selectItem(cb1);
menu.add(cb1);
menu.add(cb2);
menu.add(cb3);
menu.add(cb4);
f.setMenuBar(mb);
f.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.setSize(300, 200);
f.setVisible(true);
}
Using swing instead of awt.
JMenuBar menuBar = new JMenuBar();
JMenu color = new JMenu("Color");
JCheckBoxMenuItem cb1 = new JCheckBoxMenuItem("Black");
JCheckBoxMenuItem cb2 = new JCheckBoxMenuItem("Red");
JCheckBoxMenuItem cb3 = new JCheckBoxMenuItem("Blue");
JCheckBoxMenuItem cb4 = new JCheckBoxMenuItem("Green");
ButtonGroup group = new ButtonGroup();
group.add(cb1);
group.add(cb2);
group.add(cb3);
group.add(cb4);
menuBar.add(cb1);
menuBar.add(cb2);
menuBar.add(cb3);
menuBar.add(cb4);
setJMenuBar(menuBar); // Set the JMenuBar of the JFrame
You can add any AbstractButton to a ButtonGroup.
On OSX Java 7 (1.7.0_40) Julians answer doesnt quite work because the object returned by ItemEvent is actually a String rather than a CheckBoxItem, soiunds like a bug in OSX but got it working by modifying the itemStateChanged method
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.HashSet;
import java.util.Set;
public class CheckboxMenuItemGroup implements ItemListener
{
private Set<CheckboxMenuItem> items = new HashSet<CheckboxMenuItem>();
public void add(CheckboxMenuItem cbmi) {
cbmi.addItemListener(this);
cbmi.setState(false);
items.add(cbmi);
}
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
String itemAffected = (String)e.getItem();
for (CheckboxMenuItem item : items) {
if (item.getLabel() != itemAffected) item.setState(false);
}
}
}
public void selectItem(CheckboxMenuItem itemToSelect) {
for (CheckboxMenuItem item : items) {
item.setState(item == itemToSelect);
}
}
public CheckboxMenuItem getSelectedItem() {
for (CheckboxMenuItem item : items) {
if (item.getState()) return item;
}
return null;
}
}

How do I create this special menu bar with Java Swing?

I am trying to implement this type of menu using Swing. Is there any off-the-shelf solution (free and/or commercial) yet?
Assuming you want that image on the menu, why not something like this?
BufferedImage image = ImageIO.read(url);
yourJMenu.setHorizontalTextPosition(SwingConstants.CENTER);
yourJMenu.setVerticalTextPosition(SwingConstants.BOTTOM);
yourJMenu.setIcon(new ImageIcon(image));
EDIT : Seems you're asking to start from scratch.
Please refer to: How to Use Menus before reading this answer.
EDIT 2 : Here is an SSCCE,
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingConstants;
public class MenuTest {
public static void main(String[] argv) throws Exception {
// Create the menu bar
JMenuBar menuBar = new JMenuBar();
String imageURL = "http://blogs.discovermagazine.com/" +
"drone360/wp-content/themes/discoverblog/images/" +
"gear_icon.png";
// Create a menu
JMenu menu = new JMenu("Menu");
BufferedImage image = ImageIO.read(new URL(imageURL));
menu.setHorizontalTextPosition(SwingConstants.CENTER);
menu.setVerticalTextPosition(SwingConstants.BOTTOM);
menu.setIcon(new ImageIcon(image));
menuBar.add(menu);
// Create a menu item
JMenuItem item = new JMenuItem("Test Item");
menu.add(item);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(menuBar);
frame.setSize(500, 550);
frame.setVisible(true);
}
}
Resource courtesy : http://pscode.org/media/
import java.awt.*;
import java.awt.event.*;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.ButtonGroup;
import javax.swing.JMenuBar;
import javax.swing.KeyStroke;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JFrame;
/* MenuLookDemo.java requires images/middle.gif. */
/*
* This class exists solely to show you what menus look like.
* It has no menu-related event handling.
*/
public class MenuLookDemo {
JTextArea output;
JScrollPane scrollPane;
public JMenuBar createMenuBar() {
JMenuBar menuBar;
JMenu menu, submenu;
JMenuItem menuItem;
JRadioButtonMenuItemMenuItem;
JCheckBoxMenuItem cbMenuItem;
//Create the menu bar.
menuBar = new JMenuBar();
//Build the first menu.
menu = new JMenu("A Menu");
menu.setMnemonic(KeyEvent.VK_A);
menu.getAccessibleContext().setAccessibleDescription("The only menu in this program that has menu items");
menuBar.add(menu);
//a group of JMenuItems
menuItem = new JMenuItem("Av text-only menu item", KeyEvent.VK_T);
//menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.ALT_MASK));
menuItem.getAccessibleContext().setAccessibleDescription("This doesn't really do anything");
menu.add(menuItem);
ImageIcon icon = createImageIcon("middle.gif");
menuItem = new JMenuItem("Both text and icon", icon);
menuItem.setMnemonic(KeyEvent.VK_B);
menu.add(menuItem);
menuItem = new JMenuItem(icon);
menuItem.setMnemonic(KeyEvent.VK_D);
menu.add(menuItem);
//a group of radio button menu items
menu.addSeparator();
ButtonGroup group = new ButtonGroup();
rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
rbMenuItem.setSelected(true);
rbMenuItem.setMnemonic(KeyEvent.VK_R);
group.add(rbMenuItem);
menu.add(rbMenuItem);
rbMenuItem = new JRadioButtonMenuItem("Another one");
rbMenuItem.setMnemonic(KeyEvent.VK_O);
group.add(rbMenuItem);
menu.add(rbMenuItem);
//a group of check box menu items
menu.addSeparator();
cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
cbMenuItem.setMnemonic(KeyEvent.VK_C);
menu.add(cbMenuItem);
cbMenuItem = new JCheckBoxMenuItem("Another one");
cbMenuItem.setMnemonic(KeyEvent.VK_H);
menu.add(cbMenuItem);
//a submenu
menu.addSeparator();
submenu = new JMenu("A submenu");
submenu.setMnemonic(KeyEvent.VK_S);
menuItem = new JMenuItem("An item in the submenu");
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ActionEvent.ALT_MASK));
submenu.add(menuItem);
menuItem = new JMenuItem("Another item");
submenu.add(menuItem);
menu.add(submenu);
//Build second menu in the menu bar.
menu = new JMenu("Another Menu");
menu.setMnemonic(KeyEvent.VK_N);
menu.getAccessibleContext().setAccessibleDescription("This menu does nothing");
menuBar.add(menu);
return menuBar;
}
public Container createContentPane() {
//Create the content-pane-to-be.
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setOpaque(true);
//Create a scrolled text area.
output = new JTextArea(5, 30);
output.setEditable(false);
scrollPane = new JScrollPane(output);
//Add the text area to the content pane.
contentPane.add(scrollPane, BorderLayout.CENTER);
return contentPane;
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = MenuLookDemo.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("MenuLookDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
MenuLookDemo demo = new MenuLookDemo();
frame.setJMenuBar(demo.createMenuBar());
frame.setContentPane(demo.createContentPane());
//Display the window.
frame.setSize(450, 260);
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

Categories