JMenuItem doesn't execute action - java

I've looked through the swing tutorials and i do not see what i'm doing wrong. Why is nothing happening when i click on the jmenuitem?
my first class:
import javax.swing.*;
public class WordProcess{
/*TODO: make program end on close
*/
public static void main(String[] args) {
MainFrame frame = new MainFrame("Word Processor", 10000, 10000);
}
}
second class:
import javax.swing.*;
public class MainFrame extends JFrame {
JMenuBar menubar = new JMenuBar();
public MainFrame(String name, int x, int y) {
setTitle(name);
setSize(x, y);
setVisible(true);
setJMenuBar(menubar);
//creates file menu and adds to menubar
//TODO populate with JMenuItems
JMenu filemenu = new JMenu("file");
filemenu.setVisible(true);
menubar.add(filemenu);
buttonnew buttonnew = new buttonnew("new");
buttonnew.setVisible(true);
filemenu.add(buttonnew);
}
}
and third class:
import javax.swing.*;
import java.awt.event.*;
public class buttonnew extends JMenuItem implements ActionListener{
buttonnew(String s) {
super();
super.setText(s);
addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent ae) {
JFrame newframe = new JFrame("sup");
}
}

When the button is pressed, it will create an empty, invisible JFrame. You won't see it, since you have not called setVisible() on it, and it's tiny, as it has no contents. Otherwise, the code is fine.

Related

Same menu opened in two different JFrames works only on the last one

I'm trying to write a simple Paint application in which the user will be able to open new JFrames (in new Threads) with Drawing Panels, and each of those frames will have a JMenuBar on top, however, only the last open frame has a functional menu bar, all the remaining (open) frames show menu but the menu doesn't work (nothing happens when I click). Does anyone know how to fix this?
I've simplified the code to leave only the sections regarding JMenuBar.
The code consists of the following classes:
Main.java
package sample;
public class Main {
Main() {
MainFrameThread.getMainFrameThread().run();
}//end of Main()
public static void main(String[] args) {
new Main();
}
}//end of Main class
TopMenu.java
package sample;
import javax.swing.*;
public class TopMenu extends JMenuBar {
private JMenu menu_File;
private static JMenuItem menu_New;
public static JMenuItem getMenu_New() {
return menu_New;
}
public TopMenu() {
menu_File = new JMenu("File");
menu_New = new JMenuItem("New");
this.add(menu_File);
menu_File.add(menu_New);
}//end of TopMenu()
}//end of TopMenu extends JMenuBar
MainFrameThread.java
package sample;
public class MainFrameThread extends Thread {
private static MainFrameThread mainFrameThread = new MainFrameThread();
public static MainFrameThread getMainFrameThread() {
return mainFrameThread;
}
public MainFrameThread() {}
#Override
public void run() {
MainFrame mainFrame = new MainFrame();
}//end of public void run()
}//end of public class FrameSizeDialogThread
ActionController.java
package sample;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ActionController {
private static ActionController actionController = new ActionController();
private ListenForMenu listenForMenu = new ListenForMenu();
public static ActionController getActionController() {
return actionController;
}
public ActionController() {}
public void clickOnMenu(TopMenu topMenu) {
TopMenu.getMenu_New().addActionListener(listenForMenu);
}
//listener for menu
public class ListenForMenu implements ActionListener {
public void actionPerformed(ActionEvent ev) {
if(ev.getSource() == TopMenu.getMenu_New()) {
MainFrame newMainFrame = new MainFrame();
}//end of if(ev.getSource() == TopMenu.getMenu_New())
}//end of public void actionPerformed(ActionEvent ev)
}//end of public class ListenForMenu
}//end of ActionController class
and MainFrame.java
package sample;
import javax.swing.*;
import java.awt.*;
public class MainFrame extends JFrame {
public MainFrame() {
JFrame frame = new JFrame("Paint Application");
//creating menu
TopMenu topMenu = new TopMenu();
ActionController.getActionController().clickOnMenu(topMenu);
frame.setJMenuBar(topMenu);
//frame properties
frame.setSize(800, 600);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}//end of public MainFrame()
}//end of public class MainFrame
I'm stuck, nothing works, regardless where I initialise the MainFrame.java. Does anyone see the mistake???
however, only the last open frame has a functional menu bar
Swing components can't be shared. A Swing component can only have a single parent. So for every child window you will need to create a new JMenuBar and JMenu and JMenuItem.
However, the Action used by the JMenuItem can be shared.
private static JMenuItem menu_New;
public static JMenuItem getMenu_New() {
return menu_New;
}
None of the variable or methods related to the menus should be static. Again, you need to create a unique instance of each.

JDialog and its owner

