Java paintComponent resize/minimize erases all but last drawn component - java

Problem is specified in the title. I hit run, make a few lines here and there. When I resize or minimize the window, everything except the last line that was drawn is erased from the jframe window. This is part of a much larger photo album program. Eventually, I want to be able to save the drawing and add to the album. I believe the below code is where the issue lies. I've been scratching my head all night on this one. I figured if I created two arraylists and iterated through them, repaint() would re draw everything back, but that doesn't seem to be the case. Please help! Here's my code:
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Draw extends JPanel implements MouseListener, MouseMotionListener, ActionListener
{
private static final long serialVersionUID = 1L;
private ArrayList<ArrayList<Point>> lines;
private ArrayList<Point> points;
private Graphics g;
private Button clearButton;
public Draw()
{
clearButton = new Button("Clear slate");
g = getGraphics();
points = new ArrayList<Point>();
lines = new ArrayList<ArrayList<Point>>();
setPreferredSize(new Dimension(500, 500));
setBounds(0,0,500,500);
addMouseListener(this);
addMouseMotionListener(this);
clearButton.addActionListener(this);
this.add(clearButton, BorderLayout.SOUTH);
}
#Override
public void mouseClicked(MouseEvent e) {}
#Override
public void mouseDragged(MouseEvent e)
{
// TODO Auto-generated method stub
points.add(e.getPoint());
lines.add(points);
repaint();
}
public void paint(Graphics g)
{
super.paintComponents(g);
for(ArrayList<Point> p : lines)
{
for(int i = 0; i < points.size()-1; i++)
g.drawLine(points.get(i).x, points.get(i).y, points.get(i+1).x, points.get(i+1).y);
}
}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e)
{
points = new ArrayList<Point>();
points.add(e.getPoint());
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseMoved(MouseEvent e) {}
#Override
public void actionPerformed(ActionEvent evt)
{
if(evt.getSource()== clearButton)
{
lines.clear();
points.clear();
repaint();
}
}
}
Main method:
import javax.swing.JFrame;
public class MainDriver
{
public static void main(String a[])
{
JFrame frame = new JFrame();
Draw d = new Draw();
frame.add(d);
frame.pack();
frame.setVisible(true);
}
}

Related

Position JTextField via moving Coordinates?

