I'm trying to make a help button on a JMenuBar. Currently I can make it align to right using this
helpItem.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
The issue is that it takes up the entire space of the JMenuBar so you can basically press anywhere on the empty space of the JMenuBar and it will press that button. I fixed that by overriding the size of the JMenuItem using this
JMenuItem helpItem = new JMenuItem() {
#Override
public Dimension getMaximumSize() {
Dimension d1 = super.getPreferredSize();
Dimension d2 = super.getMaximumSize();
d2.width = d1.width;
return d2;
}
};
However, after I override getMaximumSize, setComponentOrientation doesn't align the JMenuItem to the right.
EDIT (Current code):
private void createMenuBar() {
JMenuBar newMenuBar = new JMenuBar();
newMenuBar.setName("");
JMenu newMenu = new JMenu("Menu");
JMenuItem updateItem = new JMenuItem("Update");
JMenuItem aboutMe = new JMenuItem("About");
JMenuItem exitItem = new JMenuItem("Exit");
JMenuItem helpItem = new JMenuItem();
URL iconPath = getClass().getResource("/help.png");
helpItem.setIcon(new ImageIcon(iconPath));
addMenuItemActionListeners(updateItem, aboutMe, exitItem, helpItem);
newMenu.add(updateItem);
newMenu.add(aboutMe);
newMenu.add(exitItem);
newMenuBar.add(newMenu);
newMenuBar.add(Box.createHorizontalGlue());
newMenuBar.add(helpItem);
this.setJMenuBar(newMenuBar);
}
There is no need to manually set the component size, avoid it because it's a bad practice and could break your layout.
If you just want to align the help menu on the right, you can make use of Box.createHorizontalGlue method.
Yuo can add all the other menus you're gonna use (of course, if you need), then add the glue, and then add all the other menus you want to have aligned to the right side.
This is an example:
And this is a MCVE to achieve the above result:
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.SwingUtilities;
public class GlueMenuBarTest
{
public static void main (String [] a) {
SwingUtilities.invokeLater (new Runnable () {
#Override public void run () {
createAndShowGUI ();
}
});
}
private static void createAndShowGUI () {
JFrame frame = new JFrame ("Test");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar (createGlueMenuBar ());
frame.setSize (500, 250); // just for convenience, use pack () in a real app.
frame.setLocationRelativeTo (null);
frame.setVisible (true);
}
private static JMenuBar createGlueMenuBar () {
JMenuBar menuBar = new JMenuBar ();
menuBar.add (new JMenu ("File"));
menuBar.add (new JMenu ("Edit"));
menuBar.add (new JMenu ("Search"));
menuBar.add (Box.createHorizontalGlue ());
menuBar.add (new JMenu ("Help"));
return menuBar;
}
}
If you comment the lines where i add other menus on the left, it will work as well.
Related
I'm trying to exit menu using the ActionListener, however my code doesn't work properly and the "Quit the Program" button doesn't do anything. Below is the code:
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;
public class testCoinSorterGUI extends testCoinSorter{
JTextArea output;
JScrollPane scrollPane;
public JMenuBar createMenuBar() {
JMenuBar menuBar;
JMenu menu, submenu;
JMenuItem menuItem;
JRadioButtonMenuItem rbMenuItem;
JCheckBoxMenuItem cbMenuItem;
//Create the menu bar.
menuBar = new JMenuBar();
//Build the first menu.
menu = new JMenu("Calculator");
menu.setMnemonic(KeyEvent.VK_A);
menu.getAccessibleContext().setAccessibleDescription(
"The only menu in this program that has menu items");
menuBar.add(menu);
menuItem = new JMenuItem("Coin calculator");
menu.add(menuItem);
menuItem = new JMenuItem("Multi Coin calculator");
menu.add(menuItem);
//Build second menu in the menu bar.
menu = new JMenu("Print coin list");
menu.setMnemonic(KeyEvent.VK_N);
menu.getAccessibleContext().setAccessibleDescription("This menu does nothing");
menuBar.add(menu);
//Build third menu in the menu bar.
menu = new JMenu("Set details");
menuBar.add(menu);
menuItem = new JMenuItem("Set currency");
menu.add(menuItem);
menuItem = new JMenuItem("Set minimum coin input value");
menu.add(menuItem);
menuItem = new JMenuItem("Set maximum coin input value");
menu.add(menuItem);
menu.addSeparator();
menuItem = new JMenuItem("Display program configurations");
menu.add(menuItem);
//Build fifth menu in the menu bar.
menu = new JMenu("Quit the program");
menuBar.add(menu);
menu.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
);
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 = testCoinSorterGUI.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("*** CoinSorterGUI ***");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
testCoinSorterGUI demo = new testCoinSorterGUI();
frame.setJMenuBar(demo.createMenuBar());
frame.setContentPane(demo.createContentPane());
//Display the window.
frame.setSize(680, 480);
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();
}
});
}
}
Currently I only want to test the "quit the program" button, so please ignore all the other menu.
Any help would be appreciated, I am really stucked though I think I have put the code in the correct order.
First of all:
public class testCoinSorterGUI extends testCoinSorter{
Class names should start with an upper case character. Follow the conventions used by the JDK.
I'm trying to exit menu using the ActionListener
A JMenuBar is designed to display JMenu objects.
A JMenu is designed to be clicked and display a list of JMenuItems.
An ActionListener only works on a JMenuItem.
So the logical structure of your code should be:
JMenuBar
JMenu
JMenuItem
When you add the JMenuItem you can add an "accelerator" to the menu item so the application by be closed directly from the keyboard. This save the user from using the mouse all the time and having to click on the menu and menu item.
Use a menuitem, not a menu
menu = new JMenu("Quit the program");
menuBar.add(menu);
menu.addActionListener(
Should be
JMenuItem menuI = new JMenuItem("Quit the program");
menuBar.add(menuI);
menuI.addActionListener(
public class Manubar extends JFrame {
JMenuBar jmb;
JMenu jm;
JMenu jm2;
JMenuItem jmt;
JMenuItem jmt2;
public Manubar() {
setSize(500, 500);
jmb = new JMenuBar();
jm = new JMenu("file");
jm2 = new JMenu("edit");
jmt = new JMenuItem("copy");
jmt2 = new JMenuItem("exit");
jmb.add(jm);
jmb.add(jm2);
jm.add(jmt);
jm.add(jmt2);
add(jmb, BorderLayout.NORTH);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Manubar();
}
}
Here I want to close the window when I click on exit menu item,
also before closing, it should display a popup to ask whether to close if user clicks OK then it should close.
Here I want to close the window when I click on exit menu item, also before closing, it should display a popup to ask whether to close if user clicks OK then it should close.
Check out Closing an Application. It shows you how to display a JOptionPane to confirm closing of the application first.
It shows:
the basic approach of using a WindowListener
a simplified approach by using the included custom classes
Here is your complete solution,
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Manubar extends JFrame implements ActionListener {
JMenuBar jmb;
JMenu jm;
JMenu jm2;
JMenuItem jmt;
JMenuItem jmt2;
public Manubar() {
setSize(500, 500);
jmb = new JMenuBar();
jm = new JMenu("file");
jm2 = new JMenu("edit");
jmt = new JMenuItem("copy");
jmt2 = new JMenuItem("exit");
jmb.add(jm);
jmb.add(jm2);
jm.add(jmt);
jm.add(jmt2);
add(jmb, BorderLayout.NORTH);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jmt2.addActionListener(this);
}
public static void main(String[] args) {
new Manubar();
}
#Override
public void actionPerformed(ActionEvent e) {
if("exit".equals(e.getActionCommand())){
int dialogButton = JOptionPane.YES_NO_OPTION;
JOptionPane.showConfirmDialog (null, "Would You Like to Save your Previous Note First?","Warning",dialogButton);
if(dialogButton == JOptionPane.YES_OPTION){
System.exit(NORMAL);
}
}
}
}
When I create a menu in java GUI by using JMenuBar it puts all JMenus from Left-to-right direction like this:
I want to change it to Right-to-left like this:
I want do this in an English OS, so suggestions of an Arabic or Right-to-Left solution aren't what I'm looking for.
You can use Component.applyComponentOrientation to change the orientation of the JMenuBar:
import javax.swing.*;
import java.awt.*;
public class R_L_MenuBar_Demo
{
public static void main(String[] args){
SwingUtilities.invokeLater(() -> createAndShowGUI());
}
private static void createAndShowGUI()
{
JMenuBar mb = new JMenuBar();
JMenuItem item_1 = new JMenuItem("First Item");
JMenu menu_2 = new JMenu("Second Menu");
JMenuItem item_3 = new JMenuItem("First Item in Second");
menu_2.add(item_3);
mb.add(item_1);
mb.add(menu_2);
//switch the orientation of the menubar to right to left
JButton btn_r_to_l = new JButton("Switch menubar to r_to_l");
btn_r_to_l.addActionListener(e -> {
mb.invalidate();
mb.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
mb.validate();
});
//switch the orientation of the menubar to left to right
JButton btn_l_to_r = new JButton("Switch menubar to l_to_r");
btn_l_to_r.addActionListener(e -> {
mb.invalidate();
mb.applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
mb.validate();
});
JFrame frame = new JFrame("R_L_MenuBar");
frame.setLayout(new FlowLayout());
frame.add(btn_r_to_l);
frame.add(btn_l_to_r);
frame.setJMenuBar(mb);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200 , 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
This will look like this:
The Default look (left to right)
And after switching to right-to-left:
I have the following code for a JMenuBar (This code has been taken from a free java program call JGuiD and edited for personal purposes)
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.awt.Dimension;
import java.awt.Color;
public class GuiDMenuBar extends JMenuBar
{
JMenu m_file,m_edit,m_help;
JMenuItem mi_f_new,mi_f_open,mi_f_save,mi_f_saveas,mi_f_exit;
JMenuItem mi_e_cut,mi_e_copy,mi_e_paste,mi_e_delete;
JMenuItem mi_v_motif,mi_v_java,mi_v_windows,mi_v_nimbus;
JMenuItem mi_h_help,mi_h_about;
JButton m_code;
public GuiDMenuBar()
{
setBorderPainted(true);
makeFileMenu();
makeEditMenu();
makeCodeButton();
makeHelpMenu();
}
void makeFileMenu()
{
m_file = new JMenu("File");
m_file.setMnemonic('F');
mi_f_new = new JMenuItem("New",new ImageIcon("icons/new_project.png"));
mi_f_new.setMnemonic('N');
mi_f_open = new JMenuItem("Open",new ImageIcon("icons/open_project.png"));
mi_f_open.setMnemonic('O');
mi_f_save = new JMenuItem("Save",new ImageIcon("icons/save.png"));
mi_f_save.setMnemonic('S');
mi_f_saveas = new JMenuItem("Save Java File",new ImageIcon("icons/saveas.png"));
mi_f_saveas.setMnemonic('J');
mi_f_exit = new JMenuItem("Exit",new ImageIcon("icons/exit.png"));
mi_f_exit.setMnemonic('X');
mi_f_new.setAccelerator(KeyStroke.getKeyStroke("control N"));
mi_f_open.setAccelerator(KeyStroke.getKeyStroke("control O"));
mi_f_save.setAccelerator(KeyStroke.getKeyStroke("control S"));
mi_f_saveas.setAccelerator(KeyStroke.getKeyStroke("control J"));
mi_f_exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4,InputEvent.ALT_MASK));
m_file.add(mi_f_new);
m_file.add(mi_f_open);
m_file.addSeparator();
m_file.add(mi_f_save);
m_file.add(mi_f_saveas);
m_file.addSeparator();
m_file.add(mi_f_exit);
add(m_file);
}
void makeEditMenu()
{
m_edit = new JMenu("Edit");
m_edit.setMnemonic('E');
mi_e_cut = new JMenuItem("Cut",new ImageIcon("icons/cut.png"));
mi_e_cut.setMnemonic('X');
mi_e_copy = new JMenuItem("Copy",new ImageIcon("icons/copy.png"));
mi_e_copy.setMnemonic('C');
mi_e_paste = new JMenuItem("Paste",new ImageIcon("icons/paste.png"));
mi_e_paste.setMnemonic('P');
mi_e_delete = new JMenuItem("Delete",new ImageIcon("icons/delete.png"));
mi_e_delete.setMnemonic('D');
mi_e_cut.setAccelerator(KeyStroke.getKeyStroke("control X"));
mi_e_copy.setAccelerator(KeyStroke.getKeyStroke("control C"));
mi_e_paste.setAccelerator(KeyStroke.getKeyStroke("control V"));
mi_e_delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE,0));
m_edit.add(mi_e_cut);
m_edit.add(mi_e_copy);
m_edit.add(mi_e_paste);
m_edit.add(mi_e_delete);
add(m_edit);
}
void makeHelpMenu()
{
m_help = new JMenu("Help");
m_help.setMnemonic('H');
mi_h_help = new JMenuItem("Help",new ImageIcon("icons/help.png"));
mi_h_help.setMnemonic('H');
mi_h_about = new JMenuItem("About");
mi_h_about.setMnemonic('A');
mi_h_help.setAccelerator(KeyStroke.getKeyStroke("F1"));
mi_h_about.setAccelerator(KeyStroke.getKeyStroke("control A"));
m_help.add(mi_h_help);
m_help.addSeparator();
m_help.add(mi_h_about);
add(m_help);
}
void makeCodeButton()
{
m_code = new JButton();
m_code.setOpaque(false);
m_code.setContentAreaFilled(false);
m_code.setBorder(null);
m_code.setFocusable(false);
m_code.setText("Code Shift C");
Dimension dBt = new Dimension(75,25);
m_code.setMinimumSize(dBt);
m_code.setPreferredSize(dBt);
m_code.setMaximumSize(dBt);
m_code.getModel().addChangeListener(new ChangeListener()
{
#Override
public void stateChanged(ChangeEvent e)
{
ButtonModel model = (ButtonModel) e.getSource();
if(model.isRollover())
{
m_code.setBackground(Color.RED);
m_code.setOpaque(true);
}
else
{
m_code.setBackground(null);
m_code.setOpaque(false);
m_code.setContentAreaFilled(false);
}
}
});
m_code.setMnemonic('C');
add(m_code);
}
public void addListeners(ActionListener al)
{
mi_f_new.addActionListener(al);
mi_f_open.addActionListener(al);
mi_f_save.addActionListener(al);
mi_f_saveas.addActionListener(al);
mi_f_exit.addActionListener(al);
mi_e_cut.addActionListener(al);
mi_e_copy.addActionListener(al);
mi_e_paste.addActionListener(al);
mi_e_delete.addActionListener(al);
mi_h_help.addActionListener(al);
mi_h_about.addActionListener(al);
m_code.addActionListener(al);
}
}
My aim is to make the JButton to appear like it is a JMenu. This would entail that the button only changes colour when I am interacting with the rest of the JMenuBar not just when I hover over it. For example if I had clicked on the JMenu m_file and then hovered over the JButton the background would change, however if I was not previously interacting with the JMenuBar it should not change the background when I hover over the JButton. The next thing required would be the JMenuBar treats it as a JMenu. I mean this in the sense that when F10 is clicked and the first JMenu is selected. After which you can then click on the right arrow on the arrow key pad on your keyboard, this will select the next JMenu. However using this method of navigation skips the JButton and does not allow you to interact with the JButton in anyway. I also mean this in the sense that if you interact with a JMenu and then hover over the JButton the JMenuBar shows you are still hovering over the JMenu as well (See Image).
So I suppose I have three questions.
How do you get the JButton to only change colour if the JMenuBar is already being interacted with?
How do you get the JMenuBar to treat the JButton as a JMenu in the senses that I described?
Is anyone aware of the exact colour of the background of the JMenu when you hover over it? Since I would prefer to change my JButton's background to the same colour of the JMenu's background instead of it just being red.
Thanks,
Dan
Any idea why the menu bar menuBar is not showing? everything looks fine to me.
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class mySticky extends JFrame implements ActionListener{
//weStart!
JFrame frame = new JFrame("Sticky Note");
JMenuBar menuBar = new JMenuBar();
JMenu noteMenu = new JMenu("Note");
JMenuItem newNote = new JMenuItem("New Note");
JMenuItem open = new JMenuItem("Open");
JMenuItem saveAs = new JMenuItem("Save As");
JMenuItem save = new JMenuItem("Save");
//Constructor
public mySticky(){
setSize(400,300);
setLocation(500,250);
setTitle("Sticky Note");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
menuBar.add(noteMenu);
noteMenu.add(newNote);
noteMenu.add(open);
noteMenu.add(saveAs);
noteMenu.add(save);
frame.setJMenuBar(menuBar);
}
public void actionPerformed (ActionEvent e){
}
public static void main (String [] args ){
mySticky sticky = new mySticky ();
sticky.setVisible(true);
}
}
You add the menubar to frame, which is never added to any UI. Replace
frame.setJMenuBar(menuBar);
by
setJMenuBar(menuBar);
and your menubar will become visible. Or you should add frame to the UI as well. Not sure what you tried to achieve.
And you should wrap the code of your main method in a Runnable and execute it on the EDT (for example using EventQueue.invokeLater)
Instead of frame.setJMenuBar(menuBar), try this.setJMenuBar(menuBar) in your constructor.