I can't save my Image (mid blend) to file? - java

I've tried looking at the Oracle advice on Writing/Saving an image but nothing I do works. I have a start button that starts the blend of 2 images from one to another. Then a stop button to stop the blend midway (or wherever you want) then I have a saveImage button and would like it capture the image in it's current state and save it to file. But how ? here's the code from the Frame.java
import java.awt.AlphaComposite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.Timer;
class Frame extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private Image MeSmaller1;
private Image MeSmaller2;
protected Timer timer;
private float alpha;
JPanel pnlButton = new JPanel();
static JButton btnStartBlend = new JButton("Start Blend");
static JButton btnStopBlend = new JButton("Stop Blend");
static JButton saveImage = new JButton("Save Image To File");
public Frame() {
loadImages();
initTimer();
pnlButton.add(btnStartBlend);
this.add(pnlButton);
pnlButton.add(btnStopBlend);
this.add(pnlButton);
pnlButton.add(saveImage);
this.add(pnlButton);
addListeners();
}
// start button actionlistener
public void addListeners() {
btnStartBlend.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
initTimer();
timer.start();
System.out.println("Timer started");
}
});
// stop button actionlistener
btnStopBlend.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// initTimer();
timer.stop();
System.out.println("Timer stopped");
}
});
// Save button actionlistener
saveImage.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Save image clicked");
}
});
}
private void loadImages() {
MeSmaller1 = new ImageIcon("MeSmaller1.jpg").getImage();
MeSmaller2 = new ImageIcon("MeSmaller2.jpg").getImage();
}
public void initTimer() {
timer = new Timer(1000, this);
timer.start();
timer.stop();
alpha = 1f;
}
private void doDrawing(Graphics g) {
Graphics2D g2Dim = (Graphics2D) g;
// below sets the size of picture
BufferedImage buffImage = new BufferedImage(400, 600,
BufferedImage.TYPE_INT_ARGB);
Graphics2D gBuffI = buffImage.createGraphics();
AlphaComposite aComp = AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, alpha);
// decides where images are drawn in JFrame
gBuffI.drawImage(MeSmaller1, 28, 55, null);
gBuffI.setComposite(aComp);
gBuffI.drawImage(MeSmaller2, 30, 48, null);
g2Dim.drawImage(buffImage, 10, 10, null);
}
public static void saveToFile(BufferedImage img) {
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
#Override
public void actionPerformed(ActionEvent e) {
alpha -= 0.1;
if (alpha <= 0) {
alpha = 0;
timer.stop();
System.out.println("Morph Finished please restart.");
}
repaint();
}
}
Can anyone help here it's just not working. There is also another class PictureMorph.java
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class PictureMorph extends JFrame {
private static final long serialVersionUID = 1L;
public PictureMorph() {
initUI();
}
private void initUI() {
JFrame frame = new JFrame ("Image Morph");
setTitle("Facial Image Manipulation");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new Frame());
// below set Frame Size around image
setSize(380, 470);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
PictureMorph picMorph = new PictureMorph();
picMorph.setVisible(true);
}
});
}
}
And 3 classes (that I think could be redundant now actually?) called BtnStartBlendListener, BtnStopBlendListener, SaveImageListener that don't contain much code at all. Can anyone help ?

To use a JFileChooser and end up with a user friendly file selector, you may do this:
private static Frame workFrame;
public static Frame getWorkFrame() {
return workFrame;
}
public static void setWorkFrame(Frame frame) {
workFrame = frame;
}
Then modify the save method the following way (the signature changes and also I have commented the code that uses the Scanner and replace it by the JFileChooser)
public static void save(BufferedImage img, Frame frame) {
// Scanner scan = new Scanner(System.in);
// System.out.println("Enter the file name: ");
// String fileFullPath = scan.next();
String fileFullPath = getFileToSaveTo(frame);
file = new File(fileFullPath);
saveToFile(img, file);
}
Add the following method:
public static String getFileToSaveTo(Frame frame) {
JFileChooser fc=new JFileChooser();
int returnVal=fc.showOpenDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
return fc.getSelectedFile().getAbsolutePath();
}
else {
return null;
}
}
In your main method have a call like Frame.setWorkFrame(fr);where fr is defined as Frame fr = new Frame();
This should make it work with the JFileChooser. For example here is how I call the program in my main method
public static void main(String[] args) {
JFrame theFrame = new JFrame("Testing catess...");
theFrame.setSize(400, 400);
Frame fr = new Frame();
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theFrame.add(fr, BorderLayout.CENTER);
theFrame.setVisible(true);
Frame.setWorkFrame(fr);
}
It is working fine in my tests. Test and let me know if it works

