I'm making a music/drawing application which you free draw lines with your mouse and a TrackBar passes horizontally through it and reads the lines and uses the x and y coordinate to modify music.
The problem I'm having is that TrackBar class is a JPanel and DrawBoard class is a JPanel which I add inside a Frame. But which ever is on-top is the one that will show, what I want is for them to both show, and the TrackBar to pass on top of the lines drawn.
Below Is the source code of this 3 classes and took out some unncesesary code:
The MainFrame class where I add them (with the current setup the TrackBar doesnt appear but the Drawing board appears since it overlaps it):
public class MainFrame extends JFrame {
public static ColourToolbar colourBar;
public static TrackBar tb;
public MainFrame(){
super("VIPE by Prestige WorldWide");
// Top colour toolbar for tones
colourBar = new ColourToolbar();
this.getContentPane().add(colourBar, BorderLayout.NORTH);
// This class ImagePanel is a JPanel which I overite the paintCOmponent to have background
ImagePanel bg = new ImagePanel();
bg.setLayout(new BorderLayout());
Dimension size = getPreferredSize();
size.setSize(1024,800); //w, h
bg.setPreferredSize(size);
this.getContentPane().add(bg, BorderLayout.CENTER);
// I add the TrackBar to the ImagePanel since its the Background
tb = new TrackBar();
bg.add(tb, BorderLayout.CENTER);
// I add the drawing board but It will overlap the Trackbar
DrawBoard dboard = new DrawBoard();
bg.add(dboard, BorderLayout.CENTER);
// The control toolbar where the settings and control buttons are.
Toolbar toolBar = new Toolbar();
this.getContentPane().add(toolBar, BorderLayout.SOUTH);
}
public static void main(String[] args){
MainFrame frame = new MainFrame();
frame.setBackground(Color.WHITE);
frame.setSize(1024,768);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
//frame.pack();
frame.setVisible(true);
}
}
Now the TrackBar class:
public class TrackBar extends JPanel{
private TrackBarAction tba = new TrackBarAction(this);
public static int TIME = 9;
public Timer t = new Timer(TIME, tba);
public static double x = 0, y = 0, velX = 1.0, velY = 0;
private int SKIP = 120;
public TrackBar(){
this.setOpaque(false);
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
//g2d.drawRect((int)x, (int)y, 10, 800);
Rectangle2D r2d = new Rectangle2D.Double(x, y, 8.0, 800.0); // x,x, w, h
g2d.setPaint(Color.DARK_GRAY);
g2d.fill(r2d);
g2d.draw(r2d);
}
public void reset(){
t.stop();
x = 0;
y = 0;
velX = 0.5;
velY = 0;
this.repaint();
}
public void skipForward(){
if(x+SKIP <= 1024){
x += SKIP;
} else {
x = 1024 - x;
}
this.repaint();
}
public void skipBackwards(){
if(x-SKIP >= 0){
x -= SKIP;
} else {
x = 0;
}
this.repaint();
}
}
And now the DrawBoard class:
public class DrawBoard extends JPanel implements MouseListener, MouseMotionListener{
(..)
public Color currentColor;
public static boolean eraser = false;
private int xX1, yY1;
public DrawBoard(){
Graphics2D g2d = bImage.createGraphics();
g2d.dispose();
Dimension size = getPreferredSize();
size.setSize(1024,800); //w, h
setPreferredSize(size);
//status = new JLabel("default");
//add(status, BorderLayout.SOUTH);
addMouseListener(this);
addMouseMotionListener(this);
imgLabel = new JLabel(new ImageIcon(bImage)) {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
paintInLabel(g);
}
};
imgLabel.setOpaque(false);
setOpaque(false);
add(imgLabel, BorderLayout.CENTER);
}
private void paintInLabel(Graphics g) {
if(!eraser){
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(getColor()); // this colour is when mouse is pressed
g2d.setStroke(new BasicStroke(STROKESIZE));
if (points.size() < 1) {
return;
}
for (int i = 1; i < points.size(); i++) {
int x1 = points.get(i - 1).x;
int y1 = points.get(i - 1).y;
int x2 = points.get(i).x;
int y2 = points.get(i).y;
g2d.drawLine(x1, y1, x2, y2);
}
}
}
// Where the drawing happens
#Override
public void mousePressed(MouseEvent e) {
//status.setText("you pressed down the mouse");
if(!eraser){
xX1 = e.getX();
yY1 = e.getY();
points.add(e.getPoint());
}
}
#Override
public void mouseDragged(MouseEvent e) {
//status.setText("you draged the mouse");
Graphics2D g2d = bImage.createGraphics();
// this is the eraser code
if(eraser){
//Graphics2D g2d = bImage.createGraphics();
System.out.println("eraser = true");
System.out.println("Stroke = " + STROKESIZE);
g2d.setComposite(AlphaComposite.Clear);
g2d.setColor(new Color(0, 0, 0, 0));
g2d.drawRect(e.getX(), e.getY(), STROKESIZE, STROKESIZE);
g2d.fillRect(e.getX(), e.getY(), STROKESIZE, STROKESIZE);
// g2d.setColor(c);
imgLabel.repaint();
}else {
//g2d.setComposite();
points.add(e.getPoint());
System.out.println("point = " + e.getPoint());
imgLabel.repaint();
}
}
#Override
public void mouseReleased(MouseEvent e) {
//status.setText("you release the mouse click");
if(!eraser){
Graphics2D g2d = bImage.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(getColor()); // this is the final colour
g2d.setStroke(new BasicStroke(STROKESIZE));
if (points.size() >= 2) {
for (int i = 1; i < points.size(); i++) {
int x1 = points.get(i - 1).x;
int y1 = points.get(i - 1).y;
int x2 = points.get(i).x;
int y2 = points.get(i).y;
g2d.drawLine(x1, y1, x2, y2);
}
}
g2d.dispose();
points.clear();
imgLabel.repaint();
}
//imgLabel.repaint();
}
// End of where the drawing happens
public void clearDrawBoard() {
}
private Color getColor() {
return ColourToolbar.selectedColor;
}
private void setColor(Color col){
this.currentColor = col;
}
#Override
public void mouseClicked(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet.");
}
}
BorderLayout can only have one component add to each of it a 5 positions. By adding the DrawPanel to the center position, you are effectively removing the TrackPanel.
Instead, set the layout manager of the TrackBar to BorderLayout and add the DrawPanel to it.
You could also use a JLayeredPane, but the management becomes more involved
Related
I have added 2 JComponent to JPanel.Both these JComponent have custom painted objects on them i.e multiple Circles and multiple Line2Ds.The dimensions of both these jcomponent's are set to the size of the screen which is required.When I add them to JPanel,the mouselisteners are not working.However if I comment one of them then that listener starts working.
public class MapXMLBuilder extends JFrame {
public void initialize() {
panel = new Jpanel();
addLine();//ading lines
addCircle();//adding cirlces
add(panel)
}
private void addLine() {
mDrawLine = new DrawLine(panel);
mDrawCircle.setDimensions(screenWidth, screenWidth);
panel.add(mDrawLine); //adding JComponent1 to panel
for (int i = 0; i < 10; i++) { //adding 10 circles
mDrawLine.addLine(new Point2D.Double(x, y));
}
}
private void addCircle() {
mDrawCircle = new DrawCircle(panel);
mDrawCircle.setDimensions(screenWidth, screenWidth);
panel.add(mDrawCircle); //adding JComponent1 to panel
for (int i = 0; i < 10; i++) { //adding 10 circles
mDrawCircle.addCircle(new Point2D.Double(x, y));
}
}
}
public class DrawLine extends JComponent {
public DrawLine(JPanel jpanel) {
lineList = new ArrayList();
addMouseListener(mouseAdapter);
addMouseMotionListener(mouseAdapter);
setBackground(Color.white);
}
public void addLine(int x1, int y1, int x2, int y2, Color color) {
Shape currentShape = new Line2D.Float(x1, y1, x2, y2);
lineList.add(currentShape);
repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(Color.BLACK);
for (Shape shape: lineList) {
if (shapes != null && shapes.size() > 0) {
g2d.setColor(Color.YELLOW);
g2d.draw(shape);
}
}
}
public void setDimensions(int width, int height) {
setSize(new Dimension(width, height));
}
}
public class DrawCircle extends JComponent {
public DrawCircle(JPanel jpanel) {
circleList = new ArrayList();
addMouseListener(mouseAdapter);
addMouseMotionListener(mouseAdapter);
setBackground(Color.white);
}
public void addCircle(Point2D p) {
Ellipse2D e = new Ellipse2D.Double(p.getX(), p.getY(), 5, 5);
circleList.add(e);
selectedPoint = null;
repaint();
}
public void setDimensions(int width, int height) {
setSize(new Dimension(width, height));
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
int diameter = 75;
Ellipse2D e;
Color color;
for (int j = 0; j < circleList.size(); j++) {
e = (Ellipse2D) circleList.get(j);
float alpha = 0.75f;
color = new Color(1, 0, 0, alpha); //Red
g2.setPaint(color);
Ellipse2D.Double circle = new Ellipse2D.Double(e.getX(), e.getY(), diameter, diameter);
g2.fill(circle);
}
}
}
You can forward the event from one to the other. Try something like this:
firstComponent.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent event){
// forward the event
secondComponent.dispatchEvent(event);
// handle the code here
}
});
secondComponent.addMouseListener(// etc.
I have 4 classes:
Draw, Rectangle (extends Draw), FreeHand (extends Draw) and a test class.
I add rectangles and lines drawn by free hand to an arrayList.
I have a menubar with choices Back and Clear. Back removes the last drawn object. It is done by removing the last object in the arraylist. Clear clears the windows. It is done by clear the arraylist from all items.
Now to my problem: The window does not clear. I don't know how to write the code to make it repaint properly so that the items removes from the window.
Can you please help me with how the code for this would look like, and where I put it. I appreciate it, thank you.
My problem no 2:
After I have removed the last item in the arraylist I need to draw all the items in the arrayList. I have tried
for (Draw d : shapeList) {
d.draw(g2);
}
But it does not work. Any suggestions?
Class Draw:
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public abstract class Draw extends JPanel {
public int startX, startY, endX, endY, width, height, w, h;
public String color = "Black";
public Draw(int startX, int startY, int width, int height) {
this.startX = startX;
this.startY = startY;
this.width = width;
this.height = height;
}
public abstract void draw(Graphics2D g);
#Override
public int getX() {
return startX;
}
public void setX(int startX) {
this.startX = startX;
}
#Override
public int getY() {
return startY;
}
public void setY(int startY) {
this.startY = startY;
}
#Override
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
#Override
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public void setColor(String color) {
this.color = color;
}
}
Class Rectangle:
import java.awt.Color;
import java.awt.Graphics2D;
public class Rectangle extends Draw {
public Rectangle(int x, int y, int width, int height) {
super(x, y, width, height);
}
#Override
public void draw(Graphics2D g2) {
switch (color) {
case "Red":
g2.setColor(Color.RED);
break;
case "Green":
g2.setColor(Color.GREEN);
break;
case "Blue":
g2.setColor(Color.BLUE);
break;
case "Yellow":
g2.setColor(Color.YELLOW);
break;
case "Orange":
g2.setColor(Color.ORANGE);
break;
case "Black":
g2.setColor(Color.BLACK);
break;
}
g2.drawRect(getX(), getY(), getWidth(), getHeight());
}
}
Class FreeHand:
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
public class FreeHand extends Draw {
public FreeHand(int x, int y, int width, int height) {
super(x, y, width, height);
}
/* public FreeHand() {
super();
}*/
#Override
public void draw(Graphics2D g2) {
//Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(3));
switch (color) {
case "Red":
g2.setColor(Color.RED);
break;
case "Green":
g2.setColor(Color.GREEN);
break;
case "Blue":
g2.setColor(Color.BLUE);
break;
case "Yellow":
g2.setColor(Color.YELLOW);
break;
case "Orange":
g2.setColor(Color.ORANGE);
break;
case "Black":
g2.setColor(Color.BLACK);
break;
}
g2.drawLine(getX(), getY(), getWidth(), getHeight());
}
}
Testclass:
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
public class JavaApplication30 extends JFrame implements ActionListener {
public ArrayList<Draw> shapeList = new ArrayList<>();
int startX, startY, endX, endY, w, h;
private JPanel topPanel;
private JPanel bottomPanel;
private JPanel orangePanel;
private JPanel greenPanel;
private JPanel bluePanel;
private JPanel blackPanel;
private JPanel redPanel;
private JPanel yellowPanel;
private JPanel leftPanel;
private JPanel rightPanel;
private JPanel colorPanel;
private JMenuBar menuBar;
private JMenu menu;
private JMenuItem menuItem1;
private JMenuItem menuItem2;
private JMenuItem menuItem3;
private JComboBox comboBox;
private JLabel leftLabel;
private JLabel commaLabel;
private JLabel colorLabel;
private static JLabel xLabel;
private static JLabel yLabel;
private final String labelText = "Coordinates: ";
private final String comma = ",";
private final String color = "Color: ";
private final String[] boxOptions = new String[] {"Rectangle", "Freehand"};
private String pickedColor = "Black";
private String x = "";
private String y = "";
Container cp = getContentPane();
private int count = 0;
public JavaApplication30(String title) {
super(title);
this.setLayout(new BorderLayout());
this.setLocationRelativeTo(null);
this.setSize(840, 500);
this.initComponents();
this.initMenu();
this.setVisible(true);
}
private void initComponents() {
cp.setBackground(Color.WHITE);
comboBox = new JComboBox(boxOptions);
topPanel = new JPanel(new GridLayout(1,7));
bottomPanel = new JPanel(new GridLayout(1,2));
orangePanel = new JPanel();
greenPanel = new JPanel();
bluePanel= new JPanel();
blackPanel = new JPanel();
redPanel = new JPanel();
yellowPanel = new JPanel();
colorPanel = new JPanel();
rightPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
leftPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
comboBox.setSelectedIndex(0);
comboBox.addActionListener(this);
topPanel.setPreferredSize(new Dimension(0,40));
bottomPanel.setPreferredSize(new Dimension(0,30));
colorPanel.setPreferredSize(new Dimension(60,20));
leftLabel = new JLabel(labelText);
commaLabel = new JLabel(comma);
colorLabel = new JLabel(color);
bottomPanel.setBackground(Color.LIGHT_GRAY);
orangePanel.setBackground(Color.ORANGE);
greenPanel.setBackground(Color.GREEN);
bluePanel.setBackground(Color.BLUE);
blackPanel.setBackground(Color.BLACK);
redPanel.setBackground(Color.RED);
yellowPanel.setBackground(Color.YELLOW);
colorPanel.setBackground(Color.BLACK);
topPanel.add(orangePanel);
topPanel.add(greenPanel);
topPanel.add(bluePanel);
topPanel.add(blackPanel);
topPanel.add(redPanel);
topPanel.add(yellowPanel);
topPanel.add(comboBox);
rightPanel.add(colorLabel);
rightPanel.add(colorPanel);
bottomPanel.add(leftPanel);
bottomPanel.add(rightPanel);
this.add(topPanel, BorderLayout.PAGE_START);
this.add(bottomPanel, BorderLayout.PAGE_END);
}
#Override
public void paint(Graphics g) {
if(count == 0) {
cp.repaint();
}
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(1));
for (Draw d : shapeList) {
d.draw(g2);
}
if (startX != 0 && startY != 0 && endX != 0 && endY != 0) {
int width = Math.abs(startX - endX);
int height = Math.abs(startY - endY);
int minX = Math.min(startX, endX);
int minY = Math.min(startY, endY);
Rectangle r = new Rectangle(minX, minY, width, height);
g2.setPaint(Color.WHITE);
g2.fillRect(r.getX(), r.getY(), r.getWidth(), r.getHeight());
r.setColor(pickedColor);
r.draw(g2);
}
}
#Override
public void actionPerformed(ActionEvent e) {
count++;
if (e.getSource().equals(menuItem1)) {
shapeList.clear();
//Code to clear window
}
if (e.getSource().equals(menuItem2)) {
shapeList.remove(shapeList.size() - 1);
//Code to clear window
Graphics g = getGraphics();
Graphics2D g2 = (Graphics2D) g;
for (Draw d : shapeList) {
d.draw(g2);
}
}
if (e.getSource().equals(menuItem3)) {
//Exit
}
if (e.getSource().equals(comboBox)) {
JComboBox cb = (JComboBox)e.getSource();
if (cb.getSelectedItem().equals("Rectangle")) {
this.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
startX = e.getX();
startY = e.getY();
endX = startX;
endY = startY;
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
endX = e.getX();
endY = e.getY();
int width = Math.abs(startX - endX);
int height = Math.abs(startY - endY);
int minX = Math.min(startX, endX);
int minY = Math.min(startY, endY);
Rectangle r = new Rectangle(minX, minY, width, height);
shapeList.add(r);
r.setColor(pickedColor);
startX = 0;
startY = 0;
endX = 0;
endY = 0;
repaint();
}
});
this.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
endX = e.getX();
endY = e.getY();
repaint();
}
});
}
else if (cb.getSelectedItem().equals("Freehand")) {
this.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
startX = e.getX();
startY = e.getY();
}
});
this.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
Graphics g = getGraphics();
Graphics2D g2 = (Graphics2D) g;
FreeHand fh = new FreeHand(startX, startY, e.getX(), e.getY());
shapeList.add(fh);
fh.setColor(pickedColor);
fh.draw(g2);
startX = e.getX();
startY = e.getY();
}
});
}
}
}
private void initMenu() {
menuBar = new JMenuBar();
menu = new JMenu("File");
menuBar.add(menu);
menuItem1 = new JMenuItem("Clear");
menuItem2 = new JMenuItem("Back");
menuItem3 = new JMenuItem("Exit");
menu.add(menuItem1);
menu.add(menuItem2);
menu.addSeparator();
menu.add(menuItem3);
menu.setMnemonic(KeyEvent.VK_A);
KeyStroke ks1 = KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK); //Crtl+n
KeyStroke ks2 = KeyStroke.getKeyStroke(KeyEvent.VK_I, InputEvent.CTRL_MASK); //Ctrl+i
KeyStroke ks3 = KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK); //Ctrl+e
menuItem1.setAccelerator(ks1);
menuItem2.setAccelerator(ks2);
menuItem3.setAccelerator(ks3);
menuItem1.addActionListener(this);
menuItem2.addActionListener(this);
menuItem3.addActionListener(this);
setJMenuBar(menuBar);
}
public static void main(String args[]) {
new JavaApplication30("Draw");
}
}
Your problem looks to be that your paint method is not calling the super's paint method since this will have the component clean itself of all "dirty" image bits. But having said that, you shouldn't draw directly in the JFrame. Instead draw in the paintComponent method of a JComponent or JPanel, and in that method be sure to call the super's paintComponent method:
public class MyDrawingPanel extends JPanel {
#Override
proteced void paintComponent(Graphics g) {
super.paintComponent(g); // don't forget this!
// do your drawing here
}
}
Also, why does your Draw class, and thus all classes that derive from it, extend JPanel when it is not being used as a JPanel? You are giving a lot of unnecessary overhead to these classes this way.
Edit
You ask:
So you mean I should move Everything in the paint-method to the paintComponent-method in Draw? Why protected?
No. I mean that Draw should not extend JPanel, but instead should be a logical class, not a Swing component-derived class. I think that you should create a new class, say called MyDrawingPanel where you do all of your drawing. Please see my code snippet above. Also paintComponent is declared in JComponent to be protected, not public, and I see no advantage to making it public when overriding it, so I recommend leaving it protected.
Please read the Swing Info Links to see the Swing graphics tutorials and give them a read.
Edit 2
You're also using a getGraphics() call on a component to get your Graphics object, not good as this will return an unstable Graphics object. Instead do all drawing in the paintComponent method or on a BufferedImage (that again is drawn in paintComponent).
Edit 3
Some of my code examples:
Minimal way to make a cleanable drawing area
Changing JPanel Graphics g color drawing line
Graphics in repaint draws random lines
I am trying to add shapes onto a window using JPanel and then be able to click and drag them around the window. This works if I only have one shape; but when I add more shapes, the click and drag is very funky. It does drag but not with the mouse, it isn't proportional and doesn't drag with the mouse.
Any help is appreciated. Thanks!
public class SimpleDraw {
public static void main(String[] args) {
JFrame frame = new UMLWindow();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(30, 30, 1000, 700);
frame.getContentPane().setBackground(Color.white);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
// Display the window.
frame.setVisible(true);
}
}
class UMLWindow extends JFrame {
Squares squares = new Squares();
private static final long serialVersionUID = 1L;
public UMLWindow() {
addMenus();
}
public void addMenus() {
getContentPane().add(squares);
JMenuBar menubar = new JMenuBar();
JMenu shapes = new JMenu("Shapes");
JMenuItem rectangleMenuItem = new JMenuItem("New Rectangle");
rectangleMenuItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
squares.addSquare(10, 10, 100, 100);
}
});
shapes.add(rectangleMenuItem);
menubar.add(shapes);
setJMenuBar(menubar);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
class Squares extends JPanel {
private static final long serialVersionUID = 1L;
private List<Path2D> squares = new ArrayList<Path2D>();
// private Path2D rect = new Path2D.Double();
int currentIndex;
public void addSquare(int x, int y, int width, int height) {
Path2D rect2 = new Path2D.Double();
rect2.append(new Rectangle(getWidth() / 2 - width / 2, getHeight() / 2
- height / 2, width, height), true);
squares.add(rect2);
// rect = rect2;
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
addMouseListener(myMouseAdapter);
addMouseMotionListener(myMouseAdapter);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
this.setOpaque(true);
this.setBackground(Color.WHITE);
Graphics2D g2 = (Graphics2D) g;
for (Path2D rect : squares) {
g2.draw(rect);
}
repaint();
}
class MyMouseAdapter extends MouseAdapter {
private boolean pressed = false;
private Point point;
#Override
public void mousePressed(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1) {
return;
}
for (int i = 0; i < squares.size(); i++) {
if (squares.get(i) != null
&& squares.get(i).contains(e.getPoint())) {
currentIndex = i;
pressed = true;
this.point = e.getPoint();
}
}
}
#Override
public void mouseDragged(MouseEvent e) {
if (pressed) {
int deltaX = e.getX() - point.x;
int deltaY = e.getY() - point.y;
squares.get(currentIndex).transform(
AffineTransform.getTranslateInstance(deltaX, deltaY));
point = e.getPoint();
repaint();
}
}
#Override
public void mouseReleased(MouseEvent e) {
pressed = false;
}
}
}
Lot of problems...
Most important, no you don't want to add a bunch of MouseListeners/MouseMotionListeners to your JPanel. You only want to add one, and have it control any and all squares that the JPanel holds.
Don't put a repaint() in your paintComponent method as that's a poor way to try to create an animation loop, a loop that you have absolutely no control over. Plus there's no need. The MouseAdapter should drive all the animation by itself.
class Squares extends JPanel {
private static final long serialVersionUID = 1L;
public Squares() {
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
addMouseListener(myMouseAdapter);
addMouseMotionListener(myMouseAdapter);
}
private List<Path2D> squares = new ArrayList<Path2D>();
// private Path2D rect = new Path2D.Double();
int currentIndex;
public void addSquare(int x, int y, int width, int height) {
Path2D rect2 = new Path2D.Double();
rect2.append(new Rectangle(getWidth() / 2 - width / 2, getHeight() / 2
- height / 2, width, height), true);
squares.add(rect2);
repaint(); // !!
// rect = rect2;
// !! MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
// addMouseListener(myMouseAdapter);
// addMouseMotionListener(myMouseAdapter);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
this.setOpaque(true);
this.setBackground(Color.WHITE);
Graphics2D g2 = (Graphics2D) g;
for (Path2D rect : squares) {
g2.draw(rect);
}
// !! repaint();
}
I'm making an application that has a drawing board where you draw with your mouse, it draws ontop of an Label in a BUfferedImage. What I'm trying to implement right now is an eraser, the problem is I cannot find anywhere help to make an eraser to clearRect() to an alpha background. (I cannot have a defined color background since the user can change the background to any image he wants). To sum up:
How can you erase/overwrite Graphics2D pixels with alpha pixels? The way i found was with clearRect but you need to specify a background color.
The following is my DrawBoard class which constains everything to draw.
public class DrawBoard extends JPanel implements MouseListener, MouseMotionListener{
public JLabel status;
private JLabel imgLabel; // this is where the drawing happens
public Point pstart, pfinish;
private List<Point> points = new ArrayList<Point>();
private List<BufferedImage> lines = new ArrayList<BufferedImage>();
private static final int BI_WIDTH = 1024;
private static final int BI_HEIGHT = 800;
private static int STROKESIZE = 7;
private BufferedImage bImage = new BufferedImage(BI_WIDTH, BI_HEIGHT,
BufferedImage.TYPE_INT_ARGB);
public Color currentColor;
public static boolean eraser = false;
private int xX1, yY1;
public DrawBoard(){
Graphics2D g2d = bImage.createGraphics();
g2d.dispose();
Dimension size = getPreferredSize();
size.setSize(1024,800); //w, h
setPreferredSize(size);
//status = new JLabel("default");
//add(status, BorderLayout.SOUTH);
addMouseListener(this);
addMouseMotionListener(this);
imgLabel = new JLabel(new ImageIcon(bImage)) {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
paintInLabel(g);
}
};
imgLabel.setOpaque(false);
setOpaque(false);
add(imgLabel, BorderLayout.CENTER);
}
private void paintInLabel(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(getColor()); // this colour is when mouse is pressed
g2d.setStroke(new BasicStroke(STROKESIZE));
if (points.size() < 2) {
return;
}
for (int i = 1; i < points.size(); i++) {
int x1 = points.get(i - 1).x;
int y1 = points.get(i - 1).y;
int x2 = points.get(i).x;
int y2 = points.get(i).y;
g2d.drawLine(x1, y1, x2, y2);
}
}
#Override
public void mouseExited(MouseEvent e){
}
#Override
public void mouseEntered(MouseEvent e){
}
#Override
public void mouseMoved(MouseEvent e){
}
// Where the drawing happens
#Override
public void mousePressed(MouseEvent e) {
//status.setText("you pressed down the mouse");
xX1 = e.getX();
yY1 = e.getY();
points.add(e.getPoint());
}
#Override
public void mouseDragged(MouseEvent e) {
//status.setText("you draged the mouse");
points.add(e.getPoint());
imgLabel.repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
//status.setText("you release the mouse click");
Graphics2D g2d = bImage.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(getColor()); // this is the final colour
g2d.setStroke(new BasicStroke(STROKESIZE));
if (points.size() >= 2) {
for (int i = 1; i < points.size(); i++) {
int x1 = points.get(i - 1).x;
int y1 = points.get(i - 1).y;
int x2 = points.get(i).x;
int y2 = points.get(i).y;
g2d.drawLine(x1, y1, x2, y2);
}
}
g2d.dispose();
points.clear();
imgLabel.repaint();
}
// End of where the drawing happens
public void clearDrawBoard() {
}
private Color getColor() {
return ColourToolbar.selectedColor;
}
private void setColor(Color col){
this.currentColor = col;
}
#Override
public void mouseClicked(MouseEvent e) {
//throw new UnsupportedOperationException("Not supported yet.");
}
}
You should set a custom Composite for your Graphics2D, specifically AlphaComposite.Clear before drawing the rectangle. Don't forget to reset the composite to the default (SRC_OVER) when you are done, because the same Graphics object will be reused to paint other components.
How do I draw that semi-transparent rectangle on the screen?
That cannot be a JFrame because JFrames have the usual close, minimize, maximize options in top right.
if it is indeed a swing competent, How is it drawn in thin air? Without inserting it in a JFrame whatsoever?
Please tell me what it is and how I can implement it...
The immediate idea that comes to mind is to use java.awt.Robot to capture a screen shot, paint that to frameless window. From there you can simply draw a rectangle on it
Updated with example
... Took some time ...
public class SelectionRectangle {
public static void main(String[] args) {
new SelectionRectangle();
}
public SelectionRectangle() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setUndecorated(true);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new BackgroundPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class BackgroundPane extends JPanel {
private BufferedImage background;
private Point mouseAnchor;
private Point dragPoint;
private SelectionPane selectionPane;
public BackgroundPane() {
selectionPane = new SelectionPane();
try {
Robot bot = new Robot();
background = bot.createScreenCapture(getScreenViewableBounds());
} catch (AWTException ex) {
Logger.getLogger(SelectionRectangle.class.getName()).log(Level.SEVERE, null, ex);
}
selectionPane = new SelectionPane();
setLayout(null);
add(selectionPane);
MouseAdapter adapter = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
mouseAnchor = e.getPoint();
dragPoint = null;
selectionPane.setLocation(mouseAnchor);
selectionPane.setSize(0, 0);
}
#Override
public void mouseDragged(MouseEvent e) {
dragPoint = e.getPoint();
int width = dragPoint.x - mouseAnchor.x;
int height = dragPoint.y - mouseAnchor.y;
int x = mouseAnchor.x;
int y = mouseAnchor.y;
if (width < 0) {
x = dragPoint.x;
width *= -1;
}
if (height < 0) {
y = dragPoint.y;
height *= -1;
}
selectionPane.setBounds(x, y, width, height);
selectionPane.revalidate();
repaint();
}
};
addMouseListener(adapter);
addMouseMotionListener(adapter);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawImage(background, 0, 0, this);
g2d.dispose();
}
}
public class SelectionPane extends JPanel {
private JButton button;
private JLabel label;
public SelectionPane() {
button = new JButton("Close");
setOpaque(false);
label = new JLabel("Rectangle");
label.setOpaque(true);
label.setBorder(new EmptyBorder(4, 4, 4, 4));
label.setBackground(Color.GRAY);
label.setForeground(Color.WHITE);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
add(label, gbc);
gbc.gridy++;
add(button, gbc);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.getWindowAncestor(SelectionPane.this).dispose();
}
});
addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
label.setText("Rectangle " + getX() + "x" + getY() + "x" + getWidth() + "x" + getHeight());
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(new Color(128, 128, 128, 64));
g2d.fillRect(0, 0, getWidth(), getHeight());
float dash1[] = {10.0f};
BasicStroke dashed =
new BasicStroke(3.0f,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER,
10.0f, dash1, 0.0f);
g2d.setColor(Color.BLACK);
g2d.setStroke(dashed);
g2d.drawRect(0, 0, getWidth() - 3, getHeight() - 3);
g2d.dispose();
}
}
public static Rectangle getScreenViewableBounds() {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
return getScreenViewableBounds(gd);
}
public static Rectangle getScreenViewableBounds(GraphicsDevice gd) {
Rectangle bounds = new Rectangle(0, 0, 0, 0);
if (gd != null) {
GraphicsConfiguration gc = gd.getDefaultConfiguration();
bounds = gc.getBounds();
Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(gc);
bounds.x += insets.left;
bounds.y += insets.top;
bounds.width -= (insets.left + insets.right);
bounds.height -= (insets.top + insets.bottom);
}
return bounds;
}
}
Update with SnipIt Example
Some people have suggested using a transparent window laid over the top of the screen, this actually won't work, as transparent windows don't actually respond to mouse clicks UNLESS they have something to be painted on them that will allow the mouse event to be trapped.
It's also been suggested that you use a Window as the selection mechanism, this is a valid answer, however, I would (personally) find that to be an unsuitable solution, as you want the user to simply click and drag the selection rectangle (IMHO).
Another approach is use something like SnipIt.
public class SnipIt {
public static void main(String[] args) {
new SnipIt();
}
public SnipIt() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setUndecorated(true);
// This works differently under Java 6
frame.setBackground(new Color(0, 0, 0, 0));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new SnipItPane());
frame.setBounds(getVirtualBounds());
frame.setVisible(true);
}
});
}
public class SnipItPane extends JPanel {
private Point mouseAnchor;
private Point dragPoint;
private SelectionPane selectionPane;
public SnipItPane() {
setOpaque(false);
setLayout(null);
selectionPane = new SelectionPane();
add(selectionPane);
MouseAdapter adapter = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
mouseAnchor = e.getPoint();
dragPoint = null;
selectionPane.setLocation(mouseAnchor);
selectionPane.setSize(0, 0);
}
#Override
public void mouseDragged(MouseEvent e) {
dragPoint = e.getPoint();
int width = dragPoint.x - mouseAnchor.x;
int height = dragPoint.y - mouseAnchor.y;
int x = mouseAnchor.x;
int y = mouseAnchor.y;
if (width < 0) {
x = dragPoint.x;
width *= -1;
}
if (height < 0) {
y = dragPoint.y;
height *= -1;
}
selectionPane.setBounds(x, y, width, height);
selectionPane.revalidate();
repaint();
}
};
addMouseListener(adapter);
addMouseMotionListener(adapter);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
Rectangle bounds = new Rectangle(0, 0, getWidth(), getHeight());
Area area = new Area(bounds);
area.subtract(new Area(selectionPane.getBounds()));
g2d.setColor(new Color(192, 192, 192, 64));
g2d.fill(area);
}
}
public class SelectionPane extends JPanel {
private JButton button;
private JLabel label;
public SelectionPane() {
button = new JButton("Close");
setOpaque(false);
label = new JLabel("Rectangle");
label.setOpaque(true);
label.setBorder(new EmptyBorder(4, 4, 4, 4));
label.setBackground(Color.GRAY);
label.setForeground(Color.WHITE);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
add(label, gbc);
gbc.gridy++;
add(button, gbc);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.getWindowAncestor(SelectionPane.this).dispose();
}
});
addComponentListener(new ComponentAdapter() {
#Override
public void componentResized(ComponentEvent e) {
label.setText("Rectangle " + getX() + "x" + getY() + "x" + getWidth() + "x" + getHeight());
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
// I've chosen NOT to fill this selection rectangle, so that
// it now appears as if you're "cutting" away the selection
// g2d.setColor(new Color(128, 128, 128, 64));
// g2d.fillRect(0, 0, getWidth(), getHeight());
float dash1[] = {10.0f};
BasicStroke dashed =
new BasicStroke(3.0f,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER,
10.0f, dash1, 0.0f);
g2d.setColor(Color.BLACK);
g2d.setStroke(dashed);
g2d.drawRect(0, 0, getWidth() - 3, getHeight() - 3);
g2d.dispose();
}
}
public static Rectangle getVirtualBounds() {
Rectangle bounds = new Rectangle(0, 0, 0, 0);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice lstGDs[] = ge.getScreenDevices();
for (GraphicsDevice gd : lstGDs) {
bounds.add(gd.getDefaultConfiguration().getBounds());
}
return bounds;
}
}
Update Multi Monitor Support to the Example Answer from #MadProgrammer.
Without ExtendedState(JFrame.MAXIMIZED_BOTH) and pack()
public SelectionRectangle() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setUndecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new BackgroundPane());
frame.setResizable( false );
frame.setBounds( getScreenViewableBounds() );
frame.setVisible(true);
}
});
}
public static Rectangle getScreenViewableBounds() {
GraphicsDevice[] devices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
int minx = Integer.MAX_VALUE;
int miny = Integer.MAX_VALUE;
int maxx = Integer.MIN_VALUE;
int maxy = Integer.MIN_VALUE;
for( GraphicsDevice device : devices ) {
for( GraphicsConfiguration config : device.getConfigurations() ) {
Rectangle bounds = config.getBounds();
minx = Math.min( minx, bounds.x );
miny = Math.min( miny, bounds.y );
maxx = Math.max( maxx, bounds.x + bounds.width );
maxy = Math.max( maxy, bounds.y + bounds.height );
}
}
return new Rectangle( new Point(minx, miny), new Dimension(maxx - minx, maxy - miny) );
}
You could use a transparent, undecorated frame in order to create a basic border.
public class ScreenRectangle extends JFrame {
public ScreenRectangle() {
this.setUndecorated(true);
this.setBackground(new Color(0, 0, 0, 0.25F));
// opacity ranges 0.0-1.0 and is the fourth paramater
this.add(new DrawPanel());
}
private class DrawPanel extends JPanel {
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(0, 0, this.getWidth(), this.getHeight());
// any other drawing
}
}
}
The frame may also need to be setOpaque, or the panel size may need to be handled, but this is the general idea of it.