JMenuBar & JMenu
I have a frame where when it is called I want to show a JMenu. The only way I know how to show a JMenu is by adding it to a JMenuBar and when the user selects the title of the JMenuBar(ie. File) then the attatched JMenu is shown. In my case there is only one selection to be made from the JMemuBar, so I want to bypass that step all together and just show the JMenu in the frame that is presented because the user has no other option but to look at the JMenu(Much like when you right click in Windows) . My question again is how can I just show a JMenu without having to attatch it to a JMenuBar. In other words, I do not want the title bar just the one and only JMenu when the frame is called. How can I accomplish this?
Ie
JMenu list = new JMenu("List");
list contents
JMenuBar menuBar = new JMenuBar();
menuBar.add(list);
I do not want the JMenuBar on my frame nor the included title "List". Though what I do want is the list itself when the frame is called. Again, much like right-clicking in Windows. Can someone please help me with this.
Hi,
Check the tutorial on how to use menus. It describes how to create a popup menu (right click on windows brings up a popup menu)
http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html
/Kaj
Similar Messages
-
Can i call a JMenuBar in a number of JFrame(s) ?
Hi ,
I've a program with a number of JFrames.
I wanted to add a JMenuBar for each frame of my program, this menu bar has the same design code and the same events code in all the program frames, so is there a way to create this JMenuBar once only & call it some how in every JFrame to load it directly instead of writing its same code a lot of times for every JFrame ?
Thanks ,
Heshamimport java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
class Test{
public static void main( String[] argv ) throws Throwable {
for(int i=0; i<10; i++){
SuperFrame f = new SuperFrame();
f.setLocation(i*10,i*10);
f.setSize(400,300);
f.setVisible(true);
class SuperFrame extends JFrame{
private static final long serialVersionUID = 1L;
* All the menu item goes here
JMenuBar mbar = new JMenuBar();
JMenu menu = new JMenu("Menu");
JMenuItem menuItem1 = new JMenuItem("Close");
JMenuItem menuItem2 = new JMenuItem("Exit");
public SuperFrame(){
super("Testing");
this.menu.add(menuItem1);
this.menu.add(menuItem2);
this.mbar.add(menu);
this.setJMenuBar(mbar);
menuItem1.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
dispose();
menuItem2.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
} -
How to add a JMenubar and a JTable in a JFrame in a single application
Hi all,
I require an urgent help from you.I am a beginer in programming Swing.I want to add a menu,combobox,and a table in a single application.I did coding as below:
package com.BSS;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.border.*;
import javax.swing.event.*;
public class newssa extends JFrame
public JMenuBar menuBar;
public JToolBar toolBar;
public JFrame frame;
private JLabel jLabel1;
private JLabel jLabel2;
private JLabel jLabel3;
private JLabel jLabel4;
private JLabel jLabel5;
private JLabel jLabel6;
private JComboBox jComboBox1;
private JComboBox jComboBox2;
private JComboBox jComboBox3;
private JComboBox jComboBox4;
private JComboBox jComboBox5;
private JComboBox jComboBox6;
private JTable jTable1;
private JScrollPane jScrollPane1;
private JPanel contentPane;
public newssa()
super();
initializeComponent();
this.setVisible(true);
private void initializeComponent()
jLabel1 = new JLabel();
jLabel2 = new JLabel();
jLabel3 = new JLabel();
jLabel4 = new JLabel();
jLabel5 = new JLabel();
jLabel6 = new JLabel();
jComboBox1 = new JComboBox();
jComboBox2 = new JComboBox();
jComboBox3 = new JComboBox();
jComboBox4 = new JComboBox();
jComboBox5 = new JComboBox();
jComboBox6 = new JComboBox();
frame=new JFrame();
//Included here
JMenuBar menuBar = new JMenuBar();
JMenu general = new JMenu("General");
menuBar.add(general);
JMenu actions =new JMenu("Actions");
menuBar.add(actions);
JMenu view=new JMenu("View");
menuBar.add(view);
JMenu Timescale=new JMenu("TimeScale");
menuBar.add(Timescale);
Timescale.add("Today CTRL+D");
Timescale.add("Current Week CTRL+W");
Timescale.add("Current Month CTRL+M");
Timescale.add("Current Quarter CTRL+Q");
Timescale.add("Current Year CTRL+Y");
Timescale.add("Custom TimeScale CTRL+U");
JMenu start=new JMenu("Start");
menuBar.add(start);
JMenu options=new JMenu("Options");
menuBar.add(options);
JMenu help=new JMenu("Help");
menuBar.add(help);
JFrame.setDefaultLookAndFeelDecorated(true);
frame.setJMenuBar(menuBar);
frame.pack();
frame.setVisible(true);
toolBar = new JToolBar("Formatting");
toolBar.addSeparator();
//Before this included new
String columnNames[] = { "ColorStatus", "Flash", "Service Order","Configuration","Configuration Description"};
// Create some data
String dataValues[][] =
{ "blue", "flash", "ORT001" },
{ "AVCONF", "av configuration with warrenty"}
// Create a new table instance
//jTable1 = new JTable( dataValues, columnNames );
jTable1 = new JTable(dataValues,columnNames);
jScrollPane1 = new JScrollPane(jTable1);
contentPane = (JPanel)this.getContentPane();
//scrollPane = new JScrollPane( table );
//topPanel.add( scrollPane, BorderLayout.CENTER );
// jLabel1
jLabel1.setText("Service Centers");
// jLabel2
jLabel2.setText("Service Areas");
// jLabel4
jLabel3.setText("Skills");
jLabel4.setText("Availablity Types");
// jLabel5
jLabel5.setText("From Date");
// jLabel6
jLabel6.setText("To");
// jComboBox1
jComboBox1.addItem("Coimbatore");
jComboBox1.addItem("Chennai");
jComboBox1.addItem("Mumbai");
jComboBox1.addItem("New Delhi");
jComboBox1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
jComboBox1_actionPerformed(e);
// jComboBox2
jComboBox2.addItem("North Zone");
jComboBox2.addItem("South Zone");
jComboBox2.addItem("Central Zone");
jComboBox2.addItem("Eastern Zone");
jComboBox2.addItem("Western Zone");
jComboBox2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
jComboBox2_actionPerformed(e);
// jComboBox3
jComboBox3.addItem("Microsoft Components");
jComboBox3.addItem("Java Technologies");
jComboBox3.addItem("ERP");
jComboBox3.addItem("Others");
jComboBox3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
jComboBox3_actionPerformed(e);
// jComboBox4
jComboBox4.addItem("One");
jComboBox4.addItem("Two");
jComboBox4.addItem("Three");
jComboBox4.addItem("Four");
jComboBox4.addItem("Five");
jComboBox4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
jComboBox4_actionPerformed(e);
// jComboBox5
jComboBox5.addItem("12/12/2004");
jComboBox5.addItem("13/12/2004");
jComboBox5.addItem("14/12/2004");
jComboBox5.setEditable(true);
jComboBox5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
jComboBox5_actionPerformed(e);
// jComboBox6
jComboBox6.addItem("12/11/2004");
jComboBox6.addItem("13/11/2004");
jComboBox6.addItem("14/11/2004");
jComboBox6.setEditable(true);
jComboBox6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
jComboBox6_actionPerformed(e);
// jTable1
jTable1.setModel(new DefaultTableModel(4, 4));
// jScrollPane1
jScrollPane1.setViewportView(jTable1);
// contentPane
contentPane.setLayout(null);
addComponent(contentPane, jLabel1, 2,29,84,18);
addComponent(contentPane, jLabel2, 201,33,76,18);
addComponent(contentPane, jLabel3, 384,32,59,18);
addComponent(contentPane, jLabel4, 2,77,85,18);
addComponent(contentPane, jLabel5, 197,79,84,18);
addComponent(contentPane, jLabel6, 384,80,60,18);
addComponent(contentPane, jComboBox1, 85,32,100,22);
addComponent(contentPane, jComboBox2, 276,32,100,22);
addComponent(contentPane, jComboBox3, 419,30,100,22);
addComponent(contentPane, jComboBox4, 88,76,100,22);
addComponent(contentPane, jComboBox5, 276,79,100,22);
addComponent(contentPane, jComboBox6, 421,78,100,22);
addComponent(contentPane, jScrollPane1, 33,158,504,170);
// newssa
this.setTitle("SSA Service Scheduler");
this.setLocation(new Point(0, 0));
this.setSize(new Dimension(560, 485));
/** Add Component Without a Layout Manager (Absolute Positioning) */
private void addComponent(Container container,Component c,int x,int y,int width,int height)
c.setBounds(x,y,width,height);
container.add(c);
// TODO: Add any appropriate code in the following Event Handling Methods
private void jComboBox1_actionPerformed(ActionEvent e)
int index = jComboBox1.getSelectedIndex();
switch(index)
case 0: System.out.println("Area Coimbatore Selected "); break;
case 1: System.out.println("Area Chennai selected"); break;
case 2: System.out.println("Mumbai being selected"); break;
case 3: System.out.println("New Delhi being selected"); break;
private void jComboBox2_actionPerformed(ActionEvent e)
int index = jComboBox2.getSelectedIndex();
switch(index)
case 0: System.out.println("North Zone Selcted "); break;
case 1: System.out.println("South Zone being selected"); break;
case 2: System.out.println("Central Zone being selected"); break;
case 3: System.out.println("Eastern Zone being selected"); break;
case 4: System.out.println("Western Zone being selected"); break;
private void jComboBox3_actionPerformed(ActionEvent e)
int index = jComboBox3.getSelectedIndex();
switch(index)
case 0: System.out.println("Microsoft Components being selected"); break;
case 1: System.out.println("Java Technologies being selected"); break;
case 2: System.out.println("ERP Tehnologies being selected"); break;
case 3: System.out.println("Other's selected"); break;
private void jComboBox4_actionPerformed(ActionEvent e)
int index = jComboBox4.getSelectedIndex();
switch(index)
case 0: System.out.println("One selected"); break;
case 1: System.out.println("Two selected"); break;
case 2: System.out.println("Three selected"); break;
case 3: System.out.println("Four selected"); break;
case 4: System.out.println("Five selected"); break;
private void jComboBox5_actionPerformed(ActionEvent e)
int index = jComboBox5.getSelectedIndex();
switch(index)
case 0: System.out.println("12/12/2004 being selected"); break;
case 1: System.out.println("13/12/2004 being selected"); break;
case 2: System.out.println("14/12/2004 being selected"); break;
private void jComboBox6_actionPerformed(ActionEvent e)
int index = jComboBox6.getSelectedIndex();
switch(index)
case 0: System.out.println("12/11/2004 being selected"); break;
case 1: System.out.println("13/11/2004 being selected"); break;
case 2: System.out.println("14/11/2004 being selected"); break;
public static void main(String[] args)
newssa ssa=new newssa();
//JFrame.setDefaultLookAndFeelDecorated(true);
//JDialog.setDefaultLookAndFeelDecorated(true);
//JFrame frame = new JFrame("SSA Service Scheduler");
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setJMenuBar(ssa.menuBar);
//frame.getContentPane( ).add(ssa.toolBar, BorderLayout.NORTH);
//frame.getContentPane( ).add(ssa.pane, BorderLayout.CENTER);
//frame.pack( );
//frame.setVisible(true);
try
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
catch (Exception ex)
System.out.println("Failed loading L&F: ");
System.out.println(ex);
But as a O/P ,I am getting menu in a seperate windos and the rest of the combobox and jtable in a seperate window.Kindly help me to solve the application.
VERY URGENT PLEASE..
Thanks in advance
with kind regds
Satheesh.KBut did u mean this as the next problem,Which I will come across..Yes, the second setVisible(true) seemed to be producing a smaller frame behind the main frame.
And your JMenuBar is declared twice, but not sure if this will affect the code - haven't read it all. -
Problem with Alt , JMenu and Mnemonics
I have built an application with a JMenuBar containing several JMenu's, the first of which is a File menu. All JMenus and JMenuItems have mnemonics associated with them. When I press the alt key the underlines show and focus appears to be given to the File menu (though it has not dropped down). If I then press a key, for example 'S', that is a mnemonic of the 'Save' jmenuitem in the File menu, the Save action is invoked. This should not occur because the menu has not opened yet.
The behavior is what I'd expect had an accelerator (Alt+S) been defined for the Save menu item. But I have not defined any accelerators.
Why does this happen and more importantly, is there a work around?Except for the 1st line in jbinit() it's all pretty standard stuff. Here's a snippet of the code:
public class MainFrame extends JFrame implements ChangeListener {
JMenuBar jMenuBar1 = new JMenuBar();
JMenu jMenuFile = new JMenu();
JMenuItem jMenuFileNew = new JMenuItem();
JMenuItem jMenuFileSave = new JMenuItem();
JMenu m_editMenu = new JMenu();
JMenuItem m_editCutMenuItem = new JMenuItem();
JMenuItem m_editCopyMenuItem = new JMenuItem();
JMenuItem m_editPasteMenuItem = new JMenuItem();
public MainFrame() {
jbInit();
//Component initialization
private void jbInit() {
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke(KeyEvent.VK_ALT, Event.ALT_MASK, false), "repaint");
// file menu
jMenuFile.setText("File");
jMenuFile.setMnemonic(KeyEvent.VK_F);
jMenuFileNew.setText("New...");
jMenuFileNew.setMnemonic(KeyEvent.VK_N);
jMenuFileNew.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jMenuFileNewSpecial_actionPerformed(e);
jMenuFileSave.setText("Save");
jMenuFileSave.setMnemonic(KeyEvent.VK_S);
jMenuFileSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jMenuFileSaveSpecial_actionPerformed(e);
jMenuFile.add(jMenuFileNew);
jMenuFile.add(jMenuFileSave);
// edit menu
m_editMenu.setText("Edit");
m_editMenu.setMnemonic(KeyEvent.VK_E);
m_editCutMenuItem.setText("Cut");
m_editCutMenuItem.setMnemonic(KeyEvent.VK_T);
m_editCutMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
editCutMenuItem_actionPerformed(e);
m_editCopyMenuItem.setText("Copy");
m_editCopyMenuItem.setMnemonic(KeyEvent.VK_C);
m_editPasteMenuItem.setText("Paste");
m_editPasteMenuItem.setMnemonic(KeyEvent.VK_P);
m_editMenu.add(m_editCutMenuItem);
m_editMenu.add(m_editCopyMenuItem);
m_editMenu.add(m_editPasteMenuItem);
jMenuBar1.add(jMenuFile);
jMenuBar1.add(m_editMenu);
this.setJMenuBar(jMenuBar1);
etc...
Pressing Alt+S invokes the action listener for the jMenuFileSave menu item. It should do nothing since there is no top level menu with a mnemonic of 'S'. -
JMenu with RIGHT_TO_LEFT Orientation
Hello,
I have a JFrame contains a JMenuBar and it's menus, My application direction is RIGHT_TO_LEFT, I changed the direction of the JMenuBar, JMenu, JMenuItem, to all the Heirarchy of the menus, and I got the required GUI.
Unfortunately, when the direction is RIGHT_TO_LEFT, and lets say you have the following menus structure:
File -> Open
Print -> Printer Setup
Page Setup
Save
Exit
When the orientation is RIGHT_TO_LEFT, The JMenu 'Print' expanded to left side only when you press the RIGHT arrow on the keyboard !
I extended the JMenu and JMenuItem classes and overrides the
'processMenuKeyEvent(MenuKeyEvent e)' method and I got the required thing, but I have the following questions:
1. How can I determine the menu that currently have the selection or the focus.
2. I have problems if there is nested menus as print -> Printer -> Type ....
Is there A general solution such as I can apply it to the JFrame as an example and it will reflect it on all components that it holds ?Thanks for your answer.
So there is no solution for that bug (except implementing the ComboBoxUI)?
As I found bug is in JScrollPane that used in Popup. When a JScrollPane's orientation is set to RIGHT_TO_LEFT it scrolls to the left but it is expected that it should scroll to the right.
Edited by: gilas on Aug 2, 2008 3:18 AM -
JMenu Mnemonic in JApplet not working
Hi,
Here is a code in my JApplet, but some how the Mnemonic is not working,
why??
I m using jdk1.4.1
Ashish
import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.awt.*;
import java.math.*;
import javax.accessibility.*;
public class TestMenuApplet extends JApplet
public void init()
buildMenu();
private void buildMenu()
JMenuBar menuBar = new JMenuBar();
JMenu file = new JMenu("File", true);
JMenu format = new JMenu("Format", true);
file.setMnemonic(KeyEvent.VK_F);
format.setMnemonic(KeyEvent.VK_O);
JMenuItem back = new JMenuItem("Back");
JMenuItem close = new JMenuItem("Close");
JRadioButtonMenuItem single =
new JRadioButtonMenuItem("Single");
JRadioButtonMenuItem multi =
new JRadioButtonMenuItem("Multiple", true);
ButtonGroup row = new ButtonGroup();
row.add(single);
row.add(multi);
JMenu monthly = new JMenu("Monthly");
JMenuItem one = new JMenuItem("One", KeyEvent.VK_O);
JMenuItem two = new JMenuItem("Two");
JMenuItem test = new JMenuItem("Test");
menuBar.add(file);
menuBar.add(format);
file.add(back);
file.add(close);
format.add(single);
format.add(multi);
format.addSeparator();
format.add(monthly);
format.add(test);
monthly.add(one);
monthly.add(two);
this.setJMenuBar(menuBar);
My HTML
<html>
<HEAD>
<TITLE>test</title>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Expires" content="-1">
</HEAD>
<BODY >
This is testing of applet
<br>
<!--"CONVERTED_APPLET"-->
<!-- HTML CONVERTER -->
<OBJECT
classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
WIDTH = "300" HEIGHT = "300"
codebase="http://java.sun.com/products/plugin/autodl/jinstall-1_4-win.cab#Version=1,4,0,0">
<PARAM NAME = CODE VALUE = "TestMenuApplet.class" >
<PARAM NAME="type" VALUE="application/x-java-applet;version=1.4">
<PARAM NAME="scriptable" VALUE="false">
<COMMENT>
<EMBED
type="application/x-java-applet;version=1.4"
CODE = "TestMenuApplet.class"
WIDTH = "300"
HEIGHT = "300"
scriptable=false
pluginspage="http://java.sun.com/products/plugin/index.html#download">
<NOEMBED>
</NOEMBED>
</EMBED>
</COMMENT>
</OBJECT>
<!--
<APPLET CODE = "TestMenuApplet.class"
WIDTH = "300"
HEIGHT = "300"
</APPLET>
-->
<!--"END_CONVERTED_APPLET"-->
</BODY>
</html>Did you convert your html code to call the sun VM instead of the default browser VM ?
Use the HtmlConverter.exe to do this passing the html file in argument.
Denis -
Subelements of a disabled JMenu are not cleared
Hi All!
Subelements of a disabled JMenu are not cleared from screen when the frame is repainted.
Please go thru the sample code below & comments following code:
//Subelements of a disabled JMenu are not cleared from screen
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
class MyFrame extends JFrame implements ChangeListener {
JMenuBar menuBar;
JMenu menu;
JTabbedPane tp;
MyFrame() {
super();
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
setTitle("JMenuItems of a JMenu are not cleared if JMenu is disabled.");
setSize(600, 500);
createMenu();
JPanel panel = new JPanel();
tp = new JTabbedPane();
tp.addTab("One", new JLabel(" One will go here "));
tp.addTab("Two", new JLabel(" Two will go here "));
tp.addChangeListener(this);
panel.add(tp);
getContentPane().add(BorderLayout.CENTER, panel);
getContentPane().add(BorderLayout.NORTH, menuBar);
private void createMenu()
menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.add(new JMenuItem("New"));
fileMenu.add(new JMenuItem("Open"));
fileMenu.add(new JMenuItem("Close"));
menuBar.add(fileMenu);
menuBar.add(new JMenu("Edit"));
menuBar.add(new JMenu("Search"));
menuBar.add(new JMenu("View"));
JMenu menuProblem = new JMenu("Menu");
menu = new JMenu("Child Menu");
menu.add(new JMenuItem("Menu Item 1"));
menu.add(new JMenuItem("Menu Item 2"));
menu.add(new JMenuItem("Menu Item 3"));
menuProblem.add(menu );
menuBar.add(menuProblem);
public void stateChanged(ChangeEvent e)
int index = tp.getSelectedIndex();
if( index == 0)
menu.setEnabled(true);
else
menu.setEnabled(false);
public class MenuDemo
public static void main(String args[]) {
MyFrame frame = new MyFrame();
frame.setVisible(true);
Comments:
Use JDK 1.3 and run the application. When user clicks on Menu and clicks on Child Menu, sub elements are shown and if user clicks on Tab Two, Menu Items are not cleared because it's parent menu is disabled. The same application works fine in Jdk 1.4.1.
I am searching for BUG ID from Sun's bug database. If any one of you have a work around solution for this problem or bug id, kindly post the same at the earliest.
Thanks in advance,
SandeshHI
so theres a price difference so what you do is create a GL called the price difference GL if you have one thats fine make sure you post the price difference into the price difference GL account created you can create GL account in FS00, the other way is to set a tolerance limit set the tolerance limit to 10%.
hope this solves your problem
regrds
Vignesh -
Error in Right-to-Left Jmenu movement
Hi everybody,
I started using Java 1.5 recently, I found that it does not behave correctly regarding arrow key movements in right-to-left orientation (up,down, left and right), as the following piece of code shows:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class test14 extends JFrame {
JMenuBar jmenubar = new JMenuBar();
JMenu Jmenu;
JMenuItem mi;
public test14() {
super("Menu test..");
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
enableEvents(AWTEvent.KEY_EVENT_MASK);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Exit();
setMenu();
jmenubar.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
Dimension max_size = Toolkit.getDefaultToolkit().getScreenSize();
this.setSize(max_size.width,max_size.height);
this.setLocation(1,1);
show();
public void setMenu() {
int i,c;
JMenu Jmenu = null;
JMenuItem mi;
Jmenu = new JMenu("ABCDEF");
Jmenu.setMnemonic(KeyEvent.VK_ALT);
for (i=0; i < 5;i++) {
Jmenu = new JMenu("ABCDEF");
if (i == 0) Jmenu.setMnemonic(KeyEvent.VK_ALT);
mi = new JMenuItem("abcdef");
Jmenu.add(mi);
jmenubar.add(Jmenu);
setJMenuBar(jmenubar);
private void Exit() {
setVisible(false);
//setEnabled(false);
System.exit(0);
//----- MAIN function ------------
public static void main(String args[]) {
new test14();
}ThanksThank you for considering this issue!
Yes, I think this solution is sufficient to resolve it. -
AffineTransform problem caused by JMenuBar + JTabbedPane
Hello everyone.
I am starting to think that there is a bug in Java, because otherwise what else could cause the problem I am experiencing? Namely: adding a panel with a vertical text (like a Y axis caption) using an AffineTransform (see SSCCE below) causes this text to be misplaced in some cases.
Variant A
Panel is added directly to the application frame. This causes no problems and everything is as it should be.
Variant B
Panel is placed on a tabbed pane and a menu bar is associated with the frame. The vertical text is now shifted away from the place where it should be by the height of the menu bar plus the height of tabs on the tabbed pane. Why is this happening? Am I doing something wrong?
Moreover, when one switches to another tab and then back, the text is now shifted only by the height of the tabs. Once the application window is resized at least a bit, the text jumps right back to the position shifted by tab height plus menu bar height... Strange, strange, strange...
SSCCE
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.*;
import javax.swing.*;
class MyPanel extends JPanel {
MyPanel() {
this.setPreferredSize(new Dimension(300, 200));
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2D = (Graphics2D)g;
int g2DWidth = this.getWidth();
int g2DHeight = this.getHeight();
// Horizontal line in the middle of the panel (indicates the position
// where the middle of the vertical label should be)
g2D.drawLine(30, (int)(g2DHeight / 2), g2DWidth - 10,
(int)(g2DHeight / 2));
// Vertical label
AffineTransform origTransform = g2D.getTransform();
AffineTransform rotate = AffineTransform.getRotateInstance(
-Math.PI / 2.0, 0, 0);
g2D.setTransform(rotate);
String text = "Centered?";
FontRenderContext frc = g2D.getFontRenderContext();
Font font = UIManager.getFont("Label.font");
Rectangle2D bounds = font.getStringBounds(text, frc);
g2D.drawString(text, -(int)((g2DHeight + bounds.getWidth()) / 2), 20);
g2D.setTransform(origTransform);
class Main {
private static void createAndShowGUI() {
// Menu bar
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Menu");
JMenuItem menuItem = new JMenuItem("Menu Item");
menu.add(menuItem);
menuBar.add(menu);
// Tabbed pane
JTabbedPane tabbedPane = new JTabbedPane();
JPanel panel = new MyPanel();
tabbedPane.add(panel);
JLabel label = new JLabel("Nothing interesting's going on here...");
tabbedPane.add(label);
// Frame
JFrame frame = new JFrame();
// TRICKY PART HERE =========================================
// [(Un)comment lines as necessary]
// Variant A: the panel only --------------------------------
//frame.add(panel);
// Variant B: menu bar + panel on a tabbed pane -------------
frame.setJMenuBar(menuBar);
frame.add(tabbedPane);
// ==========================================================
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}Thanks for any help.
Best regards,
vt
Edited by: -vt- on 23-Apr-2010 13:08You are ignoring the current transform on the Graphics, use the following instead of setTransform():
g2D.rotate(-Math.PI / 2.0, 0, 0); -
Error in JComboBox and JMenu with JDK 1.6
We have a Desktop application that uses JMenuBar, JMenu, and JMenuItem and JComboBox. As we use the application, is the disappearance of the menu items, ie, they are not painted and does not drop down.
We tested with jdk1.6.0 update 17.
We tested with jdk1.6.0 update 22.
We tried to force the paint component among other ways to make it work, but without success!
We would like to know if it's a bug in Swing because we know other applications that use implementations Desktop also the same problem occurs.
We look back!
Edited by: Rubens on May 13, 2012 10:16 PMWorks for me. The updates you tried are rather old too. But I would first suspect your code. Adding menu items fom the wrong thread for example.
-
JMenu, passing mnemonic/ keyevent
Hi
Im building a JMenu but as it has many items im using a function to make each JMenuItem. The function calls the JMenu constructor with the text and the image to be used. I want to pass the mnemonic but can't work out how to do it.
//example of function call
menu1.add(add("myText","myPic.gif"));
//what i need to send to function
menuItem.setMnemonic(KeyEvent.VK_T);also is it possible to do the same with accelerators, ie pass this info to the function
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, ActionEvent.ALT_MASK));thanksOkay, it's still not clear to me what you're trying it write, but is it a method like the following?
import java.awt.event.*;
import java.net.*;
import javax.swing.*;
public class Blank implements ActionListener {
static JMenuItem add(JMenu menu, ActionListener al, String text, int mnemonic, String keyStoke, String iconURL) {
JMenuItem item = new JMenuItem(text);
if (al != null)
item.addActionListener(al);
if (mnemonic != 0)
item.setMnemonic(mnemonic);
if (keyStoke != null)
item.setAccelerator(KeyStroke.getKeyStroke(keyStoke));
try {
if (iconURL != null)
item.setIcon(new ImageIcon(new URL(iconURL)));
} catch (MalformedURLException e) {
e.printStackTrace();
return menu.add(item);
public void actionPerformed(ActionEvent evt) {
System.out.println("your code here");
public static void main(String[] args) {
JMenuBar mb = new JMenuBar();
JMenu menu = new JMenu("menu");
add(menu, new Blank(), "blank", KeyEvent.VK_K, "control B", "http://forum.java.sun.com/im/ic_eye.gif");
add(menu, null, "zip", 0, null, null);
mb.add(menu);
final JFrame f = new JFrame("Blank");
f.setJMenuBar(mb);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
SwingUtilities.invokeLater(new Runnable(){
public void run() {
f.setLocationRelativeTo(null);
f.setVisible(true);
} -
JMenu causing image problems!
I have Installed a JMenu that has an Image directly below , but! When i open the menu, The Text Value of the menu Disappears and the image has "Gray-Space"where the menu drop down was opened.
Can anyone Help and tell me why this is happening and how to Solve?
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Setup");
JMenuItem numOver = new JMenuItem("Input: # of Over's");
JMenuItem numTarget = new JMenuItem("Input: Target");
public Scorebook()
menuBar.add(menu);
menu.add(numOver);
menu.add(numTarget);}Thanx for the pointer, wasnt sure on what i needed to add in code: heres the ClassLoader and ImageIcon
as for Setting Visability, i dont think i have set it i just tried menu.setVisable(true) but it didnt like it!
ClassLoader ldr = this.getClass().getClassLoader();
java.net.URL cbURL = ldr.getResource("cricketball.png");
ImageIcon cBall = new ImageIcon(cbURL);
JLabel cBallL = new JLabel(cBall);
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Setup");
JMenuItem numOver = new JMenuItem("Input: # of Over's");
JMenuItem numTarget = new JMenuItem("Input: Target");
public Scorebook()
menuBar.add(menu);
menu.add(numOver);
menu.add(numTarget);}
pnl.add(CBallL); -
Making a JButton react like a JMenu
Hi everybody,
I'm really not sure if this is possible; if it isn't, feel free to tell me. Anyway, I have a JMenuBar with multiple JMenus, interspersed with JButtons. The JButtons replace JMenus with no JMenuItems, so you can just click on them and have something come up. I've figured out how to make a JButton look like a JMenu, but the problem is that when scrolling over the JButton, it doesn't get the selected look of a JMenu (with the highlighting). I know this would be done by using mouseEntered and mouseExited in a MouseListener, so I don't need help there, but I'm getting tripped up on how to change the look of the button properly. I'd like it to change to the default of whatever system it's running on (Windows, Mac, Linux), so I can't use UIManager, I don't think.
I don't need help making a program work (because my buttons are already fine in the JMenuBar, even though they don't do what I want), just some advice, so if anyone would be willing, I'd appreciate it.
Thanks,
Jezzica85Here's my test code:
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class MenuTest {
public MenuTest() {
try {
JFrame frame = new JFrame();
frame.setSize( 200, 200 );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
JMenuBar bar = new JMenuBar();
JMenu menu1 = new JMenu( "one" );
JMenuItem item = new JMenuItem( "Blah" );
JMenuItem item2 = new JMenuItem( "Blah2" );
menu1.add( item );
menu1.add( item2 );
bar.add( menu1 );
JMenuItem button = new JMenuItem( "button" );
bar.add( button );
JMenu menu2 = new JMenu( "two" );
JMenuItem itemA = new JMenuItem( "Blah" );
JMenuItem item2A = new JMenuItem( "Blah2" );
menu2.add( itemA );
menu2.add( item2A );
bar.add( menu2 );
frame.add( bar, BorderLayout.NORTH );
frame.setVisible( true );
} catch( Exception e ) {
e.printStackTrace();
System.exit( -1 );
public static void main(String[] args) { new MenuTest(); }
}What happens to me in this is that the two JMenus are sized fine, but the JMenuItem extends as far as it can, so the second JMenu is against the far side of the JMenuBar.
Thanks,
Jezzica85 -
Can I add a JScrollPane in the JMenu
I want to add a JScrollPane to the JMenu. The JScrollPane contains a JList, so that when I click on the menu the JScrollPane shows and I can select a item from the list.
I tried for some time, but still cannot make the JScrollPane displayed yet in the menu.
Any one can help?Try this it worked, I not sure if this is what you want. a few ke things worth noticing, setPreferred size on the JPanel. That might be the reason it was not showing up, anyway here it is.
import javax.swing.*;
import java.awt.*;
import java.util.Vector;
public class temp extends JFrame{
public temp(){
super("Scroll Test");
Vector myVector = new Vector();
JPanel contentPane = new JPanel(new BorderLayout());
for(int j = 0; j < 40; j++)
myVector.add(new String(j + ""));
JList theList = new JList(myVector);
JScrollPane sp = new JScrollPane(theList);
JPanel p = new JPanel(new BorderLayout());
p.setPreferredSize(new Dimension(100, 100));
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Scroll");
p.add(sp, BorderLayout.CENTER);
menu.add(p);
menuBar.add(menu);
this.setJMenuBar(menuBar);
this.setContentPane(contentPane);
this.setSize(300, 300);
public static void main(String [] args){
JFrame j = new temp();
j.show();
Good luct write back and tell me if this is what you were looking for!
Late jason -
The problem is that for top JMenu object there is no way to turn arrow on. Here is simple example:
import javax.swing.*;
public class A extends JFrame
public A()
super("Test");
JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("menu1")
// public boolean isTopLevelMenu()
// return false;
JMenuItem item = new JMenuItem("subitem");
menu.add(item);
bar.add(menu);
setJMenuBar(bar);
public static void main(String args[])
A a = new A();
a.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
a.pack();
a.setVisible(true);
In this example, JMenu object is top level and is shown without arrow. If I overload the isTopLevelMenu then MenuSelectionManager doesn't work anymore and JMenu object doesn't show popup window anymore. How to overcome this? Probably somebody aware about "right" solution? Thanks in advance.Hi Vadik,
I wanted to do something similar recently, and noticed your post. After a bit of stuffing around creating UI (that didn't quite work!), I ended up using this simple work around:
import javax.swing.*;
public class A extends JFrame {
public A() {
super("Test");
JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("menu1");
menu.setIcon(UIManager.getIcon("Menu.arrowIcon"));
menu.setHorizontalTextPosition(JMenu.LEFT);
JMenuItem item = new JMenuItem("subitem");
menu.add(item);
bar.add(menu);
setJMenuBar(bar);
public static void main(String args[]) {
A a = new A();
a.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
a.pack();
a.setVisible(true);
}This might not be what you want, but it works for me!
-Muel
Maybe you are looking for
-
Hi folks, I updated my OS to XP, my weblogic console does't work now. In the left side of the console there should be a tree like control, but now nothing but a "x" on the left side. Can somebody please tell me how to solve this promblem? I did downl
-
Photos are gone from my iWeb page
Hello, I have iWeb 3.0.2(489) I hope I am in the correct place. When I first got iWeb, I hadn't figured out how to create a separate iWeb for each of the categories, so I have one page, with several titles on the top, and I can just click on each "ti
-
Smart directories don't update smart in dock
An half bug ? When I put my smart directory in the dock, it don't update. You can see it in the snapshot : my last file about Jeanne d'Arc don't appears. But sometimes it work well, i don't know why ? It's like window in file drag'n'drop that sometim
-
Why do I see a directory access message when trying to install iTunes?
iTunes won't install. I first got this error when trying to update to 9.2: "Error writing to file C:\Program Files\iTunes\iTunes.Resources\it.lproj\TVShowsIntro.nib\objects.xib. Verify that you have access to that directory." I then tried to uninstal
-
RME 4 - Inventory Collection Failure
I am getting the following RME inventory collection error on 4 devices. These 4 devices were recently added to the network and were all attached to a new radius server. I have tested AAA to the 4 switches and am confident that radius is working as