Since you have left the saveToFile method empty, I assume that it is the major issue that you have.
For the saveToFile method you can use javax.imageio.ImageIO. I would suggest that you pass a File object parameter to your method so it knows where to save the image.
public static void saveToFile(BufferedImage img, File file) {
String filename = file.getName();
String suffix = filename.substring(filename.lastIndexOf('.') + 1);
suffix = suffix.toLowerCase();
if (suffix.equals("jpg") || suffix.equals("png")) {
try { ImageIO.write(img, suffix, file); }
catch (IOException e) { e.printStackTrace(); }
}
else {
System.out.println("Error: filename must end in .jpg or .png");
}
}
Hope this helps
[EDIT]
The File constructor allows you to instanciate the File object with a string representing the path to the file.
Example: assuming I want to save it in, let's say C:\Tests\image1.jpg, I would do this
File myFile = new File("C:\\Tests\\image1.jpg")
,where Tests represents an existing folder and image1.jpg is of course the name of the new file in which you will save your image.
So assume that img is a variable containing the reference to your BufferedImage object you would call the above method with
Frame.saveToFile(img, myFile);
where myFile is the above File object.
You can also add a static method such as the following one to get the user to specify the path to the file. I used Scanner to get it quick, but for a more user - friendly dialog, use a JFileChooser (examples are here)
public static void save(BufferedImage img) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the file name: ");
String fileFullPath = scan.next();
File file = new File(fileFullPath);
saveToFile(img, file);
}

