Java - Scroll image by mouse dragging - java

I would like to make a join.me like in Java.
I've made the screen capture part but now I want to scroll in the image by dragging the mouse.
Here is a screen of what i've made:
First of all, I want to replace the scroll bars by mouse dragging the image. Is it possible?
Then I want to remove those scroll bars.
Today, users are able to change the zoom and use their mouse wheel to zoom in/out.
Could you help me?
Thanks.
Edit: I've found the way to hide the scroll bar using:
this.jScrollPane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
this.jScrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);

Finally, I did it myself. Here is the solution if someone need it:
Create a new class named HandScrollListener with the following code:
import java.awt.Cursor;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
import javax.swing.JViewport;
public class HandScrollListener extends MouseAdapter
{
private final Cursor defCursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
private final Cursor hndCursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
private final Point pp = new Point();
private JLabel image;
public HandScrollListener(JLabel image)
{
this.image = image;
}
public void mouseDragged(final MouseEvent e)
{
JViewport vport = (JViewport)e.getSource();
Point cp = e.getPoint();
Point vp = vport.getViewPosition();
vp.translate(pp.x-cp.x, pp.y-cp.y);
image.scrollRectToVisible(new Rectangle(vp, vport.getSize()));
pp.setLocation(cp);
}
public void mousePressed(MouseEvent e)
{
image.setCursor(hndCursor);
pp.setLocation(e.getPoint());
}
public void mouseReleased(MouseEvent e)
{
image.setCursor(defCursor);
image.repaint();
}
}
Then in your frame put:
HandScrollListener scrollListener = new HandScrollListener(label_to_move);
jScrollPane.getViewport().addMouseMotionListener(scrollListener);
jScrollPane.getViewport().addMouseListener(scrollListener);
It should work!

Related

Mouse pos relative to frame java windows is wrong

I have an application that opens a window and calculates the relative pos to frame as showed in there : How to get mouse pointer location relative to frame . In Linux this works fine, but when running it on Windows, the Y-Coordinate is around 30px to big
(probably the window border height ?). Thanks for help.
import javax.swing.JFrame;
import java.awt.Graphics;
import javax.swing.JPanel;
import javax.swing.*;
import java.awt.MouseInfo;
public class Name extends JFrame {
public Name() {
super("Name");
setTitle("Application");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,400);
setResizable(true);
setVisible(true);
int x;
int y;
while (true){
x = MouseInfo.getPointerInfo().getLocation().x-getX();
y = MouseInfo.getPointerInfo().getLocation().y-getY(); //This is around 30px to big in windows
System.out.println("X : "+Integer.toString(x)+" Y : "+Integer.toString(y));
try { //Update screen every 33 miliseconds = 25 FPS
Thread.sleep(33);
} catch(InterruptedException bug) {
Thread.currentThread().interrupt();
System.out.println(bug);
}
}
}
public static void main(String args[]){
new Name();
}
}
This code compiles without any error and works fine, but for me, it seems that in Windows the Y-Coordinate is around 30px to big.
Note : This is only a simplified version of the real application, so probably the error wont occur here. But I havent got a Windows device at home, so Im not able to test it.
The code is calculating the difference between the mouse position and the top left corner of the window, that is, the position relative to the window. I suppose you want the position relative to the top left corner of the internal frame (content pane), so try
...
while (true){
Point reference = getContentPane().getLocationOnScreen();
x = MouseInfo.getPointerInfo().getLocation().x-reference.x;
y = MouseInfo.getPointerInfo().getLocation().y-reference.y;
...
not tested on Linux...
import javax.swing.JFrame;
import java.awt.Graphics;
import javax.swing.JPanel;
import javax.swing.*;
import java.awt.MouseInfo;
import java.awt.Component;
public class Name extends JFrame {
public Name() {
super("Name");
setTitle("Application");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,400);
setResizable(true);
setContentPane(new Pane());
setVisible(true);
int x;
int y;
Component[] rel;
while (true){
rel = getComponents();
x=MouseInfo.getPointerInfo().getLocation().x-rel[0].getLocationOnScreen().x;
y=MouseInfo.getPointerInfo().getLocation().y-rel[0].getLocationOnScreen().y;
System.out.println("X : "+Integer.toString(x)+" Y : "+Integer.toString(y));
try { //Update screen every 33 miliseconds = 25 FPS
Thread.sleep(33);
} catch(InterruptedException bug) {
Thread.currentThread().interrupt();
System.out.println(bug);
}
}
}
class Pane extends JPanel {
public void paintComponent(Graphics g) { //Here is were you can draw your stuff
g.drawString("Hello World",0,20); //Display text
}
}
public static void main(String args[]){
new Name();
}
}
this did the trick

