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;
}
}
Related
I want to have a layout like this:
The grey areas will be two different menus.
I managed to make the split panes, but I can't seem to add the menus, here's my code:
package View;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.plaf.basic.BasicSplitPaneUI;
public class TaskView extends JFrame{
JMenuBar menuBar;
JMenu addTask, refresh;
private int screenHeight,screenWidth;
public TaskView() {
setTitle("TASKS");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
Toolkit myScreen = Toolkit.getDefaultToolkit();
Dimension screenSize = myScreen.getScreenSize();
screenHeight = screenSize.height;
screenWidth = screenSize.width;
setSize(screenWidth/2,screenHeight/2);
System.out.println(screenWidth/2);
setLocation(screenWidth/4,screenHeight/4);
placeComponents(this.getContentPane());
}
private void placeComponents(Container contentPane) {
JPanel jsp1 = new JPanel();
JPanel jsp2 = new JPanel();
JLabel j1 = new JLabel("Area 1");
JLabel j2 = new JLabel("Area 2");
menuBar = new JMenuBar();
addTask = new JMenu("Add Task");
refresh = new JMenu("Refresh");
menuBar.add(addTask);
menuBar.add(refresh);
jsp1.add(menuBar);
jsp1.add(j1);
jsp2.add(j2);
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
true, jsp1, jsp2);
splitPane.setUI(new BasicSplitPaneUI());
splitPane.setOneTouchExpandable(false);
contentPane.add(splitPane);
splitPane.setEnabled(false);
setVisible(true);
splitPane.setDividerLocation(300);
}
}
Every time I try to add a menu it makes a mess in the left panel and it dosn't look at all like a menu, how can i add the menus without it looking like shit?
try this
public class TaskView extends JFrame {
public TaskView() throws HeadlessException {
createGUI();
}
private void createGUI() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setPreferredSize(new Dimension(600, 400));
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, createPanel(), createPanel());
splitPane.setResizeWeight(0.5);
add(splitPane, BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
}
private JPanel createPanel() {
JPanel panel = new JPanel(new BorderLayout());
JMenuItem menuItem1 = new JMenuItem("MenuItem 1");
JMenuItem menuItem2 = new JMenuItem("MenuItem 2");
JMenuItem menuItem3 = new JMenuItem("MenuItem 3");
JMenu menu = new JMenu("Main");
menu.add(menuItem1);
menu.addSeparator();
menu.add(menuItem2);
menu.add(menuItem3);
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
menuBar.add(new JMenu("View"));
panel.add(menuBar, BorderLayout.PAGE_START);
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new TaskView().setVisible(true));
}
}
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
Following is my code.
import java.awt.Dimension;
import 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;
public class MenuBarProblem {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(new Dimension(300, 400));
JMenu menu1 = new JMenu("First");
JMenuItem item = new JMenuItem("Add menu");
menu1.add(item);
final JMenuBar mb = new JMenuBar();
mb.add(menu1);
frame.setJMenuBar(mb);
item.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JMenu menu1 = new JMenu("First");
JMenuItem item = new JMenuItem("Add menu");
menu1.add(item);
mb.add(menu1);
System.out.println(mb.getMenuCount());
}
});
frame.setVisible(true);
}
}
What I want to do is to add menus to the menubar when the menu item1 is clicked. The line System.out.println(mb.getMenuCount()); prints that the menu items are being added. (It prints 2,3,4 when the menu item1 is clicked) but the menus don't show up in the menu bar.
What should I do so that the menu items that are dynamically added get shown on the menubar? I'm using Java 1.6.
After adding the extra menu in mb use:
mb.revalidate();
This causes the component to get replainted, after the newly added menu has been inserted into the component tree.
Try calling repaint after
frame.setVisible(true);
as
frame.repaint();
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();
}
});
}
}
I am working on a simple desktop application with java. There is a menu bar, when the user clicks on menu item 1 then the content will change to form A. When a user clicks on menu item 2 then the content will display form B.
How could i achieve this?
using the same window and just the content change.
A sample for you, I just did to refresh my swing knowledge..
import java.awt.BorderLayout;
import java.awt.Color;
import 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;
import javax.swing.JPanel;
public class FrmChange extends JFrame{
private JPanel panel1 = new JPanel();
private JPanel panel2 = new JPanel();
public FrmChange(){
setDefaultCloseOperation(EXIT_ON_CLOSE);
initMenu();
panel1.setBackground(Color.BLUE);
panel2.setBackground(Color.RED);
setLayout(new BorderLayout());
}
private class MenuAction implements ActionListener {
private JPanel panel;
private MenuAction(JPanel pnl) {
this.panel = pnl;
}
#Override
public void actionPerformed(ActionEvent e) {
changePanel(panel);
}
}
private void initMenu() {
JMenuBar menubar = new JMenuBar();
JMenu menu = new JMenu("Menu");
JMenuItem menuItem1 = new JMenuItem("Panel1");
JMenuItem menuItem2 = new JMenuItem("Panel2");
menubar.add(menu);
menu.add(menuItem1);
menu.add(menuItem2);
setJMenuBar(menubar);
menuItem1.addActionListener(new MenuAction(panel1));
menuItem2.addActionListener(new MenuAction(panel2));
}
private void changePanel(JPanel panel) {
getContentPane().removeAll();
getContentPane().add(panel, BorderLayout.CENTER);
getContentPane().doLayout();
update(getGraphics());
}
public static void main(String[] args) {
FrmChange frame = new FrmChange();
frame.setBounds(200, 200, 300, 200);
frame.setVisible(true);
}
}
You could use a CardLayout, or simply remove the displayed panel and add the one you want to display the the frame content pane.
You need to add an ActionListener to each menu item in order to trigger the appropriate change ech time a menu item is clicked.
This is really basic Swing functionality. You should read the Swing Tutorial.
frame.getContentPane().remove() or removeAll();
frame.getContentPane().add(allTheNewComponents);
frame.revalidate();
frame.repaint();