My Java Swing drawing tool can't be runned - java

So, I made my first useful app - a paint and drawing tool, but... It can't be runned (started). I don't know, is the problem in my computer or in the code... Here is the code:
package MaddpawNightpainter;
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 Nightpainter2 {
JButton clearBtn, blackBtn, blueBtn, greenBtn, redBtn, magentaBtn;
Nightpainter 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() == redBtn) {
drawArea.red();
} else if (e.getSource() == magentaBtn) {
drawArea.magenta();
}
}
};
public static void main(String[] args) {
new Nightpainter().show();
}
public void show() {
// create main frame
JFrame frame = new JFrame("Nightpainter 1.0");
Container content = frame.getContentPane();
// set layout on content pane
content.setLayout(new BorderLayout());
// create draw area
drawArea = new Nightpainter();
// 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);
// add to panel
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(500, 600);
// can close frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// show the swing paint result
frame.setVisible(true);
// :)
}
}
And the other file:
package MaddpawNightpainter;
import java.awt.Color;
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;
/*
Author: Bogdan Ganev
Title: Maddpaw Nightpainter
Description: Nightpainter is a drawing tool, part of Maddpaw - Multifunctional App for Designers,
Developers And Writers
Copyright: Copyright (C) 2016 Bogdan Ganev. All rights reserved. Maddpaw, Multifunctional App for Designers,
Developers And Writers is a trademark of Bogdan Ganev. Java TM is a trademark of Oracle Corporation (R)
*/
public class Nightpainter 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 Nightpainter() {
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);
}
}
So is the problem in my computer or in the code? By the way, it's 10,3 KB...

Change the code in the NightPainter2 class to this:
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 Nightpainter2 {
static JButton clearBtn, blackBtn, blueBtn, greenBtn, redBtn, magentaBtn;
static Nightpainter drawArea;
static 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() == redBtn) {
drawArea.red();
} else if (e.getSource() == magentaBtn) {
drawArea.magenta();
}
}
};
public static void main(String[] args) {
// create main frame
JFrame frame = new JFrame("Nightpainter 1.0");
// set layout on content pane
frame.setLayout(new BorderLayout());
// create draw area
drawArea = new Nightpainter();
// add to content pane
frame.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);
// add to panel
controls.add(greenBtn);
controls.add(blueBtn);
controls.add(blackBtn);
controls.add(redBtn);
controls.add(magentaBtn);
controls.add(clearBtn);
// add to content pane
frame.add(controls, BorderLayout.NORTH);
frame.setSize(500, 600);
// can close frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// show the swing paint result
frame.setVisible(true);
// :)
}
I don't know why it worked, I just saw a line through 'show' in new NightPainter2.show(); so tried this. Didn't expect it to work, honestly :)
And you may want to add frame.setLocationRelativeTo(null); to make it open in the center of the screen.

Related

How can I save the lines painted in a JPanel?

