Image of the problem:
http://gyazo.com/56c4f7f5fc10805695fc80de567b92c5.png
private JButton settingsButton = new JButton("Settings");
private JPopupMenu settings = new JPopupMenu();
private JMenuItem accounts = new JMenuItem("Accounts");
settings.add(accounts);
settingsButton.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
settings.show(e.getComponent(), 0, 0);
}
});
So as you have seen on the image, I don't think this is any accurate. Is there any (better) method to get it on a the right spot?
I have clicked on the JButton: "Settings" and it should popup just a tad down it.
You are better off using a JMenuBar and then adding JMenus with JMenuItems, there is no point on reinventing the wheel:
JMenuBar menubar = new JMenuBar();
JMenu settings = new JMenu("Settings");
JMenuItem accounts = new JMenuItem("Accounts");
settings.add(accounts);
menubar.add(settings);
myFrame.setJMenuBar(menubar);
Related
My notepad program that I'm writing uses AbstractActions for each item in the JMenuBar, and I want to keep it consistent that way throughout my code. And now I'm implementing Cut, Copy, Paste into the program but I'm unsure of how to do that with Action.
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.text.DefaultEditorKit;
public class Home {
static Action Cut = new AbstractAction("Cut-Action") {
public void actionPerformed(ActionEvent e) {
// Where I want to use cut
new DefaultEditorKit.CutAction();
}
};
static public JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Edit");
menu.add(Cut); // Adds the cut action
// adds the non-action method
JMenuItem item = new JMenuItem(new DefaultEditorKit.CutAction());
item.setText("Cut-NonAction");
menu.add(item);
menuBar.add(menu);
return menuBar;
}
public static void main(String[] args) {
JFrame frame = new JFrame("Home");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = createMenuBar();
frame.add(menuBar, BorderLayout.NORTH);
JTextPane txt = new JTextPane();
JScrollPane s = new JScrollPane(txt);
frame.add(s, BorderLayout.CENTER);
frame.setSize(400, 300);
frame.setVisible(true);
}
}
How would I be able to use the cut action in my abstract action??
I figured it out with a little bit of trial and error.
I changed this code:
public void actionPerformed(ActionEvent e) {
new DefaultEditorKit().CutAction();
}
to:
public void actionPerformed(ActionEvent e) {
Action cut = new DefaultEditorKit.CutAction();
cut.actionPerformed(e);
}
How would I be able to use the cut action in my abstract action??
Why are you trying to do this? The is not the way to use the Actions from the editor kit.
This is the proper way to use the actions:
JMenuItem item = new JMenuItem(new DefaultEditorKit.CutAction());
Or if you happen to need the CutAction on a menu and on a toolbar you would use code like:
Action cut = new DefaultEditorKit.CutAction();
cut.putValue(Action.NAME, "Cut");
JMenuItem cutMenuItem = new JMenuItem( cut );
JButton cutButton = new JButton( cut );
Now the same Action is shared which means you can enable/disable the Action and both components will be affected. Read the section from the Swing tutorial on How to Use Actions for more information and examples.
I have a simple question; I am trying to add a menu to my program. This is what I have thus far:
public static void main(String args[]){
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {}
JFrame cipherGUIFrame = new CipherGUIFrame();
cipherGUIFrame.setVisible(true);
JMenuBar bar = new JMenuBar();;
JMenu file = new JMenu("File");
JMenu edit = new JMenu("Edit");
JMenuItem open = new JMenuItem("Open");
JMenuItem save = new JMenuItem("Save");
JMenuItem cut = new JMenuItem("Cut");
JMenuItem copy = new JMenuItem("Copy");
JMenuItem paste = new JMenuItem("Paste");
JSeparator sep = new JSeparator();
JMenuItem find = new JMenuItem("Find");
JPopupMenu options = new JPopupMenu("Options");
options.setVisible(true);
file.add(open);
file.add(save);
edit.add(cut);
edit.add(copy);
edit.add(paste);
edit.add(sep);
edit.add(find);
edit.add(options);
bar.add(file);
bar.add(edit);
cipherGUIFrame.setJMenuBar(bar);
}
I am trying to achieve an effect similar to this diagram: http://i.imgur.com/GYi0S9R.jpg .
Is "Options" not the JPopupMenu? It doesn't seem to show up! Or is it simply a JMenuItem and JPopupMenu is the new box that comes up when you hover over it?
A sub menu is just that, a menu which is contained within another menu
Try using something like...
JMenu options = new JMenu("Options");
options.add(new JRadioButtonMenuItem("Forward"));
options.add(new JRadioButtonMenuItem("Backward"));
options.addSeparator();
options.add(new JCheckBoxMenuItem("Case Sensetive"));
Take a closer look at How to Use Menus for more details
I'm just upping my knowledge on GUI and implementation of GUI's and buttons, and I've run into a little issue. I've searched for this, and even compared button codes but nothing seems different from what I'm seeing in comparison to others' code. When I add html to any button, take testOne for instance if I use:
JButton testOne = new JButton("<html><b><u>T</u>est<br>1</b></html>");
I have a button, of course, but the button is so large with tiny font, while my other buttons are normal size. Anyone have an idea why? I posted the code without a homework tag, because it's not homework, just fun practice.
public FunProject(){
super("Fun Project"); //child
//create layout and get the content pane for content
contents = getContentPane();
contents.setLayout(new FlowLayout(FlowLayout.CENTER));
leftBox = getContentPane();
leftBox.setLayout(new BoxLayout(leftBox, BoxLayout.X_AXIS));
//menuBar = new
//Create the buttons to use
JButton testOne = new JButton("Test 1");
JButton testTwo = new JButton("Test 2");
JButton testThree = new JButton("Test 3");
Also, for anyone feeling like spreading a little knowledge, how would I go about stacking my buttons? Right now they're just in a horizontal plane unstacked, but at the location I want (Center to the left). Thank you in advance.
import javax.swing.*;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import java.awt.*;
import java.awt.event.*;
public class FunProject extends JFrame implements ActionListener, KeyListener, MenuListener{
//Content only visible to me
private Container contents;
private Container leftBox;
private JButton testOne, testTwo, testThree;
private JMenuBar menuBar;
private JMenu men, file, edit, exit;
private JMenuItem fileOpen, fileSave, fileType;
private JMenuItem editOpen, editSave, editType;
//Constructor
public FunProject(){
super("Fun Project");
//create layout and get the content pane for content
contents = getContentPane();
contents.setLayout(new FlowLayout(FlowLayout.CENTER));
leftBox = getContentPane();
leftBox.setLayout(new BoxLayout(leftBox, BoxLayout.X_AXIS));
//Key Listener
this.addKeyListener(this);
//Creating Menu bar
menuBar = new JMenuBar();
//Adding header to menuBar
men = new JMenu("Test Menu");
men.addMenuListener(this);
menuBar.add(men);
//Adding exit to menuBar
exit = new JMenu("Exit Menu");
exit.setMnemonic(KeyEvent.VK_X);
exit.addMenuListener(this);
menuBar.add(exit);
//Add submenu
file = new JMenu("FILE");
file.addMenuListener(this);
men.add(file);
edit = new JMenu("EDIT");
edit.addMenuListener(this);
men.add(edit);
//Add item to submenu FILE
fileOpen = new JMenuItem("Open a file");
fileOpen.addActionListener(this);
file.add(fileOpen);
fileSave = new JMenuItem("Save a file");
fileSave.addActionListener(this);
file.add(fileSave);
fileType = new JMenuItem("File type");
fileType.addActionListener(this);
file.add(fileType);
//Add item to submenu EDIT
editOpen = new JMenuItem("Open a file");
editOpen.addActionListener(this);
edit.add(editOpen);
editSave = new JMenuItem("Save a file");
editSave.addActionListener(this);
edit.add(editSave);
edit = new JMenuItem("File type");
editType.addActionListener(this);
edit.add(editType);
//Add menu bar
this.setJMenuBar(menuBar);
//Create the buttons to use
JButton testOne = new JButton("Test 1");
JButton testTwo = new JButton("Test 2");
JButton testThree = new JButton("Test 3");
//Button modifications
testOne.setPreferredSize(new Dimension(100, 100));
//Add buttons and such to the leftBox (frame > pane)
leftBox.add(testOne);
leftBox.add(testTwo);
leftBox.add(testThree);
//Tell the program what Listener will handle events for the button or whatever you
//are implementing
testOne.addActionListener(this);
testTwo.addActionListener(this);
testThree.addActionListener(this);
//Set size and visibility to display content and color
setSize(400,300);
setVisible(true);
}
public static void main(String[] args){
FunProject fp = new FunProject();
fp.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
I was messing around with menu's (So ignore the menu code) and what they're all about. That's for later time when I learn it better.
1)try to use
h1 Tag -> JButton testOne = new JButton("<html><b><u><h1>T</u>est<br>1</b></html>");
for increase the size or font use <font> tag for changing the color or size of the font.
2)some time it depend upon the layout you used check it out
3) try ButtonObject.setBounds();
I am a beginner using GWT. I have a menubar which I want to retain on the screen even if the mouse is not over it. However when the mouse is not over the menubar and clicked somewhere on the screen then I want the menubar to disappear. I tried using the MouseOutEvent but I need it to fire only when the mouse is clicked not just out. Any help would be appreciated.
this.menu.addDomHandler(menuHoverOutHandler, MouseOutEvent.getType());
MouseOutHandler menuHoverOutHandler = new MouseOutHandler() {
public void onMouseOut(MouseOutEvent event) {
Window.alert("I am outside the region");
}
};
Below is a fully working answer taken from my live app:
The way I solved the menu close on mouse out was to run a boolean variable "isMouseOut" in the top of the constructor to keep track, and then allocate the MouseListener in a more OO friendly way to keep track of the multiple MouseIn-MouseOut events as a user interacts with the menu. Which calls a separate menuClear method acting upon the state of the boolean "isMouseOut". The class implements MouseListener. This is how its done.
Create an ArrayList adding all the menu items to this array first. Like so:
Font menuFont = new Font("Arial", Font.PLAIN, 12);
JMenuBar menuBar = new JMenuBar();
getContentPane().add(menuBar, BorderLayout.NORTH);
// Array of MenuItems
ArrayList<JMenuItem> aMenuItms = new ArrayList<JMenuItem>();
JMenuItem mntmRefresh = new JMenuItem("Refresh");
JMenuItem mntmNew = new JMenuItem("New");
JMenuItem mntmNormal = new JMenuItem("Normal");
JMenuItem mntmMax = new JMenuItem("Max");
JMenuItem mntmStatus = new JMenuItem("Status");
JMenuItem mntmFeedback = new JMenuItem("Send Feedback");
JMenuItem mntmEtsyTWebsite = new JMenuItem("EtsyT website");
JMenuItem mntmAbout = new JMenuItem("About");
aMenuItms.add(mntmRefresh);
aMenuItms.add(mntmNew);
aMenuItms.add(mntmNormal);
aMenuItms.add(mntmMax);
aMenuItms.add(mntmStatus);
aMenuItms.add(mntmFeedback);
aMenuItms.add(mntmEtsyTWebsite);
aMenuItms.add(mntmAbout);
then iterate over the arrayList at this stage adding a MouseListener using the for() loop:
for (Component c : aMenuItms) {
if (c instanceof JMenuItem) {
c.addMouseListener(ml);
}
}
Now set JMenu parents for the MenuBar:
// Now set JMenu parents on MenuBar
final JMenu mnFile = new JMenu("File");
menuBar.add(mnFile).setFont(menuFont);
final JMenu mnView = new JMenu("View");
menuBar.add(mnView).setFont(menuFont);
final JMenu mnHelp = new JMenu("Help");
menuBar.add(mnHelp).setFont(menuFont);
Then add the dropdown menuItems children to the JMenu parents:
// Now set menuItems as children of JMenu parents
mnFile.add(mntmRefresh).setFont(menuFont);
mnFile.add(mntmNew).setFont(menuFont);
mnView.add(mntmNormal).setFont(menuFont);
mnView.add(mntmMax).setFont(menuFont);
mnHelp.add(mntmStatus).setFont(menuFont);
mnHelp.add(mntmFeedback).setFont(menuFont);
mnHelp.add(mntmEtsyTWebsite).setFont(menuFont);
mnHelp.add(mntmAbout).setFont(menuFont);
Add the mouseListeners to the JMenu parents as a separate step:
for (Component c : menuBar.getComponents()) {
if (c instanceof JMenu) {
c.addMouseListener(ml);
}
}
Now that the child menuItem elements all have their own listeners that are separate to the parent JMenu elements and the MenuBar itself - It is important to identify the object type within the MouseListener() instantiation so that you get the menu auto opening on mouseover (in this example the 3x JMenu parents) BUT ALSO avoids child exception errors and allows clean identification of mouseOUT of the menu structure without trying to monitor where the mouse position is. The MouseListener is as follows:
MouseListener ml = new MouseListener() {
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
isMouseOut = true;
timerMenuClear();
}
public void mouseEntered(MouseEvent e) {
isMouseOut = false;
Object eSource = e.getSource();
if(eSource == mnHelp || eSource == mnView || eSource == mnFile){
((JMenu) eSource).doClick();
}
}
};
The above only simulates the mouse click into the JMenu 'parents' (3x in this example) as they are the triggers for the child menu dropdowns. The timerMenuClear() method calls on the MenuSelectionManager to empty whatever selectedpath point was live at the time of real mouseOUT:
public void timerMenuClear(){
ActionListener task = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(isMouseOut == true){
System.out.println("Timer");
MenuSelectionManager.defaultManager().clearSelectedPath();
}
}
};
//Delay timer half a second to ensure real mouseOUT
Timer timer = new Timer(1000, task);
timer.setInitialDelay(500);
timer.setRepeats(false);
timer.start();
}
It took me a little testing, monitoring what values I could access within the JVM during its development - but it Works a treat! even with nested menus :) I hope many find this full example very useful.
Use widget's blur handler. It detects when the widget lost focus.
I am making a simple java program that represents a Microsoft Word menu bar, and in the file menu I add an exit button... it does nothing.
I need your help to tell me what to do to make the exit button actually exit and close the program.
Here is my code:
public class MicrosoftWordMenu {
public static void main(String [] args)
{
JPanel panel = new JPanel();
JFrame frame = new JFrame("Microsoft Word");
JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("File");
JMenu menu1 = new JMenu("Edit");
JMenu menu2 = new JMenu("View");
JMenu menu3 = new JMenu("Insert");
JMenu menu4 = new JMenu("Format");
JMenu menu5 = new JMenu("Tools");
JMenu menu6 = new JMenu("Table");
JMenu menu7 = new JMenu("Window");
JMenu menu8 = new JMenu("Help");
frame.add(bar, BorderLayout.NORTH);
frame.add(panel);
bar.add(menu);
bar.add(menu1);
bar.add(menu2);
bar.add(menu3);
bar.add(menu4);
bar.add(menu5);
bar.add(menu6);
bar.add(menu7);
bar.add(menu8);
JMenuItem menuitem = new JMenuItem("New...");
JMenuItem menuitem1 = new JMenuItem("Open...");
JMenuItem menuitem2 = new JMenuItem("Close");
JMenuItem menuitem3 = new JMenuItem("Save");
JMenuItem menuitem4 = new JMenuItem("Save as...");
JMenuItem menuitem5 = new JMenuItem("Save as web page...");
JMenuItem menuitem6 = new JMenuItem("Web page preview ");
JMenuItem menuitem7 = new JMenuItem("Print ");
JMenuItem menuitem8 = new JMenuItem("Exit");
menu.add(menuitem);
menu.add(menuitem1);
menu.add(menuitem2);
menu.add(menuitem3);
menu.add(menuitem4);
menu.add(menuitem5);
menu.add(menuitem6);
menu.add(menuitem7);
menu.add(menuitem8);
frame.setSize(600,100);
frame.setVisible(true);
}
}
Also consider using Action to let components share functionality, as shown here.
Calling System.exit(0) on menu selection would do just fine.
At the moment you're just creating the GUI element, but they're basically empty shells. In particular, you've created items that appear on the menu, but you haven't added any behaviour to those items. (Since you haven't told your program anywhere what to do when an item is clicked, what did you think would happen)?
In order to provide this behaviour, you'll need to register an ActionListener, which will be called when something happens on an element, and will let you take an appropriate action at that point (such as calling System.exit(0). See the tutorial on Writing [Swing] Event listeners for details.
I always extend the AbstractAction class (which implements the ActionListener interface) which allows you to reuse your actions. By extending the AbstractAction, the actionPerformed(ActionEvent e) method will be invoked very time your button is clicked.
public class CloseAction extends AbstractAction {
public CloseAction() {
super("Close");
}
public actionPerformed(ActionEvent e) {
System.exit(1);
}
}
Now, to apply the above action to one of your buttons, you simply need to follow the below piece of code.
CloseButton.setAction(new CloseAction());
The close button will now shut down your application each time it gets pressed.
Use the ExitAction defined in Closing an Application. Then clicking on the Exit menu item will be just like clicking on the Close icon at the top right of the window. This allows for consistency when closing an application in case you ever need to do close processing.
Edit:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
...
// JMenuItem menuitem8 = new JMenuItem("Exit");
JMenuItem menuitem8 = new JMenuItem( new ExitAction() );