how to pass value to rotate method on menu item click? - java

i am developing application of rotating image.
as user click menu item as per that image should be rotate.
right now i have implemented keyboard listener, in which as user press right to left button it moves but i want to change that method and want as per menu item click.
right now it passes degrees variable to method rotate, now i want to custom that and as user click menu item it pass the value.
i don't know how to do.
my code:
public class RotateIMGn extends JPanel {
private static final long serialVersionUID = 1L;
ImageIcon image = new ImageIcon("D://Workspace//ScaleImage//src//images//img.png");
JLabel label = new JLabel(image);
JPanel rotationPanel;
final int WIDTH = 350;
final int HEIGHT = 500;
double degrees;
public RotateIMGn() {
setPreferredSize(new Dimension(446, 500));
setFocusable(true);
addKeyListener(new KeyboardListener());
rotationPanel = new JPanel();
rotationPanel = new turningCanvas();
rotationPanel.setPreferredSize(new Dimension(image.getIconWidth(), image.getIconHeight()));
add(rotationPanel);
JMenuBar menuBar = new JMenuBar();
add(menuBar);
JMenu mnFile = new JMenu("Rotate");
menuBar.add(mnFile);
ImageIcon icon90 = createImageIcon("/images/images_Right.png");
JMenuItem mntmTR90 = new JMenuItem("Rotate 90+", icon90);
mntmTR90.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
try {
} catch (Exception e) {
e.printStackTrace();
}
}
});
mnFile.add(mntmTR90);
ImageIcon icon180 = createImageIcon("/images/images_Vertical.png");
JMenuItem mntmRT180 = new JMenuItem("Rotate 180+", icon180);
mnFile.add(mntmRT180);
JSeparator separator = new JSeparator();
mnFile.add(separator);
ImageIcon micon90 = createImageIcon("/images/images_Left.png");
JMenuItem mntmTRM90 = new JMenuItem("Rotate 90-", micon90);
mnFile.add(mntmTRM90);
ImageIcon micon180 = createImageIcon("/images/images_Horizontal.png");
JMenuItem mntmRTM180 = new JMenuItem("Rotate 180-", micon180);
mnFile.add(mntmRTM180);
rotationPanel.setBounds(WIDTH / 2, HEIGHT / 2,
rotationPanel.getPreferredSize().width,
rotationPanel.getPreferredSize().height);
degrees = 0;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
}
public class turningCanvas extends JPanel {
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.rotate(Math.toRadians(degrees), image.getIconWidth() / 2,
image.getIconHeight() / 2);
image.paintIcon(this, g2d, 0, 0);
}
}
public class KeyboardListener implements KeyListener {
public void keyPressed(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.VK_LEFT) {
degrees--;
repaint();
}
if (event.getKeyCode() == KeyEvent.VK_RIGHT) {
degrees++;
repaint();
}
}
public void keyTyped(KeyEvent event) {
}
public void keyReleased(KeyEvent event) {
}
}
public static void main(String[] args) {
RotateIMGn test = new RotateIMGn();
JFrame frame = new JFrame();
frame.setContentPane(test);
frame.pack();
frame.setVisible(true);
}
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = RotateIMGn.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
}
anyone's idea will help me a lot so...

Use Swing Actions for the menu items instead of Strings. Then, in the actionPerformed method, update the degreesvariable, as you do your KeyListener.
Something like:
ImageIcon icon90 = createImageIcon("/images/images_Right.png");
JMenuItem mntmTR90 = new JMenuItem(new AbstractAction("Rotate 90+", icon90) {
public void actionPerformed(ActionEvent e) {
degrees += 90;
repaint();
}
});

Related

Show polygon's coordinates in JPanel java

