JInternalFrame is not show - java

I am new for Java. I need to have MDI in my project. When the user clicks ‘Open’ in menu bar, the internal frame is added and should be full screen on top.
I still cannot make it full screen on top when it is open. Also in my code, if I remove the following line from “AddNote” method, I cannot see the internal frame. In logic the JDesktop should add when the form is open.
JDesktopPane desktop = new JDesktopPane();
There is my code:
package MyPackage;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.*;
import java.io.*;
import java.awt.Dimension;
import java.awt.FlowLayout;
public class MainForm extends JFrame implements ActionListener {
private JMenuItem cascade = new JMenuItem("Cascade");
private int numInterFrame=0;
private JDesktopPane desktop=null;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run()
{
new MainForm();
}
});
}
public MainForm(){
super("Example");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// Name the JMenu & Add Items
JMenu menu = new JMenu("File");
menu.add(makeMenuItem("Open"));
menu.add(makeMenuItem("Save"));
menu.add(makeMenuItem("Quit"));
// Add JMenu bar
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
//menuBar.add(menuWindow);
setJMenuBar(menuBar);
this.setMinimumSize(new Dimension(400, 500));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
JDesktopPane desktop = new JDesktopPane();
this.add(desktop, BorderLayout.CENTER);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// Menu item actions
String command = e.getActionCommand();
if (command.equals("Quit")) {
System.exit(0);
} else if (command.equals("Open")) {
// Open menu item action
JFileChooser fileChooser = new JFileChooser();
int returnVal = fileChooser.showOpenDialog(MainForm.this);
if (returnVal == fileChooser.APPROVE_OPTION) {
numInterFrame=numInterFrame+1;
File file = fileChooser.getSelectedFile();
AddNote(numInterFrame);
// Load file
} else if (returnVal == JFileChooser.CANCEL_OPTION ) {
// Do something else
}
}
else if (command.equals("Save")) {
// Save menu item action
System.out.println("Save menu item clicked");
}
}
private JMenuItem makeMenuItem(String name) {
JMenuItem m = new JMenuItem(name);
m.addActionListener(this);
return m;
}
private void AddNote(int index){
JDesktopPane desktop = new JDesktopPane();
JInternalFrame internalFrame = new JInternalFrame("PDFAnnotation" + index, true, true, true, true);
internalFrame.setBounds(0, 0, 600, 100);
desktop.add(internalFrame);
PDFPanel p=new PDFPanel();
JPanel e =p.getJPanel();
internalFrame.add(e, BorderLayout.CENTER);
internalFrame.setVisible(true);
this.add(desktop, BorderLayout.CENTER);
/* Dimension size = desktop.getSize();
int w = size.width ;
int h = size.height ;
int x=0;
int y=0;
desktop.getDesktopManager().resizeFrame(internalFrame, x, y, w, h);*/
}
}

There are a number problems, which are compounded based on the fact that you are shadowing the main desktop variable...
You declare an instance field....
private JDesktopPane desktop = null;
But in your constructor, you declare it again...
JDesktopPane desktop = new JDesktopPane();
This means that the instance field remains null. Instead, in you constructor, you should be using the instance field, for example...
desktop = new JDesktopPane();
This means that in your AddNote method, you can get rid of the creation of yet another JDesktopPane...
//JDesktopPane desktop = new JDesktopPane();
JInternalFrame internalFrame = new JInternalFrame("PDFAnnotation" + index, true, true, true, true);
internalFrame.setBounds(0, 0, 600, 100);
desktop.add(internalFrame);
PDFPanel p = new PDFPanel();
JPanel e = p.getJPanel();
internalFrame.add(e, BorderLayout.CENTER);
internalFrame.setVisible(true);
//this.add(desktop, BorderLayout.CENTER);
Also, because you're using...
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
You won't need
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
You should also have a read of Code Conventions for the Java Programming Language

Related

How to get the currently selected Menu or MenuItem

