Browse for image file and display it using Java Swing - java

My problem here is,
after clicking Browse button it displays all files in a directory to choose,
then the chosen image is displayed in GUI correctly. But When i click Browse button
for the second time, it shows the old image only instead of showing the new one. Please help me in this.
For reference, i uploaded the UI.
package GUI;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
#SuppressWarnings("serial")
public class MainAppFrame extends JFrame {
private JPanel contentPane;
File targetFile;
BufferedImage targetImg;
public JPanel panel,panel_1;
private static final int baseSize = 128;
private static final String basePath =
"C:\\Documents and Settings\\Administrator\\Desktop\\Images";
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainAppFrame frame = new MainAppFrame();
frame.setVisible(true);
frame.setResizable(false);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainAppFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 550, 400);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
panel = new JPanel();
panel.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
contentPane.add(panel, BorderLayout.WEST);
JButton btnBrowse = new JButton("Browse");
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
browseButtonActionPerformed(e);
}
});
JLabel lblSelectTargetPicture = new JLabel("Select target picture..");
JButton btnDetect = new JButton("Detect");
btnDetect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
JButton btnAddDigit = new JButton("Add Digit");
btnAddDigit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
JButton button = new JButton("Recognize");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
panel_1 = new JPanel();
panel_1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
GroupLayout gl_panel = new GroupLayout(panel);
gl_panel.setHorizontalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGap(6)
.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addComponent(lblSelectTargetPicture)
.addGap(6)
.addComponent(btnBrowse))
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(btnDetect)
.addGap(18)
.addComponent(btnAddDigit))))
.addGroup(gl_panel.createSequentialGroup()
.addGap(50)
.addComponent(button))
.addGroup(gl_panel.createSequentialGroup()
.addContainerGap()
.addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 182, GroupLayout.PREFERRED_SIZE))
);
gl_panel.setVerticalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGap(7)
.addComponent(lblSelectTargetPicture))
.addGroup(gl_panel.createSequentialGroup()
.addGap(3)
.addComponent(btnBrowse)))
.addGap(18)
.addComponent(panel_1, GroupLayout.PREFERRED_SIZE, 199, GroupLayout.PREFERRED_SIZE)
.addGap(22)
.addGroup(gl_panel.createParallelGroup(Alignment.BASELINE)
.addComponent(btnDetect)
.addComponent(btnAddDigit))
.addGap(18)
.addComponent(button)
.addContainerGap())
);
panel.setLayout(gl_panel);
}
public BufferedImage rescale(BufferedImage originalImage)
{
BufferedImage resizedImage = new BufferedImage(baseSize, baseSize, BufferedImage.TYPE_INT_RGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, baseSize, baseSize, null);
g.dispose();
return resizedImage;
}
public void setTarget(File reference)
{
try {
targetFile = reference;
targetImg = rescale(ImageIO.read(reference));
} catch (IOException ex) {
Logger.getLogger(MainAppFrame.class.getName()).log(Level.SEVERE, null, ex);
}
panel_1.setLayout(new BorderLayout(0, 0));
panel_1.add(new JLabel(new ImageIcon(targetImg)));
setVisible(true);
}
private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc = new JFileChooser(basePath);
fc.setFileFilter(new JPEGImageFileFilter());
int res = fc.showOpenDialog(null);
// We have an image!
try {
if (res == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
setTarget(file);
} // Oops!
else {
JOptionPane.showMessageDialog(null,
"You must select one image to be the reference.", "Aborting...",
JOptionPane.WARNING_MESSAGE);
}
} catch (Exception iOException) {
}
}
}
//JPEGImageFileFilter.java
package GUI;
import java.io.File;
import javax.swing.filechooser.FileFilter;
/*
* This class implements a generic file name filter that allows the listing/selection
* of JPEG files.
*/
public class JPEGImageFileFilter extends FileFilter implements java.io.FileFilter
{
public boolean accept(File f)
{
if (f.getName().toLowerCase().endsWith(".jpeg")) return true;
if (f.getName().toLowerCase().endsWith(".jpg")) return true;
if(f.isDirectory())return true;
return false;
}
public String getDescription()
{
return "JPEG files";
}
}