I am new to java and i am trying to draw some lines one after another. When i right clik, the (kind of) polygon ends and then starts another one with the next (left) click. I wanna show in a JLabel the coordinates ofeach point of these polygons. It should look(foe example) like this
The coordinates should be shown only when the "Ausgabe" button is clicked. I tried to save the coordinates in a list, but i don't know how to show it in a JLabel. Here is my code until now.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.geom.*;
import java.util.ArrayList;
import java.util.List;
class MousePanel extends JPanel implements MouseListener,ActionListener{
private int x,y,x2,y2,a=1;
Point2D p= new Point2D.Double(x,y);
public final List <Point2D> coordinates= new ArrayList <Point2D>();
public final String listString= coordinates.toString();
public MousePanel(){
super();
addMouseListener(this);
}
public void paint(Graphics g){ // draws the lines
Graphics2D g2d= (Graphics2D) g;
GeneralPath gp = new GeneralPath ();
gp.moveTo (x,y);
gp.lineTo(x2,y2);
g2d.draw(gp);
}
public void mousePressed(MouseEvent mouse){
if (SwingUtilities.isLeftMouseButton(mouse)){ // if left mouse button is clicked
if (a == 1) { // the lines ar one after the another
a = 0; // set the first click coordinates
x = x2 = mouse.getX();
y = y2 = mouse.getY();
coordinates.add(p); // saves the coordinates in the list
}
else {
x = x2;
y = y2;
x2 = mouse.getX();
y2 = mouse.getY();
repaint();
coordinates.add(p);
}}
else { // if right mouse button is clicked
a = 1; // --> new polygon/ line
x = x2;
y = y2;
x2 = mouse.getX();
y2 = mouse.getY();
repaint();
coordinates. add(p);
}
}
public void mouseEntered(MouseEvent mouse){ }
public void mouseExited(MouseEvent mouse){ }
public void mouseClicked(MouseEvent mouse){ }
public void mouseReleased(MouseEvent mouse){ }
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
class MyGui extends JFrame implements ActionListener {
JLabel label = new JLabel ("<html>First line<br>Second line</html>");
public void createGUI() { // creates the frame
setTitle("Monica's first GUI");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500, 700);
JPanel container = (JPanel) getContentPane();
container.setLayout(null);
label.setBounds(0,430,500,130);
label.setBackground(Color.white);
label.setOpaque(true);
getContentPane().add(label);
JButton go = new JButton("Beenden"); // creates and adds the buttons
go.setBounds(250,580,130,40);
container.add(go);
go.addActionListener(this);
JButton go2 = new JButton("Ausgabe");
go2.setBounds(100,580,130,40);
container.add(go2);
go2.addActionListener(this);
JMenuBar menubar=new JMenuBar(); // creates the menu
JMenu menu=new JMenu("Menu");
JMenuItem exit=new JMenuItem("Exit");
JMenuItem reset=new JMenuItem ("Reset");
JMenuItem ausgabe= new JMenuItem ("Ausgabe2");
menu.add("Save");
menu.add(reset);
JMenu edit= new JMenu ("Edit");
menu.add(edit);
edit.add("Copy");
edit.add("Cut");
edit.add("Paste");
menu.add(exit);
menu.add(ausgabe);
menubar.add(menu);
setJMenuBar(menubar);
exit.addActionListener(this);
reset.addActionListener(this);
ausgabe.addActionListener(this);
}
public void actionPerformed(ActionEvent e) // the buttons respond when clicked
{
if(e.getActionCommand()=="Beenden")
{
System.exit(0);
}
if(e.getActionCommand()=="Ausgabe")
{
}
if(e.getActionCommand()=="Exit")
{
System.exit(0);
}
if (e.getActionCommand()=="Reset") // clears the JPanel
{
getContentPane().repaint();
label.setText("");
}
}
}
public class MyFirstGui {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
MyGui myGUI = new MyGui();
myGUI.createGUI();
MousePanel panel = new MousePanel();
panel.setBounds(0,0,500,430);
myGUI.getContentPane().add(panel);
myGUI.setVisible(true);
}
});
}
}
Any help???
So for this to work, you need to change a couple things about your code. The first thing is, to either make your coordinates ArrayList public static
public static final List <Point2D> coordinates= new ArrayList <Point2D>();
or to pass the instance of MousePanel you are creating to MyGui.
public class MyFirstGui {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
MousePanel panel = new MousePanel();
panel.setBounds(0,0,500,430);
MyGui myGUI = new MyGui(panel);
myGUI.createGUI();
myGUI.getContentPane().add(panel);
myGUI.setVisible(true);
}
});
}
}
You then store this instance locally in your MyGui.
class MyGui extends JFrame implements ActionListener {
private MousePanel storedMousePanel;
public MyGui(MousePanel mousePanel) {
this.storedMousePanel = mousePanel;
}
}
Next you can use either the stored instance or the static List to access your coordinates. To print them out the way you wanted, we can use a for-loop to iterate through the List and then just add all the coordinates up to one large string.
public void actionPerformed(ActionEvent e) // the buttons respond when clicked
{
if (e.getActionCommand()=="Beenden") {
...
}
else if(e.getActionCommand()=="Ausgabe")
{
getContentPane().repaint();
String labelText = "";
//Using the static List
for (int i = 0; i < MousePanel.coordinates.size(); i++) {
labelText += "(" + String.valueOf(MousePanel.coordinates.get(i).getX()) + ")(" + String.valueOf(MousePanel.coordinates.get(i).getY()) + ")\n";
}
//Using the stored instance
for (int i = 0; i < storedMousePanel.coordinates.size()) {
labelText += "(" + String.valueOf(storedMousePanel.coordinates.get(i).getX()) + ")(" + String.valueOf(storedMousePanel.coordinates.get(i).getY()) + ")\n";
}
label.setText(labelText);
}
else if(e.getActionCommand()=="Exit")
{
System.exit(0);
}
else if (e.getActionCommand()=="Reset") // clears the JPanel
{
getContentPane().repaint();
label.setText("");
}
}