How can I retrieve the currently selected menu or menu item when clicked on it and the subsequent path will be printed on console. In this code I have done the menus and sub menus up to 4 levels. And want to print the path of selected menus and submenus when clicked on. I am using swing concept for this program. Please help. Thanks in advance.
import java.awt.Component;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.MenuElement;
import javax.swing.MenuSelectionManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class Menu {
public static void main(final String args[]) {
JFrame frame = new JFrame("MenuSample Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
JMenu worldMenu = new JMenu("world");
menuBar.add(worldMenu);
JMenu indMenu = new JMenu("India");
worldMenu.add(indMenu);
/* creates menu */
JMenu odMenu = new JMenu("Odisha");
indMenu.add(odMenu);
JMenu delhiMenu = new JMenu("Delhi");
indMenu.add(delhiMenu);
JMenu upMenu = new JMenu("Uttar Pradesh");
indMenu.add(upMenu);
JMenu mpMenu = new JMenu("Madhya Pradesh");
indMenu.add(mpMenu);
JMenu ausMenu = new JMenu("Australia");
worldMenu.add(ausMenu);
JMenu AmericaMenu = new JMenu("America");
worldMenu.add(AmericaMenu);
/* creates submenu */
JMenu bbMenu = new JMenu("Bhubaneswar");
odMenu.add(bbMenu);
JMenu bmMenu = new JMenu("Berhampur");
odMenu.add(bmMenu);
/*creates sub sub menu */
JMenuItem rjMenuItem = new JMenuItem("Raj Mahal");
bbMenu.add(rjMenuItem);
JMenuItem abMenuItem = new JMenuItem("Acharya Bihar");
bbMenu.add(abMenuItem);
JMenuItem bnMenuItem = new JMenuItem("Bani Bihar");
bbMenu.add(bnMenuItem);
/* retrieving path */
MenuSelectionManager.defaultManager().addChangeListener(
new ChangeListener() {
public void stateChanged(ChangeEvent evt) {
MenuElement[] path = MenuSelectionManager.defaultManager()
.getSelectedPath();
//
int s=0;
for (int i = 0; i < path.length; i++) {
Component c = path[i].getComponent();
if (c instanceof JMenuItem) {
JMenuItem mi = (JMenuItem) c;
String label = mi.getText();
System.out.println("LEVEL----" + s);
System.out.println("you hv selected:"+label);
s++;
}
}
}
});
//
frame.setJMenuBar(menuBar);
frame.setSize(350, 250);
frame.setVisible(true);
}
}
How to get the currently selected
Menu - A parent JMenu cannot be selected. Why would you want to know
if the mouse is over it?
MenuItem - Embrace the Action interface
It is an all too common oversight to not use the Action interface. When developing with Swing make Action your friend, it will treat you well. You went down the wrong path with MenuSelectionManager.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
public class MenuExample {
private JFrame frame;
private JLabel choiceIndicator;
MenuExample create() {
frame = createFrame();
choiceIndicator = new JLabel();
frame.setJMenuBar(createMenuBar());
frame.getContentPane().add(createContent());
return this;
}
private Component createContent() {
JPanel panel = new JPanel();
panel.add(new JLabel("Last menu item choice:"));
panel.add(choiceIndicator);
return panel;
}
private JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
menuBar.add(createWorld());
return menuBar;
}
private JMenu createWorld() {
JMenu worldMenu = new JMenu("World");
worldMenu.add(createIndia());
worldMenu.add(new JMenu("Australia"));
worldMenu.add(new JMenu("America"));
return worldMenu;
}
private JMenu createIndia() {
JMenu india = new JMenu("India");
india.add(createOdisha());
india.add(new JMenu("Delhi"));
india.add(new JMenu("Uttar Pradesh"));
india.add(new JMenu("Madhya Pradesh"));
return india;
}
private JMenuItem createOdisha() {
JMenu menu = new JMenu("Odisha");
menu.add(createBhubaneswar());
menu.add(new JMenu("Berhampur"));
return menu;
}
private JMenuItem createBhubaneswar() {
JMenu menu = new JMenu("Bhubaneswar");
menu.add(choiceItem("Raj Mahal"));
menu.add(choiceItem("Acharya Bihar"));
menu.add(choiceItem("Bani Bihar"));
return menu;
}
private JMenuItem choiceItem(String text) {
return new JMenuItem(new Choice(text, choiceIndicator));
}
private JFrame createFrame() {
JFrame frame = new JFrame(getClass().getSimpleName());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
return frame;
}
void show() {
frame.setSize(350, 250);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MenuExample().create().show();
}
});
}
class Choice extends AbstractAction {
private final JLabel choiceIndicator;
public Choice(String text, JLabel choiceIndicator) {
this(text, null, null, null, choiceIndicator);
}
public Choice(String text, ImageIcon icon, String desc, Integer mnemonic, JLabel choiceIndicator) {
super(text, icon);
putValue(SHORT_DESCRIPTION, desc);
putValue(MNEMONIC_KEY, mnemonic);
this.choiceIndicator = choiceIndicator;
}
public void actionPerformed(ActionEvent e) {
choiceIndicator.setText(e.getActionCommand());
}
}
}

