Get the next image in directory on clicking JButton - Swing - java

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.

Related

Drop everywhere in a jpanel

Based on this example : https://stackoverflow.com/a/17359895/3259386
I have two panels, one for drag and the other for drop, I just drag a copy and I don't move the dragged image.
the code is...
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetAdapter;
import java.awt.dnd.DropTargetDropEvent;
import java.io.IOException;
import java.net.URL;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.TransferHandler;
import javax.swing.TransferHandler.TransferSupport;
import javax.swing.border.TitledBorder;
public class Test {
public static void main(String[] args) {
createAndShowJFrame();
}
public static void createAndShowJFrame() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = createJFrame();
frame.setVisible(true);
}
});
}
private static JFrame createJFrame() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setTitle("Test");
JPanel panel = createEmptyJPanel();
new MyDropTargetListener(panel);//this must be done or we wont be able to drop any image onto the empty panel
frame.add(panel, BorderLayout.CENTER);
try {
frame.add(createJLabelPanel(), BorderLayout.SOUTH);
} catch (Exception ex) {
ex.printStackTrace();
}
frame.pack();
return frame;
}
private static JPanel createEmptyJPanel() {
final JPanel p = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
};
p.setBorder(new TitledBorder("Drag Image onto this panel"));
TransferHandler dnd = new TransferHandler() {
#Override
public boolean canImport(TransferSupport support) {
if (!support.isDrop()) {
return false;
}
//only Strings
if (!support.isDataFlavorSupported(DataFlavor.imageFlavor)) {
return false;
}
return true;
}
#Override
public boolean importData(TransferSupport support) {
if (!canImport(support)) {
return false;
}
Transferable tansferable = support.getTransferable();
Icon ico;
try {
ico = (Icon) tansferable.getTransferData(DataFlavor.imageFlavor);
} catch (Exception e) {
e.printStackTrace();
return false;
}
p.add(new JLabel(ico));
return true;
}
};
p.setTransferHandler(dnd);
return p;
}
private static JPanel createJLabelPanel() throws Exception {
JPanel panel = new JPanel();
panel.setBorder(new TitledBorder("Drag Image from here to Panel above"));
JLabel label1 = new JLabel(new ImageIcon(new URL("http://i.stack.imgur.com/gJmeJ.png")));
JLabel label2 = new JLabel(new ImageIcon(new URL("http://i.stack.imgur.com/8BGfi.png")));
JLabel label3 = new JLabel(new ImageIcon(new URL("http://i.stack.imgur.com/1lgtq.png")));
MyDragGestureListener dlistener = new MyDragGestureListener();
DragSource ds1 = new DragSource();
ds1.createDefaultDragGestureRecognizer(label1, DnDConstants.ACTION_COPY, dlistener);
DragSource ds2 = new DragSource();
ds2.createDefaultDragGestureRecognizer(label2, DnDConstants.ACTION_COPY, dlistener);
DragSource ds3 = new DragSource();
ds3.createDefaultDragGestureRecognizer(label3, DnDConstants.ACTION_COPY, dlistener);
panel.add(label1);
panel.add(label2);
panel.add(label3);
return panel;
}
}
class MyDropTargetListener extends DropTargetAdapter {
private DropTarget dropTarget;
private JPanel p;
public MyDropTargetListener(JPanel panel) {
p = panel;
dropTarget = new DropTarget(panel, DnDConstants.ACTION_COPY, this, true, null);
}
#Override
public void drop(DropTargetDropEvent event) {
try {
DropTarget test = (DropTarget) event.getSource();
Component ca = (Component) test.getComponent();
Point dropPoint = ca.getMousePosition();
Transferable tr = event.getTransferable();
if (event.isDataFlavorSupported(DataFlavor.imageFlavor)) {
Icon ico = (Icon) tr.getTransferData(DataFlavor.imageFlavor);
if (ico != null) {
p.add(new JLabel(ico));
p.revalidate();
p.repaint();
event.dropComplete(true);
}
} else {
event.rejectDrop();
}
} catch (Exception e) {
e.printStackTrace();
event.rejectDrop();
}
}
}
class MyDragGestureListener implements DragGestureListener {
#Override
public void dragGestureRecognized(DragGestureEvent event) {
JLabel label = (JLabel) event.getComponent();
final Icon ico = label.getIcon();
Transferable transferable = new Transferable() {
#Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[]{DataFlavor.imageFlavor};
}
#Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
if (!isDataFlavorSupported(flavor)) {
return false;
}
return true;
}
#Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
return ico;
}
};
event.startDrag(null, transferable);
}
}
when I drop the element on the top panel, the element is placed in the center like this
I want to drop everywhere on the top panel.
When I set the top panel to null layout like this : p.setLayout(null);, the dropped image don't show anymore.
when I drop the element on the top panel, the element is placed in the center like this
The default layout manager for the panel is a FlowLayout.
When I set the top panel to null layout ... the dropped image don't show anymore.
When you use a null layout you are responsible for setting the size and location of the component.
//p.add(new JLabel(ico));
JLabel label = new JLabel(ico);
label.setSize( label.getPreferredSize());
label.setLocation(...);
p.add(label);
You can also use the TransferSupport class to get the DropLocation class which contains the drop point that you can use the set the location of the label.
im not gonna write any code because this will be simply too annoying but you can set a mouse cursor type and make it when they click the box uptop they add a imageicon and use a actionlistener to see if there still pressing the left click button