I was at first looking for a library to make a "mousewritten" or "handwritten" signature for java. I did not found any so I'm just trying to let the user draw in a canvas on a JPanel and then he can choose to save it, repaint it or cancel the signature. The problem I have is when I'm trying to save the drawed stuff in the canvas I get an empty .jpeg
My code so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.colorchooser.*;
import javax.swing.event.*;
import java.awt.geom.Line2D;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
public class AES_Encryption extends JFrame implements ActionListener{
public BufferedImage image = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB);
//JPanel canvas = new JPanel();
JPanel buttonPanel = new JPanel();
Point lastPos = null;
Point startPos = null;
Point finishPos = null;
Graphics g;
JButton save = new JButton("Save");
JButton cancel = new JButton("Cancel");
JButton clear = new JButton("Clear");
JPanel canvas = new JPanel();
int changer = 1;
String path="";
public AES_Encryption () {
setLocation(100,100);
setSize(600,500);
setTitle("ENCODE SECTION");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
canvas.setBackground(Color.WHITE);
clear.addActionListener(this);
clear.setActionCommand("clear");
save.addActionListener(this);
save.setActionCommand("Save");
cancel.addActionListener(this);
cancel.setActionCommand("Cancel");
//add buttons here
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(save);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(clear);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(cancel);
//set the look
getContentPane().add(canvas, BorderLayout.CENTER);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
setVisible(true);
g = canvas.getGraphics();
g.setColor(Color.BLACK);
canvas.addMouseMotionListener(new MouseMotionListener () {
public void mouseDragged (MouseEvent m) {
Point p = m.getPoint() ;
if (changer==1){
g.drawLine(lastPos.x, lastPos.y, p.x, p.y) ;
}
lastPos = p ;
}
public void mouseMoved (MouseEvent m) {}
});
canvas.addMouseListener(new MouseListener () {
public void mouseClicked(MouseEvent e) {startPos = e.getPoint();}
public void mousePressed(MouseEvent e) {lastPos = e.getPoint();}
public void mouseReleased(MouseEvent e) {
lastPos = null;
finishPos = e.getPoint();
startPos = null;}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
});
}
public void actionPerformed(ActionEvent e) {
if("clear".equals(e.getActionCommand())) {
repaint();
}
if("Save".equals(e.getActionCommand())) {
captureCanvasImage myCanvas = new captureCanvasImage();
myCanvas.capture();
}
if("Cancel".equals(e.getActionCommand())) {
dispose();
}}
class captureCanvasImage {
public void capture(){
BufferedImage imagebuf=null;
try {
imagebuf = new Robot().createScreenCapture(canvas.bounds());
} catch (AWTException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Graphics2D graphics2D = imagebuf.createGraphics();
canvas.paint(graphics2D);
try {
ImageIO.write(imagebuf,"jpeg", new File("save1.jpeg"));
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("error");
}
}
}
/*
#Override
public void invalidate() {
super.invalidate();
this.paint(this.getGraphics());
}
*/
public static void main (String [] args) {
AES_Encryption p = new AES_Encryption();
p.setVisible(true);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
p.setLocation(dim.width/2-p.getSize().width/2, dim.height/2-p.getSize().height/2);
}
}
When you create the coordinates of the line, save them in a list.
List<Point> points = new ArrayList<>(); // instance field.
canvas.addMouseMotionListener(new MouseMotionListener () {
public void mouseDragged (MouseEvent m) {
Point p = m.getPoint() ;
if (changer==1){
g.drawLine(lastPos.x, lastPos.y, p.x, p.y) ;
points.add(lastPos);// add it here.
}
lastPos = p ;
}
public void mouseMoved (MouseEvent m) {}
});
This was an example. You need to determine where to place the points.add() code. Check out the painting examples here
EDITED:
Here is an example of how to draw in a window. Do not be using graphics context outside of a painting environment like paint or paintComponent (exceptions to this are buffered images,etc which do not paint within the EDT).
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ExampleDrawDemo extends JPanel {
int WIDTH = 600;
int HEIGHT = 500;
JFrame frame = new JFrame();
List<Line> lines;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new ExampleDrawDemo().start());
}
public void start() {
Random r = new Random();
Color[] color = {
Color.RED, Color.BLUE, Color.GREEN, Color.MAGENTA, Color.ORANGE,
Color.CYAN
};
// generate some lines.
lines = IntStream.range(0, 100).mapToObj(
i -> new Line(r, color[r.nextInt(color.length)])).collect(
Collectors.toList());
setPreferredSize(new Dimension(600, 500));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
// smooth lines
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// line thickness
g2d.setStroke(new BasicStroke(2));
for (Line line : lines) {
g2d.setColor(line.color);
g2d.drawLine(line.start.x, line.start.y, line.end.x, line.end.y);
}
g2d.dispose();
}
class Line {
Point start;
Point end;
Color color;
public Line(Random r, Color color) {
this.color = color;
start = new Point(r.nextInt(WIDTH), r.nextInt(HEIGHT));
end = new Point(r.nextInt(WIDTH), r.nextInt(HEIGHT));
}
}
}

Can I change the location of the ImageIcon that I put on a JLabel in my code?