Set size on component in JPanel

I am new for Java. I have searched how to set the size of the JTextField and JButton, but I still cannot make it work. Hope someone tell me how to solve it. I declare the height and width, but the component seems doesn't take it. The JTextField and JButton with red & yellow background should be same height. Also the JTextField width is very long.
There is my code:
package MyPackage;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.*;
import java.io.*;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.*;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.ComponentOrientation;
import javax.swing.JTextField;
public class MainForm extends JFrame implements ActionListener {
private PDFNotesBean PDFNotesBean = null;
private JMenuItem cascade = new JMenuItem("Cascade");
private int numInterFrame=0;
private JDesktopPane desktop=null;
private ArrayList<File> fileList=new ArrayList<File>();
private static int categoryButtonWidth= 40;
private static int categoryTextFieldWidth=60;
private static int categoryHight=40;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run()
{
new MainForm();
}
});
}
public MainForm(){
super("Example");
//it is equal to this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// Name the JMenu & Add Items
JMenu menu = new JMenu("File");
menu.add(makeMenuItem("Open"));
menu.add(makeMenuItem("Save"));
menu.add(makeMenuItem("Quit"));
// Add JMenu bar
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
//menuBar.add(menuWindow);
setJMenuBar(menuBar);
this.setMinimumSize(new Dimension(400, 500));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
desktop = new JDesktopPane();
this.setLayout(new BorderLayout());
setCategoryPanel();
this.add(desktop, BorderLayout.CENTER);
setVisible(true);
}
private void setCategoryPanel(){
//set the color label category
JPanel panelCategory=new JPanel();
panelCategory.setLayout(new BoxLayout(panelCategory, BoxLayout.LINE_AXIS));
JButton btnCategory_1=new JButton("");
btnCategory_1.setPreferredSize(new Dimension ( categoryButtonWidth, categoryHight));
btnCategory_1.setBackground(Color.red);
btnCategory_1.addActionListener(this);
panelCategory.add(btnCategory_1);
JTextField txtCategory_1 = new JTextField();
txtCategory_1.setPreferredSize(new Dimension (categoryTextFieldWidth, categoryHight));
panelCategory.add(txtCategory_1);
JButton btnCategory_2=new JButton("");
btnCategory_2.setPreferredSize(new Dimension ( categoryButtonWidth, categoryHight));
btnCategory_2.setBackground(Color.YELLOW);
btnCategory_2.addActionListener(this);
panelCategory.add(btnCategory_2);
JTextField txtCategory_2 = new JTextField( );
txtCategory_1.setPreferredSize(new Dimension (categoryTextFieldWidth, categoryHight));
panelCategory.add(txtCategory_2);
this.add(panelCategory, BorderLayout.NORTH);
}
public void actionPerformed(ActionEvent e) {
// Menu item actions
String command = e.getActionCommand();
if (command.equals("Quit")) {
System.exit(0);
} else if (command.equals("Open")) {
// Open menu item action
JFileChooser fileChooser = new JFileChooser();
int returnVal = fileChooser.showOpenDialog(MainForm.this);
if (returnVal == fileChooser.APPROVE_OPTION) {
numInterFrame=numInterFrame+1;
File file = fileChooser.getSelectedFile();
fileList.add(file);
AddNote(file);
// Load file
} else if (returnVal == JFileChooser.CANCEL_OPTION ) {
// Do something else
}
}
else if (command.equals("Save")) {
// Save menu item action
System.out.println("Save menu item clicked");
}
}
private JMenuItem makeMenuItem(String name) {
JMenuItem m = new JMenuItem(name);
m.addActionListener(this);
return m;
}
private void AddNote(File file){
JInternalFrame internalFrame = new JInternalFrame("PDFAnnotation"
+ file.getName(), true, true, true, true);
internalFrame.setBounds(0, 0, 600, 100);
desktop.add(internalFrame);
PDFPanel p=new PDFPanel();
JPanel e =p.getJPanel(file);
internalFrame.add(e, BorderLayout.CENTER);
internalFrame.setVisible(true);
this.add(desktop, BorderLayout.CENTER);
//resize the internal frame as full screen
Dimension size = desktop.getSize();
int w = size.width ;
int h = size.height ;
int x=0;
int y=0;
desktop.getDesktopManager().resizeFrame(internalFrame, x, y, w, h);
}
}
Don't use the setPreferredSize() method.
All Swing components will have a preferred size.
For a JTextField you can use:
JTextField textField = new JTextField(5);
to indication how many characters you want to display at one time.
For the JButton, the width is determined by the text you add to the button.
When you use a BoxLayout, the width of the components is increased to fill the available space.
Just use a FlowLayout (which is the default for a JPanel) and the components will be displayed at their preferred sizes.