Each time a new image is selected, you're creating components unnecessarily and in error here:
public void setTarget(File reference) {
//....
panel_1.setLayout(new BorderLayout(0, 0));
panel_1.add(new JLabel(new ImageIcon(targetImg)));
setVisible(true);
Instead I would recommend that you have all these components created from the get-go, before any file/image has been selected, and then in this method, create an ImageIcon from the Image, and then simply use this Icon to set the Icon of an already existng JLabel rather than a new JLabel. This is done simply by calling myLabel.setIcon(new ImageIcon(targetImg));

Create an ImageViewer with method like ImageViewer.setImage(Image), display the image in a JLabel.
ImageViewer
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.util.Random;
public class ImageViewer {
JPanel gui;
/** Displays the image. */
JLabel imageCanvas;
/** Set the image as icon of the image canvas (display it). */
public void setImage(Image image) {
imageCanvas.setIcon(new ImageIcon(image));
}
public void initComponents() {
if (gui==null) {
gui = new JPanel(new BorderLayout());
gui.setBorder(new EmptyBorder(5,5,5,5));
imageCanvas = new JLabel();
JPanel imageCenter = new JPanel(new GridBagLayout());
imageCenter.add(imageCanvas);
JScrollPane imageScroll = new JScrollPane(imageCenter);
imageScroll.setPreferredSize(new Dimension(300,100));
gui.add(imageScroll, BorderLayout.CENTER);
}
}
public Container getGui() {
initComponents();
return gui;
}
public static Image getRandomImage(Random random) {
int w = 100 + random.nextInt(400);
int h = 50 + random.nextInt(200);
BufferedImage bi = new BufferedImage(
w,h,BufferedImage.TYPE_INT_RGB);
return bi;
}
public static void main(String[] args) throws Exception {
Runnable r = new Runnable() {
#Override
public void run() {
JFrame f = new JFrame("Image Viewer");
// TODO Fix kludge to kill the Timer
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final ImageViewer viewer = new ImageViewer();
f.setContentPane(viewer.getGui());
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
ActionListener animate = new ActionListener() {
Random random = new Random();
#Override
public void actionPerformed(ActionEvent arg0) {
viewer.setImage(getRandomImage(random));
}
};
Timer timer = new Timer(1500,animate);
timer.start();
}
};
SwingUtilities.invokeLater(r);
}
}

I modified your code , I hope it will fulfill your requirement. I use MigLayout (it is a Layout manager) to arrange the component.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;
public class MyFileChooser
{
JFrame frame;
JPanel panel;
JButton btnBrowse;
JButton change;
JLabel imglabel;
File targetFile;
BufferedImage targetImg;
private static final int baseSize = 128;
private static final String basePath ="/images/fimage";
JPanel panel_1;
ImageIcon icon;
public MyFileChooser()
{
// TODO Auto-generated constructor stub
frame =new JFrame();
frame.setLayout(new MigLayout());
frame.setSize(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel=new JPanel(new MigLayout());
panel_1 = new JPanel();
panel_1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(5, 5, 5), 1, true));
panel_1.setBackground(Color.pink);
btnBrowse=new JButton("browse");
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
browseButtonActionPerformed(e);
}
});
change=new JButton("Delete");
change.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
changeButtonActionPerformed(e);
}
private void changeButtonActionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
imglabel.revalidate(); //ADD THIS AS WELL
imglabel.repaint(); //ADD THIS AS WELL
imglabel.setIcon(null);
System.out.println("delete button activated");
}
});
imglabel=new JLabel("Image");
imglabel.setSize(100, 100);
imglabel.setBackground(Color.yellow);
frame.add(panel_1,"span,pushx,pushy,growx,growy");
frame.add(btnBrowse);
frame.add(change,"");
//frame.pack();
}
protected void browseButtonActionPerformed(ActionEvent e)
{
JFileChooser fc = new JFileChooser(basePath);
fc.setFileFilter(new JPEGImageFileFilter());
int res = fc.showOpenDialog(null);
// We have an image!
try {
if (res == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
imglabel.setIcon(null);
setTarget(file);
} // Oops!
else {
JOptionPane.showMessageDialog(null,
"You must select one image to be the reference.", "Aborting...",
JOptionPane.WARNING_MESSAGE);
}
} catch (Exception iOException) {
}
}
public BufferedImage rescale(BufferedImage originalImage)
{
BufferedImage resizedImage = new BufferedImage(baseSize, baseSize, BufferedImage.TYPE_INT_RGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, baseSize, baseSize, null);
g.dispose();
return resizedImage;
}
public void setTarget(File reference)
{
try {
targetFile = reference;
targetImg = rescale(ImageIO.read(reference));
} catch (IOException ex) {
// Logger.getLogger(MainAppFrame.class.getName()).log(Level.SEVERE, null, ex);
}
panel_1.setLayout(new BorderLayout(0, 0));
icon=new ImageIcon(targetImg);
imglabel=new JLabel(icon);
panel_1.add(imglabel);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
new MyFileChooser();
}
});
}
}
JPEGImageFileFilter class , you can keep this class in same pakage
import java.io.File;
import javax.swing.filechooser.FileFilter;
public class JPEGImageFileFilter extends FileFilter implements FileFilter
{
public boolean accept(File f)
{
if (f.getName().toLowerCase().endsWith(".jpeg")) return true;
if (f.getName().toLowerCase().endsWith(".jpg")) return true;
if(f.isDirectory())return true;
return false;
}
public String getDescription()
{
return "JPEG files";
}
}

