How to add JScrollPane on the JTextArea? - java

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.

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 remove the space in JMenu Items

As of now, I have this
And this is my source code for MyFrame1:
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Color;
import java.awt.Color.*;
import java.awt.Font;
import java.awt.Font.*;
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class Test
{
public static void main(String[] args)
{
new Test();
}
public Test()
{
String line = "";
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e)
{
e.printStackTrace();
}
JMenuBar mBar = new JMenuBar();
//creating new JMenuItem
JMenuItem mHelp = new JMenuItem("Help");
JMenuItem mCredits = new JMenuItem("Credits");
JMenuItem mExit = new JMenuItem("Exit");
/*try
{
BufferedReader br = new BufferedReader(new FileReader("1.txt"));
line = br.readLine();
}
catch(Exception e)
{
e.printStackTrace();
}*/
JLabel jUser = new JLabel("User is: " );
mHelp.setOpaque(false);
mHelp.setForeground(Color.DARK_GRAY);
mHelp.setFont(new Font("Verdana", Font.PLAIN,12));
mCredits.setOpaque(false);
mCredits.setForeground(Color.DARK_GRAY);
mCredits.setFont(new Font("Verdana", Font.PLAIN,12));
mExit.setOpaque(false);
mExit.setForeground(Color.DARK_GRAY);
mExit.setFont(new Font("Verdana", Font.PLAIN,12));
mBar.add(mHelp);
mBar.add(mCredits);
mBar.add(mExit);
mBar.add(jUser);
//mBar.add(line);
JFrame frame = new JFrame("MYFRAME");
frame.setJMenuBar(mBar);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
}
});
}
public class TestPane extends JPanel
{
public TestPane()
{
setBorder(new EmptyBorder(20, 20, 20, 20));
setLayout(new GridLayout(3, 3, 60, 60));
add(makeButton("Account Code"));
add(makeButton("Unit Details"));
add(makeButton("Item Details"));
add(makeButton("Clearing"));
add(makeButton("Search"));
add(makeButton("Exit"));
}
protected JButton makeButton(String text)
{
JButton btn = new JButton(text);
btn.setFont(new Font("Verdana", Font.PLAIN,18));
btn.setMargin(new Insets(30, 30, 30, 30));
btn.setBackground(Color.blue);
btn.setOpaque(true);
btn.setBorderPainted(false);
return btn;
}
}
}
I am still new and still have a small knowledge about Java and GUI. I am still learning about it so I am doing Trial-Error on my program.
I tried using UIManager, or UILayout, but still not working for me or I still dont know how to use it.
I really want to learn more about GUI and Java, please help me. Any comments, remarks, suggestions are accepted and well-appreciated.
MyFrame1:
As for the output I am aiming for this kind, pls. see next picture.
MyDesireOutput:
Also if you notice there's a bufferedReader, I am practicing to read a "1.txt" with a String, and putting it as label or (still dont know about it) in the menu bar...
First you must know these
JMenuBar:
An implementation of a menu bar. You add JMenu objects to the menu bar
to construct a menu.
JMenu:
An implementation of a menu -- a popup window containing JMenuItems
that is displayed when the user selects an item on the JMenuBar.
JMenuItem:
An implementation of an item in a menu.
So add your JMenuItems to JMenu, later add this JMenu to JMenuBar.
//creating a menu `Options`
JMenu menu = new JMenu("Options");
//creating menu items
JMenuItem mHelp = new JMenuItem("Help");
JMenuItem mCredits = new JMenuItem("Credits");
JMenuItem mExit = new JMenuItem("Exit");
//adding all menu items to menu
menu.add(mHelp);
menu.add(mCredits);
menu.add(mExit);
//adding menu to menu bar
mBar.add(menu);
//aligning label to right corner of window
mBar.add(Box.createHorizontalGlue());
mBar.add(jUser);//label
Output:
You should add your JMenuItems to JMenu objects and then add your JMenus to your JMenuBar.
JMenuBar mBar = new JMenuBar();
//creating new JMenuItem
JMenuItem mHelp = new JMenuItem("Help");
JMenu help = new JMenu("Help");
help.add(mHelp);
JMenuItem mCredits = new JMenuItem("Credits");
JMenu credits = new JMenu("Credits");
credits.add(mCredits);
JMenuItem mExit = new JMenuItem("Exit");
JMenu exit = new JMenu("Exit");
exit.add(exit);
/*try
{
BufferedReader br = new BufferedReader(new FileReader("1.txt"));
line = br.readLine();
}
catch(Exception e)
{
e.printStackTrace();
}*/
JLabel jUser = new JLabel("User is: " );
mHelp.setOpaque(false);
mHelp.setForeground(Color.DARK_GRAY);
mHelp.setFont(new Font("Verdana", Font.PLAIN,12));
mCredits.setOpaque(false);
mCredits.setForeground(Color.DARK_GRAY);
mCredits.setFont(new Font("Verdana", Font.PLAIN,12));
mExit.setOpaque(false);
mExit.setForeground(Color.DARK_GRAY);
mExit.setFont(new Font("Verdana", Font.PLAIN,12));
mBar.add(help);
mBar.add(credits);
mBar.add(exit);
But adding a JLabel to JMenuBar is not a good idea. If you want to have something like you depicted in you question, you may want to add a JPanel to the north region of your frame, and then add the User label to the FlowLayout.TRAILING region of that panel:
mBar.add(help);
mBar.add(credits);
mBar.add(exit);
//mBar.add(jUser);
//mBar.add(line);
JPanel statusPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
statusPanel.add(jUser);
statusPanel.add(new JLabel("Loen Seto"));
JFrame frame = new JFrame("MYFRAME");
frame.setJMenuBar(mBar);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(statusPanel, BorderLayout.NORTH);
frame.add(new TestPane(), BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
Good Luck

Java text box in GUI(Text Based Game)

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");

Objects not displaying in GUI - Java

I made a simple GUI in Java, which includes a menu, context menu, button, toolbar, check box and status bar. However, the button and toolbar are not displaying. This is the code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.border.EtchedBorder;
public class test extends JFrame {
private JLabel statusbar;
private JPopupMenu menu;
private Toolkit toolkit;
public test() {
initUI();
}
private void initUI() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
getContentPane().add(panel);
toolkit = this.getToolkit();
menu = new JPopupMenu();
JToolBar toolbar1 = new JToolBar();
JToolBar toolbar2 = new JToolBar();
ImageIcon iconNew = new ImageIcon(getClass().getResource("new.png")); // Icons
ImageIcon iconOpen = new ImageIcon(getClass().getResource("open.png"));
ImageIcon iconSave = new ImageIcon(getClass().getResource("save.png"));
ImageIcon iconExit = new ImageIcon(getClass().getResource("exit.png"));
JButton newb = new JButton(iconNew); // Declaring Buttons for Toolbar
JButton openb = new JButton(iconOpen);
JButton saveb = new JButton(iconSave);
JButton exitb = new JButton(iconExit);
toolbar1.add(newb); // Adding Buttons to Toolbar1
toolbar1.add(openb);
toolbar1.add(saveb);
toolbar1.setAlignmentX(0); // Alignment of Toolbar1
toolbar2.add(exitb); // Adding Buttons to Toolbar2
toolbar2.setAlignmentX(0); // Alignment of Toolbar2
exitb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
panel.add(toolbar1);
panel.add(toolbar2);
add(panel, BorderLayout.NORTH);
JMenuBar menubar = new JMenuBar(); // JMenuBar
JMenu file = new JMenu("File");
JMenu view = new JMenu("View");
file.setMnemonic(KeyEvent.VK_F);
JMenuItem eMenuItem = new JMenuItem("Exit", iconExit); // Exit Menu Item
eMenuItem.setMnemonic(KeyEvent.VK_E);
eMenuItem.setToolTipText("Exit application");
eMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W,
ActionEvent.CTRL_MASK));
eMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
JMenuItem nMenuItem = new JMenuItem("New", iconNew); // New Menu Item
nMenuItem.setToolTipText("New File");
JMenuItem oMenuItem = new JMenuItem("Open", iconOpen);
oMenuItem.setToolTipText("Open File");
JMenuItem sMenuItem = new JMenuItem("Save", iconSave);
sMenuItem.setToolTipText("Save File");
JMenu imp = new JMenu("Import..."); // Import Sub-Menu Item
imp.setMnemonic(KeyEvent.VK_M);
imp.setToolTipText("Import Data");
JMenuItem newsf = new JMenuItem("Import newsfeed list...");
JMenuItem bookm = new JMenuItem("Import bookmarks...");
JMenuItem mail = new JMenuItem("Import mail...");
imp.add(newsf); // Adding Sub-menu Items to Menu
imp.add(bookm);
imp.add(mail);
file.add(nMenuItem); // Adding Menu Items to "File" Menu-List
file.add(oMenuItem);
file.add(sMenuItem);
file.addSeparator();
file.add(imp);
file.addSeparator();
file.add(eMenuItem);
JButton quitButton = new JButton("Quit"); // Quit Button
quitButton.setBounds(870, 380, 80, 30);
quitButton.setToolTipText("Press me");
quitButton.setBackground(new Color(66, 89, 205));
quitButton.setForeground(new Color(255, 255, 255));
quitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
JButton nextButton = new JButton("Next >"); // Next Button
nextButton.setBounds(770, 380, 80, 30);
nextButton.setToolTipText("Next...");
nextButton.setBackground(new Color(66, 89, 205));
nextButton.setForeground(new Color(255, 255, 255));
nextButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
panel.add(quitButton); // Adding Buttons to panel
panel.add(nextButton);
JCheckBoxMenuItem sbar = new JCheckBoxMenuItem("Show StatuBar"); // Creating
// Status-bar
// Check-box
sbar.setState(true);
sbar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (statusbar.isVisible()) {
statusbar.setVisible(false);
} else {
statusbar.setVisible(true);
}
}
});
view.add(sbar); // Adding Check-box to the View Menu-List
JMenuItem menuItemBeep = new JMenuItem("Beep"); // Beep option in Pop-Up
menuItemBeep.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
toolkit.beep();
}
});
menubar.add(file); // Adding Menu-Lists to Menu Bar
menubar.add(view);
menu.add(menuItemBeep); // Adding Beep option in Pop-Up
JMenuItem menuItemClose = new JMenuItem("Close"); // Close option in
// Pop-Up
menuItemClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
menu.add(menuItemClose); // Adding Close option in Pop-Up
this.addMouseListener(new MouseAdapter() { // Mouse Listener for Pop-Up
#Override
public void mouseReleased(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3) {
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
setJMenuBar(menubar); // Menu-bar???
statusbar = new JLabel(" Statusbar"); // Creating Status Bar
statusbar.setBorder(BorderFactory
.createEtchedBorder(EtchedBorder.RAISED));
add(statusbar, BorderLayout.SOUTH);
panel.setLayout(null); // Panel Design and additional Arguments
panel.setBackground(new Color(18, 33, 110));
this.setTitle("My First GUI in Java");
this.setSize(1000, 500);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
test ex = new test();
ex.setVisible(true);
}
});
}
}
I'm very new to this so any comments are appreciated.
Thank you!
"However, the button and toolbar are not displaying."
Looking through your init() method, I only see you adding two components to your frame.
add(panel, BorderLayout.NORTH);
add(statusbar, BorderLayout.SOUTH);
Then with the same panel as above, you set the layout to null, when you first already specified it to be a BoxLayout
panel.setLayout(null);
I comment the above code out, and some components appear.
You are setting the Layout of panel twice once at beginning:
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
and once later on:
panel.setLayout(null);
You should try getting rid of the second one. That should fix the problem

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