How to start 2nd Jframe by click menu item in 1st java windows application (Jframe)

I am using eclipse 4.2 with Java.
I have 2 java program : AppWin.java Form1.java
AppWin.java is gui windows application with menu/menu item1.
Form1.java is a Gui Jframe
I like to call Form1.java from AppWin.java by click the menu/menu item1.
When close Form1.java, it is back to AppWin.java.
This is something like MDIFORM. I really cannot find answer.
Please help , if you know eclipse menu.
Thanks
package top;
import java.awt.EventQueue;
public class AppWin {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AppWin window = new AppWin();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
...
With your help, I made a big step.
Thanks to all of you!
Next is my final demo, in windows 7, eclipse 4.2, java Gui
Hope it is helpful to others.
There are 3 parts : AppWin, Form1, Form2. AppWin is top main which call Form1 and Form2 with menu/item.
//1
package top;
import java.awt.EventQueue;
public class AppWin {
private JFrame frame;
private Form1 form1;
private Form2 form2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AppWin window = new AppWin();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public AppWin() {
initialize();
form1 = new Form1();
form2 = new Form2();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu mnNewMenu = new JMenu("Menu1");
menuBar.add(mnNewMenu);
JMenuItem mntmNewMenuItem = new JMenuItem("menu item1");
mntmNewMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
form1.setVisible(true);
}
});
mnNewMenu.add(mntmNewMenuItem);
JMenuItem mntmNewMenuItem_1 = new JMenuItem("menu item2");
mntmNewMenuItem_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
form2.setVisible(true);
}
});
mnNewMenu.add(mntmNewMenuItem_1);
JMenu mnNewMenu_1 = new JMenu("Menu2");
menuBar.add(mnNewMenu_1);
JMenuItem mntmMenuItem = new JMenuItem("Menu item3");
mnNewMenu_1.add(mntmMenuItem);
}
}
//2
package top;
import java.awt.BorderLayout;
public class Form1 extends JFrame {
private JPanel contentPane;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Form1 frame = new Form1();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Form1() {
// setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JLabel lblNewLabel = new JLabel("this Form1");
contentPane.add(lblNewLabel, BorderLayout.WEST);
textField = new JTextField();
contentPane.add(textField, BorderLayout.CENTER);
textField.setColumns(10);
JButton btnNewButton = new JButton("New button");
contentPane.add(btnNewButton, BorderLayout.EAST);
}
}
//3
package top;
import java.awt.BorderLayout;
public class Form2 extends JDialog {
private final JPanel contentPanel = new JPanel();
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
Form2 dialog = new Form2();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public Form2() {
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setLayout(new FlowLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
{
JLabel lblThisForm = new JLabel("This Form2");
contentPanel.add(lblThisForm);
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
}
}
Thanks again
You better use JDesktopPane + JInternalFrame for that purpose instead. Here's a quick sample.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class JInternalFrameSample {
private JPanel pnlMain;
private JDesktopPane desk;
public JInternalFrameSample(){
pnlMain = new JPanel(new BorderLayout()){
#Override public Dimension getPreferredSize(){
return new Dimension(600,600);
}
};
desk = new JDesktopPane();
JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("Internal Frame");
JMenuItem item = new JMenuItem();
item.setAction(new AbstractAction("Create New") {
#Override
public void actionPerformed(ActionEvent arg0) {
JInternalFrame iFrame = new JInternalFrame("Created from Menu");
iFrame.setResizable(true);
iFrame.setClosable(true);
iFrame.setIconifiable(true);
iFrame.setSize(new Dimension(300, 300));
iFrame.setLocation(0, 0);
//iFrame.getContentPane().setLayout(new BorderLayout());
//iFrame.getContentPane().add( new YourCustomUI().getUI() );
iFrame.setVisible(true);
desk.add(iFrame);
}
});
menu.add(item);
bar.add(menu);
pnlMain.add(bar, BorderLayout.PAGE_START);
pnlMain.add(desk, BorderLayout.CENTER);
}
private JPanel getUI(){
return pnlMain;
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("Demo");
frame.getContentPane().setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new JInternalFrameSample().getUI());
frame.pack();
frame.setVisible(true);
}
});
}
}
See also : How to Use Internal Frames
If you do not like the JDesktopPane and JInternalFrame solution, just use your AppWin JFrame as is, and open modal JDialogs for the rest of the forms, instead of JFrames. Modal dialogs can float around the desktop and do not allow you to click your AppWin, until they are closed.
It is usually better to use just one main JFrame for an application, unless you have some wizard application that moves progressively from one JFrame to the other and back. Even with a wizard app, you can stick with one JFrame and update progressively just the ContentPane with JPanels.
Here is the AppWin JFrame:
public class AppWin extends javax.swing.JFrame {
private Form1 form1;
private Form1 form2;
...
private FormN formN;
public AppWin() {
initComponents();
form1 = new Form1(this, true);
form2 = new Form2(this, true);
...
formN = new FormN(this, true);
}
...
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
form1.setVisible(true);
}
And here is your Form1 JDialog:
public class Form1 extends javax.swing.JDialog {
public Form1(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
}
...
private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {
setVisible(false);
}
I only use NetBeans for GUI building because that's more convenient. In the following I can tell you how to achieve what you want to do but I can't tell you how to layout all the components because NetBeans do that for me.
So basically you want to 1. show secondFrame by clicking a menuitem and then close mainFrame, 2. show mainFrame after closing secondFrame, yes? Then, the key is to pass the reference of mainFrame to secondFrame, and write your own method of formClosing event of secondFrame. Something like this:
In the menuItem method in your mainframe:
private void menuItemActionPerformed(java.awt.event.ActionEvent evt) {
//pass 'this' frame's (mainFrame) reference to the secondFrame
SecondFrame newFrame = new SecondFrame(this);
newFrame.setVisible(true); //show the secondFrame
this.setVisible(false); //hide this frame (mainFrame)
}
In your secondFrame:
public class SecondFrame extends javax.swing.JFrame {
private MainFrame mainFrame;
//define your own constructor that can use mainFrame's reference
public SecondFrame(MainFrame mainFrame) {
initComponents();
this.mainFrame = mainFrame;
}
private void initComponents(){
//bind your own event for closing second frame
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
/***********your stuff***************/
}
//show mainFrame when closing this frame and then dispose this frame
private void formWindowClosing(java.awt.event.WindowEvent evt) {
mainFrame.setVisible(true);
this.dispose();
}
}
The codes above is for disposing the secondFrame when closing it. If you just want to hide the secondFrame when closing for future use, then the codes will be slightly different. Let me know what you up to.
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
form1.setVisible(true);
dispose();
}