draw and save an image

I'm coding the simple project to draw lines and save likes an image,but when I run, it shows an errors that I can't fix. Please help me.
Here is my code:
package image;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Point;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class paint extends JFrame{
private Point points[] = new Point[10000];
private Point pointends[] = new Point[10000];
private int pointCount = 0;
private JButton save_btn;
public paint()
{
panel paint2 = new panel();
add(paint2,BorderLayout.CENTER);
}
private class panel extends JPanel
{
public panel()
{
setBackground(Color.WHITE);
save_btn = new JButton();
save_btn.setText("123");
this.add(save_btn);
/* save btnhandler = new save();
save_btn.addActionListener(btnhandler);*/
MouseHandler handler = new MouseHandler();
this.addMouseMotionListener(handler);
this.addMouseListener(handler);
}
#Override
protected void paintComponent(Graphics g)
{
// TODO Auto-generated method stub
super.paintComponent(g);
for(int i = 0;i <pointCount;i++)
{
g.setColor(Color.RED);
g.drawLine(points[i].x, points[i].y, pointends[i].x, pointends[i].y);
}
}
}
private class MouseHandler extends MouseAdapter
{
#Override
public void mouseDragged(MouseEvent e)
{
// TODO Auto-generated method stub
pointends[ pointCount-1] = e.getPoint();
repaint();
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
super.mousePressed(e);
//find point
if(pointCount < points.length)
{
points[ pointCount ] = e.getPoint();//find point
pointends[ pointCount ] = e.getPoint();
pointCount++;
repaint();
}
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
super.mouseReleased(e);
/*pointends[pointCount]=e.getPoint();
repaint();
pointCount++;
*/
}
}
}
and the class of save event
package image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.Buffer;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;
public class save implements ActionListener{
private paint paint1 = new paint();
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
String str = JOptionPane.showInputDialog(null, "Enter file name: ");
//
BufferedImage bufImage = new BufferedImage(paint1.getWidth(), paint1.getHeight(),BufferedImage.TYPE_INT_RGB);
try {
ImageIO.write(bufImage, "jpg", new File(str + ".jpg"));
} catch (IOException ox) {
// TODO: handle exception
ox.printStackTrace();
}
}
}//end class
The Problem is that Your paint JFrame creates an instance of your save ActionListener, and your save ActionListener creates an instance of your paint JFrame. Thus you run into an infinite loop of constructors.
Instead of creating a new paint object, pass the current one in the constructor for save.
private paint paint1 = null;
public save(paint panel) {
this.paint1 = panel;
}
Now, in your panel constructor, pass a reference to the current instance to the ActionListener:
save btnhandler = new save(my_paint); // see Update below
save_btn.addActionListener(btnhandler);
This should fix your immediate problem. However, I recommend restructuring your code a bit, and you should also try to follow Java coding conventions, e.g., using CamelCase names for classes, and using correct indentation. This will make it much easier for others (and yourself) to read and undertand your code.
Update: I just realized that your object structure is a bit more complicated... your paint JFrame creates a panel JPanel, which creates a save ActionListener, which again creates a paint JFrame. The basic argument and solution remain the same, but instead of using new save(this) you have to either pass a reference to the JFrame containing the JPanel, or change the type of the field in your ActionListener.
Alternatively you could make bothe the JPanel and the ActionListener inner classes of the paint JFrame. This way you can access the JFrame directly from within the ActionListener and do not have to pass a reference at all, thus circumvent the problem entirely and giving a bit more structure to the code.

LWJGL - How to create a button to close the application