The issues you experienced are mostly related to the fact that you declared final some of the variables, notably the BufferedImage and the File object (which were null and since you make them final their values can't be changed)
I corrected these issues. Here is the whole code, except the imports statements which are the same as those you had in the link to your source code.
After you click on the save button, enter a full path to the file to save: example C:\test1.jpg in the console.
class Frame extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
static BufferedImage bufferedImage = null; // Don't need to make this final
static File file = null; // Don't need to make this final
private Image MeSmaller1;
private Image MeSmaller2;
protected Timer timer;
private float alpha;
JPanel pnlButton = new JPanel();
static JButton btnStartBlend = new JButton("Start Blend");
static JButton btnStopBlend = new JButton("Stop Blend");
static JButton saveImage = new JButton("Save Image To File");
public Frame() {
loadImages();
initTimer();
pnlButton.add(btnStartBlend);
this.add(pnlButton);
pnlButton.add(btnStopBlend);
this.add(pnlButton);
pnlButton.add(saveImage);
this.add(pnlButton);
addListeners();
}
// start button action listener
public void addListeners() {
btnStartBlend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
initTimer();
timer.start();
System.out.println("Timer started");
}
});
// stop button actionlistener
btnStopBlend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// initTimer();
timer.stop();
System.out.println("Timer stopped");
}
});
// Save button actionlistener
saveImage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent saveImage) {
save(bufferedImage);
System.out.println("Save image clicked");
}
});
}
private void loadImages() {
// I did my local test using
//MeSmaller1 = new ImageIcon("C:\\Tests\\Alain_Lompo.jpg").getImage();
//MeSmaller2 = new ImageIcon("C:\\Tests\\Alain_Lompo.jpg").getImage();
MeSmaller1 = new ImageIcon("MeSmaller1.jpg").getImage();
MeSmaller2 = new ImageIcon("MeSmaller2.jpg").getImage();
}
public void initTimer() {
timer = new Timer(1000, this);
timer.start();
timer.stop();
alpha = 1f;
}
private void doDrawing(Graphics g) {
Graphics2D g2Dim = (Graphics2D) g;
// below sets the size of picture
bufferedImage = new BufferedImage(400, 600,
BufferedImage.TYPE_INT_ARGB);
Graphics2D gBuffI = bufferedImage.createGraphics();
AlphaComposite aComp = AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, alpha);
// decides where images are drawn in JFrame
gBuffI.drawImage(MeSmaller1, 28, 55, null);
gBuffI.setComposite(aComp);
gBuffI.drawImage(MeSmaller2, 30, 48, null);
g2Dim.drawImage(bufferedImage, 10, 10, null);
}
public static void save(BufferedImage img) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the file name: ");
String fileFullPath = scan.next();
file = new File(fileFullPath);
saveToFile(img, file);
}
public static void saveToFile(BufferedImage img, File file) {
String filename = file.getName();
String suffix = filename.substring(filename.lastIndexOf('.') + 1);
suffix = suffix.toLowerCase();
if (suffix.equals("jpg") || suffix.equals("png")) {
try { ImageIO.write(img, suffix, file); }
catch (IOException e) { e.printStackTrace(); }
}
else {
System.out.println("Error: filename must end in .jpg or .png");
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
public void actionPerformed(ActionEvent e) {
alpha -= 0.1;
if (alpha <= 0) {
alpha = 0;
timer.stop();
System.out.println("Morph Finished please restart.");
}
repaint();
}
public static void main(String[] args) {
JFrame theFrame = new JFrame("Testing catess...");
theFrame.setSize(400, 400);
Frame fr = new Frame();
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theFrame.add(fr, BorderLayout.CENTER);
theFrame.setVisible(true);
}
}

Related

How to write some 'pause' in method?

Here I have a method
public static Color pickColor(){
final aero.colorpicker.Frame frame = new aero.colorpicker.Frame();
new Thread(new Runnable() {
#Override
public void run() {
while (!frame.isSelected()) {
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
return frame.getColorPicked();
}
isSelected() is flag that makes us know that user CHOOSED the color he want.
The problem is - if I use it like
Color c = pickColor(); in c will write default (black) color of aero.colorpicker.Frame class.
I need pause here, which will wait for select.
package aero.colorpicker;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by Aero on 28.12.2014.
*/
public class Frame extends JFrame {
//MAINFIELD
private Color colorPicked = Color.black;
private boolean selected = false;
//GUIFIELDS
private JPanel rightPanel;
private JLabel R;
private JLabel G;
private JLabel B;
private JTextField RData;
private JTextField GData;
private JTextField BData;
private JPanel RPanel;
private JPanel GPanel;
private JPanel BPanel;
private ColorPanel colorPanel;
private JButton pick;
private BufferedImage colors;
private JLabel imageLabel;
public Frame(){
initFrame();
setVisible(true);
}
private void initComponents(){
rightPanel = new JPanel();
R = new JLabel("R");
G = new JLabel("G");
B = new JLabel("B");
RData = new JTextField();
GData = new JTextField();
BData = new JTextField();
RPanel = new JPanel();
GPanel = new JPanel();
BPanel = new JPanel();
colorPanel = new ColorPanel();
pick = new JButton("Pick");
}
private void addListeners(){
RData.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
getRed();
colorPanel.repaint();
}
});
GData.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
getGreen();
colorPanel.repaint();
}
});
BData.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
getBlue();
colorPanel.repaint();
}
});
pick.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
getRed();
getBlue();
getGreen();
Frame.this.setVisible(false);
}
});
imageLabel.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
int x, y;
x = e.getX();
y = e.getY();
setColorPicked(new Color(colors.getRGB(x, y)));
colorPanel.repaint();
RData.setText(Integer.toString(getColorPicked().getRed()));
BData.setText(Integer.toString(getColorPicked().getBlue()));
GData.setText(Integer.toString(getColorPicked().getGreen()));
}
});
}
private void getRed(){
int r;
try {
r = Integer.parseInt(RData.getText());
}catch (NumberFormatException nfe){
RData.setText("0");
r = 0;
}
setColorPicked(r, getColorPicked().getGreen(), getColorPicked().getBlue());
}
private void getGreen(){
int g;
try {
g = Integer.parseInt(GData.getText());
}catch (NumberFormatException nfe){
GData.setText("0");
g = 0;
}
setColorPicked(getColorPicked().getRed(), g, getColorPicked().getBlue());
}
private void getBlue(){
int b;
try {
b = Integer.parseInt(BData.getText());
}catch (NumberFormatException nfe){
BData.setText("0");
b = 0;
}
setColorPicked(getColorPicked().getRed(), getColorPicked().getGreen(), b);
}
private void initFrame(){
this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
this.setLayout(new BorderLayout());
this.setSize(369, 194);
this.setTitle("Color picker");
this.setResizable(false);
initComponents();
InputStream input = Frame.class.getClassLoader().getResourceAsStream("colorGradient.jpg");
try {
colors = ImageIO.read(input);
} catch (IOException e) {
e.printStackTrace();
}
imageLabel = new JLabel(new ImageIcon(colors));
this.add(imageLabel, BorderLayout.CENTER);
rightPanel.setLayout(new GridLayout(5, 1));
RPanel.setLayout(new GridLayout(1, 2));
GPanel.setLayout(new GridLayout(1, 2));
BPanel.setLayout(new GridLayout(1, 2));
RPanel.add(R);
RPanel.add(RData);
GPanel.add(G);
GPanel.add(GData);
BPanel.add(B);
BPanel.add(BData);
rightPanel.add(RPanel);
rightPanel.add(GPanel);
rightPanel.add(BPanel);
rightPanel.add(colorPanel);
rightPanel.add(pick);
this.add(rightPanel, BorderLayout.EAST);
this.repaint();
addListeners();
}
public Color getColorPicked() {
return colorPicked;
}
private void setColorPicked(Color colorPicked) {
this.colorPicked = colorPicked;
}
private void setColorPicked(int r, int g, int b){
this.colorPicked = new Color(r, g, b);
}
private void setSelected(){
selected = true;
}
public boolean isSelected(){
return selected;
}
private class ColorPanel extends JPanel{
public void paintComponent(Graphics g){
g.setColor(colorPicked);
g.fillRect(0, 0, getWidth(), getHeight());
}
}
}
Your issue here is that your method pickColor creates the thread that waits for a colour to be picked, starts it and then exits. In other words pickColor isn't waiting for the thread to complete. The thread itself does nothing when it does complete.
One solution would be to wait until the thread completes before exiting the method. That would still be poor design, however. It is possible (in fact, likely) that you are calling pickColor within the thread processing UI events (i.e. the dispatch thread) which will make the UI unresponsive. It also uses a unnecessary busy wait.
If this is what you want to do then you'll need to understand how to create a new event queue. You also need to understand how to use semaphores to block the thread. I'll provide the code here but I wouldn't recommend dumping it into your application without understanding what you are doing. This is designed to be a subclass of your dialog class so that the method used to close the dialog can be overwritten to notify the blocked thread.
For the method that shows the colour picking dialog:
public synchronized Color pickColor() {
// code to create and show the dialog
EventQueue tempEventQueue = new EventQueue();
Toolkit.getDefaultToolkit().getSystemEventQueue().push(tempEventQueue);
try {
wait();
} catch (InterruptedException ex) {
// stop waiting on interrupt
} finally {
tempEventQueue.pop();
}
// return colour from dialog
}
For the method that is called when the user closes the dialog:
public synchronized void closeChooser() {
notifyAll();
super.closeChooser(); // or whatever it's called
}
The correct solution is to have two methods: one to open the colour pick dialog and then a second which is called when the dialog closes. I don't know what capabilities aero.colorpicker.Frame has but if it doesn't provide this then you could subclass it and override whatever method is called when the user accepts or cancels.

