Using desktop as a clear white board - java

Some software uses the monitor as a clear white board to draw. The white board is transparent, and you can see the desktop underneath the clear white board
So how this is possible?
I mean in Java is it like making the JFrame to screen size and making it transparent to draw or how is this being done?
We have a similar requirement so we're trying to understand how to do this?

Here is one way to do it: you create a transparent window on which you put a JLabel displaying a BufferedImage. As the users presses and drags the mouse, you draw on the BufferedImage and repaint the label to update the content.
Some example code to get started:
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class TestTransparentFrame extends JLabel {
private boolean drawing = false;
private Point lastPoint;
private BufferedImage image;
public TestTransparentFrame() {
addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
updateImage();
}
});
MouseAdapter mouseAdapter = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
drawing = true;
lastPoint = e.getPoint();
}
#Override
public void mouseReleased(MouseEvent e) {
drawing = false;
lastPoint = null;
}
#Override
public void mouseExited(MouseEvent e) {
drawing = false;
lastPoint = null;
}
#Override
public void mouseDragged(MouseEvent e) {
if (drawing && lastPoint != null) {
Graphics graphics = image.getGraphics();
graphics.setColor(Color.RED);
((Graphics2D) graphics).setStroke(new BasicStroke(5.0f));
graphics.drawLine(lastPoint.x, lastPoint.y, e.getX(), e.getY());
repaint();
lastPoint = e.getPoint();
}
}
};
addMouseListener(mouseAdapter);
addMouseMotionListener(mouseAdapter);
}
protected void updateImage() {
if (image == null || image.getWidth() < getWidth() || image.getHeight() < getHeight()) {
if (image == null) {
image = getGraphicsConfiguration().createCompatibleImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
} else {
BufferedImage newImage = getGraphicsConfiguration().createCompatibleImage(getWidth(), getHeight(),
BufferedImage.TYPE_INT_ARGB);
newImage.getGraphics().drawImage(image, 0, 0, null);
image = newImage;
}
} else {
image = image.getSubimage(0, 0, getWidth(), getHeight());
}
setIcon(new ImageIcon(image));
}
protected void initUI() {
JFrame frame = new JFrame(TestTransparentFrame.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);
frame.setBackground(new Color(255, 255, 255, 1));
TestTransparentFrame comp = new TestTransparentFrame();
frame.setContentPane(comp);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
}
/**
* #param args
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestTransparentFrame().initUI();
}
});
}
}
And the result:

Related

Brighten Image(JLabel) on a JFrame on hover

I have a JLabel image on a JFrame that I want too brighten upon hovering, have tried a few things however nothing seems to be working, here's my current code:
public class DivinationLogo extends JLabel {
private BufferedImage logo;
public DivinationLogo() {
super();
try {
logo = ImageIO.read(getClass().getResourceAsStream("/assets/images/logo.png"));
} catch (IOException e) {
e.printStackTrace();
}
// setIcon(new ImageIcon(logo));
setIconTextGap(0);
setBorder(null);
setText(null);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
Functions.openWebPage(Config.website);
}
#Override
public void mouseEntered(MouseEvent e) {
Functions.brightnessControl(logo, .3F);
}
#Override
public void mouseExited(MouseEvent e) {
Functions.brightnessControl(logo, 1.0F);
}
});
setBounds(-5, 1, 247, 106);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(logo, -5, 1, null);
}
}
Functions.brightnessControl:
public static Image brightnessControl(Image image, float brightness) {
BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics bg = bi.getGraphics();
if (bi.getColorModel().hasAlpha()) {
System.out.println("Image has got an alpha channel");
}
bg.drawImage(image, 0, 0, null);
bg.dispose();
RescaleOp rescaleOp = new RescaleOp(brightness, 0, null);
rescaleOp.filter(bi, bi);
image = bi;
return bi;
}
Currently, it does nothing which confuses me. If anyone knows how this is achieved, please feel free too let me know :)
Ok, so the basic idea is, when the mouse enters the component, you want to generate a "bright" version of the component (I know, obvious, but bear with me)
The problem is, you have a Graphics context and you need a image :/
The following is not overly optimised, but without spending a lot of time adding in PropertyChange support, this will give you the basic idea.
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.awt.image.RescaleOp;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
JFrame frame = new JFrame();
frame.setLayout(new GridBagLayout());
JLabel label = new BrightLabel();
label.setIcon((new ImageIcon(ImageIO.read(Main.class.getResource("background.png")))));
frame.add(label);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
public class BrightLabel extends JLabel {
private MouseAdapter mouseHandler;
private boolean isHover = false;
#Override
public void addNotify() {
super.addNotify();
mouseHandler = new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
isHover = true;
repaint();
}
#Override
public void mouseExited(MouseEvent e) {
isHover = false;
repaint();
}
};
System.out.println("...");
addMouseListener(mouseHandler);
}
#Override
public void removeNotify() {
super.removeNotify();
if (mouseHandler != null) {
removeMouseListener(mouseHandler);
}
mouseHandler = null;
}
#Override
protected void paintComponent(Graphics g) {
if (!isHover) {
super.paintComponent(g);
return;
}
BufferedImage img = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
super.paintComponent(g2d);
g2d.dispose();
Image bright = brightnessControl(img, 1.3f);
g.drawImage(bright, 0, 0, this);
}
public Image brightnessControl(Image image, float brightness) {
BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics bg = bi.getGraphics();
if (bi.getColorModel().hasAlpha()) {
System.out.println("Image has got an alpha channel");
}
bg.drawImage(image, 0, 0, null);
bg.dispose();
RescaleOp rescaleOp = new RescaleOp(brightness, 0, null);
rescaleOp.filter(bi, bi);
image = bi;
return bi;
}
}
}
Essentially, when the mouse enters or exists the component, we set the isHover property. We then call repaint to trigger a new paint pass.
When the component is painted, if isHover is true, we take over the painting process slightly, generating our own buffer and painting the component to it. This gives us our base image. From there we brighten the image and paint it to the Graphics context
Arguments in java are passed by value so your the function you have to brighten the image doesn't have an effect on the image you passed to it.
You're missing the repaint() call after changing the image.
You definitely don't want to prepare the hover image every time you hover over the image. Pre-calculate the hover in the constructor and assign it to a separate image.
Create a member variable for if hover is true and use that in the paint method to figure out which image to paint.

Swing Paint Project - Draw a thicker line with Java

package com.ssaurel.swingpaint;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JComponent;
/**
* Component for drawing !
*
* #author sylsau
*
*/
public class DrawArea extends JComponent {
// Image in which we're going to draw
private Image image;
// Graphics2D object ==> used to draw on
private Graphics2D g2;
// Mouse coordinates
private int currentX, currentY, oldX, oldY;
public DrawArea() {
setDoubleBuffered(false);
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
// save coord x,y when mouse is pressed
oldX = e.getX();
oldY = e.getY();
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
// coord x,y when drag mouse
currentX = e.getX();
currentY = e.getY();
if (g2 != null) {
// draw line if g2 context not null
g2.drawLine(oldX, oldY, currentX, currentY);
// refresh draw area to repaint
repaint();
// store current coords x,y as olds x,y
oldX = currentX;
oldY = currentY;
}
}
});
}
protected void paintComponent(Graphics g) {
if (image == null) {
// image to draw null ==> we create
image = createImage(getSize().width, getSize().height);
g2 = (Graphics2D) image.getGraphics();
// enable antialiasing
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// clear draw area
clear();
}
g.drawImage(image, 0, 0, null);
}
// now we create exposed methods
public void clear() {
g2.setPaint(Color.white);
// draw white on entire draw area to clear
g2.fillRect(0, 0, getSize().width, getSize().height);
g2.setPaint(Color.black);
repaint();
}
public void red() {
// apply red color on g2 context
g2.setPaint(Color.red);
}
public void black() {
g2.setPaint(Color.black);
}
public void magenta() {
g2.setPaint(Color.magenta);
}
public void green() {
g2.setPaint(Color.green);
}
public void blue() {
g2.setPaint(Color.blue);
}
}
package com.ssaurel.swingpaint;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SwingPaint {
JButton clearBtn, markerBtn, blackBtn, blueBtn, greenBtn, redBtn, magentaBtn;
DrawArea drawArea;
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == clearBtn) {
drawArea.clear();
} else if (e.getSource() == blackBtn) {
drawArea.black();
} else if (e.getSource() == blueBtn) {
drawArea.blue();
} else if (e.getSource() == greenBtn) {
drawArea.green();
} else if (e.getSource() == markerBtn) {
drawArea.black();
} else if (e.getSource() == redBtn) {
drawArea.red();
} else if (e.getSource() == magentaBtn) {
drawArea.magenta();
}
}
};
public static void main(String[] args) {
new SwingPaint().show();
}
public void show() {
// create main frame
JFrame frame = new JFrame("Swing Paint");
Container content = frame.getContentPane();
// set layout on content pane
content.setLayout(new BorderLayout());
// create draw area
drawArea = new DrawArea();
// add to content pane
content.add(drawArea, BorderLayout.CENTER);
// create controls to apply colors and call clear feature
JPanel controls = new JPanel();
clearBtn = new JButton("Clear");
clearBtn.addActionListener(actionListener);
blackBtn = new JButton("Black");
blackBtn.addActionListener(actionListener);
blueBtn = new JButton("Blue");
blueBtn.addActionListener(actionListener);
greenBtn = new JButton("Green");
greenBtn.addActionListener(actionListener);
redBtn = new JButton("Red");
redBtn.addActionListener(actionListener);
magentaBtn = new JButton("Magenta");
magentaBtn.addActionListener(actionListener);
markerBtn = new JButton("Marker");
markerBtn.addActionListener(actionListener);
// add to panel
controls.add(markerBtn);
controls.add(greenBtn);
controls.add(blueBtn);
controls.add(blackBtn);
controls.add(redBtn);
controls.add(magentaBtn);
controls.add(clearBtn);
// add to content pane
content.add(controls, BorderLayout.NORTH);
frame.setSize(900, 720);
// can close frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// show the swing paint result
frame.setVisible(true);
}
}
the code here explains a drawing tool running on a java language using netbeans. what I would like is that the "Marker" to be thicker than default. It's thin to draw this way. well at least for me. anyways, I am lost on how to make it thicker.
Now that you have edited the post to explain that you want your lines to be drawn thicker (which is not the same as 'bold' - bold applies only to fonts) you need to look up Java "stroke styles".
Here is the official filling and stroking tutorial. There are plenty of others.
(Is not a good answer anymore because the op changed his post!)
You need to change your font.
So you need to call on your swing component
.setFont().deriveFont(Font.BOLD));
Or go with
.setFont(new Font("serif", Font.BOLD, 16))
To set a new font