I'm trying to use a few JDialogs inside my form JPanel to notify the user of incorrect data and form submission.
I'm just a bit confused with the JDialog constructor. I'd want to link the dialog to the panel (only because that's where it's created), but obviously the only owner parameters that are allowed are top level Frames (which I don't think I can access from the JPanel), or a Dialog (which I can't see helping me).
I could pass a reference for the Frame down to the JPanel, but isn't that a bit strange design wise? Or am I misunderstanding the class, or just more generally where the JDialog should be instantiated?
Hope I've made myself clear, I can make a sscce if it helps. Thanks.
the only owner parameters that are allowed are top level Frames (which I don't think I can access from the JPanel
You can access the parent frame of the panel by using:
Window window = SwingUtilities.windowForComponent( yourPanelHere );
Then just use the window as the owner of the dialog.
JComponent.getTopLevelAncestor gives you the owner of the JPanel:
Returns the top-level ancestor of this component (either the
containing Window or Applet), or null if this component has not been
added to any container.
You can try it:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class DialogTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
EventQueue.invokeLater(new Runnable() {
public void run() {
DialogFrame frame = new DialogFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
/**
* Frame contains menu. When we choose menu "File-> About" JDialog will be shown
*/
class DialogFrame extends JFrame {
public DialogFrame() {
setTitle("DialogTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// Menu
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
// Add About & Exit.
// Choose About - > About
JMenuItem aboutItem = new JMenuItem("About");
aboutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (dialog == null) //if not
{
dialog = new AboutDialog(DialogFrame.this);
}
dialog.setVisible(true); // to show dialog
}
});
fileMenu.add(aboutItem);
// When Exit
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
fileMenu.add(exitItem);
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
private AboutDialog dialog;
}
/*
* Modal dialog waits on click
*/
class AboutDialog extends JDialog {
public AboutDialog(JFrame owner) {
super(owner, "About DialogTest", true);
// Mark with HTML centration
add(new JLabel(
"<html><h1><i>Все о Java</i></h1><hr>"
+ "Something about java and JDialog</html>"),
BorderLayout.CENTER);
// When push "ok" dialog window will be closed
JButton ok = new JButton("ok");
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
setVisible(false);
}
});
// Button ОК down of panel
JPanel panel = new JPanel();
panel.add(ok);
add(panel, BorderLayout.SOUTH);
setSize(260, 160);
}
}

Two frames in different classes, how to use actionListener

I probably have a really simple problem. I want to create two frames - mainfr (in the class called Pag) and dscrpt (in a class called Apras). I managed to create the first frame (mainfr) and the second frame (dscrpt) using button skaiciav from the frame mainfr. When question is how to come back to the first frame using the button griz located in frame dscrp?
package grap;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Pag implements ActionListener {
JFrame mainfr;
JFrame apras;
JLabel psl_apras;
JLabel galim_veiksm;
JLabel paspaud;
public Pag() {
//Create JFrame container
mainfr = new JFrame("Turinys");
//Choosing layout type
mainfr.setLayout(new FlowLayout());
//window resolution
mainfr.setSize(500, 300);
//Program terminates on close
mainfr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Label's
psl_apras = new JLabel("Mokomoji programa");
galim_veiksm = new JLabel("Galimi veiksmai");
//adding them to main frame
mainfr.add(psl_apras);
mainfr.add(galim_veiksm);
//Button
JButton skaiciav = new JButton("Description");
//action listener
skaiciav.addActionListener(this);
//adding button to frame
mainfr.add(skaiciav);
//another label
paspaud = new JLabel("Press button");
//adding label to frame
mainfr.add(paspaud);
//making frame visible
mainfr.setVisible(true);
}
//action listener method
public void actionPerformed(ActionEvent a) {
if(a.getActionCommand().equals("Description"))
{
Apras.suk();
mainfr.setVisible(false);
}
//Started to get confused here
/*if(a.getActionCommand().equals("back")){
mainfr.setVisible(true);
apras.setVisible(false);
dscrp.dispose();
*/
}
public static void main (String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Pag();
}
});
}
}
Second class
package grap;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Apras {
static JFrame dscrp;
static void suk() {
dscrp = new JFrame("Description");
dscrp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame2.setLocationByPlatform(true);
dscrp.setBackground(Color.WHITE);
JButton griz = new JButton("back");
//griz.addActionListener();
dscrp.add(griz);
dscrp.setSize(500, 300);
dscrp.setVisible(true);
}
}