I tried using, "label.setBounds(100,100,250,250)" and "label.setLocation(100,100)" but the image does not move from the top and center of the JLabel.
import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Machine extends JPanel
{
public Machine()
{
ImageIcon imageIcon = new ImageIcon("res/robot.png");
JLabel label = new JLabel(imageIcon);
add(label);
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.add(new Machine());
frame.setVisible(true);
frame.setSize(new Dimension(1080, 720));
}
}
What are you trying to do?
The default layout of a JPanel is a FlowLayout with center alignment and the label is displayed at its preferred size. So the label is displayed in the center.
You have a couple of options:
Change the alignment of the FlowLayout to be either LEFT or RIGHT
Don't add the label to the panel. Just add it directly to the frame which uses a BorderLayout.
Then you can do something like:
label.setHorizontalAlignment(JLabel.LEFT);
label.setVerticalAlignment(JLabel.CENTER);
Edit:
was just trying to get the image to be in the middle of the frame
Then post your actual requirement when you ask a question. We don't know what "can I change the location" means to you.
So you would either use the BorderLayout and adjust the horizontal/vertical alignment as already demonstrated.
Or, you could set the layout manager of the frame to be a GridBagLayout and then add the label directly to the frame and use:
frame.add(label, new GridBagConstraints());
Now the label will move dynamically as the frame is resized.
If you want to place an image in a certain location, perhaps best is to draw it directly in your JPanel in a paintComponent method override, using one of Graphics drawImage(...) methods, one that allows placement of the image.
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class Machine extends JPanel {
private static final String IMG_PATH = "https://upload.wikimedia.org/wikipedia/commons/"
+ "thumb/f/f2/Abraham_Lincoln_O-55%2C_1861-crop.jpg/"
+ "250px-Abraham_Lincoln_O-55%2C_1861-crop.jpg";
private BufferedImage img;
private int x;
private int y;
public Machine() {
setPreferredSize(new Dimension(1080, 720));
x = 100; // or wherever you want to draw the image
y = 100;
try {
URL imgUrl = new URL(IMG_PATH);
img = ImageIO.read(imgUrl);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, x, y, this);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Machine());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
Version 2: MouseListener / MouseMotionListener so that the image can be moved
import java.awt.Dimension;
import java.awt.Graphics;
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.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class Machine extends JPanel {
private static final String IMG_PATH = "https://upload.wikimedia.org/"
+ "wikipedia/commons/thumb/f/f2/"
+ "Abraham_Lincoln_O-55%2C_1861-crop.jpg/"
+ "250px-Abraham_Lincoln_O-55%2C_1861-crop.jpg";
private BufferedImage img;
private int x;
private int y;
public Machine() {
setPreferredSize(new Dimension(1080, 720));
x = 100; // or wherever you want to draw the image
y = 100;
MyMouse mouse = new MyMouse();
addMouseListener(mouse);
addMouseMotionListener(mouse);
try {
URL imgUrl = new URL(IMG_PATH);
img = ImageIO.read(imgUrl);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, x, y, this);
}
}
private class MyMouse extends MouseAdapter {
private Point offset;
#Override
public void mousePressed(MouseEvent e) {
// check if left mouse button pushed
if (e.getButton() != MouseEvent.BUTTON1) {
return;
}
// get bounds of the image and see if mouse press within bounds
Rectangle r = new Rectangle(x, y, img.getWidth(), img.getHeight());
if (r.contains(e.getPoint())) {
// set the offset of the mouse from the left upper
// edge of the image
offset = new Point(e.getX() - x, e.getY() - y);
}
}
#Override
public void mouseDragged(MouseEvent e) {
if (offset != null) {
moveImg(e);
}
}
#Override
public void mouseReleased(MouseEvent e) {
if (offset != null) {
moveImg(e);
}
offset = null;
}
private void moveImg(MouseEvent e) {
x = e.getX() - offset.x;
y = e.getY() - offset.y;
repaint();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Machine());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}

3 buttons to draw 3 different objects in a jPanel

i have a simple question but for some reason I'm stuck and cant figure it out.
I have a simple code with 3 buttons in a JPanel each one of the buttons should draw at the JPanel with the overriden PaintComponent and it does but What i want to do is make the shapes stay.
(after i will change it to random positions )
any help would be apreciated thank you!
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Ex3 extends JFrame implements ActionListener
{
JButton circle, triang, square;
JPanel jp, jButton;
boolean drawSq, drawCir, drawTr;
public static void main(String[] args)
{
JFrame frame = new Ex3();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public Ex3()
{
super("Ex3");
setSize(400, 500);
circle = new JButton("Circle");
triang = new JButton("Triangle");
square = new JButton("Square");
drawCir = false;
drawSq = false;
drawTr = false;
//setLayout(new FlowLayout(FlowLayout.CENTER, 20, 30));
jButton = new JPanel();
jp = new CustomPanel();
circle.addActionListener(this);
triang.addActionListener(this);
square.addActionListener(this);
jButton.add(circle);
jButton.add(triang);
jButton.add(square);
jButton.add(new JLabel("Kayy"));
jp.setBackground(Color.gray);
add(jp, BorderLayout.CENTER);
add(jButton, BorderLayout.NORTH);
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == circle)
{
drawCir = true;
System.out.println("created cricle");
}
if(e.getSource() == triang)
{
drawTr = true;
System.out.println("created triangle");
}
if(e.getSource() == square)
{
drawSq = true;
System.out.println("created square");
}
repaint();
}
class CustomPanel extends JPanel
{
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(drawSq)
{
g.setColor(Color.blue);
g.drawRect(((int)Math.random()* 20), 50, 200, 150);
drawSq = false;
}
else if(drawTr)
{
g.setColor(Color.green);
}
else if(drawCir)
{
g.setColor(Color.red);
g.drawOval(182, 124, 200, 200);
}
else
{
}
//drawSq = false;
drawTr = false;
drawCir = false;
}
}
}
What i want to do is make the shapes stay
Then you need to repaint the shapes every time the component is repainted.
There are two common approaches to do this:
paint to a BufferedImage
keep a list of Object to paint and iterate through the list to paint each object
Check out Custom Painting Approaches for working examples of each approach. Which approach you use will depend on your exact requirements.
Also, you should never change the state of your component in the painting method. You can't control when the paintComponent() method is invoked. Sometimes the system will repaint a component. So the presence of your Boolean variables indicates a design problem.