How to Update Image in an Applet

How do i get an java applet to search an image from the specified path. I want to make a simple imageviewer applet which has 2 buttons NEXT,PREV . By clicking Next it should show next image and by clicking prev it should show the previous image.
i have written the following code .Please help me in writing the code for the updatenext() and updateprev() function.
public class pic extends Applet implements ActionListener
{
Button prev,next;
private static final String PREV="Previous";
private static final String NEXT="Next";
Image img;
public void init()
{
img=getImage(getCodeBase(),"image1.jpg");
prev = new Button();
prev.setLabel(PREV);
prev.setActionCommand(PREV);
prev.addActionListener(this);
add(prev);
next = new Button();
next.setLabel(NEXT);
next.setActionCommand(NEXT);
next.addActionListener(this);
add(next);
}
public void paint(Graphics g)
{
g.drawImage(img,0,0,600,700,this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals(NEXT))
updatenext();
else if(e.getActionCommand().equals(PREV))
updateprev();
}
void updatenext()
{
//updateImagehere
}
void updateprev()
{
//updateimage here
repaint();
}
}
A very simple example is this.
import java.applet.*;
import java.awt.*;
public class AppletImage extends Applet{
Image img;
MediaTracker tr;
public void paint(Graphics g) {
tr = new MediaTracker(this);
img = getImage(getCodeBase(), "demoimg.gif");
tr.addImage(img,0);
g.drawImage(img, 0, 0, this);
}
public static void main(String args[]){
AppletImage appletImage = new AppletImage();
appletImage.setVisible(true);
}
}
try this and ya u can take image according to your self.
If you want to get a list of the files in the location of your applet you can create a File object of the current directory with:
File currentDir = new File(getCodeBase().getPath());
Then to iterate over the files call:
for (File file : currentDir.listFiles()) {
// do something with the file
}
You will need to filter out directories and non image files, I would suggest you use a FileNameFilter as an argument when calling listFiles().
EDIT:
Here's an example of the solution you could use with this method:
public class pic extends Applet implements ActionListener
{
Button prev, next;
private static final String PREV = "Previous";
private static final String NEXT = "Next";
Image img;
private File[] imageFiles;
private int currentIndex = 0;
public void init()
{
File baseDir = new File(getCodeBase().getPath());
imageFiles = baseDir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
String image = ".*\\.(png|jpg|jpeg|gif)";
Pattern pattern = Pattern.compile(image);
Matcher matcher = pattern.matcher(name.toLowerCase());
return matcher.matches();
}
});
setImage();
prev = new Button();
prev.setLabel(PREV);
prev.setActionCommand(PREV);
prev.addActionListener(this);
add(prev);
next = new Button();
next.setLabel(NEXT);
next.setActionCommand(NEXT);
next.addActionListener(this);
add(next);
}
public void paint(Graphics g)
{
g.drawImage(img, 0, 0, 600, 700, this);
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals(NEXT))
updatenext();
else if (e.getActionCommand().equals(PREV))
updateprev();
}
private void setImage() {
img = getImage(getCodeBase(), imageFiles[currentIndex].getName());
}
void updatenext()
{
// needs circular increment
if (currentIndex == imageFiles.length - 1) {
currentIndex = 0;
} else {
currentIndex++;
}
setImage();
repaint();
}
void updateprev()
{
// needs circular decrement
if (currentIndex == 0) {
currentIndex = imageFiles.length-1;
} else {
currentIndex--;
}
setImage();
repaint();
}
}

how to add full image in JDialog this dialog is created by JOptionPane