Related

Java OpenCV Video capture cut off

i am Brand new to OpenCV in java been trying to create an image capture program which both records the user and allows images to be moved to the captured image area on the GUI, my only issue is the recording seems to be cut off even when I specified a region for where it should be displayed, any help will be highly appricated.
package gesture.recognition;
import com.sun.xml.internal.ws.api.Component;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.*;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.*;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.core.Size;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.videoio.VideoCapture;
import static org.opencv.videoio.Videoio.CV_CAP_PROP_FRAME_HEIGHT;
import static org.opencv.videoio.Videoio.CV_CAP_PROP_FRAME_WIDTH;
public class GestureRecognition extends javax.swing.JFrame {
private DaemonThread myThread = null;
int count = 0;
VideoCapture webSource = null;
Mat vid = new Mat();
MatOfByte mem = new MatOfByte();
int CANVAS_INITIAL_WIDTH =400;
int CANVAS_INITIAL_HEIGHT =500;
int Video_display=400;
int Button_Area=200;
float h,s,v;
int alpha,r,g,b;
BufferedImage img = null;
File f = null;
Mat hsv = new Mat();
class Canvas extends JPanel
{
// Called every time there is a change in the canvas contents.
public void paintComponent(Graphics g)
{
super.paintComponent(g);
draw(g);
}
}
class DaemonThread implements Runnable
{
protected volatile boolean runnable = false;
#Override
public void run()
{
synchronized(this)
{
while(runnable)
{
if(webSource.grab())
{
try
{
webSource.retrieve(vid);
Imgcodecs.imencode(".jpg", vid, mem);
Image im = ImageIO.read(new ByteArrayInputStream(mem.toArray()));
BufferedImage buff = (BufferedImage) im;
Graphics g=freehandSliderPanel.getGraphics();
if (g.drawImage(im, 0, 0, null));
// if (g.drawImage(buff,0, 0, getWidth(), getHeight() -150 , 0 , 0, buff.getWidth(), buff.getHeight(),null))
if(runnable == false)
{
System.out.println("Going to wait()");
this.wait();
}
}
catch(IOException | InterruptedException ex)
{
System.out.println("Error");
}
}
}
}
}
}
private Canvas canvas;
private JPanel controlPanel;
private JPanel messageArea;
private JButton jButton1;
private JPanel freehandSliderPanel;
public GestureRecognition()
{
setTitle("Gesture Recognition");
setLayout(new BorderLayout()); // Layout manager for the frame.
// Canvas
canvas = new Canvas();
canvas.setBorder(new TitledBorder(new EtchedBorder(), "Video"));
canvas.setPreferredSize(new Dimension(CANVAS_INITIAL_WIDTH, CANVAS_INITIAL_HEIGHT));
add(canvas, BorderLayout.WEST);
controlPanel = new JPanel();
controlPanel.setBorder(new TitledBorder(new EtchedBorder(), "Picture"));
controlPanel.setPreferredSize(new Dimension(Video_display, CANVAS_INITIAL_HEIGHT));
// the following two lines put the control panel in a scroll pane (nicer?).
JScrollPane controlPanelScrollPane = new JScrollPane(controlPanel);
controlPanelScrollPane.setPreferredSize(new Dimension(Video_display + 30, CANVAS_INITIAL_HEIGHT));
add(controlPanelScrollPane, BorderLayout.EAST);
messageArea = new JPanel();
messageArea.setBackground(canvas.getBackground());
messageArea.setBorder(new TitledBorder(new EtchedBorder(), "Message Area"));
messageArea.setPreferredSize(new Dimension(Video_display + CANVAS_INITIAL_WIDTH, Button_Area));
add(messageArea, BorderLayout.SOUTH);
jButton1 = new JButton("Start Video");
jButton1.setPreferredSize(new Dimension(Button_Area - 10, 50));
messageArea.add(jButton1);
freehandSliderPanel = new JPanel();
freehandSliderPanel.setPreferredSize(new Dimension(CANVAS_INITIAL_WIDTH - 20, 90));
canvas.setLayout(new GridLayout(0, 1));
freehandSliderPanel.setBorder(new TitledBorder(new EtchedBorder(), "Display"));
canvas.add(freehandSliderPanel,BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
jButton1.setText("Video Capture");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
}
void draw(Graphics g)
{
}// end draw method
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
webSource =new VideoCapture(0);
myThread = new DaemonThread();
Thread t = new Thread(myThread);
t.setDaemon(true);
myThread.runnable = true;
t.start();
jButton1.setEnabled(false); //start button
// jButton2.setEnabled(true); // stop button
}
public static void main(String args[]) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
GestureRecognition GestureRecognitionInstance = new GestureRecognition();
/*Create and display the form */
/* java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
}
});
*/ }
}
So far it displays the GUI but as you can see it simply cuts off the image like so
Example image