Java -- How to create a moveable menu [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Does anyone have any example code to make a draggable menu?
I am new to Java and I am trying to find a way to make a menu that is draggable with the mouse. Like a lot of programs have. You can drag the top menu bar around the screen so that you can drop it in other locations. I think that Java can do this as well because I have seen some applications that I think were written in Java do this very same thing.
Question: How do I create a draggable menu in a JFrame in Java?
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;
public class MyExample extends JFrame {
public MyExample() {
initUI();
}
public final void initUI() {
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
file.setMnemonic(KeyEvent.VK_F);
JMenuItem eMenuItem = new JMenuItem("Exit");
eMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0); //exit the system
}
});
file.add(eMenuItem);
menubar.add(file);
setJMenuBar(menubar);
setTitle("My Menu");
setSize(300, 100);
setLocationRelativeTo(); //I tried draggable
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
MyExample e = new MyExample();
e.setVisible(true);
}
}
I want to be able to drag the menu from the top of the JFrame to another location out of the window and leave it there. I have used Toolbar and that worked good but I was trying to see if this can be done with a menu. If you look at any software application the usually is a grabable area right next tot he File location. This you can click and drag around the area.
ImageIcon icon = new ImageIcon(getClass().getResource("10cd.jpg"));
JMenu file1 = new JMenu("File");
file1.setMnemonic(KeyEvent.VK_F);
JMenu file2 = new JMenu("Open");
file2.setMnemonic(KeyEvent.VK_F);
JMenu file3 = new JMenu("A");
file3.setMnemonic(KeyEvent.VK_F);
JMenu file4 = new JMenu("B");
file4.setMnemonic(KeyEvent.VK_F);
JMenu file5 = new JMenu("C");
file5.setMnemonic(KeyEvent.VK_F);
JMenu file6 = new JMenu("D");
file6.setMnemonic(KeyEvent.VK_F);
JMenuItem eMenuItem1a = new JMenuItem("File 1"/*, icon*///);
/*eMenuItem1a.setMnemonic(KeyEvent.VK_E);
eMenuItem1a.setToolTipText("Exit application");
JMenuItem eMenuItem1b = new JMenuItem("File 2"/*, icon*///);
/* eMenuItem1b.setMnemonic(KeyEvent.VK_E);
eMenuItem1b.setToolTipText("Exit application");
JMenuItem eMenuItem1c = new JMenuItem("File 3"/*, icon*///);
/* eMenuItem1c.setMnemonic(KeyEvent.VK_E);
eMenuItem1c.setToolTipText("Exit application");
JMenuItem eMenuItem2 = new JMenuItem("Exit"/*, icon*///);
/* eMenuItem2.setMnemonic(KeyEvent.VK_E);
eMenuItem2.setToolTipText("Exit application");
JMenuItem eMenuItem3 = new JMenuItem("Exit"/*, icon*///);
/*eMenuItem3.setMnemonic(KeyEvent.VK_E);
eMenuItem3.setToolTipText("Exit application");
JMenuItem eMenuItem4 = new JMenuItem("Exit"/*, icon*///);
/*eMenuItem4.setMnemonic(KeyEvent.VK_E);
eMenuItem4.setToolTipText("Exit application");
eMenuItem1a.addActionListener(new myListenerOne());
eMenuItem1b.addActionListener(new myListenerTwo());
eMenuItem1c.addActionListener(new myListenerThree());
eMenuItem2.addActionListener(new myListenerOne());
eMenuItem3.addActionListener(new myListenerTwo());
eMenuItem4.addActionListener(new myListenerThree());
file1.add(eMenuItem1a);
file1.add(eMenuItem1b);
file1.add(eMenuItem1c);
file2.add(eMenuItem2);
file3.add(eMenuItem3);
file4.add(eMenuItem4);
menubar.add(file1);
menubar.add(file2);
menubar.add(file3);
menubar.add(file4);
menubar.add(file5);
menubar.add(file6);
setJMenuBar(menubar);
//Actionlisteners below
class myListenerOne implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Action Class Listener 1");
System.exit(0);
}
}
class myListenerTwo implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Action Class Listener 2");
System.exit(0);
}
}
class myListenerThree implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Action Class Listener 3");
System.exit(0);
}
}
Here is another menu example that I forgot to include this morning. Was sick and just didn't think about it actually. Anyway, what I was wondering was if the menu could be set to a movable menu, so that when you click on it and drag it that it can be moved to any where in the frame. I have seen this done on some java applications I have used but just haven't seen it in a while.
import javax.swing.JToolBar;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import java.net.URL;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ToolBarDemo extends JPanel
implements ActionListener {
protected JTextArea textArea;
protected String newline = "\n";
static final private String PREVIOUS = "previous";
static final private String UP = "up";
static final private String NEXT = "next";
public ToolBarDemo() {
super(new BorderLayout());
//Create the toolbar.
JToolBar toolBar = new JToolBar("Still draggable");
addButtons(toolBar);
//Create the text area used for output. Request
//enough space for 5 rows and 30 columns.
textArea = new JTextArea(5, 30);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
//Lay out the main panel.
setPreferredSize(new Dimension(450, 130));
add(toolBar, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);
}
protected void addButtons(JToolBar toolBar) {
JButton button = null;
//first button
button = makeNavigationButton("Back24", PREVIOUS,
"Back to previous something-or-other",
"Previous");
toolBar.add(button);
//second button
button = makeNavigationButton("Up24", UP,
"Up to something-or-other",
"Up");
toolBar.add(button);
//third button
button = makeNavigationButton("Forward24", NEXT,
"Forward to something-or-other",
"Next");
toolBar.add(button);
}
protected JButton makeNavigationButton(String imageName,
String actionCommand,
String toolTipText,
String altText) {
//Look for the image.
String imgLocation = imageName + ".gif";
URL imageURL = ToolBarDemo.class.getResource(imgLocation);
//Create and initialize the button.
JButton button = new JButton();
button.setActionCommand(actionCommand);
button.setToolTipText(toolTipText);
button.addActionListener(this);
if (imageURL != null) { //image found
button.setIcon(new ImageIcon(imageURL, altText));
} else { //no image found
button.setText(altText);
System.err.println("Resource not found: "
+ imgLocation);
}
return button;
}
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
String description = null;
// Handle each button.
if (PREVIOUS.equals(cmd)) { //first button clicked
description = "taken you to the previous <something>.";
} else if (UP.equals(cmd)) { // second button clicked
description = "taken you up one level to <something>.";
} else if (NEXT.equals(cmd)) { // third button clicked
description = "taken you to the next <something>.";
}
displayResult("If this were a real app, it would have "
+ description);
}
protected void displayResult(String actionDescription) {
textArea.append(actionDescription + newline);
textArea.setCaretPosition(textArea.getDocument().getLength());
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Doug's Test ToolBarDemo!!!!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add content to the window.
frame.add(new ToolBarDemo());
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Turn off metal's use of bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}
The following code adds a JToolBar to the frame. I like this because it is draggable but it looks different than a regular menu. I was more interested in if you could set a menu to draggable.
Try using a JToolBar if you don't want to create your own floating window.
http://docs.oracle.com/javase/tutorial/uiswing/components/toolbar.html

Image won't display on a JPanel

Just started out using Java and am a beginner. I tried to create a photo viewer which can search a directory for an image and open the image but my program won't display the image.
When i run the program, it opens up and shows a menubar which i use to search my directories, but even if i select an image it won't display. TIA.
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.imageio.ImageIO;
public class ICS
{
private JPanel gui;
private JFileChooser fileChooser;
FilenameFilter fileNameFilter;
private JMenuBar menuBar;
DefaultListModel model;
public ICS() {
gui = new JPanel(new GridLayout());
final JLabel imageView = new JLabel();
gui.add(imageView);
fileChooser = new JFileChooser();
String[] imageTypes = ImageIO.getReaderFileSuffixes();
menuBar = new JMenuBar();
JMenu menu = new JMenu("GET PHOTO HERE");
menuBar.add(menu);
JMenuItem browse = new JMenuItem("browse");
menu.add(browse);
browse.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
int result = fileChooser.showOpenDialog(gui);
if (result==JFileChooser.APPROVE_OPTION) {
File eg = fileChooser.getSelectedFile();
}
}
});
}
public void loadImages(File directory) throws IOException {
File[] imageFiles = directory.listFiles(fileNameFilter);
BufferedImage[] images = new BufferedImage[imageFiles.length];
}
public Container getGui() {
return gui;
}
public JMenuBar getMenuBar() {
return menuBar;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
ICS imageList = new ICS();
JFrame f = new JFrame("Image Browser");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.add(imageList.getGui());
f.setJMenuBar(imageList.getMenuBar());
f.setLocationByPlatform(true);
f.pack();
f.setSize(800,600);
f.setVisible(true);
}
});
}
}
You're not doing anything with your selected file. Given that you have an empty JLabel in your JPanel, you could simply set the Icon for that component:
imageView.setIcon(new ImageIcon(eg.getPath()));
It's not doing anything with the image because you've never told it to. In your action listener, you've created a file chooser and gotten the selected file, but you never do anything with it. You just define it as a local variable inside the action listener, which is then immediately destroyed when your listener exits.
What you should be doing is, inside of your action listener, make a function call that actually displays your image after you retrieve the file the user selected.
Also, ICS is a terrible name for a class. You should be descriptive of your class names for your own reference and sanity when your program gets larger and you're trying to remember what everything did.

Categories