my question is i want to add full background image if JDialog, this JDialog is created by JOptionPane. This image does not cover full Dialog.
If you have any solution please let me know.
public class BrowseFilePath {
public static final String DIALOG_NAME = "what-dialog";
public static final String PANE_NAME = "what-pane";
private static JDialog loginRegister;
private static String path;
private static JPanel Browse_panel = new JPanel(new BorderLayout());
private static JLabel pathLbl = new JLabel("Please Choose Folder / File");
private static JTextField regtxt_file = new JTextField(30);
private static JButton browse_btn = new JButton("Browse");
private static JButton ok_btn = new JButton("Ok");
private static JButton close_btn = new JButton("Cancel");
/*public static void main(String [] arg){
showFileDialog();
}*/
public static void showFileDialog() {
JOptionPane.setDefaultLocale(null);
JOptionPane pane = new JOptionPane(createRegInputComponent());
pane.setName(PANE_NAME);
loginRegister = pane.createDialog("ShareBLU");
/* try {
loginRegister.setContentPane(new JLabel(new ImageIcon(ImageIO.read(AlertWindow.getBgImgFilePath()))));
} catch (IOException e) {
e.printStackTrace();
}*/
loginRegister.setName(DIALOG_NAME);
loginRegister.setSize(380,150);
loginRegister.setVisible(true);
if(pane.getInputValue().equals("Ok")){
String getTxt = regtxt_file.getText();
BrowseFilePath.setPath(getTxt);
}
else if(pane.getInputValue().equals("Cancel")){
regtxt_file.setText("");
System.out.println("Pressed Cancel Button =======********=");
System.exit(0);
}
}
public static String getPath() {
return path;
}
public static void setPath(String path) {
BrowseFilePath.path = path;
}
private static JComponent createRegInputComponent() {
Browse_panel = new JBackgroundPanel();
Browse_panel.setLayout(new BorderLayout());
Box rows = Box.createVerticalBox();
Browse_panel.setBounds(0,0,380,150);
Browse_panel.add(pathLbl);
pathLbl.setForeground(Color.white);
pathLbl.setBounds(20, 20, 200, 20);
Browse_panel.add(regtxt_file);
regtxt_file.setToolTipText("Select File/Folder..");
regtxt_file.setBounds(20, 40, 220, 20);
Browse_panel.add(browse_btn);
browse_btn.setToolTipText("Browse");
browse_btn.setBounds(250, 40, 90, 20);
Browse_panel.add(ok_btn);
ok_btn.setToolTipText("Ok");
ok_btn.setBounds(40, 75, 80, 20);
Browse_panel.add(close_btn);
close_btn.setToolTipText("Cancel");
close_btn.setBounds(130, 75, 80, 20);
ActionListener chooseMe = createChoiceAction();
ok_btn.addActionListener(chooseMe);
close_btn.addActionListener(chooseMe);
browse_btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
int selection = JFileChooser.FILES_AND_DIRECTORIES;
fileChooser.setFileSelectionMode(selection);
fileChooser.setAcceptAllFileFilterUsed(false);
int rVal = fileChooser.showOpenDialog(null);
if (rVal == JFileChooser.APPROVE_OPTION) {
path = fileChooser.getSelectedFile().toString();
regtxt_file.setText(path);
}
}
});
rows.add(Box.createVerticalStrut(105));
Browse_panel.add(rows,BorderLayout.CENTER);
return Browse_panel;
}
public static ActionListener createChoiceAction() {
ActionListener chooseMe = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JButton choice = (JButton) e.getSource();
// find the pane so we can set the choice.
Container parent = choice.getParent();
while (!PANE_NAME.equals(parent.getName())) {
parent = parent.getParent();
}
JOptionPane pane = (JOptionPane) parent;
pane.setInputValue(choice.getText());
// find the dialog so we can close it.
while ((parent != null) && !DIALOG_NAME.equals(parent.getName()))
{
parent = parent.getParent();
//parent.setBounds(0, 0, 350, 150);
}
if (parent != null) {
parent.setVisible(false);
}
}
};
return chooseMe;
}
}
Don't use JOptionPane but use a full-blown JDialog. Set the content pane to a JComponent that overrides paintComponent() and returns an appropriate getPreferredSize().
Example code below:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestBackgroundImage {
private static final String BACKHGROUND_IMAGE_URL = "http://cache2.allpostersimages.com/p/LRG/27/2740/AEPND00Z/affiches/blue-fiber-optic-wires-against-black-background.jpg";
protected void initUI() throws MalformedURLException {
JDialog dialog = new JDialog((Frame) null, TestBackgroundImage.class.getSimpleName());
dialog.setModal(true);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
final ImageIcon backgroundImage = new ImageIcon(new URL(BACKHGROUND_IMAGE_URL));
JPanel mainPanel = new JPanel(new BorderLayout()) {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(backgroundImage.getImage(), 0, 0, getWidth(), getHeight(), this);
}
#Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.width = Math.max(backgroundImage.getIconWidth(), size.width);
size.height = Math.max(backgroundImage.getIconHeight(), size.height);
return size;
}
};
mainPanel.add(new JButton("A button"), BorderLayout.WEST);
dialog.add(mainPanel);
dialog.setSize(400, 300);
dialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new TestBackgroundImage().initUI();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Don't forget to provide an appropriate parent Frame

Screenshot program