I have made it open a full screen window but now how can i create a button to have it exit the application?
Also, do you know any good tutorials to learn. I can't seem to find many?
Lastly can i use the opengl code that i learn to work with java in c++ or is that opengl completely different?
This is the code i have:
package game;
import static org.lwjgl.opengl.GL11.*;
import org.lwjgl.opengl.*;
import org.lwjgl.*;
public class Main {
public Main() {
try {
Display.setDisplayMode(Display.getDesktopDisplayMode());
Display.setFullscreen(true);
Display.create();
} catch(LWJGLException e) {
e.printStackTrace();
}
}
}
lwjgl does not provide any high level widgets such as buttons. You'll need to draw the button using gl calls (use the button image as texture for a quad. Start with a colored rectangle before trying textures). Then you'll need to check for mouse click events in the button area. You may want to consider using a higher level library on top of lwjgl to simplify this.
Here is some code that I made that draws and handles buttons.
You can specify the X, Y and Texture of each button and when the button is clicked the variable isClicked becomes true. As for closing the application , use
if(EXITBUTTON.isClicked)
{
System.exit(0);
}
Button Class:
You need LWJGL and Slick Util.
import java.awt.Rectangle;
import java.io.IOException;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.Color;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;
public class Button {
public int X;
public int Y;
public Texture buttonTexture;
public boolean isClicked=false;
Rectangle bounds = new Rectangle();
public void addButton(int x, int y , String TEXPATH){
X=x;
Y=y;
try {
buttonTexture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream(TEXPATH));
System.out.println(buttonTexture.getTextureID());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bounds.x=X;
bounds.y=Y;
bounds.height=buttonTexture.getImageHeight();
bounds.width=buttonTexture.getImageWidth();
System.out.println(""+bounds.x+" "+bounds.y+" "+bounds.width+" "+bounds.height);
}
public void Draw(){
if(bounds.contains(Mouse.getX(),(600 - Mouse.getY()))&&Mouse.isButtonDown(0)){
isClicked=true;
}else{
isClicked=false;
}
Color.white.bind();
buttonTexture.bind(); // or GL11.glBind(texture.getTextureID());
GL11.glBegin(GL11.GL_QUADS);
GL11.glTexCoord2f(0,0);
GL11.glVertex2f(X,Y);
GL11.glTexCoord2f(1,0);
GL11.glVertex2f(X+buttonTexture.getTextureWidth(),Y);
GL11.glTexCoord2f(1,1);
GL11.glVertex2f(X+buttonTexture.getTextureWidth(),Y+buttonTexture.getTextureHeight());
GL11.glTexCoord2f(0,1);
GL11.glVertex2f(X,Y+buttonTexture.getTextureHeight());
GL11.glEnd();
}
}

Chroma key effect in Java