switching images dynamically on jframe

I have an assignment to create a GUI that switches images when a menu item is selected (ex. file, new picture) and also contains buttons for zooming in and out on the images. When I try switching images with my code, the image only partly loads. When I minimize the window and then reopen it, the image is fully loaded. I'm wondering why this is happening.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
public class ImageZoom extends JPanel {
private Image image;
int x, y;
private JButton zoomIn;
private JButton zoomOut;
private JMenuBar bar;
private JMenu file;
private JMenuItem choosePic = new JMenuItem("New Picture");
private String pics[] = {"waterfall.jpg", "mountains.jpg"};
private int picIndex = 1;
int imageHeight = getHeight();
int imageWidth = getWidth();
int zoom = 1;
Image images[] = new Image[2];
public ImageZoom() {
try {
images[0] = ImageIO.read(new File("waterfall.jpg"));
images[1] = ImageIO.read(new File("mountains.jpg"));
} catch (IOException e) {}
zoomIn = new JButton("+");
zoomOut = new JButton("-");
JPanel panel = new JPanel();
bar = new JMenuBar();
file = new JMenu("File");
file.add(choosePic);
bar.add(file);
choosePic.addActionListener (new ActionListener() {
public void actionPerformed (ActionEvent e) {
if (e.getSource() == choosePic) {
repaint();
}
}
});
zoomIn.addActionListener (new ActionListener() {
public void actionPerformed (ActionEvent e) {
if (e.getSource() == zoomIn) {
if (zoom < 6) {
zoom += 1;
repaint();
}
}
}
});
zoomOut.addActionListener( new ActionListener() {
public void actionPerformed (ActionEvent e) {
if (e.getSource() == zoomOut) {
if (zoom > 1) {
zoom -= 1;
repaint();
}
}
}
});
}
public JPanel getButtonPanel () {
JPanel panel = new JPanel();
panel.add(zoomIn);
panel.add(zoomOut);
return panel;
}
public Image getImage() {
try {
image = ImageIO.read(new File(pics[picIndex % 2]));
picIndex++;
}
catch (IOException e){}
return image;
}
protected void paintComponent (Graphics g) {
imageHeight = getHeight() * zoom;
imageWidth = getWidth() * zoom;
super.paintComponent(g);
g.drawImage(getImage(), 0, 0, imageWidth, imageHeight, null);
}
public void createJFrame () {
JFrame frame = new JFrame();
ImageZoom imgZoom = new ImageZoom();
frame.setJMenuBar(bar);
frame.add(imgZoom);
frame.add(getButtonPanel(), BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(650, 650);
frame.setResizable(false);
frame.setVisible(true);
}
}
class Test {
public static void main (String[] args) {
ImageZoom zoom = new ImageZoom();
zoom.createJFrame();
}
}
For simplicity, you should just be using a JLabel and calling its setIcon method to switch the images. You could dynamically scale the images as required (just maintain a reference to the original)
Problem #1
You should be passing this to drawImage, this will allow the component to act as the ImageObserver and schedule additional reprints as required based on events from the image's state, which leads to
Problem #2
You should not be calling getImage from within the paintComponent method, paintComponent could be called for any number of reasons, many of which you don't control or even know about and paintComponent should simply paint the current state of the component and never, ever try and change the state
Side Note: Instead of repeatedly trying to load the images, it would be better to load them once and continue to reuse the loaded reference

Drawing shapes on the image using swing

Here is my code. I am drawing rectangle, oval, lines on the image. Drawing a line is working fine. I can draw the rectangle, but it is not visible on mouse drag. How to modify this program to show rectangle on mouse drag. How to provide eraser for this program to erase only the shapes while preserving the background image.
package com.sobis.hindalco.bean
import java.awt.*;
import java.awt.RenderingHints.Key;
import java.awt.event.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriter;
public class ImageEdit extends JFrame{
private BufferedImage originalImage;
private BufferedImage canvasImage;
private JPanel gui;
private Color color = Color.WHITE;
private JLabel output = new JLabel("You DooDoodle!");
BufferedImage image=null;
private BufferedImage colorSample = new BufferedImage(
16,16,BufferedImage.TYPE_INT_RGB);
private JLabel imageLabel;
private int activeTool;
public static final int RECTANGLE_TOOL = 0;
public static final int DRAW_TOOL = 1;
public static final int TEXT_TOOL = 2;
public static final int ERASER_TOOL = 3;
public static final int OVAL_TOOL = 4;
Point startDrag, endDrag;
private Point selectionStart;
private Rectangle selection;
private boolean dirty = false;
// private Stroke stroke = new BasicStroke(
// 3,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND,1.7f);
private RenderingHints renderingHints;
public JComponent getGui() {
if(gui==null) {
Map<Key, Object> hintsMap = new
HashMap();
hintsMap.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
hintsMap.put(RenderingHints.KEY_DITHERING,
RenderingHints.VALUE_DITHER_ENABLE);
hintsMap.put(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
renderingHints = new RenderingHints(hintsMap);
setImage(new BufferedImage(320,240,BufferedImage.TYPE_INT_RGB));
gui = new JPanel(new BorderLayout(4,4));
gui.setBorder(new EmptyBorder(5,3,5,3));
JPanel imageView = new JPanel(new GridBagLayout());
imageView.setPreferredSize(new Dimension(480,320));
imageLabel = new JLabel(new ImageIcon(canvasImage));
JScrollPane imageScroll = new JScrollPane(imageView);
imageView.add(imageLabel);
imageLabel.addMouseMotionListener(new
ImageMouseMotionListener());
imageLabel.addMouseListener(new ImageMouseListener());
gui.add(imageScroll,BorderLayout.CENTER);
JToolBar tb = new JToolBar();
tb.setFloatable(false);
JButton colorButton = new JButton("Color");
colorButton.setMnemonic('o'); colorButton.setToolTipText("Choose a Color");
ActionListener colorListener = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Color c = JColorChooser.showDialog(
gui, "Choose a color", color);
if(c!=null) {
setColor(c);
}
}
};
colorButton.addActionListener(colorListener);
colorButton.setIcon(new ImageIcon(colorSample));
tb.add(colorButton);
setColor(color);
// final SpinnerNumberModel strokeModel =
// new SpinnerNumberModel(3,1,16,1);
/// JSpinner strokeSize = new JSpinner(strokeModel);
ChangeListener strokeListener = new ChangeListener() {
#Override
public void stateChanged(ChangeEvent arg0) {
}
};
tb.addSeparator();
ActionListener clearListener = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int result = JOptionPane.OK_OPTION;
if(dirty) {
result = JOptionPane.showConfirmDialog(
gui, "Erase the current painting?");
}
if(result==JOptionPane.OK_OPTION) {
clear(canvasImage);
}
}
};
JButton clearButton = new JButton("Clear");
tb.add(clearButton);
clearButton.addActionListener(clearListener);
gui.add(tb, BorderLayout.PAGE_START);
JToolBar tools = new JToolBar(JToolBar.VERTICAL);
tools.setFloatable(false);
JButton crop = new JButton("Crop");
final JRadioButton select = new JRadioButton("Rectangle", true);
final JRadioButton eraser = new JRadioButton("Eraser", true);
final JRadioButton draw = new JRadioButton("Draw");
final JRadioButton text = new JRadioButton("Text");
final JRadioButton oval = new JRadioButton("oval");
tools.add(select);
tools.add(draw);
tools.add(text);
tools.add(eraser);
tools.add(oval);
ButtonGroup bg = new ButtonGroup();
bg.add(select);
bg.add(text);
bg.add(draw);
bg.add(eraser);
bg.add(oval);
ActionListener toolGroupListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==select) {
activeTool = RECTANGLE_TOOL;
}else if(ae.getSource()==draw) {
activeTool = DRAW_TOOL;
}else if(ae.getSource()==text) {
activeTool = TEXT_TOOL;
}else if(ae.getSource()==eraser) {
activeTool = ERASER_TOOL;
}else if(ae.getSource()==oval) {
activeTool = OVAL_TOOL;
}
}
};
select.addActionListener(toolGroupListener);
draw.addActionListener(toolGroupListener);
text.addActionListener(toolGroupListener);
eraser.addActionListener(toolGroupListener);
oval.addActionListener(toolGroupListener);
gui.add(tools, BorderLayout.LINE_END);
gui.add(output,BorderLayout.PAGE_END);
clear(colorSample);
clear(canvasImage);
}
return gui;
}
/** Clears the entire image area by painting it with the current color. */
public void clear(BufferedImage bi) {
try{
image = ImageIO.read(new File("D:\\images.jpeg"));
}catch(Exception e){
}
this.originalImage = image;
int w = image.getWidth();
int h = image.getHeight();
canvasImage = new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = this.canvasImage.createGraphics();
g.setRenderingHints(renderingHints);
g.drawImage(image, 0, 0, gui);
g.dispose();
selection = new Rectangle(0,0,w,h);
if(this.imageLabel!=null) {
imageLabel.setIcon(new ImageIcon(canvasImage));
this.imageLabel.repaint();
}
if(gui!=null) {
gui.invalidate();
}
}
public void setImage(BufferedImage image1) {
try{
image = ImageIO.read(new File("D:\\images.jpeg"));
}catch(Exception e){
}
this.originalImage = image;
int w = image.getWidth();
int h = image.getHeight();
canvasImage = new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = this.canvasImage.createGraphics();
g.setRenderingHints(renderingHints);
g.drawImage(image, 0, 0, gui);
g.dispose();
selection = new Rectangle(0,0,w,h);
if(this.imageLabel!=null) {
imageLabel.setIcon(new ImageIcon(canvasImage));
this.imageLabel.repaint();
}
if(gui!=null) {
gui.invalidate();
}
}
/** Set the current painting color and refresh any elements needed. */
public void setColor(Color color) {
this.color = color;
clear(colorSample);
}
private JMenu getFileMenu(boolean webstart){
JMenu file = new JMenu("File");
file.setMnemonic('f');
//JMenuItem newImageItem = new JMenuItem("New");
//newImageItem.setMnemonic('n');
ActionListener newImage = new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
BufferedImage bi = new BufferedImage(
360, 300, BufferedImage.TYPE_INT_ARGB);
clear(bi);
setImage(bi);
}
};
if(webstart) {
//TODO Add open/save functionality using JNLP API
}else{
//TODO Add save functionality using J2SE API
file.addSeparator();
ActionListener saveListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser ch = getFileChooser();
int result = ch.showSaveDialog(gui);
if(result==JFileChooser.APPROVE_OPTION ) {
try {
File f = ch.getSelectedFile();
ImageIO.write(ImageEdit.this.canvasImage, "png",
f); ImageEdit.this.originalImage =
ImageEdit.this.canvasImage;
dirty = false;
} catch (IOException ioe) {
showError(ioe);
ioe.printStackTrace();
}
}
}
};
JMenuItem saveItem = new JMenuItem("Save");
saveItem.addActionListener(saveListener);
saveItem.setMnemonic('s');
file.add(saveItem);
}
if(canExit()) {
ActionListener exit = new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.exit(0);
}
};
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.setMnemonic('x');
file.addSeparator();
exitItem.addActionListener(exit);
file.add(exitItem);
}
return file;
}
private void showError(Throwable t) {
JOptionPane.showMessageDialog(
gui,
t.getMessage(),
t.toString(),
JOptionPane.ERROR_MESSAGE);
}
JFileChooser chooser = null;
public JFileChooser getFileChooser() {
if(chooser==null) {
chooser = new JFileChooser();
FileFilter ff= new FileNameExtensionFilter( "myfiles","jpg",
"jpeg","png");
chooser.addChoosableFileFilter(ff);
}
return chooser;
}
public boolean canExit() {
boolean canExit = false;
SecurityManager sm = System.getSecurityManager();
if(sm==null) {
canExit = true;
}else{
try {
sm.checkExit(0);
canExit = true;
} catch(Exception stayFalse) {
}
}
return canExit;
}
public JMenuBar getMenuBar(boolean webstart){
JMenuBar mb = new JMenuBar();
mb.add(this.getFileMenu(webstart));
return mb;
}
public void openPanel() {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
// use default
}
ImageEdit bp = new ImageEdit();
JFrame f = new JFrame("Image Editing");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(bp.getGui());
f.setJMenuBar(bp.getMenuBar(false));
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
public void text(Point point) {
String text = JOptionPane.showInputDialog(gui, "Text to add",
"Text");
if(text!=null) {
Graphics2D g = this.canvasImage.createGraphics();
g.setRenderingHints(renderingHints);
g.setColor(this.color);
// g.setStroke(stroke);
int n = 0;
g.drawString(text,point.x,point.y);
g.dispose();
this.imageLabel.repaint();
}
}
public void draw(Point point) {
Graphics2D g = this.canvasImage.createGraphics();
g.setRenderingHints(renderingHints);
g.setColor(this.color);
int n = 0;
g.drawLine(point.x, point.y, point.x+n, point.y+n);
g.dispose();
this.imageLabel.repaint();
}
public void drawRectangle() {
Graphics2D g = this.canvasImage.createGraphics();
g.setRenderingHints(renderingHints);
g.setColor(this.color);
g.drawRect(Math.min(startDrag.x, endDrag.x), Math.min(
startDrag.y,endDrag.y), Math.abs(startDrag.x -endDrag.x),
Math.abs(startDrag.y - endDrag.y));
this.imageLabel.repaint();
}
public void eraser(Point point) {
Graphics2D g = this.canvasImage.createGraphics();
g.setRenderingHints(renderingHints);
g.setColor(this.color);
int n = 0;
g.clearRect(point.x, point.y, point.x+n, point.y+n);
g.dispose();
this.imageLabel.repaint();
}
public void oval() {
Graphics2D g = this.canvasImage.createGraphics();
g.setRenderingHints(renderingHints);
g.setColor(this.color);
// g.setStroke(stroke);
int n = 0;
// g.clearRect(x1,y1,x2,y2);
g.dispose();
this.imageLabel.repaint();
}
class ImageMouseListener extends MouseAdapter {
#Override
public void mousePressed(MouseEvent arg0) {
if(activeTool==ImageEdit.TEXT_TOOL) {
// TODO
text(arg0.getPoint());
}else if(activeTool==ImageEdit.ERASER_TOOL) {
// TODO
eraser(arg0.getPoint());
}else if(activeTool==ImageEdit.ERASER_TOOL) {
// TODO
draw(arg0.getPoint());
}else{
startDrag = new Point(arg0.getX(), arg0.getY());
endDrag = startDrag;
}
}
#Override
public void mouseReleased(MouseEvent arg0) {
if(activeTool==ImageEdit.RECTANGLE_TOOL) {
endDrag = new Point( arg0.getX(), arg0.getY());
drawRectangle();
}
}
}
class ImageMouseMotionListener implements MouseMotionListener {
#Override
public void mouseDragged(MouseEvent arg0) {
reportPositionAndColor(arg0);
endDrag = new Point( arg0.getX(), arg0.getY());
if(activeTool==ImageEdit.DRAW_TOOL) {
draw(arg0.getPoint());
}else if(activeTool==ImageEdit.RECTANGLE_TOOL) {
endDrag = new Point( arg0.getX(), arg0.getY());
}else if(activeTool==ImageEdit.OVAL_TOOL) {
oval();
}
}
#Override
public void mouseMoved(MouseEvent arg0) {
reportPositionAndColor(arg0);
}
}
private void reportPositionAndColor(MouseEvent me) {
String text = "";
if(activeTool==ImageEdit.RECTANGLE_TOOL) {
text += "Selection (X,Y:WxH): " +
(int)selection.getX() +
"," +
(int)selection.getY() +
":" +
(int)selection.getWidth() +
"x" +
(int)selection.getHeight();
}else{
text += "X,Y: " + (me.getPoint().x+1) + "," +
(me.getPoint().y+1);
}
output.setText(text);
}
}
How to modify this program to show rectangle on mouse drag.
You can check out Custom Painting Approaches.
Both approaches draw a temporary Rectangle as you hold down the mouse and drag it. Basically you need to handle mousePressed to track the starting point, mouseDragged to get the current mouse point (and to a repaint()) and mouseReleased to save the actual Rectangle.
How to provide eraser for this program to erase only the shapes while preserving the background image.
You would probably want to use the Draw On Component approach from the above link. Then you would iterated through the List of shapes to determine if the mouse point is contained by the shape. If so, then you would remove the shapes from the List. So this will only permit erasure of entire shapes.