gif animation flickering in applet

My gif animation flickers too much. I've heard about double buffering that can help but how do I do that to my gif animation? Or is there a better faster shortcut to it. This is just a small test applet thing Im doing for fun but will implement the lessons in class.
Context:
import java.net.*;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class HiroshimaBlock extends Applet implements ActionListener {
TextField distanceText = new TextField(10);
TextField accelerationText = new TextField(10);
Button security = new Button("Account Manager");
Button launch = new Button("LAUNCH!");
Button Reportl = new Button("Report Logs");
Image dancer;
URL base;
MediaTracker mt;
Timer tm = new Timer(10, this);
TextArea answers = new TextArea("I am ready for your first trip.", 4, 20,
TextArea.SCROLLBARS_NONE);
Image image;
#Override
public void init() {
setSize(550, 500);
// Some messages for the top of the Applet:
addHorizontalLine(Color.orange);
addNewLine();
// JOptionPane.showMessageDialog(null, "HiroshimaBlock",
// "Welcome to HiroshimaBlock", JOptionPane.PLAIN_MESSAGE);
// The two text fields and the launch button:
Frame c = (Frame) this.getParent().getParent();
c.setTitle("HiroshimaBlock");
mt = new MediaTracker(this);
try {
base = getDocumentBase();
} catch (Exception e) {
}
dancer = getImage(base, "dancer1.gif");
mt.addImage(dancer, 9);
try {
mt.waitForAll();
} catch (InterruptedException e) {
}
loadImage();
// add(distanceText);
// add(new Label("Distance of trip in light years"));
addNewLine();
addNewLine();
// add(accelerationText);
// add(new Label("Acceleration of rocket in g's"));
addNewLine();
add(launch);
addNewLine();
add(security);
addNewLine();
add(Reportl);
// A text area for printing the answers:
// answers.setEditable(false);
// add(answers);
addNewLine();
addNewLine();
addHorizontalLine(Color.orange);
}
public void loadImage() {
URL url = getClass().getResource("hsblock.png");
image = getToolkit().getImage(url);
}
public void paint(Graphics g) {
g.drawImage(image, 20, 20, this);
this.security.setLocation(25, 200);
addNewLine();
this.launch.setLocation(25, 230);
this.Reportl.setLocation(25, 260);
this.security.setSize(100, 25);
this.launch.setSize(100, 25);
this.Reportl.setSize(100, 25);
g.drawImage(dancer, 150, 200, this);
tm.start();
}
private void addHorizontalLine(Color c) {
// Add a Canvas 10000 pixels wide but only 1 pixel high, which acts as
// a horizontal line to separate one group of components from the next.
Canvas line = new Canvas();
line.setSize(10000, 1);
line.setBackground(c);
add(line);
}
private void addNewLine() {
// Add a horizontal line in the background color. The line itself is
// invisible, but it serves to force the next Component onto a new line.
addHorizontalLine(getBackground());
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
You want to:
Create a drawing class that extends JPanel (or JComponent)
Override the paintComponent(Graphics g) method of your class.
Call the super's method first in this method
And then do your animation drawing in this method.
This will give you Swing's automatic double buffering which should help smooth out your animation.
Display your drawing JPanel in your JApplet by adding it to the applet's contentPane.
For example:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.lang.reflect.InvocationTargetException;
import java.nio.Buffer;
import javax.swing.*;
public class SimpleAnimation extends JApplet {
#Override
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
DrawPanel drawPanel = new DrawPanel();
getContentPane().add(drawPanel);
}
});
} catch (InvocationTargetException | InterruptedException e) {
e.printStackTrace();
}
}
}
class DrawPanel extends JPanel {
private static final int I_WIDTH = 20;
private static final int I_HEIGHT = 20;
private static final int TIMER_DELAY = 15;
private int x = 0;
private int y = 0;
private BufferedImage img = new BufferedImage(I_WIDTH, I_HEIGHT, BufferedImage.TYPE_INT_ARGB);
public DrawPanel() {
Graphics2D g2 = img.createGraphics();
g2.setColor(Color.red);
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.fillOval(1, 1, I_WIDTH - 2, I_HEIGHT - 2);
g2.dispose();
new Timer(TIMER_DELAY, new TimerListener()).start();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, x, y, this);
}
}
private class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
x++;
y++;
repaint();
}
}
}
Well LOL I made it stop flickering by using update LOLOLOL
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Test extends Applet {
Image img;
public void init() {
setSize(700, 700);
img = getImage(getDocumentBase(), "dancer1.gif");
}
public void update(Graphics g) {
g.drawImage(img, 140, 200, this);
}
public void paint(Graphics g) {
update(g);
}
}