JScrollPane and Zooming Images

I'm trying to write a simple class that extends from JPanel that can zoom in and zoom out on an image and then uses a JScrollPane at the top level to allow someone to scroll back and forth across the zoomed image. I've having trouble with the JScrollPane portion.
When clicking one of the zoom buttons (whether it be in, out, or reset), the button must be clicked twice in order for the JScrollBars to appear(or in the case of the reset button, disappear). Even after they've appear if you continue to zoom in or out the bars do not update according to the new level of zoom. Resizing the window fixes this issue but I'm looking for a more concrete solution.
ImagePanel Code:
package com.zephyr.graphics;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class ImagePanel extends JPanel implements PropertyChangeListener{
private File imageFile;
private BufferedImage image;
private double zoomMultiplier;
public ImagePanel()
{
imageFile = null;
image = null;
zoomMultiplier = 1;
}
public ImagePanel(File imageFile)
{
this.imageFile = imageFile;
try {
image = ImageIO.read(imageFile);
} catch (IOException e) {
image = null;
}
zoomMultiplier = 1;
}
public void setImageFile(File imageFile)
{
this.imageFile = imageFile;
if(imageFile == null)
{
image = null;
}
else
{
try {
image = ImageIO.read(imageFile);
} catch (IOException e) {
image = null;
}
}
zoomMultiplier = 1;
this.revalidate();
this.repaint();
}
public File getImageFile()
{
return imageFile;
}
public void paintComponent(Graphics g)
{
g.clearRect(0, 0, this.getWidth(), this.getHeight());
if(image == null)
{
this.setPreferredSize(new Dimension(this.getParent().getWidth(), this.getParent().getHeight()));
g.setColor(Color.black);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
}
else
{
double preferredWidth = this.getParent().getWidth() * zoomMultiplier;
double preferredHeight = this.getParent().getHeight() * zoomMultiplier;
this.setPreferredSize(new Dimension((int)preferredWidth, (int)preferredHeight));
Image scaled = image.getScaledInstance((int)preferredWidth, (int)preferredHeight, Image.SCALE_DEFAULT);
g.drawImage(scaled, 0, 0, null);
}
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
if(evt.getPropertyName().equals("Image File"))
{
setImageFile((File)evt.getNewValue());
}
else if(evt.getPropertyName().equals("Zoom In"))
{
double additive = ((Number)evt.getNewValue()).doubleValue();
zoomMultiplier += additive;
this.revalidate();
this.repaint();
}
else if(evt.getPropertyName().equals("Zoom Out"))
{
double subtractive = ((Number)evt.getNewValue()).doubleValue();
zoomMultiplier -= subtractive;
this.revalidate();
this.repaint();
}
else if(evt.getPropertyName().equals("Zoom Reset"))
{
zoomMultiplier = 1;
this.revalidate();
this.repaint();
}
}
}
Main Class
package com.zephyr.graphics;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeSupport;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class Main {
public static void main(String[] args)
{
PropertyChangeSupport pcs = new PropertyChangeSupport(Main.class);
JFileChooser chooser = new JFileChooser(System.getProperty("user.home"));
chooser.setDialogTitle("Select an image");
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
File file = null;
if(chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
file = chooser.getSelectedFile();
}
else
{
System.err.println("NO FILE WAS SELECTED OR THE WINDOW WAS CLOSED");
return;
}
JFrame frame = new JFrame("ImagePanel Tester");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImagePanel iPanel = new ImagePanel(file);
pcs.addPropertyChangeListener(iPanel);
JScrollPane iScroll = new JScrollPane(iPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
iScroll.setPreferredSize(new Dimension(1024, 768));
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
JButton zoomIn = new JButton("Zoom In");
zoomIn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
pcs.firePropertyChange("Zoom In", null, new Double(.25));
frame.revalidate();
frame.repaint();
}
});
controlPanel.add(zoomIn);
JButton zoomOut = new JButton("Zoom Out");
zoomOut.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pcs.firePropertyChange("Zoom Out", null, new Double(.25));
frame.revalidate();
frame.repaint();
}
});
controlPanel.add(zoomOut);
JButton zoomReset = new JButton("Zoom Reset");
zoomReset.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pcs.firePropertyChange("Zoom Reset", null, null);
frame.revalidate();
frame.repaint();
}
});
controlPanel.add(zoomReset);
JButton changeImage = new JButton("Change Image");
changeImage.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(chooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION)
{
File tempFile = chooser.getSelectedFile();
pcs.firePropertyChange("Image File", null, tempFile);
frame.revalidate();
frame.repaint();
}
}
});
controlPanel.add(changeImage);
frame.add(iScroll, BorderLayout.CENTER);
frame.add(controlPanel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
frame.revalidate(); //Shouldn't really be necessary, but seems to be helping
}
}
After some heavy digging, the Scrollable interface saved me. Implementing this and it's respective methods following this example as well as removing the preferredSize references from paintComponent fixes the issues that I was having.