Erase bufferedImage from JPanel by clicking a button on another JPanel

I'm just trying to open an image in one panel and click a button on another panel to make that image disappear.
The following is just a very shorten version of the original code and addresses the specific problem.
public class NahualProductionTest {
public static void main(String[] args) {
NahualImagesPanel nahualPanel1 = new NahualImagesPanel();
NahualSettingsPanel nahualPanel2 = new NahualSettingsPanel();
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(1,2));
frame.add(nahualPanel1);
frame.add(nahualPanel2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(900,400);
frame.setLocation(200,200);
frame.setVisible(true);
}
}
public class NahualSettingsPanel extends JPanel {
private JButton button;
private NahualImagesPanel images;
public NahualSettingsPanel(){
images = new NahualImagesPanel();
button = new JButton("Add");
add(button);
button.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
if (e.getSource()==button)
images.setVoid();
}
}
);
}
}
public class NahualImagesPanel extends JPanel{
private BufferedImage tempImage;
private int width, height, x, y;
private double wrate = 0;
private double hrate = 0;
private JButton load;
private PicPanel pics;
public NahualImagesPanel(){
setLayout(new BorderLayout());
pics = new PicPanel();
pics.setBackground(Color.DARK_GRAY);
JPanel commands = new JPanel();
commands.setLayout(new GridLayout(1,1));
load = new JButton("Add Image");
commands.add(load);
add(pics, BorderLayout.CENTER);
add(commands, BorderLayout.SOUTH);
load.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e1){
if (e1.getSource()==load){
try{
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.showOpenDialog(null);
tempImage = ImageIO.read(chooser.getSelectedFile());
rescale(tempImage);
repaint();
} catch (IOException exception){
exception.printStackTrace();
System.exit(1);
} catch (IllegalArgumentException iae){}
}
}
}
);
}
public void setVoid(){
tempImage = null; //tempImage is set to null but after repaint() the image is still there
pics.revalidate();
pics.repaint();
}
public void rescale(Image img){
width = tempImage.getWidth();
height = tempImage.getHeight();
if (width>270 || height>250){
if (width-270>height-250){
wrate = (double) (width-270)/width;
width = 270;
height = height - (int) (wrate*height);
x = 10;
y = 15;
}
if (width-270<height-250) {
hrate = (double) (height-250)/height;
height = 250;
width = width - (int) (hrate*width);
x = (300-width)/2;
y = 15;
}
}
}
public class PicPanel extends JPanel{
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
System.out.println(tempImage);
g.drawImage(tempImage, x, y, width, height, null);
//System.out.println(tempImage);
}
}
}

