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);
}
}
}
Related
I've looked all over and I can only find cases of people using their custom JPannel to draw an image over another image but what I'm trying to do is draw a component over the JPannel and no matter what I try it always moves the JPannel when it draws the next frame. It feels like ther must be a way to override the meathod that draws it on front and allows you to draw it in the very back but there was none that i could find.
public class MovingBackgroundDemo {
private JToggleButton button = new JToggleButton("Button");
private JFrame frame = new JFrame();
private int framewidth =frame.getWidth();
private int frameheight =frame.getHeight();
public MovingBackgroundDemo() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addComponentListener(new ComponentAdapter()
{
public void componentResized(ComponentEvent evt) {
framewidth =frame.getWidth();
frameheight =frame.getHeight();
button.setBounds(framewidth/2 - framewidth/14 - framewidth/6,frameheight/6, framewidth/6, frameheight / 12);
}
});
frame.add(button);
frame.add(new AnimatingPanel());
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private class AnimatingPanel extends JPanel {
private static final int DIM_W = 350;
private static final int DIM_H = 350;
private static final int INCREMENT = 10;
private BufferedImage backgroundImage;
private Image runnerImage;
private int dx1, dy1, dx2, dy2;
private int srcx1, srcy1, srcx2, srcy2;
private int IMAGE_WIDTH;
public AnimatingPanel() {
initImages();
initImagePoints();
Timer timer = new Timer(40, new ActionListener() {
public void actionPerformed(ActionEvent e) {
moveBackground();
repaint();
}
});
timer.start();
FlowLayout layout = (FlowLayout)getLayout();
layout.setHgap(0);
layout.setVgap(0);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
g.drawImage(backgroundImage, dx1, dy1, dx2, dy2, srcx1, srcy1,
srcx2, srcy2, this);
g.drawImage(runnerImage, 0, 0, getWidth(), getHeight(), this);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(350, 350);
}
private void initImagePoints() {
dx1 = 0;
dy1 = 0;
dx2 = DIM_W;
dy2 = DIM_H;
srcx1 = 0;
srcy1 = 0;
srcx2 = DIM_W;
srcy2 = DIM_H;
}
private void initImages() {
try {
File icoen = new File("the picture");
runnerImage = ImageIO.read(icoen);
File icon = new File("the other one");
backgroundImage = ImageIO.read(icon);
IMAGE_WIDTH = backgroundImage.getWidth();
System.out.println(IMAGE_WIDTH);
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void moveBackground() {
if (srcx1 > IMAGE_WIDTH) {
srcx1 = 0 - DIM_W;
srcx2 = 0;
} else {
srcx1 += INCREMENT;
srcx2 += INCREMENT;
}
}
}
public static void main(String[] args) {
new MovingBackgroundDemo();
}
}
Any tips?
This:
frame.add(button);
frame.add(new AnimatingPanel());
Should be:
JPanel animationPanel = new AnimatingPanel();
animationPanel.add(button);
frame.add(animationPanel);
The first code is trying to add the two components (button and panel) to the same exact layout position in the frame. That won't work (properly, or in some cases, at all).
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
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.
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);
}
}
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();
}
});