I've written a program which makes a screenshot of JFrame by clicking on JMenuItem. If I only run the .java file in Eclipse, everything works and the screenshot shows the JFrame perfectly. But if I open the JFrame as a link from another JFrame, the screenshot is black instead of showing the JFrame. Here's my code:
JFrame1.java:
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class JFrame1 extends JFrame {
static JFrame1 frame1 = new JFrame1();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame1.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void CloseFrame(){
super.dispose();
}
public JFrame1() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(50, 50, 800, 740);
JButton ok = new JButton("OK");
getContentPane().add(ok);
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CloseFrame();
JFrame2 frame2 = new JFrame2();
frame2.setVisible(true);
}
});
}
}
With a button (ok) I can go to JFrame2.java.
JFrame2.java:
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class JFrame2 extends JFrame {
static JFrame2 frame2 = new JFrame2();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame2.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private void createMenuBar() {
JMenuBar menubar = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem screen = new JMenuItem("Screenshot");
screen.addActionListener(new AbstractAction() {
#Override
public void actionPerformed (ActionEvent e)
{
Dimension size = frame2.getSize ();
BufferedImage img = new BufferedImage (size.width, size.height, BufferedImage.TYPE_3BYTE_BGR);
Graphics g = img.getGraphics ();
frame2.printAll (g);
g.dispose ();
try
{
ImageIO.write (img, "png", new File ("screenshot.png"));
}
catch (IOException ex)
{
ex.printStackTrace ();
}
}
});
file.add(screen);
menubar.add(file);
setJMenuBar(menubar);
}
public JFrame2() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(50, 50, 800, 740);
createMenuBar();
}
}
If I click now on "Screenshot", it is just black.
And if I run only JFrame2.java without running JFrame1.java before, the real image is saved.
Why does the screenshot is black after going from one JFrame1 to JFrame2?
You're painting from the wrong frame...
In your first frame, you are doing this...
JFrame2 frame2 = new JFrame2();
frame2.setVisible(true);
Looks pretty harmless, but, in JFrame2 you are doing this...
public class JFrame2 extends JFrame {
static JFrame2 frame2 = new JFrame2();
And...
public void actionPerformed (ActionEvent e)
{
Dimension size = frame2.getSize ();
BufferedImage img = new BufferedImage (size.width, size.height, BufferedImage.TYPE_3BYTE_BGR);
Graphics g = img.getGraphics ();
frame2.printAll (g);
g.dispose ();
try
{
ImageIO.write (img, "png", new File ("screenshot.png"));
}
catch (IOException ex)
{
ex.printStackTrace ();
}
}
But, frame2 (inside JFrame2) is not visible on the screen.
This is why static is evil and should be avoid. This is also why you should not extend directly from something like JFrame. You can to easily get yourself into a knot of not knowing what is actually on the screen and what you are referencing...
For example...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class JavaApplication254 {
public static void main(String[] args) {
new JavaApplication254();
}
public JavaApplication254() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JButton btn = new JButton("Click me away...");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
TestPane testPane = new TestPane();
SnapshotAction snapshotAction = new SnapshotAction(testPane);
JMenuBar mb = new JMenuBar();
JMenu mnuFile = new JMenu("File");
mnuFile.add(snapshotAction);
mb.add(mnuFile);
JFrame frame = new JFrame("More Testing");
frame.setJMenuBar(mb);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(testPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.add(btn);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setBorder(new EmptyBorder(20, 20, 20, 20));
JLabel label = new JLabel("I be a bananan");
label.setOpaque(true);
label.setBackground(Color.YELLOW);
label.setForeground(Color.RED);
label.setBorder(
new CompoundBorder(
new LineBorder(Color.RED),
new EmptyBorder(20, 20, 20, 20)));
setLayout(new GridBagLayout());
add(label);
}
}
public class SnapshotAction extends AbstractAction {
private JComponent parent;
public SnapshotAction(JComponent parent) {
this.parent = parent;
putValue(NAME, "Take Snapshot...");
}
#Override
public void actionPerformed(ActionEvent e) {
if (parent.isDisplayable()) {
BufferedImage img = new BufferedImage(parent.getWidth(), parent.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
parent.printAll(g2d);
g2d.dispose();
try {
ImageIO.write(img, "png", new File("Snapshot.png"));
Toolkit.getDefaultToolkit().beep();
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(parent, "Failed to generate snapshot: " + ex.getMessage());
}
}
}
}
}
Which will output...
Related
I need the frame to update and display how many times the Button has been pressed (the button's text to update)
If I can use actionPreformed() to be locked on to specific events (Button press, or the Menu item being pressed), then I think that should help...
Problems:
When Button is pressed it creates more frames
The existing Frame(s) do not update (I only want there to be one frame anyway)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class ButtonFrame implements InternalFrameListener, ActionListener
{
JFrame myFrame = null;
private int clicked;
final String F=("Clicked: "+clicked+" Times!");
public static void main(String[] a)
{
(new ButtonFrame()).test();
}
private void test()
{
myFrame = new JFrame("Internal Frame with a Button");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(400,400);
myFrame.setContentPane(new JDesktopPane());
JMenuBar Start_Bar = new JMenuBar();
JMenu Start_Menu = new JMenu("Frame");
JMenuItem Start_Item = new JMenuItem("Start");
Start_Item.addActionListener(this);
Start_Menu.add(Start_Item);
Start_Bar.add(Start_Menu);
myFrame.setJMenuBar(Start_Bar);
myFrame.setVisible(true);
}
public void actionPerformed(ActionEvent Start_Item)
{
JInternalFrame f = new JInternalFrame("Button Frame");
f.setResizable(true);
f.setClosable(false);
f.setMaximizable(true);
f.setIconifiable(true);
f.setSize(200,200);
f.setLocation(100,100);
f.addInternalFrameListener(this);
f.setVisible(true);
Button objButton1;
objButton1=new Button ("Clicked: "+clicked+" Times!");
objButton1.setBounds(20,90,40,50);
f.add(objButton1);
objButton1.addActionListener(this);
myFrame.getContentPane().add(f);
}
public void actionPreformed(ActionEvent objButton1)
{
clicked++;
}
public void internalFrameActivated(InternalFrameEvent e)
{
System.out.println("Internal Button Ready");
}
public void internalFrameClosed(InternalFrameEvent e)
{
System.out.println("Internal frame closed");
}
public void internalFrameClosing(InternalFrameEvent e)
{
System.out.println("Internal frame closing");
}
public void internalFrameDeactivated(InternalFrameEvent e)
{
System.out.println("Internal frame deactivated");
}
public void internalFrameDeiconified(InternalFrameEvent e)
{
System.out.println("Internal frame deiconified");
}
public void internalFrameIconified(InternalFrameEvent e)
{
System.out.println("Internal frame iconified");
}
public void internalFrameOpened(InternalFrameEvent e)
{
System.out.println("Internal frame opened");
}
}
Based on your description, you solution is screaming isolation and separation of code responsibility, the code responsible for managing the button should be separated from the code managing the frame and desktop pane
This way, you can use separate ActionListeners as well as isolate the functionality to a single instance of the button class
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
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;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JDesktopPane dp = new JDesktopPane();
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar Start_Bar = new JMenuBar();
JMenu Start_Menu = new JMenu("Frame");
JMenuItem Start_Item = new JMenuItem("Start");
Start_Item.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JInternalFrame f = new JInternalFrame("Button", true, true, true, true);
f.setSize(200, 200);
f.setLocation(100, 100);
f.add(new ButtonPane());
f.setVisible(true);
dp.add(f);
}
});
Start_Menu.add(Start_Item);
Start_Bar.add(Start_Menu);
frame.setJMenuBar(Start_Bar);
frame.add(dp);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ButtonPane extends JPanel {
private JButton button;
private int count = 0;
public ButtonPane() {
setLayout(new GridBagLayout());
button = new JButton("0");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
count++;
button.setText(Integer.toString(count));
}
});
add(button);
}
}
}
This question already has answers here:
Inserting an image under a JTextArea
(2 answers)
Closed 8 years ago.
I want to set background in JTextArea (having transparency), but I don't have any idea. Maybe it's not very important, but I just want have characteristically program. Please help.
This part of code, I create JTextArea.
notatnik_k = new JTextArea();
JScrollPane scrollPane2 = new JScrollPane(notatnik_k);
scrollPane2.setBounds(20,30, 263,200);
notatnik_k.setEditable(false);
add(scrollPane2);
This photo showing my problem:
Is there a simply way, to do it?
You will need to extend your JTextArea class and create a setBackground(Image image) method. This method would set a field to the image you want to use and then invoke the the repaint method (this.repaint()).
You should then override the paintComponent(Graphics) method to paint the component with the image you set using setBackground(Image image).
I found here on the site this sample of code, and I did a little change but I have one error and don't know why it's incorrect? It's shows error: "The method setBackgroundImage(Image) is undefined for the type JTextArea"
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class BackgroundDemo {
public JTextArea notatnik;
private static void createAndShowUI() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
final JFrame frame = new JFrame("BackgroundDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel buttonsPanel = new JPanel();
final JTextArea notatnik = new JTextArea();
JScrollPane scrollPane1 = new JScrollPane(notatnik);
scrollPane1.setBounds(20,270, 380,110);
JButton loadButton = new JButton("Set background");
buttonsPanel.add(loadButton);
loadButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser(System.getProperty("user.home"));
int returnVal = fc.showOpenDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
Image image = ImageIO.read(fc.getSelectedFile());
if (image != null)
notatnik.setBackgroundImage(image);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});
JPanel content = new JPanel(new BorderLayout());
content.add(buttonsPanel, BorderLayout.SOUTH);
frame.add(scrollPane1);
frame.add(content);
frame.setSize(new Dimension(800, 500));
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
static class MyTextArea extends JTextArea {
private Image backgroundImage;
public MyTextArea() {
super();
setOpaque(false);
}
public void setBackgroundImage(Image image) {
this.backgroundImage = image;
this.repaint();
}
#Override
protected void paintComponent(Graphics g) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
if (backgroundImage != null) {
g.drawImage(backgroundImage, 0, 0, this);
}
super.paintComponent(g);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
I have created a program in which a window opens which says click to start.When we press start button it opens another window and make it fullscreen. I have add keylistener to this fullscreen window to move an image.But its not working. If you wanna see the code please ask me .
public g1(){
panel = new JPanel();
cake = new ImageIcon("G:\\naman1.jpg").getImage();
start = new JButton("Start");
restart = new JButton("Restart");
exit = new JButton("EXIT");
panel.add(start);
panel.setFocusable(true);
start.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
new g1().run(); //this method is from superclass it calls init }
}
);
panel.setBackground(Color.GRAY);
}
public void init(){
super.init(); //it makes the window fullscreen
Window w = s.getFullScreenWindow();
w.setFocusable(true);
w.addKeyListener(this);}
Try this:
The MainFrame
package moveimages;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainFrame extends JFrame {
JButton startBtn;
public MainFrame() {
this.setTitle("Moving Images");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(initComponents());
this.setSize(new Dimension(1024, 768));
this.setVisible(true);
}
private JPanel initComponents() {
JPanel jPanel = new JPanel();
startBtn = new JButton("start");
startBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
final ImageWindow imageWindow = new ImageWindow();
}
});
jPanel.add(startBtn);
return jPanel;
}
}
This is the ImageWindow
package moveimages;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
public class ImageWindow extends JFrame {
public ImageWindow() {
this.add(new JLabel("Window"));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setSize(screenSize.width, screenSize.height);
final ImagePanel imagePanel = new ImagePanel();
this.getContentPane().add(imagePanel);
this.setVisible(true);
}
class ImagePanel extends JPanel {
URL url;
int panelX;
int panelY;
boolean isDragged;
ImagePanel() {
this.panelX = this.getWidth();
this.panelY = this.getHeight();
try {
this.url = new URL("http://i.stack.imgur.com/XZ4V5.jpg");
final ImageIcon icon = new ImageIcon(url);
final JLabel imageLabel = new JLabel(icon);
Action moveLeft = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
if(imageLabel.getX() - 1 > 0)
imageLabel.setLocation(imageLabel.getX()-1, imageLabel.getY());
}
};
Action moveUp = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
if(imageLabel.getY() - 1 > 0) {
imageLabel.setLocation(imageLabel.getX(), imageLabel.getY()-1);
}
}
};
Action moveDown = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
if(getParent().getHeight()-icon.getIconHeight() > imageLabel.getY() + 1) {
imageLabel.setLocation(imageLabel.getX(), imageLabel.getY()+1);
}
}
};
Action moveRight = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
if(getParent().getWidth()-icon.getIconWidth() > imageLabel.getX()+1) {
imageLabel.setLocation(imageLabel.getX()+1, imageLabel.getY());
}
}
};
imageLabel.getInputMap().put(KeyStroke.getKeyStroke("A"), "moveLeft");
imageLabel.getInputMap().put(KeyStroke.getKeyStroke("W"), "moveUp");
imageLabel.getInputMap().put(KeyStroke.getKeyStroke("S"), "moveDown");
imageLabel.getInputMap().put(KeyStroke.getKeyStroke("D"), "moveRight");
imageLabel.getActionMap().put("moveLeft", moveLeft);
imageLabel.getActionMap().put("moveUp", moveUp);
imageLabel.getActionMap().put("moveDown", moveDown);
imageLabel.getActionMap().put("moveRight", moveRight);
this.add(imageLabel);
} catch (MalformedURLException ex) {
Logger.getLogger(ImageWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Start the App
package moveimages;
import javax.swing.SwingUtilities;
public class MoveImages {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MainFrame frame = new MainFrame();
});
}
}
Maybe it helps you to refactor your current app.
I am trying to create a button panel where the button that was clicked becomes 'differently colored'; i.e show the background image. p.s I only need this approach(with 2 images), and not anything else. Thanks !
Eg:
public class TestPane extends JPanel {
private BufferedImage imgUnclicked;
private BufferedImage imgClicked;
private Point mousePoint;
public TestPane() {
try {
imgUnclicked = ImageIO.read(new File("C:\\Users\\Me\\Desktop\\tmp\\Uncolored.png"));
imgClicked = ImageIO.read(new File("C:\\Users\\Me\\Desktop\\tmp\\Colored.png"));
} catch (IOException ex) {
Logger.getLogger(Spotlight.class.getName()).log(Level.SEVERE, null, ex);
}
addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
mousePoint = e.getPoint();
repaint();
}
});
}
}
#Override
protected void paintComponent(Graphics g) {
//Draw imgClicked
//Draw imgUnclicked with some rectangular area around mouse click subtracted
}
}
No need to reinvent the wheel. Instead use a JToggleButton (appropriately configured). A button will react to both mouse and keyboard input.
import java.awt.*;
import java.net.*;
import javax.imageio.ImageIO;
import javax.swing.*;
class ChangeImageOnClick {
public static void main(String[] args) throws Exception {
URL url1 = new URL("http://i.stack.imgur.com/gJmeJ.png");
final Image img1 = ImageIO.read(url1);
URL url2 = new URL("http://i.stack.imgur.com/wCF8S.png");
final Image img2 = ImageIO.read(url2);
Runnable r = new Runnable() {
#Override
public void run() {
JToggleButton btn = new JToggleButton("Click me!");
btn.setIcon(new ImageIcon(img1));
btn.setSelectedIcon(new ImageIcon(img2));
btn.setContentAreaFilled(false);
btn.setBorderPainted(false);
JOptionPane.showMessageDialog(null, btn);
}
};
SwingUtilities.invokeLater(r);
}
}
A different idea. Basically, load an image into a JLabel, set the Layout of the label and add two opaque components to it.
By using a simple MouseListener, you can either make the component invisible or transparent based on your needs...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class HideAndShow {
public static void main(String[] args) {
new HideAndShow();
}
public HideAndShow() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new BorderLayout());
try {
BufferedImage img = ImageIO.read(new File("/Users/swhitehead/Dropbox/MegaTokyo/Haibane_Miho___Take_2_by_garrbage.png"));
JLabel label = new JLabel(new ImageIcon(img.getScaledInstance(-1, 200, Image.SCALE_SMOOTH)));
add(label);
label.setLayout(new GridLayout(2, 1));
JPanel top = new JPanel();
top.add(new JLabel("Top"));
JPanel bottom = new JPanel();
bottom.add(new JLabel("Bottom"));
MouseAdapter ma = new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
((JPanel)e.getComponent()).setOpaque(false);
repaint();
}
};
top.addMouseListener(ma);
bottom.addMouseListener(ma);
label.add(top);
label.add(bottom);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Add an ActionListener to your button and call setIcon with the imgClicked.
Something like this:
JButton btn = new JButton();
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
btn.setIcon(imgClicked);
}
});
I want to achieve following functionality :
Eg :
When user selects "Profile Pic"item from JComboBox releted images from "Profile Pic" folder should be loaded on same frame.
Again when user selects "Product Img" item related images from "Product Img" folder should be loaded replacing previous images.
Following is code snippet , please suggest any changes
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
public class NewClass1 {
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.setResizable(false);//make it un-resizeable
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Test");
ArrayList<BufferedImage> images = null;
try {
images = getImagesArrayList();
} catch (Exception ex) {
ex.printStackTrace();
}
final ImageViewPanel imageViewPanel = new ImageViewPanel(images);
JScrollPane jsp = new JScrollPane(imageViewPanel);
jsp.setPreferredSize(new Dimension(400, 400));
frame.add(jsp);
final javax.swing.JComboBox filter = new javax.swing.JComboBox<>();
filter.addItem("All");
filter.addItem("Profile Pic");
filter.addItem("Company Logo");
filter.addItem("Product Img");
JPanel controlPanel = new JPanel();
JButton addLabelButton = new JButton("Delete Selected Image");
addLabelButton.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
imageViewPanel.removeFocusedImageLabel();
}
});
JLabel label =new JLabel("Filter By :");
filter.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
String cat=(String) filter.getSelectedItem();
createJFrame(cat);
}
});
controlPanel.add(addLabelButton);
controlPanel.add(label);
controlPanel.add(filter);
frame.add(controlPanel, BorderLayout.NORTH);
frame.pack();
return frame;
}
private static ArrayList<BufferedImage> getImagesArrayList(String cat) throws Exception {
System.out.println(cat);
ArrayList<BufferedImage> images = new ArrayList<>();
if(cat.equals("Profile Pic"))
images.add(resize(ImageIO.read(new URL("http://192.168.1.25:8080/pic/ProfilePic/1.jpg")), 100, 100));
else if(cat.equals("Product Img"))
{
images.add(resize(ImageIO.read(new URL("http://192.168.1.25:8080/pic/ProductImg/2.jpg")), 100, 100));
}
return images;
}
private static ArrayList<BufferedImage> getImagesArrayList() throws Exception {
ArrayList<BufferedImage> images = new ArrayList<>();
images.add(resize(ImageIO.read(new URL("http://localhost:8080/pic/All/a.jpg")), 100, 100));
images.add(resize(ImageIO.read(new URL("http://localhost:8080/pic/All/b.jpg")), 100, 100));
return images;
}
public static BufferedImage resize(BufferedImage image, int width, int height) {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TRANSLUCENT);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(image, 0, 0, width, height, null);
g2d.dispose();
return bi;
}
}
I would urge you to have another look at the code I posted (which you seem to be using) Deleting images from JFrame.
However:
In your code I see:
filter.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
String cat=(String) filter.getSelectedItem();
createJFrame(cat);
}
});
I cannot even find the method createJFrame(String cat);?
As far as I see you should be doing this:
filter.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
String cat=(String) filter.getSelectedItem();
ArrayList<BufferedImage> images=getImagesArrayList(cat);//get the new images for the selected item in combo
//refresh the layout by removing old pics and itertating the new array and adding pics to the panel as you iterate
layoutLabels(images);
}
});
....
private JLabel NO_IMAGES=new JLabel("No Images");
private void layoutLabels(ArrayList<BufferedImage> images) {
removeAll();//remove all components from our panel (the panel should only have the images on if not use setActionCommand("Image") on your images/JLabels and than use getComponents of JPanel and iterate through them looking for getActionCommand.equals("Image")
if (images.isEmpty()) {//if the list is empty
add(NO_IMAGES);//add Jlabel to show message of no images
} else {
remove(NO_IMAGES);
for (BufferedImage i : images) {//iterate through ArrayList of images
add(new JLabel(new ImageIcon(i)));//add each to the panel using JLabel as container for image
}
}
revalidate();
repaint();
}