I also need to find a library which allows to implement the "chroma key" effect in Java. The video contains some part in green color, which is replaced which a picture during the rendering in order to create a new video.
I am linking my question with a similar question which was already answered but with uncomplete answer (Looking for Chromakey library in Java). Could you please specify how did you do to have something up and working so quickly? I have been unsuccessful for some months fighting against the same issue.
c00kiemon5ter pointed several resources:
JavaCV
JAI (Java Advanced Imaging API)
Java Image Processing Cookbook
Which one did work for you?
JavaCV contains lots of methods to process video streams.
This code should get you started: http://tech.groups.yahoo.com/group/OpenCV/message/59118 but it's probably too slow in Java. Try this approach:
Create a filter which turns all the green pixels into a mask (look for things that "select by color").
Use the mask to copy the background image into the video.
I would like to contribute with a piece of code which gave me quite good results. I wonder if I used the classes and methods that Aaron Digulla suggested.
Please note that in this case my video has black background, that is why I am replacing the black color with the background image. I expect to obtain better results when I can edit the video to have green background, because black color is more likely to be used within the video main characters and replacing wrong pixels causes a quite awful effect.
--
package transparentvideo;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImageProducer;
import java.awt.image.RGBImageFilter;
import java.io.File;
import javax.media.Manager;
import javax.media.Player;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TransparentVideo
{
Player mediaPlayer;
JFrame invisibleFrame;
JFrame visibleFrame;
JLabel videoScreen;
JPanel offScreenVideo;
String backgroundImageFile="nature.jpg";
String videoFile="girl.mov";
public TransparentVideo()
{
invisibleFrame = new JFrame();
invisibleFrame.setSize(400, 400);
Container container=invisibleFrame.getContentPane();
offScreenVideo = getvidComp();
offScreenVideo.setPreferredSize(container.getSize());
offScreenVideo.setVisible(true);
container.add(offScreenVideo);
invisibleFrame.setVisible(true);
visibleFrame=new JFrame();
visibleFrame.setSize(container.getSize());
visibleFrame.setLocationRelativeTo(null);
videoScreen = new JLabel();
visibleFrame.getContentPane().add(videoScreen);
visibleFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
visibleFrame.setVisible(true);
invisibleFrame.setVisible(false);
try
{
while(true)
{
if(mediaPlayer.getState()==Player.Started)
reDraw();
Thread.sleep(100);
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
public void reDraw()
{
BufferedImage bi=new BufferedImage(videoScreen.getWidth(), videoScreen.getHeight(),
BufferedImage.TYPE_INT_ARGB);
bi.getGraphics().drawImage(new ImageIcon(backgroundImageFile).getImage(), 0 , 0 ,
videoScreen.getWidth(), videoScreen.getHeight(), null);
BufferedImage screenShot = createImage((JComponent) offScreenVideo,
new Rectangle(invisibleFrame.getBounds()));
Image im = makeColorTransparent(new ImageIcon(screenShot).getImage(), Color.BLACK);
bi.getGraphics().drawImage(im, 0 ,0 , videoScreen.getWidth(), videoScreen.getHeight(), null);
videoScreen.setIcon(new ImageIcon(bi));
}
public static BufferedImage createImage(Component component, Rectangle region)
{
if (!component.isDisplayable()) {
Dimension d = component.getSize();
if (d.width == 0 || d.height == 0) {
d = component.getPreferredSize();
component.setSize(d);
}
layoutComponent(component);
}
BufferedImage image = new BufferedImage(region.width, region.height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
if (!component.isOpaque())
{
g2d.setColor(component.getBackground());
g2d.fillRect(region.x, region.y, region.width, region.height);
}
g2d.translate(-region.x, -region.y);
component.paint(g2d);
g2d.dispose();
return image;
}
public static void layoutComponent(Component component)
{
synchronized (component.getTreeLock())
{
component.doLayout();
if (component instanceof Container)
{
for (Component child : ((Container) component).getComponents())
{
layoutComponent(child);
}
}
}
}
public JPanel getvidComp()
{
Manager.setHint(Manager.LIGHTWEIGHT_RENDERER,true);
try
{
mediaPlayer = Manager.createRealizedPlayer(new File(videoFile).toURL());
mediaPlayer.realize();
mediaPlayer.prefetch();
JPanel video=new JPanel(new BorderLayout());
video.add(mediaPlayer.getVisualComponent()) ;
mediaPlayer.start();
return video;
}
catch( Exception d)
{
return null;
}
}
public static Image makeColorTransparent( Image im, final Color color)
{
ImageFilter filter = new RGBImageFilter()
{
public int markerRGB = color.getRGB() | 0xFF000000;
public final int filterRGB(int x, int y, int rgb)
{
Color c=new Color(rgb);
int red=c.getRed();
int green=c.getGreen();
int blue=c.getBlue();
//if(red<140 && green<140 && blue<140)
{
int alpha=Math.max(Math.max(red , green), Math.max(green, blue))*3;
c=new Color(red , green , blue , alpha>255 ?255 :alpha );
}
return c.getRGB();
}
};
ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
return Toolkit.getDefaultToolkit().createImage(ip);
}
public static void main(String[] args) {
new TransparentVideo();
}
}

Mouse Pointer Problem in Java Swing

I have created the following simple Java Swing program which outputs a 3*3 square in the window every time the user clicks their mouse. The squares remain in the window even if the user clicks more than once. The program compiles and runs just fine, however, when one clicks in the window the square is drawn far below where the mouse pointer is. I've been racking my brain over this one for a while -- what can I change here to get the square to appear exactly with the pointer on each click? Many thanks for any help!
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class ClickCloud extends JComponent {
final ArrayList<Point2D> points = new ArrayList<Point2D>();
public void addPoint(Point2D a) {
points.add(a);
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
for (int i = 0; i < points.size(); i++) {
Point2D aPoint = points.get(i);
g2.draw(new Rectangle2D.Double(aPoint.getX(), aPoint.getY(), 3, 3));
}
}
public static void main(String[] args) {
final ClickCloud cloud = new ClickCloud();
JFrame aFrame = new JFrame();
class ClickListen implements MouseListener {
#Override
public void mouseClicked(MouseEvent arg0) {
}
#Override
public void mouseEntered(MouseEvent arg0) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
public void mousePressed(MouseEvent arg0) {
cloud.addPoint(arg0.getPoint());
cloud.repaint();
}
#Override
public void mouseReleased(MouseEvent arg0) {
}
}
aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
aFrame.setSize(500, 500);
aFrame.add(cloud);
aFrame.addMouseListener(new ClickListen());
aFrame.setVisible(true);
}
}
You're adding the MouseListener to the JFrame, but displaying the results in the JComponent and relative to the JComponent. So the location of the Point clicked will be relative to the JFrame's coordinates, but then displayed relative to the JComponent's coordinates which will shift things down by the distance of the title bar. Instead simply add the MouseListener to the same component that is responsible for displaying the results so that the display and clicking coordinates match:
aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
aFrame.setSize(500, 500);
aFrame.add(cloud);
//!! aFrame.addMouseListener(new ClickListen()); // !! Removed
cloud.addMouseListener(new ClickListen()); // !! added
aFrame.setVisible(true);
By the way: Thanks for creating and posting a decent SSCCE as this makes it so much easier to analyse and solve your problem.

Categories