move image from one panel to another

I have Code where I can move image.
Everything works well.
here I have only one ImagePanel (children of JPanel) on the frame.
Questions:
I need to drag and drop image from one JPanel to another JPanel.
Then I need to move dragged image to current panel.
Can you give me an example code, please?
class ImagePanel extends JPanel {
int x, y;
BufferedImage image;
ImagePanel() {
setBackground(Color.white);
setSize(450, 400);
addMouseMotionListener(new MouseMotionHandler());
Image img = getToolkit().getImage("C:\\2.png");
MediaTracker mt = new MediaTracker(this);
mt.addImage(img, 1);
try {
mt.waitForAll();
} catch (Exception e) {
System.out.println("Image not found.");
}
image = new BufferedImage(img.getWidth(this), img.getHeight(this),BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();
g2.drawImage(img, 0, 0, this);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2D = (Graphics2D) g;
g2D.drawImage(image, x, y, this);
}
class MouseMotionHandler extends MouseMotionAdapter {
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
public void mouseMoved(MouseEvent e) {
}
}
}
I need to do that code, with this following design. I need to add image with some layout (I don't need to done this with Point pixels). or how to add image with some layout? for example Grid bag layout. I don't need Points (x,y). because I need to add another components too.
public class DragAndDrop {
private JFrame frame;
/* .. another component here .. */
private JPanel leftPanel; // here is my image
public JPanel rightContentPanel; // destination of dragable image
public static void main(String[] args) {
DragAndDrop window = new DragAndDrop();
}
public DragAndDrop() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.getContentPane().setLayout(new BorderLayout(0, 0));
leftPanel = new leftPanel();
/* add components to left panel */
rightContentPanel = new rightPanel();
/* add component to right panel */
frame.getContentPane().add(rightContentPanel, BorderLayout.CENTER);
frame.getContentPane().add(leftPanel, BorderLayout.WEST);
frame.setVisible(true);
frame.setResizable(false);
}
}
class leftPanel extends JPanel {
/ ... /
}
class rightPanel extends JPanel{
/ ... /
}
There's probably any number of ways to achieve what you want. You could use the glass pane or JXLayer or you could stop treating the two panels as separate elements and more like they were just windows into a large virtual space.
This example basically treats the parent component as the "virtual space" into which the two image panes are windows.
They both share the same image and image location details. They, individual, convert the image location (which is in virtual coordinates) to local coordinates and draw as much of the image as would appear on them...
Mouse control is maintained by the parent. This greatly simplifies the process, as it can notify both the panels simultaneously
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
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.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class CrossImage {
public static void main(String[] args) {
new CrossImage();
}
public CrossImage() {
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 img;
private ImagePane left;
private ImagePane right;
private Point imagePoint;
public TestPane() {
setBorder(new EmptyBorder(10, 10, 10, 10));
setLayout(new GridLayout(0, 2, 10, 10));
left = new ImagePane();
right = new ImagePane();
imagePoint = new Point(10, 10);
left.setImageLocation(imagePoint);
right.setImageLocation(imagePoint);
try {
img = ImageIO.read(new File("Background.jpg"));
left.setImage(img);
right.setImage(img);
} catch (IOException ex) {
ex.printStackTrace();
}
add(left);
add(right);
MouseAdapter mouseHandler = new MouseAdapter() {
private Point delta;
#Override
public void mousePressed(MouseEvent e) {
Point origin = e.getPoint();
Rectangle bounds = new Rectangle(imagePoint, new Dimension(img.getWidth(), img.getHeight()));
if (bounds.contains(origin)) {
delta = new Point(origin.x - imagePoint.x, origin.y - imagePoint.y);
}
}
#Override
public void mouseDragged(MouseEvent e) {
if (delta != null) {
imagePoint = e.getPoint();
imagePoint.translate(-delta.x, -delta.y);
left.setImageLocation(imagePoint);
right.setImageLocation(imagePoint);
}
}
#Override
public void mouseReleased(MouseEvent e) {
delta = null;
}
};
addMouseListener(mouseHandler);
addMouseMotionListener(mouseHandler);
}
}
public class ImagePane extends JPanel {
private Image image;
private Point imageLocation;
public ImagePane() {
setBorder(new LineBorder(Color.DARK_GRAY));
}
#Override
public Dimension getPreferredSize() {
return image == null ? super.getPreferredSize() : new Dimension(image.getWidth(this), image.getHeight(this));
}
public void setImage(Image image) {
this.image = image;
repaint();
}
public void setImageLocation(Point imageLocation) {
this.imageLocation = imageLocation;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null && imageLocation != null) {
Point p = SwingUtilities.convertPoint(getParent(), imageLocation, this);
g.drawImage(image, p.x, p.y, this);
}
}
}
}