How do i temporarily store an image of the JPanel or PaintComponent in Java?

I'm trying to make a paint program, and this class is the main area where you drag your mouse to paint. The problem is the clip has to be rectangular, so any other lines within that rectangle of the clip (the clip gets bigger the faster you move) will get covered by the new clip, however the new clip isn't all needed.
My ideas of solutions are:
To somehow set the clip to a line (but I think that clip would have to be set in the repaint method, not the setClip() in paint component)
To save the image currently on the paint component and set it to the backgroud
Possibly set the ocupancy of the clip lower in the areas without the line?
Thank you for looking at it, here is the code (with some parts left out for simpler reading) and if you know a solution I would love to hear it. Thanks!
public class Canvas extends JPanel implements MouseMotionListener, MouseListener{
int sizeX, sizeY;
String title;
int[] backColor = new int[3];
int brushSize=20;
Point currentP = new Point();
Point pastP = new Point();
Point paintP = new Point();
int diffX, diffY;
boolean initialize=true;
boolean initClip=true;
Canvas(){
backColor[0] = newProject.colorA;
backColor[1] = newProject.colorB;
backColor[2] = newProject.colorC;
if(backColor[0]>=255){
backColor[0]=255;
}
if(backColor[1]>=255){
backColor[1]=255;
}
if(backColor[2]>=255){
backColor[2]=255;
}
sizeX = newProject.sizeX;
sizeY = newProject.sizeY;
//System.out.println(sizeX + " " + sizeY);
setSize(sizeX,sizeY);
setBackground(Color.white);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(brushSize));
if(initialize){
g.setColor(new Color(backColor[0], backColor[1], backColor[2]));
g.fillRect(0, 0, sizeX, sizeY);
g.setColor(Color.red);
g.drawRect(0,0,50,50);
System.out.println("Initialize");
}
else{
g2.drawLine(currentP.x, currentP.y, pastP.x,pastP.y);
}
//System.out.println("Paint");
}
#Override
public void mouseDragged(MouseEvent e) {
if(initClip) //if mouse has been released since last dragged
currentP = e.getPoint(); //This causes PastP and CurrentP to be equal
initClip=false; //since pastP is set equal to CurrentP afterward
pastP = currentP;
currentP = e.getPoint();
diffX=Math.abs(currentP.x-pastP.x); //find the differences to find how big of
diffY=Math.abs(currentP.y-pastP.y); //a clip it needs
if(diffX==0){ //if no movement, set it to brush size so the
diffX=brushSize; //clip shows up
}
if(diffY==0){
diffY=brushSize;
}
initialize=false;
if(currentP.x-pastP.x>0){ //figures out which direction it moved
paintP.x=pastP.x; //sets the clip variable to the correct corner
}
else{
paintP.x=currentP.x;
}
if(currentP.y-pastP.y>0){
paintP.y=pastP.y;
}
else{
paintP.y=currentP.y;
}
System.out.println(paintP);
repaint(paintP.x, paintP.y, diffX, diffY); //repaint with point PaintP and the
//difference it moved
}
#Override
public void mouseReleased(MouseEvent arg0) {
initClip=true;
}
I'm not sure why you would bother. Each time paintComponent is called by the paint system, you are expected to repaint the entire component anyway.
Instead, simply paint what you need to paint, then paint the selection on top of it...
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class DrawSelection {
public static void main(String[] args) {
new DrawSelection();
}
public DrawSelection() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private BufferedImage background;
private Rectangle clipRect;
public TestPane() {
try {
background = ImageIO.read(new File("/path/to/your/image"));
} catch (IOException ex) {
ex.printStackTrace();
}
MouseAdapter ma = new MouseAdapter() {
private Point cp;
#Override
public void mousePressed(MouseEvent e) {
cp = e.getPoint();
clipRect = null;
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
cp = null;
}
#Override
public void mouseDragged(MouseEvent e) {
Point p = e.getPoint();
int x = Math.min(p.x, cp.x);
int y = Math.min(p.y, cp.y);
int width = Math.max(p.x, cp.x) - x;
int height = Math.max(p.y, cp.y) - y;
clipRect = new Rectangle(x, y, width, height);
repaint();
}
};
addMouseListener(ma);
addMouseMotionListener(ma);
}
#Override
public Dimension getPreferredSize() {
return background == null ? new Dimension(200, 200) : new Dimension(background.getWidth(), background.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (background != null) {
int x = (getWidth() - background.getWidth()) / 2;
int y = (getHeight() - background.getHeight()) / 2;
g2d.drawImage(background, x, y, this);
}
if (clipRect != null) {
g2d.setColor(UIManager.getColor("List.selectionBackground"));
g2d.setComposite(AlphaComposite.SrcOver.derive(0.5f));
g2d.fill(clipRect);
}
g2d.dispose();
}
}
}
If you want to optimise the paint process, why not draw the parts of the image to a backing buffer and simply paint the buffer, then paint the selection or other dynamic parts on top of it within the paintComponent?