(The above image is taken from AutoCAD)
My application draws a line on a JPanel using two Point class variables: "startPoint" and "finishPoint".
"startPoint" is set from the first mouse click. Once a starting point has been established the finishPoint variable is set on the position of the cursor. Therefore the line moves/grows dynamically with the mouse movement until the "finishPoint" is finalised by a second mouse click.
During the period where a startPoint has been established and the line dynamically changes I would like to position a JTextField on the line midpoint (well... slightly off-center so it's not obscuring the line) if possible?
I know I'll get shouted at if I try and position a component without the use of a layout manager, but I can't see how a layout manager can help. I would like to position the JTextField using Coordinates. The only way I can think of doing that is to somehow add the textfield into a shape. Beyond that I'm at a loss.
Can someone put me in the right direction?
My code should anybody want to see it:
package Drawing;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
/*
* An extension to P2PLines. A line from point A to point B but with an animation.
*/
public class LineAnimation extends JPanel implements MouseListener, MouseMotionListener
{
private Graphics g;
private Point lineStart = new Point(0, 0);
private Point lineFinish = new Point(0, 0);
private boolean drawing;
int globalX = 0, globalY;
ArrayList<Line2D> edges = new ArrayList<>();
public LineAnimation()
{
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
drawing = false;
}
#Override public void mouseClicked(MouseEvent me) {}
#Override public void mousePressed(MouseEvent me)
{
if (drawing)
{
g = getGraphics(); // Get Graphics content
g.setColor(Color.black);
lineFinish.move(me.getX(), me.getY());
g.drawLine(lineStart.x, lineStart.y, me.getX(), me.getY());
edges.add(new Line2D.Float(lineStart.x, lineStart.y, lineFinish.x, lineFinish.y));
drawing = false;
g.dispose();
}
else
{
lineStart.move(me.getX(), me.getY());
drawing = true;
}
}
#Override public void paintComponent(Graphics g)
{
super.paintComponent(g);
drawPreviousLine((Graphics2D)g);
if (drawing)
{g.drawLine(lineStart.x, lineStart.y, globalX, globalY);}
}
private void drawPreviousLine(Graphics2D g)
{
for(Line2D lines: edges)
{g.draw(lines);}
}
#Override
public void mouseMoved(MouseEvent me)
{
repaint();
globalX = me.getX();
globalY = me.getY();
}
#Override public void mouseReleased(MouseEvent me) {}
#Override public void mouseEntered(MouseEvent me) {}
#Override public void mouseExited(MouseEvent me) {}
#Override public void mouseDragged(MouseEvent me) {}
public static void main(String[] args)
{
JFrame frame = new JFrame("Drawing Frame");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
LineAnimation drawingFrame = new LineAnimation();
frame.add(drawingFrame);
frame.setVisible(true);
drawingFrame.addMouseListener(drawingFrame);
drawingFrame.addMouseMotionListener(drawingFrame);
}
}

Why my JPanel is not painting anything after I changed the design to same class [duplicate]

import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.*;
import java.util.*;
public class test1 extends JFrame implements MouseListener {
private JPanel JP = new JPanel();
public test1() {
JP.setBorder(BorderFactory.createLineBorder(Color.black));
JP.addMouseListener(this);
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
this.add(JP);
this.pack();
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
test1 frame = new test1();
frame.setSize(400,400);
frame.setVisible(true);
}
});
}
public void mouseClicked(MouseEvent e) {
//drawCircle(e.getX(), e.getY());
//repaint();
ballball ball;
ball = new ballball();
//ball.paintComponent(Graphics g);
System.out.println("ballball");
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
//this.mouseX=e.getX();
//this.mouseY=e.getY();
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
}
class ballball extends test1 implements Runnable {
private int squareX = 50;
private int squareY = 50;
private int squareW = 100;
private int squareH = 100;
public boolean draw;
private Vector<Object> v = new Vector<Object>();
public ballball() {
/*addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
draw = true;
//Thread thread1 = new Thread(this.moveSquare(50, 50));
repaint();
//moveSquare(e.getX(),e.getY());
}
});*/
/*addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
moveSquare(e.getX(),e.getY());
}
});*/
System.out.println("ball created");
this.repaint();
}
public void run() {
}
private void moveSquare(int x, int y) {
int OFFSET = 1;
if ((squareX!=x) || (squareY!=y)) {
repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
squareX=x;
squareY=y;
repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
}
}
public void paint(Graphics g) {
g.drawString("abcasdfasffasfas", 10, 10);
}
//#Override
public void paintComponent(Graphics g) {
//if (draw) {
// existing code
System.out.println("paint");
//super.paintComponent(g);
//g.drawString("This is my custom Panel!",10,20);
//g.setColor(Color.RED);
//g.fillRect(squareX,squareY,squareW,squareH);
//g.setColor(Color.BLACK);
//g.drawRect(squareX,squareY,squareW,squareH);
Shape circle = new Ellipse2D.Float(squareX,squareY,100f,100f);
Graphics2D ga = (Graphics2D)g;
ga.draw(circle);
//}
}
}
The aim of the program is to click to create the circle, the ballball class extends the test1, when test1 detect the mouse click, the ballball object created. But the paint/paintComponent method is never be executed. In my program structure, is it possible to paint the circle to the super class JPanel?
JFrame is not a JComponent, it doesn't have a paintComponent method you can override. Instead you could extend a JPanel and add it to the frame.

The Dimension of my screen is not being measured, MacOSX and NetBeans