Drawing multiple shapes depending on user Java Swing

I am trying to implement a menu based graph - wherein i will represent a vertex by a circle and each circle will have an index provided by the user.The user has to go to File menu and click on Addvertex to create a new node with an index.The Problem though is - The circle is drawn only once - any subsequent clicks to addVertex does not result in drawing of a circle -Can't understand Why...
Here is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.*;
import java.util.*;
public class FileChoose extends JFrame {
public FileChoose() {
JMenuBar l=new JMenuBar();
JMenu file=new JMenu("File");
JMenuItem open=new JMenuItem("Addvertex");
open.addActionListener(new Drawer());
JMenuItem close=new JMenuItem("Exit");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JMenu tools=new JMenu("Tools");
file.add(open);
file.add(close);
this.setJMenuBar(l);
l.add(tools);
l.add(file);
this.setSize(new Dimension(200, 200));
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
}
void HelloHere(String p) {
Draw d = new Draw(p);
this.add(d);
setExtendedState(MAXIMIZED_BOTH);
}
class Drawer extends JFrame implements ActionListener {
Integer index;
public void actionPerformed(ActionEvent e) {
JPanel pn = new JPanel();
JTextField jt = new JTextField(5);
JTextField jt1 = new JTextField(5);
pn.add(jt);
pn.add(jt1);
int result=JOptionPane.showConfirmDialog(null, pn, "Enter the values", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
index = Integer.parseInt(jt.getText());
System.out.println(jt1.getText());
}
this.setVisible(true);
this.setSize(500, 500);
this.setLocationRelativeTo(null);
HelloHere(index.toString());
}
}
public static void main(String [] args) {
FileChoose f = new FileChoose();
f.setVisible(true);
}
}
class Draw extends JPanel {
String inp;
public Draw(String gn) {
inp = gn;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Random r = new Random();
int x = r.nextInt(100);
g2.drawOval(x, x * 2, 100, 100);
g2.drawString(inp, x + (x / 2), x + (x / 2));
}
}
Some pointers:
Use EDT for creation and manipulation of Swing Components.
Dont extend JFrame class unnecessarily.
Use anonymous Listeners where possible/allowed
Make sure JFrame#setVisible(..) is the last call on JFrame instance specifically pointing here:
this.setVisible(true);
this.setSize(500, 500);
this.setLocationRelativeTo(null);
HelloHere(index.toString());
Call pack() on JFrame instance rather than setSize(..)
Do not use multiple JFrames see: The Use of Multiple JFrames: Good or Bad Practice?
The problem you are having is here:
Draw d = new Draw(p);
this.add(d);
You are creating a new instance of Draw JPanel each time and then overwriting the last JPanel added with the new one (this is default the behavior of BorderLayout). To solve this read below 2 points:
Call revalidate() and repaint() on instance after adding components to show newly added components.
Use an appropriate LayoutManager
As I am not sure of you expected results I have done as much fixing of the code as I could hope it helps:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
public class FileChoose {
JFrame frame;
public FileChoose() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar l = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem open = new JMenuItem("Addvertex");
open.addActionListener(new ActionListener() {
Integer index;
#Override
public void actionPerformed(ActionEvent e) {
JPanel pn = new JPanel();
JTextField jt = new JTextField(5);
JTextField jt1 = new JTextField(5);
pn.add(jt);
pn.add(jt1);
int result = JOptionPane.showConfirmDialog(null, pn, "Enter the values", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
index = Integer.parseInt(jt.getText());
System.out.println(jt1.getText());
}
HelloHere(index.toString());
}
});
JMenuItem close = new JMenuItem("Exit");
close.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JMenu tools = new JMenu("Tools");
file.add(open);
file.add(close);
frame.setJMenuBar(l);
l.add(tools);
l.add(file);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
void HelloHere(String p) {
Draw d = new Draw(p);
frame.add(d);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.revalidate();
frame.repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
FileChoose f = new FileChoose();
}
});
}
}
class Draw extends JPanel {
String inp;
public Draw(String gn) {
inp = gn;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Random r = new Random();
int x = r.nextInt(100);
g2.drawOval(x, x * 2, 100, 100);
g2.drawString(inp, x + (x / 2), x + (x / 2));
}
}
UPDATE:
Declare this globally in your Draw class: Random r=new Random(); as if you iniate a new Random instance each time you call paintComponent() the distributions will not be significant/random enough
Every time the user creates a new node you create a new JPanel that is added to the JFrame of your application. In the absence of a specific layout it uses a BorderLayout. BorderLayout does not allow for more than one component to be added at each location. Your other calls to add are probably ignored.

