I need help implementing the event handlers for Show Picture, Increase Red, Incr
ID: 2247078 • Letter: I
Question
I need help implementing the event handlers for Show Picture, Increase Red, Increase Green, Increase Blue, Blur and Set Original. There are methods in the Picture class already written. I need to use FileChooser to select the file. Most of the code needs to be implemented in DrawImageControlPanel.java. I have tried and been unsuccessful so I was hoping to get some guidance.
Here are the files I am working with:
File: ControlFrame.java
// ControlFrame.java
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JOptionPane;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import java.awt.BorderLayout;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public class ControlFrame extends JFrame
{
private JPanel mainPanel;
private final JPanel calcPanel;
private JSlider widthJSlider;
private JTextField xValTextField;
private JTextField yValTextField;
private JLabel calcJLabel;
private JButton calcJButton;
private String xStr;
private String yStr;
public ControlFrame(String title)
{
super( title );
mainPanel = new JPanel( new BorderLayout() );
mainPanel.setSize(200, 250);
calcPanel = new JPanel( new FlowLayout() );
calcPanel.setSize(200, 200);
final DrawControlPanel drawPanel = new DrawControlPanel();
drawPanel.setSize(200, 200);
final DrawImageControlPanel drawImagePanel = new DrawImageControlPanel();
drawImagePanel.setSize(800, 600);
this.setContentPane( mainPanel );
JMenu fileMenu = new JMenu( "File" );
fileMenu.setMnemonic( 'F' );
JMenuItem aboutItem = new JMenuItem( "About..." );
aboutItem.setMnemonic( 'A' );
fileMenu.add( aboutItem );
aboutItem.addActionListener(
new ActionListener() // Beginning of anonymous inner class
{
public void actionPerformed( ActionEvent event )
{
JOptionPane.showMessageDialog( ControlFrame.this,
"This application provides enhanced control over multimedia projects.",
"About", JOptionPane.PLAIN_MESSAGE );
}
} // End of anonymous inner class
);
final JMenuBar bar = new JMenuBar(); // Create a JMenuBar so we can attach menus to it.
setJMenuBar( bar ); // Attach the JMenuBar to the ControlFrame.
bar.add( fileMenu ); // Add the file menu to the JMenuBar.
final JMenu colorMenu = new JMenu( "Color" );
colorMenu.setMnemonic( 'C' );
JMenuItem redItem = new JMenuItem( "Red" );
colorMenu.add( redItem );
redItem.addActionListener(
new ActionListener() // Beginning of anonymous inner class
{
public void actionPerformed( ActionEvent event )
{
drawPanel.setFillColor( Color.RED );
repaint();
}
} // End of anonymous inner class
);
JMenuItem blueItem = new JMenuItem( "Blue" );
colorMenu.add( blueItem );
blueItem.addActionListener(
new ActionListener() // Beginning of anonymous inner class
{
public void actionPerformed( ActionEvent event )
{
drawPanel.setFillColor( Color.BLUE );
repaint();
}
} // End of anonymous inner class
);
JMenuItem magentaItem = new JMenuItem( "Magenta" );
colorMenu.add( magentaItem );
magentaItem.addActionListener(
new ActionListener() // Beginning of anonymous inner class
{
public void actionPerformed( ActionEvent event )
{
drawPanel.setFillColor( Color.MAGENTA );
repaint();
}
} // End of anonymous inner class
);
JMenuItem cyanItem = new JMenuItem( "Cyan" );
colorMenu.add( cyanItem );
cyanItem.addActionListener(
new ActionListener() // Beginning of anonymous inner class
{
public void actionPerformed( ActionEvent event )
{
drawPanel.setFillColor( Color.CYAN );
repaint();
}
} // End of anonymous inner class
);
// create Image menu which allows image manipulation operations to be performed.
final JMenu imageMenu = new JMenu( "Image" );
imageMenu.setMnemonic( 'I' );
JMenuItem imageOp1Item = new JMenuItem( "Increase Red" );
imageMenu.add( imageOp1Item );
imageOp1Item.addActionListener(
new ActionListener() // Beginning of anonymous inner class
{
public void actionPerformed( ActionEvent event )
{
// Picture picture = new Picture("C:/intro-prog-java/mediasources/Donald.jpg");
// // drawImagePanel.increaseRed();
// picture.getBufferedImage();
// repaint();
}
} // End of anonymous inner class
);
JMenuItem imageOp2Item = new JMenuItem( "Increase Green" );
imageMenu.add( imageOp2Item );
imageOp1Item.addActionListener(
new ActionListener() // Beginning of anonymous inner class
{
public void actionPerformed( ActionEvent event )
{
// drawImagePanel.increaseGreen();
repaint();
}
} // End of anonymous inner class
);
JMenuItem imageOp3Item = new JMenuItem( "Increase Blue" );
imageMenu.add( imageOp3Item );
imageOp1Item.addActionListener(
new ActionListener() // Beginning of anonymous inner class
{
public void actionPerformed( ActionEvent event )
{
// drawImagePanel.increaseBlue();
repaint();
}
} // End of anonymous inner class
);
JMenuItem imageOp4Item = new JMenuItem( "Blur" );
imageMenu.add( imageOp4Item );
imageOp1Item.addActionListener(
new ActionListener() // Beginning of anonymous inner class
{
public void actionPerformed( ActionEvent event )
{
// drawImagePanel.Blur();
repaint();
}
} // End of anonymous inner class
);
JMenuItem imageOp8Item = new JMenuItem( "Set Original" );
imageMenu.add( imageOp8Item );
imageOp8Item.addActionListener(
new ActionListener() // Beginning of anonymous inner class
{
public void actionPerformed( ActionEvent event )
{
// drawImagePanel.setOriginalImage();
repaint();
}
} // End of anonymous inner class
);
// create Sound menu which loads a Sound object.
final JMenu soundMenu = new JMenu( "Sound" );
imageMenu.setMnemonic( 'O' );
JMenuItem soundOp1Item = new JMenuItem( "Play" );
soundMenu.add( soundOp1Item );
soundOp1Item.addActionListener(
new ActionListener() // Beginning of anonymous inner class
{
public void actionPerformed( ActionEvent event )
{
// soundPanel.play();
repaint();
}
} // End of anonymous inner class
);
JMenuItem soundOp2Item = new JMenuItem( "Stop" );
soundMenu.add( soundOp2Item );
soundOp2Item.addActionListener(
new ActionListener() // Beginning of anonymous inner class
{
public void actionPerformed( ActionEvent event )
{
// soundPanel.stop();
repaint();
}
} // End of anonymous inner class
);
JMenuItem soundOp3Item = new JMenuItem( "Increase Volume" );
soundMenu.add( soundOp3Item );
soundOp3Item.addActionListener(
new ActionListener() // Beginning of anonymous inner class
{
public void actionPerformed( ActionEvent event )
{
// soundPanel.increaseVolume();
repaint();
}
} // End of anonymous inner class
);
JMenuItem soundOp4Item = new JMenuItem( "Decrease Volume" );
soundMenu.add( soundOp4Item );
soundOp4Item.addActionListener(
new ActionListener() // Beginning of anonymous inner class
{
public void actionPerformed( ActionEvent event )
{
// soundPanel.decreaseVolume();
repaint();
}
} // End of anonymous inner class
);
JMenuItem soundOp5Item = new JMenuItem( "Mirror" );
soundMenu.add( soundOp5Item );
soundOp5Item.addActionListener(
new ActionListener() // Beginning of anonymous inner class
{
public void actionPerformed( ActionEvent event )
{
// soundPanel.mirror();
repaint();
}
} // End of anonymous inner class
);
JMenuItem soundOp6Item = new JMenuItem( "Set Original" );
soundMenu.add( soundOp6Item );
soundOp6Item.addActionListener(
new ActionListener() // Beginning of anonymous inner class
{
public void actionPerformed( ActionEvent event )
{
// soundPanel.setOriginalSound();
repaint();
}
} // End of anonymous inner class
);
JMenuItem calcPanelItem = new JMenuItem( "Calculate" );
calcPanelItem.setMnemonic( 'C' );
fileMenu.add( calcPanelItem );
calcPanelItem.addActionListener(
new ActionListener()
{
public void actionPerformed( ActionEvent event )
{
bar.remove( colorMenu );
mainPanel.remove( drawPanel );
mainPanel.remove( widthJSlider );
xValTextField.setText("");
yValTextField.setText("");
calcJLabel.setText( "" );
mainPanel.add( calcPanel, BorderLayout.CENTER );
validate();
repaint();
}
}
);
JMenuItem drawPanelItem = new JMenuItem( "DrawPanel" );
drawPanelItem.setMnemonic( 'D' );
fileMenu.add( drawPanelItem );
drawPanelItem.addActionListener(
new ActionListener()
{
public void actionPerformed( ActionEvent event )
{
bar.add( colorMenu );
mainPanel.remove( calcPanel );
drawPanel.setBackground( Color.WHITE );
mainPanel.add( drawPanel, BorderLayout.CENTER );
mainPanel.add( widthJSlider, BorderLayout.SOUTH );
validate();
repaint();
}
}
);
// Add a menu item named Show Picture to the File menu that will show the image of a Picture object.
JMenuItem drawImagePanelItem = new JMenuItem( "Show Picture" );
drawImagePanelItem.setMnemonic( 'S' );
fileMenu.add( drawImagePanelItem );
drawImagePanelItem.addActionListener(
new ActionListener()
{
public void actionPerformed( ActionEvent event )
{
// remove menus for color and sound
bar.remove( colorMenu );
//bar.remove( soundMenu );
// if sound is played, stop the sound
//soundPanel.stop();
// remove panels for draw, sound and calculation
mainPanel.remove( drawPanel );
// mainPanel.remove( soundPanel );
mainPanel.remove( calcPanel );
// remove slider feature
mainPanel.remove( widthJSlider );
// set original image to be shown
// drawImagePanel.setOriginalImage();
// add panel for showing image
// mainPanel.add( drawImagePanel, BorderLayout.CENTER );
// add image menu
bar.add( imageMenu );
validate();
repaint();
}
}
);
// Add a menu item named Load Sound to the File menu that will load sound
JMenuItem loadSoundPanelItem = new JMenuItem( "Load Sound" );
loadSoundPanelItem.setMnemonic( 'L' );
fileMenu.add( loadSoundPanelItem );
loadSoundPanelItem.addActionListener(
new ActionListener()
{
public void actionPerformed( ActionEvent event )
{
// remove menus for color and image
bar.remove( colorMenu );
bar.remove( imageMenu );
// remove panels for draw, draw image and calculation
mainPanel.remove( drawPanel );
mainPanel.remove( calcPanel );
// mainPanel.remove( drawImagePanel );
// remove slider feature
mainPanel.remove( widthJSlider );
// set original sound
// soundPanel.setOriginalSound();
// add panel for controlling sound
//mainPanel.add( soundPanel, BorderLayout.CENTER );
// add sound menu
bar.add( soundMenu );
validate();
repaint();
}
}
);
JMenuItem exitItem = new JMenuItem( "Exit" );
exitItem.setMnemonic( 'x' );
fileMenu.add( exitItem );
exitItem.addActionListener(
new ActionListener()
{
public void actionPerformed( ActionEvent event )
{
System.exit( 0 );
}
}
);
widthJSlider = new JSlider( SwingConstants.HORIZONTAL, 0, 100, drawPanel.getOvalWidth() );
widthJSlider.setMajorTickSpacing( 10 );
widthJSlider.setPaintTicks( true );
widthJSlider.addChangeListener(
new ChangeListener()
{
public void stateChanged( ChangeEvent e )
{
drawPanel.setOvalWidth( widthJSlider.getValue() );
repaint();
}
}
);
xValTextField = new JTextField( 3 );
xValTextField.addActionListener(
new ActionListener()
{
public void actionPerformed( ActionEvent event )
{
xStr = event.getActionCommand();
}
}
);
calcPanel.add( xValTextField );
yValTextField = new JTextField( 3 );
yValTextField.addActionListener(
new ActionListener()
{
public void actionPerformed( ActionEvent event )
{
yStr = event.getActionCommand();
}
}
);
calcPanel.add( yValTextField );
calcJButton = new JButton( "Calculate" );
calcJButton.addActionListener(
new ActionListener()
{
public void actionPerformed( ActionEvent event )
{
try {
int x = Integer.parseInt( xStr );
int y = Integer.parseInt( yStr );
int result = x + y;
calcJLabel.setText(xStr + " + " + yStr + " = " + result);
}
catch (NumberFormatException e) {
JOptionPane.showMessageDialog( ControlFrame.this, "You must enter a valid number and then <ENTER> for each textbox!", "Invalid Input", JOptionPane.ERROR_MESSAGE );
e.printStackTrace();
}
}
}
);
calcPanel.add( calcJButton );
calcJLabel = new JLabel();
calcPanel.add( calcJLabel, BorderLayout.CENTER );
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setSize( 200, 250 );
setVisible( true );
validate();
}
}
File: DrawControlApp.java
// DrawControlApp.java
import java.awt.Color;
import javax.swing.JFrame;
public class DrawControlApp
{
public static void main( String args[] )
{
JFrame frame = new ControlFrame( "Controlling Multimedia Projects..." );
frame.setSize( 900, 700 );
}
}
File: DrawControlPanel.java
// DrawControlPanel.java
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class DrawControlPanel extends JPanel
{
private Color fillColor = Color.CYAN;
private int ovalWidth = 90;
public DrawControlPanel()
{
setSize( 200, 200 );
}
public void paintComponent( Graphics g )
{
super.paintComponent( g ); // invoke the superclass paintComponent
this.setBackground( Color.WHITE );
g.setColor( fillColor );
g.fillOval( 50, 50, ovalWidth, 60 );
}
void setFillColor(Color fillColor)
{
this.fillColor = fillColor;
}
void setOvalWidth(int ovalWidth)
{
this.ovalWidth = ovalWidth;
}
int getOvalWidth()
{
return ovalWidth;
}
}
File: DrawImageControlPanel.java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class DrawImageControlPanel extends JPanel{
public DrawImageControlPanel()
{
setSize( 800, 600 );
}
}
File: FileChooser.java
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import java.util.Properties;
import java.io.*;
/**
* A class to make working with a file chooser easier
* for students. It uses a JFileChooser to let the user
* pick a file and returns the choosen file name.
*
* Copyright Georgia Institute of Technology 2004
* @author Barb Ericson ericson@cc.gatech.edu
*/
public class FileChooser
{
///////////////////////////// class fields ///////////////////
/**
* Properities to use during execution
*/
private static Properties appProperties = null;
/**
* Property key for the media directory
*/
private static final String MEDIA_DIRECTORY = "mediaDirectory";
/**
* Name for property file
*/
private static final String PROPERTY_FILE_NAME =
"SimplePictureProperties.txt";
/////////////////////// methods /////////////////////////////
/**
* Method to let the user pick a file and return
* the full file name as a string. If the user didn't
* pick a file then the file name will be null.
* @return the full file name of the picked file or null
*/
public static String pickAFile()
{
JFileChooser fileChooser = null;
// start off the file name as null
String fileName = null;
// get the current media directory
String mediaDir = getMediaDirectory();
/* create a file for this and check that the directory exists
* and if it does set the file chooser to use it
*/
try {
File file = new File(mediaDir);
if (file.exists())
fileChooser = new JFileChooser(file);
} catch (Exception ex) {
}
// if no file chooser yet create one
if (fileChooser == null)
fileChooser = new JFileChooser();
/* create a JFrame to be the parent of the file
* chooser open dialog if you don't do this then
* you may not see the dialog.
*/
JFrame frame = new JFrame();
// get the return value from choosing a file
int returnVal = fileChooser.showOpenDialog(frame);
// if the return value says the user picked a file
if (returnVal == JFileChooser.APPROVE_OPTION)
fileName = fileChooser.getSelectedFile().getPath();
return fileName;
}
/**
* Method to get the full path for the passed file name
* @param fileName the name of a file
* @return the full path for the file
*/
public static String getMediaPath(String fileName)
{
String path = null;
String directory = getMediaDirectory();
// get the full path
path = directory + fileName;
return path;
}
/**
* Method to get the directory for the media
* @return the media directory
*/
public static String getMediaDirectory()
{
String directory = null;
// check if the application properties are null
if (appProperties == null)
{
appProperties = new Properties();
// load the properties from a file
try {
FileInputStream in = new FileInputStream(PROPERTY_FILE_NAME);
appProperties.load(in);
in.close();
} catch (Exception ex) {
directory = "c:/intro-prog-java/mediasources/";
}
}
// get the media directory
if (appProperties != null)
directory = (String) appProperties.get(MEDIA_DIRECTORY);
return directory;
}
/**
* Method to set the media path by setting the directory to use
* @param directory the directory to use for the media path
*/
public static void setMediaPath(String directory)
{
// check if the directory exists
File file = new File(directory);
if (!file.exists())
System.out.println("Sorry but " + directory +
" doesn't exist, try a different directory.");
else {
/* check if there is an application properties object
* and if not create one
*/
if (appProperties == null)
appProperties = new Properties();
// set the media directory property
appProperties.put(MEDIA_DIRECTORY,directory);
// write out the application properties to a file
try {
FileOutputStream out =
new FileOutputStream(PROPERTY_FILE_NAME);
appProperties.store(out,
"Properties for the Simple Picture class");
out.close();
System.out.println("The media directory is now " +
directory);
} catch (Exception ex) {
System.out.println("Couldn't save media path to a file");
}
}
}
}
File Picture.java
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.text.*;
/**
* A class that represents a picture. This class inherits from
* SimplePicture and allows the student to add functionality to
* the Picture class.
*
* Copyright Georgia Institute of Technology 2004-2005
* @author Barbara Ericson ericson@cc.gatech.edu
*/
public class Picture extends SimplePicture
{
///////////////////// constructors //////////////////////////////////
/**
* Constructor that takes no arguments
*/
public Picture ()
{
/* not needed but use it to show students the implicit call to super()
* child constructors always call a parent constructor
*/
super();
}
/**
* Constructor that takes a file name and creates the picture
* @param fileName the name of the file to create the picture from
*/
public Picture(String fileName)
{
// let the parent class handle this fileName
super(fileName);
}
/**
* Constructor that takes the width and height
* @param width the width of the desired picture
* @param height the height of the desired picture
*/
public Picture(int width, int height)
{
// let the parent class handle this width and height
super(width,height);
}
/**
* Constructor that takes a picture and creates a
* copy of that picture
*/
public Picture(Picture copyPicture)
{
// let the parent class do the copy
super(copyPicture);
}
////////////////////// methods ///////////////////////////////////////
/**
* Method to return a string with information about this picture.
* @return a string with information about the picture such as fileName,
* height and width.
*/
public String toString()
{
String output = "Picture, filename " + getFileName() +
" height " + getHeight()
+ " width " + getWidth();
return output;
}
//decreaseRed Method
public void decreaseRedForEach ()
{
Pixel[] pixelArray = this.getPixels();
int value = 0;
//loop through all the pixels in the array
for (Pixel pixelObj : pixelArray)
{
//get the red value
value = pixelObj.getRed();
//decrease the red value by 50% (1/2)
value = (int) (value * 0.5);
//set the red value of the current pixel to the new value
pixelObj.setRed(value);
}
}
//method to decrease Red by half in the current picture using a while loop
public void decreaseRed1()
{
Pixel[] pixelArray = this.getPixels();
Pixel pixel = null;
int value = 0;
int index = 0;
//loop through all the pixels in the array
while (index < pixelArray.length)
{
//get the current pixel
pixel = pixelArray[index];
//get the red value
value = pixel.getRed();
//decrease the red value by 50% (1/2)
value = (int) (value * 0.5);
//set the red value of the current pixel to the new value
pixel.setRed(value);
//increment the index
index = index + 1;
}
}
public void drawBox(Color color, int topLeftX, int topLeftY, int width, int height)
{
//get the graphics context for drawing
Graphics g = this.getGraphics();
//set the current color
g.setColor(color);
//draw the filled rectangle
g.fillRect(topLeftX, topLeftY, width,height);
}
/**
* Method to increase the amount of red by 30%
**/
public void increaseRed()
{
Pixel[] pixelArray = this.getPixels();
Pixel pixel = null;
int value = 0;
int index = 0;
//loop through all the pixels
while (index < pixelArray.length)
{
//get the current pixel
pixel = pixelArray[index];
//get the value
value = pixel.getRed();
//change the value to 1.3 times what it was
value = (int) (value * 1.3);
//set the red value to 1.3 time what it was
pixel.setRed(value);
//increment the index
index++;
}
}
/**
* Method to increase the amount of red by an increase factor
**/
public void increaseRed(double increaseFactor)
{
Pixel[] pixelArray = this.getPixels();
Pixel pixel = null;
int value = 0;
int index = 0;
//loop through all the pixels
while (index < pixelArray.length)
{
//get the current pixel
pixel = pixelArray[index];
//get the value
value = pixel.getRed();
//change the value to increase factor times what it was
value = (int) (value * increaseFactor);
//set the red value to increase factor times what it was
pixel.setRed(value);
//increment the index
index++;
}
}
/**
* Method to increase the amount of green by 30%
**/
public void increaseGreen()
{
Pixel[] pixelArray = this.getPixels();
Pixel pixel = null;
int value = 0;
int index = 0;
//loop through all the pixels
while (index < pixelArray.length)
{
//get the current pixel
pixel = pixelArray[index];
//get the value
value = pixel.getGreen();
//change the value to 1.3 times what it was
value = (int) (value * 1.3);
//set the red value to 1.3 times what it was
pixel.setGreen(value);
//increment the index
index++;
}
}
/**
* Method to increase the amount of green by an increase factor
**/
public void increaseGreen(double increaseFactor)
{
Pixel[] pixelArray = this.getPixels();
Pixel pixel = null;
int value = 0;
int index = 0;
//loop through all the pixels
while (index < pixelArray.length)
{
//get the current pixel
pixel = pixelArray[index];
//get the value
value = pixel.getGreen();
//change the value to increase factor times what it was
value = (int) (value * increaseFactor);
//set the red value to increase factor times what it was
pixel.setGreen(value);
//increment the index
index++;
}
}
/**
* Method to increase the amount of blue by 30%
**/
public void increaseBlue()
{
Pixel[] pixelArray = this.getPixels();
Pixel pixel = null;
int value = 0;
int index = 0;
//loop through all the pixels
while (index < pixelArray.length)
{
//get the current pixel
pixel = pixelArray[index];
//get the value
value = pixel.getBlue();
//change the value to 1.3 times what it was
value = (int) (value * 1.3);
//set the red value to 1.3 times what it was
pixel.setBlue(value);
//increment the index
index++;
}
}
/**
* Method to increase the amount of blue by an increase factor
**/
public void increaseBlue(double increaseFactor)
{
Pixel[] pixelArray = this.getPixels();
Pixel pixel = null;
int value = 0;
int index = 0;
//loop through all the pixels
while (index < pixelArray.length)
{
//get the current pixel
pixel = pixelArray[index];
//get the value
value = pixel.getBlue();
//change the value to increase factor times what it was
value = (int) (value * increaseFactor);
//set the red value to increase factor times what it was
pixel.setBlue(value);
//increment the index
index++;
}
}
/**
* Method to create a new picture that is scaled up by the
* passed number of times
* @return the new scaled up picture
*/
public Picture scaleUp(int numTimes)
{
Picture targetPicture = new Picture(this.getWidth() * numTimes, this.getHeight() * numTimes);
Pixel sourcePixel = null;
Pixel targetPixel = null;
int targetX = 0;
int targetY = 0;
// loop through the source picture columns
for (int sourceX = 0; sourceX < this.getWidth(); sourceX++)
{
//loop through the source picture rows
for(int sourceY=0; sourceY < this.getHeight(); sourceY++)
{
//get the source pixel
sourcePixel = this.getPixel(sourceX, sourceY);
//loop copying to the target y
for (int indexY = 0; indexY < numTimes; indexY++)
{
//loop copying to the target x
for (int indexX = 0; indexX < numTimes; indexX++)
{
targetX = sourceX * numTimes + indexX;
targetY = sourceY * numTimes + indexY;
targetPixel = targetPicture.getPixel(targetX, targetY);
targetPixel.setColor(sourcePixel.getColor());
}
}
}
}
return targetPicture;
}
/**
* Method to blur the pixels
* @param numPixels the number of pixels to average in all
* directions so if the numPixels is 2 then we will average
* all pixels in the triangle defined by 2 before the
* current pixel to 2 after the current pixel
* */
public void blur(int startX, int endX, int startY, int endY)
{
Pixel pixel = null;
Pixel samplePixel = null;
int redValue = 0;
int greenValue = 0;
int blueValue = 0;
int count = 0;
int numPixels = 2;
//loop through the pixels
for (int x=startX; x < endX; x++){
for (int y=startY; y < endY; y++) {
//get the current pixel
pixel = this.getPixel(x,y);
//reset the count and red, green and blue values
count = 0;
redValue = greenValue = blueValue = 0;
/* loop through pixel numPixels before x to
* numPixels after x
* */
for (int xSample = x - numPixels;
xSample <= x + numPixels;
xSample++){
for (int ySample = y - numPixels;
ySample <= y + numPixels;
ySample++) {
/* check that we are in the range of acceptable
* pixels
*/
if (xSample >= 0 && xSample < this.getWidth() && ySample >= 0 && ySample < this.getHeight())
{
samplePixel = this.getPixel(xSample, ySample);
// System.out.println("samplePixel: " + samplePixel);
redValue = redValue + samplePixel.getRed();
// System.out.println("redValue: " + redValue);
greenValue = greenValue + samplePixel.getGreen();
//System.out.println("greenValue: " + greenValue);
blueValue = blueValue + samplePixel.getBlue();
//System.out.println("blueValue: " + blueValue);
count = count + 1;
//System.out.println("count: " + count);
}
}
}
// use average color of surrounding pixels
Color newColor = new Color(redValue / count, greenValue / count, blueValue / count);
pixel.setColor(newColor);
}
}
}
/**
* Method that will copy all of the passed source picture into
* the current picture object starting with the left corner
* given by xStart, yStart.
* @param sourcePicture the picture object to copy
* @param xStart the x position to start the copy into on the
* target
* @param yStart the y position to start the copy into on the
* target
*/
public void copyPictureTo(Picture sourcePicture, int xStart, int yStart)
{
Pixel sourcePixel = null;
Pixel targetPixel = null;
// loop through the columns
for (int sourceX = 0, targetX = xStart; sourceX < sourcePicture.getWidth(); sourceX++, targetX++)
{
//loop through the rows
for (int sourceY = 0, targetY = yStart; sourceY < sourcePicture.getHeight(); sourceY++, targetY++)
{
sourcePixel = sourcePicture.getPixel(sourceX,sourceY);
targetPixel = this.getPixel(targetX,targetY);
targetPixel.setColor(sourcePixel.getColor());
}
}
}
/**
* Method to do chromakey using a blue background
* @param newBg the new background image to use to replace
* the blue from the current picture
*/
public void chromakey(Picture newBg)
{
Pixel[] pixelArray = this.getPixels();
Pixel currPixel = null;
Pixel newPixel = null;
//loop through the pixels
for (int i = 0; i <pixelArray.length; i++)
{
//get the current pixel
currPixel = pixelArray[i];
/* if the color at the current pixel is mostly blue
* (blue value is greater than green and red
* combined), then use new background color
*/
if (currPixel.getRed() + currPixel.getGreen() < currPixel.getBlue())
{
newPixel = newBg.getPixel(currPixel.getX(), currPixel.getY());
currPixel.setColor(newPixel.getColor());
}
}
}
/**
* Method to do chromakey using a blue background
* starting at specified coordinates to a background picture
*/
public void chromakeyBlue(Picture sourcePicture, int xStart, int yStart)
{
Pixel sourcePixel = null;
Pixel targetPixel = null;
// loop through the rows
for (int sourceX = 1, targetX = xStart; sourceX < sourcePicture.getWidth(); sourceX++, targetX++)
{
//loop through the columns
for (int sourceY = 1, targetY = yStart; sourceY < sourcePicture.getHeight(); sourceY++, targetY++)
{
sourcePixel = sourcePicture.getPixel(sourceX,sourceY);
targetPixel = this.getPixel(targetX,targetY);
/* if the color at the current pixel is mostly blue
* (blue value is greater than green and red
* combined), then use the new background color
*/
if (sourcePixel.getRed() + sourcePixel.getGreen() > sourcePixel.getBlue())
{
targetPixel.setColor(sourcePixel.getColor());
}
else
{
targetPixel.setColor(targetPixel.getColor());
}
}
}
}
} // end of class Picture, put all new methods before this
File: DigitalPicture.java
import java.awt.Image;
import java.awt.image.BufferedImage;
/**
* Interface to describe a digital picture. A digital picture can have a
* associated file name. It can have a title. It has pixels
* associated with it and you can get and set the pixels. You
* can get an Image from a picture or a BufferedImage. You can load
* it from a file name or image. You can show a picture. You can
* create a new image for it.
*
* Copyright Georgia Institute of Technology 2004
* @author Barb Ericson ericson@cc.gatech.edu
*/
public interface DigitalPicture
{
public String getFileName(); // get the file name that the picture came from
public String getTitle(); // get the title of the picture
public void setTitle(String title); // set the title of the picture
public int getWidth(); // get the width of the picture in pixels
public int getHeight(); // get the height of the picture in pixels
public Image getImage(); // get the image from the picture
public BufferedImage getBufferedImage(); // get the buffered image
public int getBasicPixel(int x, int y); // get the pixel information as an int
public void setBasicPixel(int x, int y, int rgb); // set the pixel information
public Pixel getPixel(int x, int y); // get the pixel information as an object
public void load(Image image); // load the image into the picture
public boolean load(String fileName); // load the picture from a file
public void show(); // show the picture
}
Explanation / Answer
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.ImageIcon;
public class Test extends Frame {
ImageIcon a;
WindowListener wl = new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
public Test() {
a = new ImageIcon("myImage.jpg");
setSize(a.getIconWidth(), a.getIconHeight());
setLocationRelativeTo(null);
addWindowListener(wl);
setVisible(true);
}
public void paint(Graphics g) {
super.paint(g);
g.drawImage(a.getImage(), 0, 0, this);
}
public static void main(String[] args) {
Test myTest = new Test();
}
}
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JFrameWithPicture {
public JFrameWithPicture() throws MalformedURLException, IOException {
initComponents();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
try {
new JFrameWithPicture();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
private void initComponents() throws MalformedURLException, IOException {
JFrame frame = new JFrame("Frame with JPanel and background");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final Image background = ImageUtils.scaleImage(300, 300, ImageIO.read(new URL("http://images2.layoutsparks.com/1/98191/naruto-14-red-design.jpg")));
final Dimension jpanelDimensions = new Dimension(new ImageIcon(background).getIconWidth(), new ImageIcon(background).getIconHeight());
frame.add(new JPanel() {
@Override
protected void paintComponent(Graphics grphcs) {
super.paintComponent(grphcs);
grphcs.drawImage(background, 0, 0, this);
}
@Override
public Dimension getPreferredSize() {
return jpanelDimensions;
}
});
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
}
class ImageUtils {
public static BufferedImage scaleImage(int width, int height, String filename) {
BufferedImage bi;
try {
ImageIcon ii = new ImageIcon(filename);
bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(ii.getImage(), 0, 0, width, height, null);
} catch (Exception e) {
return null;
}
return bi;
}
static Image scaleImage(int width, int height, BufferedImage filename) {
BufferedImage bi;
try {
bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = (Graphics2D) bi.createGraphics();
g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
g2d.drawImage(filename, 0, 0, width, height, null);
} catch (Exception e) {
return null;
}
return bi;
}
}
import javax.swing.*;
public class DisplayImage {
public DisplayImage() {
JFrame frame = new JFrame("Display Image");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = (JPanel)frame.getContentPane();
JLabel label = new JLabel();
label.setIcon(new ImageIcon("myImage"));// your image here
panel.add(label);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main (String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new DisplayImage();
}
});
}
}
import javax.swing.*;
import java.io.*;
public class DisplayImage {
public DisplayImage() {
JFrame frame = new JFrame("rf.JPEG");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = (JPanel)frame.getContentPane();
JLabel label = new JLabel();
System.out.println(new File("RF.JPEG"));
System.out.println(new File("RF.JPEG").exists());
label.setIcon(new ImageIcon("myImage"));
panel.add(label);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main (String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new DisplayImage();
}
});
}
}
import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class GetSetPixels{
public static void main(String args[])throws IOException{
BufferedImage img = null;
File f = null;
try{
f = new File("D:\Image\Sample.jpg");
img = ImageIO.read(f);
}catch(IOException e){
System.out.println(e);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.