package spaceinvaders;
//#author AlexB
import java.awt.Color;
import java.awt.*;
import java.awt.Graphics2D;
import java.awt.event.KeyAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class SpaceInvaders extends KeyAdapter implements MouseListener {
private JFrame frame;
private JPanel panel;
public static int screenSizeX;
public static int screenSizeY;
private Dimension screenSize;
public SpaceInvaders() throws IOException
{
//screenSize = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
screenSize = Toolkit.getDefaultToolkit().getScreenSize(); //Finds the screen size
screenSizeX = (int)screenSize.getWidth(); //The length of the screen
screenSizeY = (int)screenSize.getHeight(); //The height of the screen
frame = new JFrame("Space Invaders");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setResizable(false);
frame.setSize(screenSizeX, screenSizeY);
panel = new MyPanel();
frame.getContentPane().add(panel);
frame.addMouseListener(this);
frame.addKeyListener(this);
spriteStore.getImage();
}
#Override
public void mouseClicked(MouseEvent me)
{
}
#Override
public void mousePressed(MouseEvent me)
{
}
#Override
public void mouseReleased(MouseEvent me)
{
}
#Override
public void mouseEntered(MouseEvent me)
{
}
#Override
public void mouseExited(MouseEvent me)
{
}
class MyPanel extends JPanel
{
#Override
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2D = (Graphics2D)g;
g2D.setColor(Color.BLACK);
g2D.fillRect(0,0, screenSizeX, screenSizeY);
g2D.drawImage(spriteStore.player, playerEntity.xCoord, screenSizeY-100, null);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
SpaceInvaders spaceInvaders;
try
{
spaceInvaders = new SpaceInvaders();
}
catch (IOException ex) {}
}
}
);
System.out.println("" + screenSizeX + "" + screenSizeY);
}
}
The question is why does my dimension not measure? When it prints out the screenSizeX and screenSizeY it provides the value 0 for both. I am using a mac, and netbeans, this code normally worked on a windows computer.

How do I zoom on Swing components using AffineTransform?

I am trying to create a panel where I will have the possibility to zoom on custom made JComponent objects.
I have tried to call the scale() method in the AffineTransform class with different values, but I have not succeeded. My objects just disappear.
Below is my component that is used in the main frame class. Everything works except the zooming. Could some of you explain the concepts of AffineTransform. I donĀ“t think the JavaDoc explenation is enough for me.
Here is an executable SSCCE:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.HeadlessException;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class JavaApplication1 extends JFrame {
public static void main(String[] args) {
new JavaApplication1();
}
private MyComponent myComponent = new MyComponent();
public JavaApplication1() throws HeadlessException {
this.setSize(400,400);
this.setVisible(true);
this.add(myComponent);
}
class MyComponent extends JComponent {
private int x, y;
private double scale=1;
private MouseAdapter mouseAdapter = new MouseAdapter();
private AffineTransform transform = new AffineTransform();
public MyComponent() {
this.addMouseListener(mouseAdapter);
this.addMouseWheelListener(mouseAdapter);
this.addMouseMotionListener(mouseAdapter);
}
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.DARK_GRAY);
g2.fillRect(0, 0, 400, 400);
g2.setColor(Color.RED);
g2.setTransform(transform);
transform.scale(scale, scale);
g2.drawString("My String!", x, y);
}
private class MouseAdapter implements MouseWheelListener, MouseListener, MouseMotionListener {
#Override
public void mouseWheelMoved(MouseWheelEvent e) {
if(e.getWheelRotation() == 1) {
scale+=0.1;
}else {
scale-=0.1;
}
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
}
}
}
}
transform.scale accepts two double parameters, one for the x axis and the other for the y axis, being 1 the neutral value (no change in scale), and the two parameters the multipliers.
Ex: transform.scale(2,2) will show the component twice as big, while transform.scale(0.5,0.5) will show it twice as small.
http://docs.oracle.com/javase/6/docs/api/java/awt/geom/AffineTransform.html#scale(double, double)