java statusbar resize corner (handle)

I try to make a window with a resize handle at the bottom right.
So far I managed to detect the mouse hover and dragging.
The mouse cursor is changing to resize cursor successfully.
But the actually resize operation I'm unsure how to solve.
The Idea I testet at first place is to just setsize on parent when dragging on resize handle.
It works, but then the window get's resize immediately, that's not how the standard resize looks.
The standard resize is a transparent window with white border (may be different on different systems and look and feel).
Is it possible to trigger/use the built in resize mechanism?
Below you have a sample code.
Thanks!
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.RenderingHints;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class main extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
main frame = new main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public class StatusBar extends JPanel implements MouseListener, MouseMotionListener {
private Polygon resizeCorner = new Polygon();
private int offsetX;
private int offsetY;
private Dimension offsetSize;
private Cursor resizeCursor = new Cursor(Cursor.SE_RESIZE_CURSOR);
private Cursor defaultCursor = new Cursor(Cursor.DEFAULT_CURSOR);
public StatusBar() {
super();
setPreferredSize(new Dimension(200,40));
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
private void createResizeHandle() {
resizeCorner.reset();
resizeCorner.addPoint(getWidth()-2, getHeight()-2);
resizeCorner.addPoint(getWidth()-40, getHeight()-2);
resizeCorner.addPoint(getWidth()-2, getHeight()-40);
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2;
g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g2.setColor(Color.red);
createResizeHandle();
g2.drawPolygon(resizeCorner);
}
#Override
public void mouseDragged(MouseEvent e) {
if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
int width = (int) (this.offsetSize.getWidth() - this.offsetX + e.getXOnScreen());
int height = (int) (this.offsetSize.getHeight() - this.offsetY + e.getYOnScreen());
this.getRootPane().getParent().setSize(width, height);
createResizeHandle();
}
}
#Override
public void mouseMoved(MouseEvent e) {
if (resizeCorner.contains(e.getX(), e.getY())) {
setCursor(resizeCursor);
} else {
setCursor(defaultCursor);
}
}
#Override
public void mouseClicked(MouseEvent arg0) {
}
#Override
public void mouseEntered(MouseEvent arg0) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent e) {
if (resizeCorner.contains(e.getX(), e.getY())) {
this.offsetX = e.getXOnScreen();
this.offsetY = e.getYOnScreen();
this.offsetSize = this.getRootPane().getParent().getSize();
}
}
#Override
public void mouseReleased(MouseEvent arg0) {
}
}
public main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JLabel lblNewLabel = new JLabel("New label");
StatusBar bar = new StatusBar();
contentPane.add(lblNewLabel, BorderLayout.NORTH);
contentPane.add(bar, BorderLayout.SOUTH);
}
}
lots of small mistakes, starts with correct naming for ClassName ... end with usage java reserved words for class/void/method's name(s)
minor changes (now it works for me), with one my mistake against Swing rules, I set there setPreferredSize(new Dimension(400, 300));, lets childrens returns PreferredSize for Container
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class MyToolBar extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
public class StatusBarX extends JPanel implements MouseListener, MouseMotionListener {
private static final long serialVersionUID = 1L;
private Polygon resizeCorner = new Polygon();
private int offsetX;
private int offsetY;
private Dimension offsetSize;
private Cursor resizeCursor = new Cursor(Cursor.SE_RESIZE_CURSOR);
private Cursor defaultCursor = new Cursor(Cursor.DEFAULT_CURSOR);
public StatusBarX() {
super();
setPreferredSize(new Dimension(200, 40));
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
private void createResizeHandle() {
resizeCorner.reset();
resizeCorner.addPoint(getWidth() - 2, getHeight() - 2);
resizeCorner.addPoint(getWidth() - 40, getHeight() - 2);
resizeCorner.addPoint(getWidth() - 2, getHeight() - 40);
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2;
g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2.setColor(Color.red);
createResizeHandle();
g2.drawPolygon(resizeCorner);
}
#Override
public void mouseDragged(MouseEvent e) {
if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
int width = (int) (this.offsetSize.getWidth() - this.offsetX + e.getXOnScreen());
int height = (int) (this.offsetSize.getHeight() - this.offsetY + e.getYOnScreen());
this.getRootPane().getParent().setSize(width, height);
createResizeHandle();
}
}
#Override
public void mouseMoved(MouseEvent e) {
if (resizeCorner.contains(e.getX(), e.getY())) {
setCursor(resizeCursor);
} else {
setCursor(defaultCursor);
}
}
#Override
public void mouseClicked(MouseEvent arg0) {
}
#Override
public void mouseEntered(MouseEvent arg0) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent e) {
if (resizeCorner.contains(e.getX(), e.getY())) {
this.offsetX = e.getXOnScreen();
this.offsetY = e.getYOnScreen();
this.offsetSize = this.getRootPane().getParent().getSize();
}
}
#Override
public void mouseReleased(MouseEvent arg0) {
}
}
public MyToolBar() {
JLabel lblNewLabel = new JLabel("New label");
StatusBarX bar = new StatusBarX();
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
contentPane.add(lblNewLabel, BorderLayout.NORTH);
contentPane.add(bar, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(100, 100);
setPreferredSize(new Dimension(400, 300));
add(contentPane);
pack();
setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
MyToolBar frame = new MyToolBar();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
The standard resize is a transparent window with white border (may be different on different systems and look and feel).
When using Windows XP the standard is to resize top level components (frame, dialog etc) immediately. It doesn't matter what the LAF is.
In general other components don't have resizing functionality built in. The only exception to this that I can think of is JInternalFrame. In this case is does support the "outline" resizing of a component.
So if you want to add this type of functionality to your component then you would need to look at the internal frame UI to find the resizing code.
I would guess that the code would display a Glass Pane when dragging starts and then do the outline custom painting on the Glass Plane. Then on mouseReleased the frame size would be changed.
In case you are interested, Component Resizing shows how I do resizing for any component. It does immediate resizing, not outline resizing.

Categories