Change JLabel colour repeatedly each time when JButton pressed

I'm trying to make a traffic light program, changing the foreground colour of JLabel from red to yellow to green, everytime I press JButton (i.e once i press JButton, JLabel turns red, then when i again press JButton it turns yellow and so on). But somehow the colour changes only once to red & nothing happens on further pressing JButton. Any kind of help would be appreciated. Thanks.
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class traffic {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
traffic window = new traffic();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public traffic() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 798, 512);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblTrafficLight = new JLabel("Traffic Light");
lblTrafficLight.setFont(new Font("Tahoma", Font.BOLD, 40));
lblTrafficLight.setHorizontalAlignment(SwingConstants.CENTER);
lblTrafficLight.setBounds(190, 11, 403, 61);
frame.getContentPane().add(lblTrafficLight);
JLabel lblRed = new JLabel("RED");
lblRed.setHorizontalAlignment(SwingConstants.CENTER);
lblRed.setFont(new Font("Tahoma", Font.PLAIN, 40));
lblRed.setBounds(273, 125, 249, 61);
frame.getContentPane().add(lblRed);
JButton btnButton = new JButton("Button");
btnButton.setActionCommand("B");
btnButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.RED);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.YELLOW);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.GREEN);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.YELLOW);
}
if(btnButton.getActionCommand().equals("B"))
{
lblRed.setForeground(Color.RED);
}
}
});
btnButton.setBounds(353, 346, 89, 23);
frame.getContentPane().add(btnButton);
}
}
You're using the same actionCommand, B for each if block, and so all of the blocks will always run, and the last block will be the one seen.
e.g.,
int x = 1;
if (x == 1) {
// do something
}
if (x == 1) {
// do something else
}
all blocks will be done!
Either change the actionCommands used, or don't use actionCommand String but rather an incrementing int index. Also, don't use MouseListeners for JButtons but rather ActionListeners.
For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
public class Traffic2 extends JPanel {
private static final int PREF_W = 400;
private static final int PREF_H = 300;
private static final String[] STRINGS = {"Red", "Blue", "Orange", "Yellow", "Green", "Cyan"};
private Map<String, Color> stringColorMap = new HashMap<>();
private JLabel label = new JLabel("", SwingConstants.CENTER);
private int index = 0;
public Traffic2() {
stringColorMap.put("Red", Color.red);
stringColorMap.put("Blue", Color.blue);
stringColorMap.put("Orange", Color.orange);
stringColorMap.put("Yellow", Color.YELLOW);
stringColorMap.put("Green", Color.GREEN);
stringColorMap.put("Cyan", Color.CYAN);
label.setFont(label.getFont().deriveFont(Font.BOLD, 40f));
String key = STRINGS[index];
label.setText(key);
label.setForeground(stringColorMap.get(key));
JPanel centerPanel = new JPanel(new GridBagLayout());
centerPanel.add(label);
JPanel topPanel = new JPanel();
topPanel.add(new JButton(new AbstractAction("Change Color") {
#Override
public void actionPerformed(ActionEvent e) {
index++;
index %= STRINGS.length;
String key = STRINGS[index];
label.setText(key);
label.setForeground(stringColorMap.get(key));
}
}));
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(centerPanel, BorderLayout.CENTER);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
Traffic2 mainPanel = new Traffic2();
JFrame frame = new JFrame("Traffic2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_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();
}
});
}
}

