Create menu on button click in Java - 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);
}

Related

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.

JInternalFrame is not show

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

Get the next image in directory on clicking JButton - Swing

I am displaying an image on the screen now I want to press Jbutton and display the next image in that directory. And other button(previous) should display the previous image. All of it in a loop. So that first image is displayed after the last image of the directory. This is my code so far:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import net.miginfocom.swing.MigLayout;
class ImageFilter extends FileFilter {
#Override
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String name = f.getAbsolutePath();
if (name.matches(".*((.jpg)|(.gif)|(.png))"))
return true;
else
return false;
}
#Override
public String getDescription() {
return "Image Files(*.jpg, *.gif, *.png)";
}
}
#SuppressWarnings("serial")
class bottompanel extends JPanel {
JButton prev, next;
bottompanel() {
this.setLayout(new MigLayout("debug", "45%[center][center]", ""));
prev = new JButton("Previous");
next = new JButton("Next");
next.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
}
});
this.add(prev, " w 100!");
this.add(next, "w 100!");
}
}
#SuppressWarnings("serial")
class imgpanel extends JPanel {
imgpanel(JLabel image) {
this.setLayout(new MigLayout("debug", "", ""));
this.add(image, "push,align center");
}
}
#SuppressWarnings("serial")
class DispImg extends JFrame {
JMenuBar jmenubar;
JMenu jmenu;
JMenuItem jopen, jexit;
JLabel image;
BufferedImage img, dimg;
DispImg() {
// initializing the Frame
this.setTitle("Display Test");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setLayout(new MigLayout("debug", "[fill,grow]", "[]push[]"));
this.setLocationByPlatform(true);
this.setMinimumSize(new Dimension(800, 600));
this.setVisible(true);
this.setResizable(false);
// create label
image = new JLabel(" ");
//add label to panel
this.add(new imgpanel(image), "wrap");
//add buttons to bottompanel
this.add(new bottompanel(), "gaptop 10");
// Making Menubar
jmenubar = new JMenuBar();
jmenu = new JMenu("File");
jopen = new JMenuItem("Open");
jopen.setMnemonic(KeyEvent.VK_O);
KeyStroke key1 = KeyStroke.getKeyStroke(KeyEvent.VK_O, Event.CTRL_MASK);
jopen.setAccelerator(key1);
jopen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser fc = new JFileChooser();
fc.setFileFilter(new ImageFilter());
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
img = ImageIO.read(file);
float width = img.getWidth();
float height = img.getHeight();
if (img.getHeight() > 500 && (width / height) > 1) {
Image thumb = img.getScaledInstance(-1, 620,
Image.SCALE_SMOOTH);
image.setIcon(new ImageIcon(thumb));
} else if (img.getHeight() > 500
&& (width / height) <= 1) {
Image thumb = img.getScaledInstance(460, -1,
Image.SCALE_SMOOTH);
image.setIcon(new ImageIcon(thumb));
} else {
image.setIcon(new ImageIcon(img));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
jexit = new JMenuItem("Exit");
jexit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
jmenu.add(jopen);
jmenu.addSeparator();
jmenu.add(jexit);
jmenubar.add(jmenu);
this.setJMenuBar(jmenubar);
}
public static void main(String s[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new DispImg();
}
});
}
}
when i added actionListener() on next button nothing happened and the new image is not displayed
You don't have any code in the actionListener, so I'm not sure what you expect to happen.
Don't know how to fetch the next image from the directory
You would probably use the JFileChooser to select the directory (and maybe initial image to display).
Once you have the directory then you could use the File.listFiles(...) method to get a list of all the image files in the directory. Then your Next/Previous button would add/subtract one to access the next/previous File in the array.

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.

How to draw shape by right clicking a panel in Swing?