I'm making a screenshot program so when you press the screenshot button, a JMessageDial pops up and prompts you with your image, it the tells you to drag your mouse and make a box around the area that you want to take a screenshot of. I can't seem to find how to get the image inside the box when the user clicks okay.
So what I need help with is getting the image inside of the rectangle the user "draws" with his mouse, and store that in a variable.
Here is the specific code:
public void selectArea(final BufferedImage screen) throws Exception {
final BufferedImage screenCopy = new BufferedImage(screen.getWidth(), screen.getHeight(), screen.getType());
final JLabel screenLabel = new JLabel(new ImageIcon(screenCopy));
JScrollPane screenScroll = new JScrollPane(screenLabel);
screenScroll.setPreferredSize(new Dimension((int)(screen.getWidth()/2), (int)(screen.getHeight()/2)));
JPanel panel = new JPanel(new BorderLayout());
panel.add(screenScroll, BorderLayout.CENTER);
final JLabel selectionLabel = new JLabel("Draw a rectangle");
panel.add(selectionLabel, BorderLayout.SOUTH);
repaint(screen, screenCopy);
screenLabel.repaint();
screenLabel.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseMoved(MouseEvent me) {
start = me.getPoint();
repaint(screen, screenCopy);
selectionLabel.setText("Start Point: " + start);
screenLabel.repaint();
}
#Override
public void mouseDragged(MouseEvent me) {
end = me.getPoint();
captureRect = new Rectangle(start, new Dimension(end.x-start.x, end.y-start.y));
try {
paintFinalImage(new BufferedImage((int)screenCopy.getGraphics().getClipBounds(captureRect).getWidth()+1,
(int)screenCopy.getGraphics().getClipBounds(captureRect).getHeight()+1, screen.getType()));
} catch (Exception e) {
e.printStackTrace();
}
repaint(screen, screenCopy);
screenLabel.repaint();
selectionLabel.setText("Rectangle: " + captureRect);
}
});
JOptionPane.showMessageDialog(null, panel, "Select your image", JOptionPane.OK_OPTION, new ImageIcon(""));
uploadImage(screenShot);
System.out.println("Final rectangle: " + screenCopy.getGraphics().getClipBounds(captureRect));
}
And this is the full class if you need it:
package com.screencapture;
import java.awt.*;
public class Main implements ActionListener, ItemListener, KeyListener, NativeKeyListener {
private final Image icon = Toolkit.getDefaultToolkit().getImage("./data/icon.gif");
private final TrayIcon trayIcon = new TrayIcon(icon, "Screen Snapper");
private JFrame frame;
private Rectangle captureRect;
private JComboBox<String> imageType;
private boolean hideWhenMinimized = false;
private final String API_KEY = "b84e430b4a65d16a6955358141f21a61";
private static Robot robot;
private BufferedImage screenShot;
private Point end;
private Point start;
public static void main(String[] args) throws Exception {
robot = new Robot();
new Main().start();
}
public void start() throws Exception {
GlobalScreen.getInstance().registerNativeHook();
GlobalScreen.getInstance().addNativeKeyListener(this);
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
frame = new JFrame("White power!");
frame.setPreferredSize(new Dimension(250, 250));
frame.getContentPane().setLayout(null);
frame.setIconImage(icon);
frame.addKeyListener(this);
frame.addWindowListener(new WindowListener() {
#Override
public void windowOpened(WindowEvent e) {}
#Override
public void windowClosing(WindowEvent e) {}
#Override
public void windowClosed(WindowEvent e) {}
#Override
public void windowIconified(WindowEvent e) {
if (hideWhenMinimized)
frame.setVisible(false);
}
#Override
public void windowDeiconified(WindowEvent e) {}
#Override
public void windowActivated(WindowEvent e) {}
#Override
public void windowDeactivated(WindowEvent e) {}
});
JLabel lblImageType = new JLabel("Image Format:");
lblImageType.setBounds(10, 11, 90, 14);
frame.getContentPane().add(lblImageType);
String[] imageTypes = {"PNG", "JPG"};
imageType = new JComboBox<String>(imageTypes);
imageType.setBounds(106, 8, 51, 20);
frame.getContentPane().add(imageType);
JButton btnTakeScreenShot = new JButton("ScreenShot");
btnTakeScreenShot.setBounds(24, 69, 115, 23);
frame.getContentPane().add(btnTakeScreenShot);
btnTakeScreenShot.addActionListener(this);
setTrayIcon();
frame.pack();
frame.setVisible(true);
}
public void setTrayIcon() throws AWTException {
CheckboxMenuItem startup = new CheckboxMenuItem("Run on start-up");
CheckboxMenuItem hide = new CheckboxMenuItem("Hide when minimized");
String[] popupMenuOptions = {"Open", "Exit"};
if (SystemTray.isSupported()) {
SystemTray tray = SystemTray.getSystemTray();
trayIcon.setImageAutoSize(true);
PopupMenu popupMenu = new PopupMenu();
for (String option : popupMenuOptions) {
if (option == "Exit") {
popupMenu.add(startup);
popupMenu.add(hide);
popupMenu.add(option);
} else {
popupMenu.add(option);
}
}
trayIcon.setPopupMenu(popupMenu);
popupMenu.addActionListener(this);
startup.addItemListener(this);
hide.addItemListener(this);
trayIcon.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.setVisible(true);
}
});
tray.add(trayIcon);
}
}
public void selectArea(final BufferedImage screen) throws Exception {
final BufferedImage screenCopy = new BufferedImage(screen.getWidth(), screen.getHeight(), screen.getType());
final JLabel screenLabel = new JLabel(new ImageIcon(screenCopy));
JScrollPane screenScroll = new JScrollPane(screenLabel);
screenScroll.setPreferredSize(new Dimension((int)(screen.getWidth()/2), (int)(screen.getHeight()/2)));
JPanel panel = new JPanel(new BorderLayout());
panel.add(screenScroll, BorderLayout.CENTER);
final JLabel selectionLabel = new JLabel("Draw a rectangle");
panel.add(selectionLabel, BorderLayout.SOUTH);
repaint(screen, screenCopy);
screenLabel.repaint();
screenLabel.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseMoved(MouseEvent me) {
start = me.getPoint();
repaint(screen, screenCopy);
selectionLabel.setText("Start Point: " + start);
screenLabel.repaint();
}
#Override
public void mouseDragged(MouseEvent me) {
end = me.getPoint();
captureRect = new Rectangle(start, new Dimension(end.x-start.x, end.y-start.y));
try {
paintFinalImage(new BufferedImage((int)screenCopy.getGraphics().getClipBounds(captureRect).getWidth()+1,
(int)screenCopy.getGraphics().getClipBounds(captureRect).getHeight()+1, screen.getType()));
} catch (Exception e) {
e.printStackTrace();
}
repaint(screen, screenCopy);
screenLabel.repaint();
selectionLabel.setText("Rectangle: " + captureRect);
}
});
JOptionPane.showMessageDialog(null, panel, "Select your image", JOptionPane.OK_OPTION, new ImageIcon(""));
uploadImage(screenShot);
System.out.println("Final rectangle: " + screenCopy.getGraphics().getClipBounds(captureRect));
}
public void paintFinalImage(BufferedImage image) throws Exception {
screenShot = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
Graphics2D g = screenShot.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
}
public void repaint(BufferedImage orig, BufferedImage copy) {
Graphics2D g = copy.createGraphics();
g.drawImage(orig, 0, 0, null);
if (captureRect != null) {
g.setColor(Color.BLACK);
g.draw(captureRect);
}
g.dispose();
}
public void uploadImage(BufferedImage image) throws Exception {
String IMGUR_POST_URI = "http://api.imgur.com/2/upload.xml";
String IMGUR_API_KEY = API_KEY;
String readLine = null;
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(image, imageType.getSelectedItem().toString(), outputStream);
URL url = new URL(IMGUR_POST_URI);
String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(Base64.encodeBase64String(outputStream.toByteArray()).toString(), "UTF-8");
data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(IMGUR_API_KEY, "UTF-8");
URLConnection urlConnection = url.openConnection();
urlConnection.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data);
wr.flush();
InputStream inputStream;
if (((HttpURLConnection) urlConnection).getResponseCode() == 400) {
inputStream = ((HttpURLConnection) urlConnection).getErrorStream();
} else {
inputStream = urlConnection.getInputStream();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
readLine = line;
}
wr.close();
reader.close();
} catch(Exception e){
e.printStackTrace();
}
String URL = readLine.substring(readLine.indexOf("<original>") + 10, readLine.indexOf("</original>"));
System.out.println(URL);
Toolkit.getDefaultToolkit().beep();
StringSelection stringSelection = new StringSelection(URL);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
}
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
System.out.println(command);
if (command.equalsIgnoreCase("open")) {
frame.setVisible(true);
} else if (command.equalsIgnoreCase("exit")) {
System.exit(-1);
} else if (command.equalsIgnoreCase("screenshot")) {
try {
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
final BufferedImage screen = robot.createScreenCapture(new Rectangle(screenSize));
selectArea(screen);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
#Override
public void itemStateChanged(ItemEvent e) {
System.out.println(e.getItem() + ", " +e.getStateChange());
String itemChanged = e.getItem().toString();
if (itemChanged.equalsIgnoreCase("run on start-up")) {
//TODO
} else if (itemChanged.equalsIgnoreCase("hide when minimized")) {
if (e.getStateChange() == ItemEvent.DESELECTED) {
hideWhenMinimized = false;
} else if (e.getStateChange() == ItemEvent.SELECTED) {
hideWhenMinimized = true;
}
}
}
#Override
public void keyTyped(KeyEvent e) {
System.out.println("KeyTyped: "+e.getKeyCode());
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void nativeKeyPressed(NativeKeyEvent e) {
}
#Override
public void nativeKeyReleased(NativeKeyEvent e) {
System.out.println("KeyReleased: "+e.getKeyCode());
System.out.println(KeyEvent.getKeyText(e.getKeyCode()));
if (e.getKeyCode() == 154) {
try {
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
final BufferedImage screen = robot.createScreenCapture(new Rectangle(screenSize));
selectArea(screen);
frame.setVisible(true);
} catch(Exception e1) {
e1.printStackTrace();
}
}
}
#Override
public void nativeKeyTyped(NativeKeyEvent e) {
}
}
I recommend that you simplify your problem to solve it. Create a small compilable and runnable program that doesn't have all the baggage of your current code, but whose only goal is to display an image, and let the user select a sub-portion of that image. Then if your attempt fails, you can post your attempt here, and we can actually both run it, and understand it, and hopefully then be able to fix it.
For example, here's a small bit of compilable and runnable code that uses a MouseListener to select a small section of an image. Perhaps you can get some ideas from it:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class ImagePlay extends JPanel {
public static final String IMAGE_PATH = "http://upload.wikimedia.org/wikipedia/" +
"commons/thumb/3/39/European_Common_Frog_Rana_temporaria.jpg/" +
"800px-European_Common_Frog_Rana_temporaria.jpg";
private static final Color RECT_COLOR = new Color(180, 180, 255);
private BufferedImage img = null;
Point p1 = null;
Point p2 = null;
public ImagePlay() {
URL imgUrl;
try {
imgUrl = new URL(IMAGE_PATH);
img = ImageIO.read(imgUrl );
ImageIcon icon = new ImageIcon(img);
JLabel label = new JLabel(icon) {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
myLabelPaint(g);
}
};
setLayout(new BorderLayout());
add(new JScrollPane(label));
MouseAdapter mAdapter = new MyMouseAdapter();
label.addMouseListener(mAdapter);
label.addMouseMotionListener(mAdapter);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void myLabelPaint(Graphics g) {
if (p1 != null && p2 != null) {
int x = Math.min(p1.x, p2.x);
int y = Math.min(p1.y, p2.y);
int width = Math.abs(p1.x - p2.x);
int height = Math.abs(p1.y - p2.y);
g.setXORMode(Color.DARK_GRAY);
g.setColor(RECT_COLOR);
g.drawRect(x, y, width, height);
}
}
private class MyMouseAdapter extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
p1 = e.getPoint();
p2 = null;
repaint();
}
#Override
public void mouseDragged(MouseEvent e) {
p2 = e.getPoint();
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
p2 = e.getPoint();
repaint();
int x = Math.min(p1.x, p2.x);
int y = Math.min(p1.y, p2.y);
int width = Math.abs(p1.x - p2.x);
int height = Math.abs(p1.y - p2.y);
BufferedImage smlImg = img.getSubimage(x, y, width, height);
ImageIcon icon = new ImageIcon(smlImg);
JLabel label = new JLabel(icon);
JOptionPane.showMessageDialog(ImagePlay.this, label, "Selected Image",
JOptionPane.PLAIN_MESSAGE);
}
}
private static void createAndShowGui() {
ImagePlay mainPanel = new ImagePlay();
JFrame frame = new JFrame("ImagePlay");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
It uses a publicly available image obtained online, a MouseListener that's added to a JLabel, and the JLabel has its paintComponent(...) method overridden so as to show the guide lines from the MouseListener/Adapter. It creates the sub image via BufferedImage's getSubimage(...) method, and then it displays it in a JOptionPane, but it would be trivial to save the image if desired.

JFrame.setVisible(false) and Robot.createScreenCapture timing

I'm trying to capture the screen without including my application's window. To do this I first call setVisible(false), then I call the createScreenCapture method, and finally I call setVisible(true). This isn't working however and I'm still getting my applications window in the screen capture. If I add a call to sleep this seems to resolve the issue, but I know this is bad practice. What is the right way to do this?
Code:
setVisible(false);
BufferedImage screen = robot.createScreenCapture(rectScreenSize);
setVisible(true);
Have you tried to use SwingUtilities.invokeLater() and run the capture inside of the runnable passed as an argument? My guess is that the repaint performed to remove your application is performed right after the end of the current event in the AWT-EventQueue and thus invoking the call immediately still captures your window. Invoking the createCapture in a delayed event through invokeLater should fix this.
you have to delay this action by implements Swing Timer, for example
import javax.imageio.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
public class CaptureScreen implements ActionListener {
private JFrame f = new JFrame("Screen Capture");
private JPanel pane = new JPanel();
private JButton capture = new JButton("Capture");
private JDialog d = new JDialog();
private JScrollPane scrollPane = new JScrollPane();
private JLabel l = new JLabel();
private Point location;
private Timer timer1;
public CaptureScreen() {
capture.setActionCommand("CaptureScreen");
capture.setFocusPainted(false);
capture.addActionListener(this);
capture.setPreferredSize(new Dimension(300, 50));
pane.add(capture);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(pane);
f.setLocation(100, 100);
f.pack();
f.setVisible(true);
createPicContainer();
startTimer();
}
private void createPicContainer() {
l.setPreferredSize(new Dimension(700, 500));
scrollPane = new JScrollPane(l,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setBackground(Color.white);
scrollPane.getViewport().setBackground(Color.white);
d.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
d.add(scrollPane);
d.pack();
d.setVisible(false);
d.addWindowListener(new WindowListener() {
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
f.setVisible(true);
}
public void windowClosed(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
});
}
private void startTimer() {
timer1 = new Timer(1000, new AbstractAction() {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
capture.doClick();
f.setVisible(false);
}
});
}
});
timer1.setDelay(500);
timer1.setRepeats(false);
timer1.start();
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("CaptureScreen")) {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); // gets the screen size
Robot r;
BufferedImage bI;
try {
r = new Robot(); // creates robot not sure exactly how it works
Thread.sleep(1000); // waits 1 second before capture
bI = r.createScreenCapture(new Rectangle(dim)); // tells robot to capture the screen
showPic(bI);
saveImage(bI);
} catch (AWTException e1) {
e1.printStackTrace();
} catch (InterruptedException e2) {
e2.printStackTrace();
}
}
}
private void saveImage(BufferedImage bI) {
try {
ImageIO.write(bI, "JPG", new File("screenShot.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
private void showPic(BufferedImage bI) {
ImageIcon pic = new ImageIcon(bI);
l.setIcon(pic);
l.revalidate();
l.repaint();
d.setVisible(false);
//location = f.getLocationOnScreen();
//int x = location.x;
//int y = location.y;
//d.setLocation(x, y + f.getHeight());
d.setLocation(150, 150);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
d.setVisible(true);
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
CaptureScreen cs = new CaptureScreen();
}
});
}
}

Categories