How to change background in JFrame consisting of JPanels?

I'm trying to change the background of my JFrame.
I tried using the setBackground(Color) method to all the JPanel objects and only the area covered between Buttons and all other fields is covered. Can anyone help me here?
output img:
code :
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JPanel;
import java.awt.FlowLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JOptionPane;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Color;
import javax.swing.JLabel;
import java.awt.event.WindowEvent;
import javax.swing.ImageIcon;
import javax.swing.UIManager;
public class calculator extends JFrame implements ActionListener, KeyListener
{
public JButton[] dig=new JButton[10];
public JButton sin,cos,tan,toNegative,add,subtract,divide,multiply,quad,clear,equals,result,back;
public JTextField txt,a,b,c;
public JPanel inputField,digits,quadSwitcher,eqCls,extras,zero,addSubt;
public int width=280,height=400;
public static String input="";
private ImageIcon img;
private Color color1=Color.ORANGE;
public calculator()
{
super("Calculator");try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}catch(Exception e){}
img=new ImageIcon("calc.png");
this.setIconImage(img.getImage());
setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
setSize(width,height);
txt=new JTextField(null,20);
txt.setEditable(true);
inputField=new JPanel();
txt.setPreferredSize(new Dimension(width-50,30));
inputField.add(txt);
this.add(inputField);
txt.addKeyListener(this);
for(int i=0;i<10;i++)
dig[i]=new JButton(i+"");
sin=new JButton("sin");
cos=new JButton("cos");
tan=new JButton("tan");
toNegative=new JButton("+/-");
add=new JButton("add");
subtract=new JButton("Subtract");
add=new JButton("Add");
multiply=new JButton("Multiply");
quad=new JButton("Quadratic Equation");
quad.addActionListener(this);
divide=new JButton("Divide");
equals=new JButton("=");
quadSwitcher=new JPanel();
quadSwitcher.add(quad);
this.add(quadSwitcher);
digits=new JPanel();
digits.setLayout(new GridLayout(3,3,5,5));
for(int i=9;i>=1;i--)
digits.add(dig[i]);
extras=new JPanel();
extras.setLayout(new GridLayout(2,3,4,4));
extras.add(sin);
extras.add(cos);
extras.add(tan);
extras.add(toNegative);
extras.add(multiply);
extras.add(divide);
this.add(digits);
zero=new JPanel();
dig[0].setPreferredSize(new Dimension((width/2)-10,25));
zero.add(dig[0]);
this.add(zero);
this.add(extras);
addSubt=new JPanel();
addSubt.setLayout(new GridLayout(1,2,10,0));
addSubt.setPreferredSize(new Dimension(width-35,30));
addSubt.add(add);
addSubt.add(subtract);
this.add(addSubt);
eqCls=new JPanel();
eqCls.setLayout(new GridLayout(1,2,10,0));
eqCls.setPreferredSize(new Dimension(width-35,30));
clear=new JButton("clear");
eqCls.add(equals);
eqCls.add(clear);
clear.addActionListener(this);
this.add(eqCls);
for(int i=0;i<10;i++)
dig[i].addActionListener(this);
sin.addActionListener(this);
cos.addActionListener(this);
tan.addActionListener(this);
toNegative.addActionListener(this);
equals.addActionListener(this);
add.addActionListener(this);
subtract.addActionListener(this);
multiply.addActionListener(this);
divide.addActionListener(this);
setVisible(true);
this.setBackground(Color.ORANGE);
inputField.setBackground(color1);
quadSwitcher.setBackground(color1);
eqCls.setBackground(color1);
addSubt.setBackground(color1);
digits.setBackground(color1);
extras.setBackground(color1);
zero.setBackground(color1);
inputField.setOpaque(true);
JOptionPane.showMessageDialog(this,"Developed By Saksham Puri.");
}
public static void main(String args[])
{
calculator ob=new calculator();
}
#Override
public void keyPressed(KeyEvent e)
{
int keyCode=e.getKeyCode();
if(keyCode==KeyEvent.VK_ENTER){
input=txt.getText();
txt.setText(performOperation(input));}
}
#Override
public void actionPerformed(ActionEvent e)
{
String str=e.getActionCommand();
if(Character.isDigit(str.charAt(0))) txt.setText(txt.getText()+""+str);
else if(str.equalsIgnoreCase("clear"))
txt.setText("");
else if(str.equalsIgnoreCase("tan")) txt.setText(txt.getText()+""+str);
else if(str.equalsIgnoreCase("sin"))txt.setText(txt.getText()+""+str);
else if(str.equalsIgnoreCase("cos"))txt.setText(txt.getText()+""+str);
else if(str.equalsIgnoreCase("add"))txt.setText(txt.getText()+""+"+");
else if(str.equalsIgnoreCase("subtract"))txt.setText(txt.getText()+""+"-");
else if(str.equalsIgnoreCase("+/-"))txt.setText(txt.getText()+""+"-");
else if(str.equalsIgnoreCase("multiply"))txt.setText(txt.getText()+""+"*");
else if(str.equalsIgnoreCase("divide"))txt.setText(txt.getText()+""+"/");
else if(str.equalsIgnoreCase("=")){input=txt.getText(); txt.setText(performOperation(input));}
else if(str.equalsIgnoreCase("Quadratic Equation")) setQuad();
else if(str.equalsIgnoreCase("back"))back();
else if(str.equalsIgnoreCase("calculate")){back(); txt.setText(calcQuad()); revalidate(); repaint();}
}
public void back()
{
inputField.removeAll();
quadSwitcher.removeAll();
inputField.add(txt);
quadSwitcher.add(quad);
revalidate();
repaint();
}
public String calcQuad()
{
return Quad.solveQuad(Integer.parseInt(a.getText()),Integer.parseInt(b.getText()),Integer.parseInt(c.getText()));
}
public void setQuad()
{
inputField.removeAll();
quadSwitcher.removeAll();
a=new JTextField("a",4);
a.setEditable(true);
b=new JTextField("b",4);
b.setEditable(true);
c=new JTextField("c",4);
c.setEditable(true);
inputField.add(a);
inputField.add(new JLabel("x^2 + "));
inputField.add(b);
inputField.add(new JLabel("x + "));
inputField.add(c);
result=new JButton("Calculate");
back=new JButton("Back");
back.addActionListener(this);
result.addActionListener(this);
quadSwitcher.add(result);
quadSwitcher.add(back);
revalidate();
repaint();
}
#Override
public void keyReleased(KeyEvent e){}
public void keyTyped(KeyEvent e){}
public String performOperation(String str)
{
return "Performed Operation";
}
}
just the color
getContentPane().setBackground(Color.LIGHT_GRAY); //for example
put an image on the background
//create a JComponent to store your image
class ImagePanel extends JComponent
{
private Image image;
public ImagePanel(String str) {
BufferedImage image=null;
try {
image = ImageIO.read(new File(str));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.image = image;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
//in your JFrame class
ImagePanel contentPane = new ImagePanel("./background.png");
this.setContentPane(contentPane);
getContentPane().setBackground(Color.LIGHT_GRAY);// just in case your image does not fit the entire view

Keylistener not working with fullscreen

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.

Categories

Resources