I am trying to create a swing program. In my program I want to achieve something like this: right click on a panel and select the menu "Draw rectangle" and program should draw a very simple rectangle on the panel. Here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.BevelBorder;
public class MainWindow extends JFrame {
JFrame frame = null;
AboutDialog aboutDialog = null;
JLabel statusLabel = null; //label on statusPanel
public MainWindow() {
frame = new JFrame("Project");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//MENUS
JMenuBar menuBar = new JMenuBar(); //menubar
JMenu menuDosya = new JMenu("Dosya"); //menus on menubar
JMenu menuYardim = new JMenu("Yardım"); //menus in menus
menuBar.add(menuDosya);
menuBar.add(menuYardim);
JMenuItem menuItemCikis = new JMenuItem("Çıkış", KeyEvent.VK_Q); //dosya menus
menuItemCikis.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
menuDosya.add(menuItemCikis);
JMenuItem menuItemYardim = new JMenuItem("Hakkında", KeyEvent.VK_H); //hakkinda menus
menuItemYardim.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
JDialog f = new AboutDialog(new JFrame());
f.show();
}
});
menuYardim.add(menuItemYardim);
frame.setJMenuBar(menuBar);
//TOOLBAR
JToolBar toolbar = new JToolBar();
JButton exitButton = new JButton("Kapat");
toolbar.add(exitButton);
//STATUSBAR
JPanel statusPanel = new JPanel();
statusPanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
frame.add(statusPanel, BorderLayout.SOUTH);
statusPanel.setPreferredSize(new Dimension(frame.getWidth(), 20));
statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.X_AXIS));
statusLabel = new JLabel("Ready.");
statusLabel.setHorizontalAlignment(SwingConstants.LEFT);
statusPanel.add(statusLabel);
//MAIN CONTENT OF THE PROGRAM
final JPanel mainContentPanel = new JPanel();
//RIGHT CLICK MENU
final JPopupMenu menuSag = new JPopupMenu("RightClickMenu");
JMenuItem menuRightClickRectangle = new JMenuItem("draw rectangle");
menuRightClickRectangle.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//CircleShape cs=new CircleShape();
mainContentPanel.add(new CircleShape()); //trying to draw.
mainContentPanel.repaint();
//mainContentPanel.repaint(); boyle olacak.
}
});
JMenuItem menuRightClickCircle = new JMenuItem("Daire çiz");
menuSag.add(menuRightClickRectangle);
menuSag.add(menuRightClickCircle);
mainContentPanel.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3) {
menuSag.show(e.getComponent(), e.getX(), e.getY());
statusLabel.setText("X=" + e.getX() + " " + "Y=" + e.getY());
}
}
});
JButton west = new JButton("West");
JButton center = new JButton("Center");
JPanel content = new JPanel(); //framein icindeki genel panel. en genel panel bu.
content.setLayout(new BorderLayout());
content.add(toolbar, BorderLayout.NORTH);
content.add(statusPanel, BorderLayout.SOUTH);
content.add(west, BorderLayout.WEST);
content.add(mainContentPanel, BorderLayout.CENTER);
frame.setContentPane(content);
frame.setPreferredSize(new Dimension(400, 300));
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}
The problem is nothing is drawn on the panel. I guess there is an event loss in the program but i don't know how to solve this issue.
Please modify the code in the following way. Add a new class like this:
class MainPanel extends JPanel {
private List<Rectangle> rectangles = new ArrayList<Rectangle>();
private void addRectangle(Rectangle rectangle) {
rectangles.add(rectangle);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
for (Rectangle rectangle : rectangles) {
g2.drawRect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
}
}
}
Then, instead of
final JPanel mainContentPanel = new JPanel();
you should do:
final MainPanel mainContentPanel = new MainPanel();
And the action listener for the menu item becomes something like this:
menuRightClickRectangle.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
// TODO: add your own logic here, currently a hardcoded rectangle
mainContentPanel.addRectangle(new Rectangle(10, 10, 100, 50));
mainContentPanel.repaint();
}
});
You can't do that by calling add method.To draw a shape you will have to override paintComponent method:
Example of drawing rectangle:
public void paintComponent(Graphics g){
g.setColor(Color.RED);
g.fillRect(50,50,50,50);
}
Hmm did a short example for you:
Test.java:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class Test {
private final JFrame frame = new JFrame();
private final MyPanel panel = new MyPanel();
private void createAndShowUI() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test().createAndShowUI();
}
});
}
}
MyPanel.java:
class MyPanel extends JPanel {
private final JPopupMenu popupMenu = new JPopupMenu();
private final JMenuItem drawRectJMenu = new JMenuItem("Draw Rectangle here");
private int x = 0, y = 0;
private List<Rectangle> recs = new ArrayList<>();
public MyPanel() {
initComponents();
}
private void initComponents() {
setBounds(0, 0, 600, 600);
setPreferredSize(new Dimension(600, 600));
popupMenu.add(drawRectJMenu);
add(popupMenu);
addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
checkForTriggerEvent(e);
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
private void checkForTriggerEvent(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3) {
x = e.getX();
y = e.getY();
popupMenu.show(e.getComponent(), x,y);
}
}
});
drawRectJMenu.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
addRec(new Rectangle(x, y, 100, 100));
repaint();
}
});
}
public void addRec(Rectangle rec) {
recs.add(rec);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for (Rectangle rec : recs) {
g2d.drawRect(rec.x, rec.y, rec.width, rec.height);
}
}
}

Categories