how to set up an background image on the panel in java such that my buttons are clearly visible?

here my buttons on panel are visible only when i place my mouse over them and secret password button and JTextfield even then not visible .please suggest some ideas to get over this problem.I have three buttons and labels and text field.
public class FileOperation extends JFrame
{
private Player player;
private File file;
private class BackgroundPanel extends Panel
{
Image img;
public BackgroundPanel()
{
try
{
img = Toolkit.getDefaultToolkit().createImage("17.jpg");
}
catch(Exception e){/*handled in paint()*/}
}
#Override
public void paint(Graphics g)
{
super.paint(g);
if(img != null) g.drawImage(img, 0,0,this.getWidth(),this.getHeight(),this);
else g.drawString("No Image",100,100);
}
}
public FileOperation()
{
super( "File Protection Tool" );
BackgroundPanel panel = new BackgroundPanel();
panel.setLayout (null);
JLabel label5=new JLabel("SecretPassword");
final JTextField hashkey = new JTextField(15);
JButton openFilee = new JButton( "Open file to encrypt" );
openFilee.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
openFile(0,hashkey);
}
});
JButton openFiled = new JButton("Open file to decrypt");
openFiled.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent d )
{
openFile(1,hashkey);
}
});
JButton openFilefol = new JButton("Choose folder to lock");
openFilefol.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent d )
{
openFilefol();
}
});
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();
int screenHeight = screenSize.height;
int screenWidth = screenSize.width;
setSize(screenWidth / 2, screenHeight / 2);
setLocation(screenWidth / 4, screenHeight / 4);
setTitle("FileEncrypt");
hashkey.setBounds(200,210,150,20);
label5.setBounds(100,210,150,20);
openFilee.setBounds(50,120,190,20);
openFiled.setBounds(300,120,190,20);
openFilefol.setBounds(80,240,190,20);
panel.add(openFilee);
panel.add(openFiled);
panel.add(openFilefol);
panel.add(label5);
panel.add(hashkey);
panel.setVisible(true);
getContentPane().add(panel);
}
You need to use JPanel instead of Panel and override paintComponent
private class BackgroundPanel extends JPanel
{
Image img;
public BackgroundPanel()
{
try
{
img = Toolkit.getDefaultToolkit().createImage("17.jpg");
}
catch(Exception e){/*handled in paint()*/}
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(img != null) g.drawImage(img, 0,0,this.getWidth(),this.getHeight(),this);
else g.drawString("No Image",100,100);
}
}

Categories