Big image on smaller JFrame/Applet

I have a pretty big image that I want to display on my JFrame and applet, the JFrame/Applet is 765x503 in size but the image is way larger. I need a way to display the image in real size. How can I make it so I can move the screen around to display some of the image and be able to move around the image?
I want to be able to drag the screen around, not use Scrollbars.
JScrollPane might be the one you need.. add both vertical and horizontal scrolls
The basic idea is you need to provide some kind of offset that should be applied to the image to be drawn.
When the user presses the mouse button at a point on the image, you record the click point. When the drag the mouse, you delta the difference. This gives you the amount the offset is to be moved. Based on the original position, you simply add this difference to the and generate a new offset.
There are other ways to do it, but generally, this is the method I use.
I've also added code to check to see if the drag would put the image out of bounds of the viewable area, you'll have to decide if you want to use it...
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class BigImage {
public static void main(String[] args) {
new BigImage();
}
public BigImage() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private BufferedImage bg;
private Point offset = new Point(0, 0);
public TestPane() {
try {
bg = ImageIO.read(new File("/path/to/image"));
} catch (IOException ex) {
ex.printStackTrace();
}
MouseAdapter ma = new MouseAdapter() {
private Point clickPoint;
private Point origin;
#Override
public void mousePressed(MouseEvent e) {
setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
clickPoint = e.getPoint();
origin = new Point(offset);
}
#Override
public void mouseReleased(MouseEvent e) {
setCursor(Cursor.getDefaultCursor());
clickPoint = null;
}
#Override
public void mouseDragged(MouseEvent e) {
int x = e.getPoint().x - clickPoint.x;
int y = e.getPoint().y - clickPoint.y;
offset.x = origin.x + x;
offset.y = origin.y + y;
if (offset.x > 0) {
offset.x = 0;
}
if (offset.x + bg.getWidth() < getWidth()) {
offset.x = -bg.getWidth() + getWidth();
}
if (offset.y > 0) {
offset.y = 0;
}
if (offset.y + bg.getHeight() < getHeight()) {
offset.y = -bg.getHeight() + getHeight();
}
repaint();
}
};
addMouseListener(ma);
addMouseMotionListener(ma);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(800, 600);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (bg != null) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawImage(bg, offset.x, offset.y, this);
g2d.dispose();
}
}
}
}

Categories

Resources