Why does the JFrame resizes itself when image is added to it

the size of the frame is set to 500x500, but when i add an image to it the frame resizes to the size of the image. I tried using this
jf.setPreferredSize(new Dimension(500, 500));
but then the image would not appear.
import java.awt.*;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import java.awt.event.*;
public class Test implements ActionListener {
ImageIcon imgIcon;
JFrame jf ;
JPanel jp_image,jp_option;
BufferedImage img;
Test(){
jf = new JFrame("photo editor");
jf.setPreferredSize(new Dimension(500, 500));
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jp_image = new JPanel();
jp_option = new JPanel();
jp_image.setPreferredSize(new Dimension(200, 500));
jp_option.setPreferredSize(new Dimension(300, 500));
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true, jp_option, jp_image);
jf.getContentPane().add(splitPane);
jf.setSize(1900, 1000);
JMenuBar mbar = new JMenuBar();
jf.setJMenuBar(mbar);
JMenu File = new JMenu("File");
JMenuItem New;
File.add(New = new JMenuItem("New..."));
mbar.add(File);
jf.setVisible(true);
New.addActionListener(this);
}
public void actionPerformed(ActionEvent ae){
String arg = ae.getActionCommand();
if(arg.equals("New...")){
File file = null;
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(" jpg,gif,jpeg,png", "jpg", "gif" , "jpeg" , "png");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(null);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("File Choosed: " + chooser.getCurrentDirectory() + "\\" +chooser.getSelectedFile().getName());
file = chooser.getSelectedFile();
}
try{
img = ImageIO.read(file);
jp_image.add(new JLabel(new ImageIcon(img)));
jp_image.setSize(300, 500);
jf.setPreferredSize(new Dimension(500, 500));// no image appears
//jf.pack(); the image appears but the frame resizes
}
catch(Exception e){
System.out.println("No Image Selected");
}
}
}
public static void main(String args[]){
Test t = new Test();
}
}
how can i set the image in the panel without resizing the frame.
You're adding a component to the GUI but not telling the component's container's layout manager that you're doing this. Be sure to call repaint() and revalidate() on the container after adding the JLabel. For example:
img = ImageIO.read(file);
jp_image.add(new JLabel(new ImageIcon(img)));
jp_image.setSize(300, 500);
jf.setPreferredSize(new Dimension(500, 500));// no image appears
jp_image.revalidate();
jp_image.repaint();
Even better- add the JLabel just once on GUI creation and don't re-add it when you get an image, but instead simply set its Icon. For example:
public class Test implements ActionListener {
ImageIcon imgIcon;
JFrame jf;
JPanel jp_image, jp_option;
BufferedImage img;
private JLabel imageLabel = new JLabel();
Test() {
// ...
jp_image.add(imageLabel); //!!
// ...
}
public void actionPerformed(ActionEvent ae) {
String arg = ae.getActionCommand();
if (arg.equals("New...")) {
// ...
try {
img = ImageIO.read(file);
imageLabel.setIcon(new ImageIcon(img)); //!!
} catch (Exception e) {
e.printStackTrace();
}
}

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 fit ImageIcon within JButton borders

I want to color some JButtons, some other questions here showed me, that it would be easier
to paint a little image (did it with gimp) and set it as icon for the JButton.
The number and size of the buttons should be variable (they're in a grid), so I want a high res image that I can scale how i need it.
The problem now is, I don't know how to 'cut the edges' of the icon, because the buttons have rounded edges.
Here you can see that the image is not inside of the button border.
And here is my method in the class that extends JButton.
public void setYellow() {
URL u = getClass().getResource("/img/yellow.png");
ImageIcon i = new javax.swing.ImageIcon(u);
//Image img = i.getImage();
//img = img.getScaledInstance(size, size, java.awt.Image.SCALE_SMOOTH);
//i = new ImageIcon(img);
setIcon(i);
}
EDIT
package test;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import control.Control;
import view.Field;
import view.View;
public class HelloWorldSwing {
/**
* #param args
*/
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
TestView.initialize();
}
});
}
}
class TestView {
private static TestView view = new TestView();
public static TestView getView() {
return view;
}
private TestView() {
JFrame frame = new JFrame("HelloWorldSwing");
frame.setLayout(new GridLayout(0,3));
int buttonSize = 40;
frame.getContentPane().add(new MyButton(buttonSize));
frame.getContentPane().add(new MyButton(buttonSize));
frame.getContentPane().add(new MyButton(buttonSize));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void initialize() {
}
}
class MyButton extends JButton {
int size;
public MyButton(int size) {
this.size = size;
setPreferredSize(new Dimension(size, size));
this.addActionListener(new ButtonHandler());
setBorder(LineBorder.createGrayLineBorder());
setOpaque(true);
}
public void setYellow() {
//URL u = getClass().getResource("/img/test.png"); // 64x64 png pic
URL u1 = null;
try {
u1 = new URL("http://assets1.qypecdn.net/uploads/users/0195/7210"
+ "/calvin_yellow_original_thumb.jpg");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ImageIcon i = new javax.swing.ImageIcon(u1);
// Image img = i.getImage();
// img = img.getScaledInstance(size, size, java.awt.Image.SCALE_SMOOTH);
// i = new ImageIcon(img);
setIcon(i);
// setBorderPainted(false);
// setContentAreaFilled(false); did not help
}
}
class ButtonHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
MyButton mb = (MyButton) e.getSource();
mb.setYellow();
}
}
EDIT 2
Here are the pictures where the lines in setYellow()
setBorderPainted(false);
setContentAreaFilled(false);
are not commented out (unfortunately there is no difference)
Before button is clicked:
After button is clicked:
UPDATE
I added Borders to the MyButton constructor
setBorder(LineBorder.createGrayLineBorder());
and now the icons are inside the button borders. I added pictures.
But as you can see, we don't have these rounded button edges anymore.
button.setBorderPainted(false);
button.setContentAreaFilled(false);
As seen in this answer.
Update
I do not quite get what you are trying to achieve if not this.
I made the rollover icon to be orange so that we could easily see the size of one button, but otherwise I put 4 in a row to ensure the minimum frame width did not insert extra space between the buttons in a row.
import java.awt.*;
import java.awt.Image;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class HelloWorldSwing {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
TestView.getView();
}
});
}
}
class TestView {
private static TestView view = new TestView();
public static TestView getView() {
return view;
}
private TestView() {
JFrame frame = new JFrame("HelloWorldSwing");
frame.setLayout(new GridLayout(3,4));
int buttonSize = 40;
for (int i=0; i<12; i++) {
frame.getContentPane().add(new MyButton(buttonSize));
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void initialize() {
}
}
class MyButton extends JButton {
int size;
public MyButton(int size) {
this.size = size;
setPreferredSize(new Dimension(size, size));
this.addActionListener(new ButtonHandler());
setOpaque(true);
setYellow();
}
public Image getImage(int sz, Color color) {
BufferedImage bi = new BufferedImage(sz,sz,BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
g.setColor(color);
g.fillRect(0, 0, sz, sz);
g.dispose();
return bi;
}
public void setYellow() {
Image img = getImage(64, Color.YELLOW).getScaledInstance(size, size, java.awt.Image.SCALE_SMOOTH);
setIcon(new ImageIcon(img));
Image rollover = getImage(64, Color.ORANGE).getScaledInstance(size, size, java.awt.Image.SCALE_SMOOTH);
setRolloverIcon(new ImageIcon(rollover));
setBorderPainted(false);
setContentAreaFilled(false);
}
}
class ButtonHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
MyButton mb = (MyButton) e.getSource();
mb.setYellow();
}
}

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