JLabel mouse events for Drag and Drop

I want to enable the drag and drop feature over a JLabel by overriding mouse events over it , but when I define the drag and drop in mousePressed event ,the mouseReleased does not take effect on that JLabel. Am I doing something wrong ?
Thumbnails[I_Loop].setText("1");
Thumbnails[I_Loop].setTransferHandler(new TransferHandler("text"));
Thumbnails[I_Loop].addMouseListener( new MouseAdapter() {
public void mouseReleased(MouseEvent me) {
System.out.println("here mouse released");
}
public void mousePressed(MouseEvent me) {
System.out.println("here mouse pressed");
JComponent comp = (JComponent) me.getSource();
TransferHandler handler = comp.getTransferHandler();
handler.exportAsDrag(comp, me, TransferHandler.COPY);
});
*Thumbnails is array of JLabel
When running the program , the drag and drop works but the statement "here mouse released" does not get printed. However, When I remove the code responsible for DND from the mousePressed() method, "here mouse released" is printed.
What is the wrong in this code?
#Thomas is correct, but two alternatives are worth noting:
This example shows how to drag a component using JLayeredPane; this variation expands on the concept; this more recent example uses a similar approach.
The code below shows how to use a MouseMotionListener; this more complex example uses the same principle.
Code:
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JFrame;
import javax.swing.JPanel;
/** #see https://stackoverflow.com/a/5312702/230513 */
public class MouseDragTest extends JPanel {
private static final String TITLE = "Drag me!";
private static final int W = 640;
private static final int H = 480;
private Point textPt = new Point(W / 2, H / 2);
private Point mousePt;
public MouseDragTest() {
this.setFont(new Font("Serif", Font.ITALIC + Font.BOLD, 32));
this.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
mousePt = e.getPoint();
repaint();
}
});
this.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
int dx = e.getX() - mousePt.x;
int dy = e.getY() - mousePt.y;
textPt.setLocation(textPt.x + dx, textPt.y + dy);
mousePt = e.getPoint();
repaint();
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(W, H);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int w2 = g.getFontMetrics().stringWidth(TITLE) / 2;
g.drawString(TITLE, textPt.x - w2, textPt.y);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame(TITLE);
f.add(new MouseDragTest());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
}
Well, if I remember correctly, the drag and drop machinery catches all mouse events and processes them itself. Thus, the normal MouseEvents are not thrown anymore. You'd need to register a DropTargetListener on the JLabel's DropTarget.
Does it have to be a JLabel? I made a class with a string that might get you started..
import java.awt.Graphics;
import java.awt.MouseInfo;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class mainProgram extends JPanel implements Runnable
{
private static final long serialVersionUID = 1L;
public static boolean MOUSE_DOWN = false;
public static String str;
public mainProgram()
{
JFrame win = new JFrame("Window");
win.add(this);
win.setSize(700,500);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.setVisible(true);
str = "Drag me!";
new Thread(this).start();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(MOUSE_DOWN)
{
g.drawString(str, MouseInfo.getPointerInfo().getLocation().x, MouseInfo.getPointerInfo().getLocation().y);
}
}
#Override
public void run()
{
Thread t = Thread.currentThread();
this.addMouseListener(new MouseListener()
{
#Override
public void mouseClicked(MouseEvent arg0)
{
}
#Override
public void mouseEntered(MouseEvent arg0)
{
}
#Override
public void mouseExited(MouseEvent arg0)
{
}
#Override
public void mousePressed(MouseEvent arg0)
{
MOUSE_DOWN = true;
}
#Override
public void mouseReleased(MouseEvent arg0)
{
MOUSE_DOWN = false;
}
});
while(t==Thread.currentThread())
{
if(MOUSE_DOWN)
repaint();
try {Thread.sleep(10);}
catch (InterruptedException e) {e.printStackTrace();}
}
}
}

Categories