Create menu on button click in Java

For a project we want to create a button which will make a tiny menu when it is clicked (the way it works is similar to back button's drop-down menu in Firefox although the way to activate is a simple left click). Only real constraint is that it has to be in Java (preferably swing if possible). So, any ideas, examples, codes on how to do it?
Use a JPopupMenu. E.G.
PopUpMenuDemo.java
import java.awt.event.*;
import javax.swing.*;
class PopUpMenuDemo {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
final JButton b = new JButton("Pop Up");
final JPopupMenu menu = new JPopupMenu("Menu");
menu.add("A");
menu.add("B");
menu.add("C");
b.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
menu.show(b, b.getWidth()/2, b.getHeight()/2);
}
} );
JOptionPane.showMessageDialog(null,b);
}
};
SwingUtilities.invokeLater(r);
}
}
Screenshot
I would probably do it like this:
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnClickMe = new JButton("Click me");
btnClickMe.setBounds(10, 30, 89, 23);
frame.getContentPane().add(btnClickMe);
final JPopupMenu menu = new JPopupMenu();
JMenuItem item1 = new JMenuItem("Item1");
JMenuItem item2 = new JMenuItem("Item2");
JMenuItem item3 = new JMenuItem("Item3");
menu.add(item1);
menu.add(item2);
menu.add(item3);
btnClickMe.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e){
if ( e.getButton() == 1 ){ // 1-left, 2-middle, 3-right button
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
This is the code for menuButton, it looks like a button, and when you click on it a menu appears. You can customize it by adding the image icon to the menu and by methods:
setFocusable(false);
setBorderPainted(false);
setOpaque(false);
If you want to get it like FireFox then set the icon for the menu and call the above methods, and then set the rollover icon, selected icon & rollover selected icon.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class menuButton extends JFrame
{
JMenuBar fileMenuBar,editMenuBar;
JMenu fileMenu,editMenu;
JMenuItem newFile,open,save,saveas,exit;
JMenuItem cut,copy,paste,undo,redo;
public menuButton()
{
setTitle("menu Button");
setSize(500,500);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
fileMenuBar=new JMenuBar();
editMenuBar=new JMenuBar();
fileMenu=new JMenu("File");
editMenu=new JMenu("Edit");
newFile=new JMenuItem("New");
newFile.setAccelerator(KeyStroke.getKeyStroke('N',InputEvent.CTRL_MASK));
open=new JMenuItem("Open");
open.setAccelerator(KeyStroke.getKeyStroke('O',InputEvent.CTRL_MASK));
save=new JMenuItem("Save");
save.setAccelerator(KeyStroke.getKeyStroke('S',InputEvent.CTRL_MASK));
saveas=new JMenuItem("Save As");
saveas.setAccelerator(KeyStroke.getKeyStroke('A',InputEvent.CTRL_MASK));
exit=new JMenuItem("Exit");
exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4,InputEvent.ALT_MASK));
cut=new JMenuItem("Cut");
cut.setAccelerator(KeyStroke.getKeyStroke('X',InputEvent.CTRL_MASK));
copy=new JMenuItem("Copy");
copy.setAccelerator(KeyStroke.getKeyStroke('C',InputEvent.CTRL_MASK));
paste=new JMenuItem("Paste");
paste.setAccelerator(KeyStroke.getKeyStroke('V',InputEvent.CTRL_MASK));
undo=new JMenuItem("Undo");
undo.setAccelerator(KeyStroke.getKeyStroke('Z',InputEvent.CTRL_MASK));
redo=new JMenuItem("Redo");
redo.setAccelerator(KeyStroke.getKeyStroke('R',InputEvent.CTRL_MASK));
editMenu.add(cut);
editMenu.add(copy);
editMenu.add(paste);
editMenu.addSeparator();
editMenu.add(undo);
editMenu.add(redo);
fileMenu.add(newFile);
fileMenu.add(open);
fileMenu.add(save);
fileMenu.add(saveas);
fileMenu.add(exit);
fileMenuBar.add(fileMenu);
editMenuBar.add(editMenu);
add(fileMenuBar);
add(editMenuBar);
}
public static void main(String args[])
{
new menuButton();
}
}
see this it may be help you
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
public class GUI implements ActionListener, MouseListener, MouseMotionListener, KeyListener {
private final BufferedImage offscreenImage; // double buffered image
private final BufferedImage onscreenImage; // double buffered image
private final Graphics2D offscreen;
private final Graphics2D onscreen;
private JFrame frame; // the top-level component
private JPanel center = new JPanel(); // center panel
// create a GUI with a menu, some buttons, and a drawing window of size width-by-height
public GUI(int width, int height) {
offscreenImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
onscreenImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
offscreen = (Graphics2D) offscreenImage.getGraphics();
onscreen = (Graphics2D) onscreenImage.getGraphics();
// the drawing panel
ImageIcon icon = new ImageIcon(onscreenImage);
JLabel draw = new JLabel(icon);
draw.addMouseListener(this);
draw.addMouseMotionListener(this);
// label cannot get keyboard focus
center.add(draw);
center.addKeyListener(this);
// west panel of buttons
JPanel west = new JPanel();
west.setLayout(new BoxLayout(west, BoxLayout.PAGE_AXIS));
JButton button1 = new JButton("button 1");
JButton button2 = new JButton("button 2");
JButton button3 = new JButton("button 3");
JButton button4 = new JButton("button 4");
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);
button1.setToolTipText("Click me");
west.add(button1);
west.add(button2);
west.add(button3);
west.add(button4);
// menu
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
menuBar.add(menu);
JMenuItem menuSave = new JMenuItem(" Save... ");
menuSave.addActionListener(this);
menuSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
menu.add(menuSave);
// setup the frame and add components
frame = new JFrame();
frame.setJMenuBar(menuBar);
frame.add(west, BorderLayout.WEST);
frame.add(center, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.pack();
// give the focus to the center panel
center.requestFocusInWindow();
frame.setVisible(true);
}
// draw picture (gif, jpg, or png) centered on (x, y)
public void picture(int x, int y, String filename) {
ImageIcon icon = new ImageIcon(filename);
Image image = icon.getImage();
offscreen.drawImage(image, x, y, null);
show();
}
// display the drawing canvas on the screen
public void show() {
onscreen.drawImage(offscreenImage, 0, 0, null);
frame.repaint();
}
/*************************************************************************
* Event callbacks
*************************************************************************/
// for buttons and menus
public void actionPerformed(ActionEvent e) {
Object cmd = e.getActionCommand();
if (cmd.equals(" Save... ")) System.out.println("File -> Save");
else if (cmd.equals("button 1")) System.out.println("Button 1 pressed");
else if (cmd.equals("button 2")) System.out.println("Button 2 pressed");
else if (cmd.equals("button 3")) System.out.println("Button 3 pressed");
else if (cmd.equals("button 4")) System.out.println("Button 4 pressed");
else System.out.println("Unknown action");
// don't hog the keyboard focus
center.requestFocusInWindow();
}
// for the mouse
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
System.out.println("Mouse pressed at " + x + ", " + y);
offscreen.setColor(Color.BLUE);
offscreen.fillOval(x-3, y-3, 6, 6);
show();
}
public void mouseClicked (MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
public void mouseEntered (MouseEvent e) { }
public void mouseExited (MouseEvent e) { }
public void mouseDragged (MouseEvent e) { }
public void mouseMoved (MouseEvent e) { }
// for the keyboard
public void keyPressed (KeyEvent e) { }
public void keyReleased(KeyEvent e) { }
public void keyTyped(KeyEvent e) {
System.out.println("Key = '" + e.getKeyChar() + "'");
}
// test client
public static void main(String[] args) {
GUI gui = new GUI(800, 471);
gui.picture(0, 0, "map.png");
gui.show();
}
}
If you like lesser code lines in your code try below code:
Inside your buttons actionPerformed:
private void yourButtonActionPerformed(java.awt.event.ActionEvent evt) {
final JPopupMenu yourMenu = new JPopupMenu("Settings");
menu.add("Name");
menu.add("Id");
menu.add(new Button()); // can even add buttons and other components as well.
menu.show(yourButton, yourButton.getWidth()/2, yourButton.getHeight()/2);
}

Categories