I have a JMenu A within a JMenuBar aligned to the right of the screen. Within this menu are several JMenuItems, along with another JMenu B. Since menu A is right aligned, I need menu B to open to the left. In order to do this I found the code
setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);.
The issue however, is that this messes with the text alignment of menu 2, which I would like to stay exactly like the other menu items.
I have also tried manually aligning menu 2 using SwngConstants.leftAlign, however this is too severe:
How can I make the menu expand to the left, while retaining the default text alignment? Thanks in advance! The code I used to produce the above images is seen below:
import java.awt.*;
import javax.swing.*;
public class Test{
public Test(){
JFrame frame = new JFrame();
JMenuBar menuBar = new JMenuBar();
JMenu menu1 = new JMenu("Menu 1");
JMenu menu2 = new JMenu("Menu 2");
JMenuItem menuitem1 = new JMenuItem("Menu Item 1");
JMenuItem menuitem2 = new JMenuItem("Menu Item 2");
JMenuItem menuitem3 = new JMenuItem("Menu Item 3");
JMenuItem menuitem4 = new JMenuItem("Menu Item 4");
menuBar.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
menu1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
menu2.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
menu2.setHorizontalAlignment(SwingConstants.LEFT);
menuBar.add(menu1);
menu1.add(menuitem1);
menu1.add(menuitem2);
menu1.add(menu2);
menu2.add(menuitem3);
menu2.add(menuitem4);
frame.setJMenuBar(menuBar);
frame.getContentPane().setBackground(Color.WHITE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(270,170));
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args){
try{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
UIManager.getLookAndFeelDefaults().put("Label.font", new Font("Arial", Font.PLAIN, 12));
UIManager.getLookAndFeelDefaults().put("Button.font", new Font("Arial", Font.PLAIN, 12));
UIManager.getLookAndFeelDefaults().put("ComboBox.font", new Font("Arial", Font.PLAIN, 12));
UIManager.getLookAndFeelDefaults().put("JTextField.font", new Font("Arial", Font.PLAIN, 12));
new Test();
} catch(Exception e){
JOptionPane.showConfirmDialog(null, e.getMessage());
}
}
}
UPDATE: If I remove the lines of code aligning the menus right to left and move the frame to the edge of the display screen, then the menus act as desired (i.e. the menu will not expand off the monitor). Perhaps there is a way to tell the menu not to expand off the JFrame rather than the monitor?
UPDATE: Thank you #StanislavL for the idea. Overriding menu 2 with the following code does the trick, it also gets rid of that unsightly overlap between the two menus. Note that menu 2 no longer needs ComponentOrientation.RIGHT_TO_LEFT.
JMenu menu2 = new JMenu("Menu 2"){
protected Point getPopupMenuOrigin(){
return new Point(-this.getPopupMenu().getPreferredSize().width, 0);
}
};
You can try to override
public ComponentOrientation getComponentOrientation()
method of JMenu to return your alignmnet
or JMenu has method you can override
protected Point getPopupMenuOrigin()
Related
I just started studying some java GUI techniques and I have created a small program which has a menu bar a menu as well as an item within that menu. Now what I want to do is to implement a file chooser so when the item in the menu is selected then the file chooser is executed. The problem is that the file chooser that I created is in another class. Is there any possible way to start my file chooser's class when the item in the menu is clicked?
Here is my code
public class menu {
public static void main(String[] args){
//to menu
JFrame frame = new JFrame("Menu");
frame.setVisible(true);
frame.setSize(600,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar bar = new JMenuBar();
frame.setJMenuBar(bar);
JMenu search = new JMenu("Browse");
bar.add(search);
final JMenuItem songstoplay = new JMenuItem("Browse Songs To Play");
search.add(songstoplay);
//to outline
final Container content = frame.getContentPane();
content.setLayout(new GridLayout(3, 1));
JLabel text = new JLabel("My first iteration", JLabel.CENTER);
text.setVerticalAlignment(JLabel.TOP);
text.setFont(new Font("Serif", Font.PLAIN, 30));
content.add(text);
JLabel text2 = new JLabel();
text2.setText("List of drives connected: C:/");
text2.setFont(new Font("Serif", Font.PLAIN, 20));
text2.setVerticalAlignment(JLabel.TOP);
content.add(text2);
}
}
If you want to use the JFileChooser, you have to add an eventlistener on your menuitem. Better you take a look at this: http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html
or the direct link to the code from the example above:
http://docs.oracle.com/javase/tutorial/uiswing/examples/components/FileChooserDemoProject/src/components/FileChooserDemo.java
Im trying to get it so that when i click on a menu option, the windows changes from the 'welcome text' to 4 buttons which the user can then click on. However, when i click on the simulation button, nothing happens.. the window doesnt change at all.. Ive summarized my code to the basic stuff by the way. anyone see anything i cant?
JFrame GUI = new JFrame("Graphical User Interface");
public gui()
{
JMenuBar menubar = new JMenuBar();
JMenu Simulation = new JMenu("Simulation");
theLabel = new JLabel("Welcome to the Main Menu. ",JLabel.CENTER);
GUI.add(theLabel);
menubar.add(Simulation);
Simulation.add(Simulationmenu);
Simulationmenu.addActionListener(this);
GUI.setJMenuBar(menubar);
GUI.setLocation(500,250);
GUI.setSize(300, 200);
GUI.setVisible(true);
}
public void actionPerformed(ActionEvent E){
if(E.getSource() == Simulationmenu){
// Buttons in the menu i want to output once clicked on 'simulation'
thePanel = new JPanel(new GridLayout(4,0));
Run = new JButton("Run");
Pause = new JButton("Pause");
Reset = new JButton("Reset");
DisplayMaps = new JButton("Display Maps?");
// Add the components to the panel:
thePanel.add("West", Run);
thePanel.add("Center", Pause);
thePanel.add("East", Reset);
thePanel.add("West", DisplayMaps);
// Add the panel to the contentPane of the frame:
GUI.add(thePanel);
// add this object as listener to the two buttons:
Run.addActionListener(this);
Seems your problem in next, you add a new panel(thePanel) to your JFrame(GUI) when it is showing, but in this case you must to call revalidate() method of JFrame(GUI).
Add GUI.revalidate() after GUI.add(thePanel);, it helps you.
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 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() );
I'm trying to modify a GUI. It is hosting a GLCanvas displaying JOGL content.
Here is the code to set it up:
private void setupWindow() {
this.frame = new JFrame(WINDOW_TITLE);
frame.setSize(width, height);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
menuBar.add(menu);
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(listener);
menu.add(exitItem);
frame.setJMenuBar(menuBar);
}
Currently, the canvas takes up the entire space in the window, aside from the menu bar. I'd like to make space for other controls in the window, like buttons and list boxes. How can I do it?
I tried inserting the following, but it didn't work:
private void setupWindow() {
this.frame = new JFrame(WINDOW_TITLE);
frame.setSize(width, height);
// ** inserted the following:
JPanel canvasPanel = new JPanel(new BorderLayout());
canvasPanel.add(canvas);
canvasPanel.setSize(30, 40);
canvasPanel.setVisible(true);
// **
frame.add(canvasPanel);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
menuBar.add(menu);
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(listener);
menu.add(exitItem);
frame.setJMenuBar(menuBar);
}
This doesn't modify the appearance of the window at all.
What should I be doing here? I'm not too familiar with Java GUIs.
Update: Changing the constructor's argument from BorderLayout to FlowLayout causes the GLCanvas to disappear.
Per Anon's answer, you really need to better understand the layout managers. Your question is too open ended.
In case this helps though:
JPanel canvasPanel = new JPanel(new BorderLayout());
frame.add(canvasPanel, BorderLayout.CENTER);
canvasPanel.add(canvas);
Box leftBtnsBox = Box.createVerticalBox();
frame.add(leftBtns, BorderLayout.WEST);
leftBtns.add(new JButton("Button 1"));
leftBtns.add(new JButton("Button 2"));
This code sets a BordeLayout explicitly, but I think the default layout manager for panels (and content panes) is BorderLayout. This code will put two buttons to the top left of the canvas panel arranged vertically. Because you are using these layout managers, your second code example's setSize had no effect.
I suggest checking out this guide to layout managers - it will give you enough info to see what you should try.