Applet not painting - java

I am having issues with my Applet not painting the required graphics.
For some reason, it updates the coloring in the graphics, as you can see this when it prints, it recognizes the mouse is being moved, the graphics are not null, but it still refuses to paint.
How can this be fixed?
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JApplet;
public class GameApplet extends JApplet implements MouseListener, MouseMotionListener{
/**
*
*/
private static final long serialVersionUID = -6796451079056583597L;
Graphics2D g;
Image image;
Point p = new Point(-100, -100);
public void init(){
init(1000, 900);
}
public void init(int x, int y){
setSize(x, y);
image = createImage(x, y);
g = (Graphics2D) image.getGraphics();
//if(Graphic.setGraphic(image.getGraphics())){
if(g != null)
System.out.println("Graphics made");
//}
g.setColor(Color.GREEN);
g.fillRect(0, 0, x, y);
System.out.println(g+", "+ (g != null));
addMouseListener(this);
addMouseMotionListener(this);
//Graphic.paint();
setVisible(true);
}
#Override
public void paint(Graphics g){
g.setColor(Color.red);
g.fillRect(0, 0, 500, 500);
}
public void update(Graphics g){
paint(g);
}
#Override
public Graphics getGraphics(){
return g;
}
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(e);
}
#Override
public void mousePressed(MouseEvent e) {
p = e.getPoint();
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void mouseDragged(MouseEvent e) {
}
#Override
public void mouseMoved(MouseEvent e) {
showStatus(e.toString());
g.fillOval(e.getPoint().x - 5, e.getPoint().y - 5, 10, 10);
p = e.getPoint();
repaint();
}
}

As per my recommendations, do all drawing in a JPanel or JComponent's paintComponent method. Get the image's Graphics object only when you need it and dispose of it when you're done with it. For example:
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.lang.reflect.InvocationTargetException;
import javax.swing.*;
#SuppressWarnings("serial")
public class GameApplet2 extends JApplet {
protected static final int APP_WIDTH = 1000;
protected static final int APP_HEIGHT = 900;
#Override
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
GameAppletPanel panel = new GameAppletPanel(GameApplet2.this);
getContentPane().add(panel);
panel.init(APP_WIDTH, APP_HEIGHT);
setSize(APP_WIDTH, APP_HEIGHT);
}
});
} catch (InterruptedException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
#SuppressWarnings("serial")
class GameAppletPanel extends JPanel {
Image image;
Point p = new Point(-100, -100);
private JApplet applet;
public GameAppletPanel(JApplet applet) {
this.applet = applet;
}
public void init() {
init(1000, 900);
}
public void init(int x, int y) {
setSize(x, y);
image = createImage(x, y);
Graphics2D g = (Graphics2D) image.getGraphics();
g.setColor(Color.GREEN);
g.fillRect(0, 0, x, y);
g.dispose();
System.out.println(g + ", " + (g != null));
MyMouseAdapter mmAdapter = new MyMouseAdapter();
addMouseListener(mmAdapter);
addMouseMotionListener(mmAdapter);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
g.setColor(Color.red);
g.fillRect(0, 0, 500, 500);
}
private class MyMouseAdapter extends MouseAdapter {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(e);
}
#Override
public void mousePressed(MouseEvent e) {
p = e.getPoint();
repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
applet.showStatus(e.toString());
Graphics2D g2 = (Graphics2D) image.getGraphics();
g2.fillOval(e.getPoint().x - 5, e.getPoint().y - 5, 10, 10);
p = e.getPoint();
g2.dispose();
repaint();
}
}
}

The "don't paint in top-level containers" still needs attending to, but it was not the immediate source(s) of the problem. Try this simpler code.
// <applet code='GameApplet' width=400 height=200></applet>
import java.awt.*;
import java.awt.event.*;
import javax.swing.JApplet;
public class GameApplet extends JApplet
implements MouseListener, MouseMotionListener{
Point p = new Point(-100, -100);
public void init(){
addMouseListener(this);
addMouseMotionListener(this);
}
#Override
public void paint(Graphics g){
g.setColor(Color.red);
g.fillRect(0, 0, 500, 500);
g.setColor(Color.blue);
g.fillOval(p.x - 5, p.y - 5, 10, 10);
}
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(e);
}
#Override
public void mousePressed(MouseEvent e) {
p = e.getPoint();
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
#Override
public void mouseDragged(MouseEvent e) {}
#Override
public void mouseMoved(MouseEvent e) {
showStatus(e.toString());
p = e.getPoint();
repaint();
}
}

Related

MouseInputListener isn't working on a JButtons

I have two JButtons that are extending two different inner classes of an outer class extending JPanel. I implemented MouseInputListener on the JButtons but it does not seem to be working. I tried placing the MouseInputListener on the outer class but it was not working either. I have a different class extending JFrame and also implementing MouseInputListener so I think it might be some overlay or hierarchy error but I'm not sure.
public class Frame extends JFrame implements MouseInputListener{
static Dimension windowSize = Toolkit.getDefaultToolkit().getScreenSize();
static int windowWidth = (int) windowSize.getWidth();
static int windowHeight = (int) windowSize.getHeight();
TopBar design = new TopBar(windowWidth, windowHeight);
public Frame(){
EventQueue.invokeLater(new Runnable() {
#Override
public void run(){
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
pack();
setSize(windowSize);
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
add(design);
setState(java.awt.Frame.NORMAL);
//setBackground(Color.decode("#449d9d"));
}
});
addMouseListener(this);
addMouseMotionListener(this);
}
#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) {
}
#Override
public void mouseMoved(MouseEvent e) {
System.out.println(getWidth() + " " + getHeight());
remove(design);
windowWidth = getWidth();
windowHeight = getHeight();
design = new TopBar(windowWidth, windowHeight);
add(design);
}}
and
public class TopBar extends JPanel{
int windowWidth;
int windowHeight;
public class resourcesButton extends JButton implements MouseInputListener{
public resourcesButton(int windowWidth, int windowHeight){
setText("Resourses");
setFont(new Font("Helvetica", Font.PLAIN, 24));
setBorder(new RoundedBorder(Color.decode("#f75280"),2,16,16));
setBackground(Color.decode("#f75280"));
setForeground(Color.decode("#0c120c"));
setOpaque(true);
setCursor(new Cursor(Cursor.HAND_CURSOR));
setBounds((int)(windowWidth/1.5), (int)(windowHeight/6.5)/2/3, (int)(windowWidth/8.33), (int)(9*(windowWidth/8.33)/16));
setHorizontalAlignment(SwingConstants.CENTER);
setVerticalAlignment(SwingConstants.CENTER);
addMouseListener(this);
addMouseMotionListener(this);
}
#Override
public void mouseClicked(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {
setCursor(new Cursor(Cursor.HAND_CURSOR));
}
#Override
public void mouseExited(MouseEvent e) {
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
#Override
public void mouseDragged(MouseEvent e) {
System.out.println("Check");
}
#Override
public void mouseMoved(MouseEvent e) {}
}
public class startButton extends JButton implements MouseInputListener{
public startButton(int windowWidth, int windowHeight){
setText("Start Diagnosis");
setFont(new Font("Helvetica", Font.PLAIN, windowHeight/45));
setBorder(new RoundedBorder(Color.decode("#f75280"),2,16,16));
setBackground(Color.decode("#f75280"));
setForeground(Color.decode("#0c120c"));
setOpaque(true);
setCursor(new Cursor(Cursor.HAND_CURSOR));
setBounds((int)(windowWidth/1.25), (int)(windowHeight/6.5)/2/3, (int)(windowWidth/8.33), (int)(9*(windowWidth/8.33)/16));
setHorizontalAlignment(SwingConstants.CENTER);
setVerticalAlignment(SwingConstants.CENTER);
addMouseListener(this);
addMouseMotionListener(this);
}
#Override
public void mouseClicked(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {
setCursor(new Cursor(Cursor.HAND_CURSOR));
}
#Override
public void mouseExited(MouseEvent e) {
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
#Override
public void mouseDragged(MouseEvent e) {
System.out.println("Check");
}
#Override
public void mouseMoved(MouseEvent e) {}
}
public TopBar(int windowWidth, int windowHeight){
setLayout(null);
this.windowWidth = windowWidth;
this.windowHeight = windowHeight;
add(new resourcesButton(windowWidth, windowHeight));
add(new startButton(windowWidth, windowHeight));
}
#Override
protected void paintComponent (Graphics graphic){
BufferedImage logo = null;
try {
logo = ImageIO.read(new File("SySLogo.png"));
} catch (IOException e) {
e.printStackTrace();
}
super.paintComponent(graphic);
Graphics2D g2d = (Graphics2D) graphic.create();
g2d.setColor(Color.decode("#449d9d"));
g2d.fillRect(0, 0, windowWidth, (int)(windowHeight/6.5));
try {
g2d.drawImage(resizeImage(logo, (int)(windowWidth/8.33), (int)(windowHeight/8.6481)), windowWidth/16, (int)(windowHeight/48), this);
} catch (IOException e) {
g2d.drawImage(logo, windowWidth/16, (int)(windowHeight/48), this);
e.printStackTrace();
}
g2d.setColor(Color.decode("#f2eee3"));
g2d.drawLine(0, (int)(windowHeight/6.5), windowWidth, (int)(windowHeight/6.5));
}
private BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) throws IOException {
BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = resizedImage.createGraphics();
graphics2D.drawImage(originalImage, 0, 0, targetWidth, targetHeight, null);
graphics2D.dispose();
return resizedImage;
}
}

How to use graphics(Piant component) on any one layer of JLayeredPane

I am trying to draw a line at run time on any one layer of JlayeredPane. What i am currently facing is that line drawn getting erased automatically once i release the mouse. I want that drawn line to be there until i click the mouse again.
I am calling the below written class, this way
iDimension = new getDimension();
iDimension.setBounds(1, 12, 441, 380);
//iDimension.setOpaque(true);
iDimension.setBackground(new Color(0,0,0,100));
I have added iDimension With Layered pane in this way
layeredPane.add(iDimension, new Integer(1),0);
Here is the getDimension Class
public class getDimension extends JPanel {
public getDimension() {
setDoubleBuffered(true);
this.setBorder(UIManager.getBorder("ComboBox.border"));
this.repaint();
}
Point pointStart = null;
Point pointEnd = null;
{
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
pointStart = e.getPoint();
}
public void mouseReleased(MouseEvent e) {
pointStart = null;
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
pointEnd = e.getPoint();
}
public void mouseDragged(MouseEvent e) {
pointEnd = e.getPoint();
repaint();
}
});
}
public void paint(Graphics g) {
super.paint(g);
if (pointStart != null) {
g.setColor(Color.GREEN);
g.drawLine(pointStart.x, pointStart.y, pointEnd.x, pointEnd.y);
// System.out.println("" + pointStart.x +"," + pointStart.y +"," + pointEnd.x +"," +pointEnd.y);
}
}
}
I am a newbie in java. Kindly correct if there is any ambiguity in my question.
What i am currently facing is that line drawn getting erased automatically once i release the mouse. I want that drawn line to be there until i click the mouse again.
The code is only doing what you tell it to do:
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
pointStart = e.getPoint();
}
public void mouseReleased(MouseEvent e) {
pointStart = null;
}
});
and:
public void paint(Graphics g) {
super.paint(g);
if (pointStart != null) { // *********
g.setColor(Color.GREEN);
g.drawLine(pointStart.x, pointStart.y, pointEnd.x, pointEnd.y);
}
}
Note that if pointStart is null, you don't draw the line -- but you set it to null on mouseReleased! Solution -- don't do that.
e.g.,
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
#SuppressWarnings("serial")
public class GetDimension extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = PREF_W;
private Point pointStart = null;
private Point pointEnd = null;
public GetDimension() {
this.setBorder(UIManager.getBorder("ComboBox.border"));
this.repaint();
MouseAdapter myMouse = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
pointStart = e.getPoint();
repaint();
}
public void mouseDragged(MouseEvent e) {
pointEnd = e.getPoint();
repaint();
}
};
addMouseListener(myMouse);
addMouseMotionListener(myMouse);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (pointStart != null && pointEnd != null) {
g.setColor(Color.GREEN);
g.drawLine(pointStart.x, pointStart.y, pointEnd.x, pointEnd.y);
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
GetDimension mainPanel = new GetDimension();
JFrame frame = new JFrame("GetDimension");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
}

Rotating an image nuisance

Alright guys i'm trying to make an Asteroids type game and I need to be able to rotate an image around so that the front of the ship follows my mouse. I have looked for a few hours now and have found a couple of things but none that satisfy my needs.
If anyone knows how to do this please share!
thanks in advance
here is the code i have now
package Asteroids;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
#SuppressWarnings("serial")
public class Asteroids extends JFrame implements Runnable, MouseListener,
MouseMotionListener, KeyListener {
private Image dbImage;
private Graphics dbg;
int x, y, mx, my;
int a, b, c, degree;
double scale = 1.0;
ImageIcon shipIcon = new ImageIcon(this.getClass().getClassLoader()
.getResource("AstroidsShip.png"));
Image ship = shipIcon.getImage();
public static void main(String[] args) {
Asteroids frame = new Asteroids();
Thread thread = new Thread(frame);
thread.start();
}
public Asteroids() {
addMouseListener(this);
addMouseMotionListener(this);
addKeyListener(this);
setTitle("Astroids");
setSize(500, 500);
setBackground(Color.WHITE);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
x = getWidth() / 2 - 10;
y = getHeight() - getHeight() / 2;
}
public void run() {
while (true) {
try {
} catch (Exception e) {
}
}
}
public void paint(Graphics g) {
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
paintComponent(dbg);
g.drawImage(dbImage, 0, 0, this);
}
public void paintComponent(Graphics g) {
g.drawString("POS: " + mx + ", " + my, 10, 40);
System.out.println(getAngle());
g.drawImage(ship, x, y, this);
g.drawLine(x + 12, y + 10, mx, my);
repaint();
}
public int getAngle() {
a = mx - (x + 12);
b = (y - 10) - my;
return degree = (int) Math.toDegrees(Math.atan2(b, a));
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void mouseDragged(MouseEvent e) {
}
#Override
public void mouseMoved(MouseEvent e) {
mx = e.getX();
my = e.getY();
}
#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) {
}
}
You can use Java2D. It allows to rotate the image and do a lot lot of other cool operations on the image. It also have got hardware acceleration support (through DirectX or OpenGL).
Java2D is built-in in JRE.
Inside your paintComponent method, you could make the code look like:
public void paintComponent(Graphics g) {
g.drawString("POS: " + mx + ", " + my, 10, 40);
System.out.println(getAngle());
Graphics2D g2d = new (Graphics2D)g;
g2d.translate(X, Y);
g2d.rotate(DEGREES);
g2d.drawImage(ship, 0, 0, WIDTH, HEIGHT, this);
g.drawLine(x + 12, y + 10, mx, my);
repaint();
}
For more complex use, you could create a method with all of your ship drawing calculations:
public void paintComponent(Graphics g) {
g.drawString("POS: " + mx + ", " + my, 10, 40);
System.out.println(getAngle());
drawShip(g);
g.drawLine(x + 12, y + 10, mx, my);
repaint();
}
public void drawShip(Graphics g){
Graphics2D g2d = (Graphics2D)g;
g2d.translate(X, Y);
g2d.rotate(DEGREES);
g2d.drawImage(ship, 0, 0, WIDTH, HEIGHT, this);
}
One way is to use a rotate instance from one of the methods of AffineTransform that accepts anchors for the X,Y co-ordinates.

How to draw thin line with no gap while dragging the cursor?

I have this following class, which refresh a jpeg file in layer 0 and layer 1 is used to draw/paint/sketch up anything related to smash things. But in my drawing when I want to do a thin line, it breaks. Because the mouse cursor movement needs to be slower.
How to resolve on fast mouse move, that the line remains joined?
Annotation.java
package test;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Annotation {
// Image
private static Image backgroundImage;
private static BufferedImage _bufImage = null;
// Enum
public static enum Shape { RECTANGLE, OVAL, LINE }
private static enum State { IDLE, DRAGGING }
private static final Shape INIIIAL_SHAPE = Shape.RECTANGLE;
private static final Color INITIAL_COLOR = Color.RED;
private static Shape _shape = INIIIAL_SHAPE;
private static Color _color = INITIAL_COLOR;
private static State _state = State.IDLE;
private static Point _start = null;
private static Point _end = null;
// JPanel
private static JPanel p;
private static JPanel mp;
/* Run: */
public static void main(String args[]) {
c();
}
/* GUI */
public static void c() {
try {
backgroundImage = ImageIO.read(new File("/var/tmp/test.jpeg"));
} catch (IOException e) {
e.printStackTrace();
}
myTimer();
loadAnnotation();
loadBackground();
JFrame f;
f = new JFrame();
f.setLayout(new BorderLayout());
f.add(mp);
f.pack();
f.setVisible(true);
}
/* 5 seconds to load picture */
public static void myTimer() {
javax.swing.Timer t = new javax.swing.Timer(5000, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
backgroundImage = ImageIO.read(new File("/var/tmp/test.jpeg"));
mp.repaint();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
/* Layer 0:
* Load background picture */
public static void loadBackground() {
mp = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(backgroundImage, 0, 0, 1024, 600, null);
}
public Dimension getPreferredSize() {
return new Dimension(1024, 600);
}
};
mp.add(p);
}
/* Layer 1:
* Annotation: Draw on top of background picture anything! */
public static void loadAnnotation() {
p = new JPanel() {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.RED);
if (_bufImage == null) {
int w = this.getWidth();
int h = this.getHeight();
_bufImage = new BufferedImage(1024,600, BufferedImage.TRANSLUCENT);
Graphics2D gc = _bufImage.createGraphics();
}
g2.drawImage(_bufImage, null, 0, 0);
if (_state == State.DRAGGING) {
g2.drawLine(_start.x, _start.y, _end.x , _end.y);
}
}
public Dimension getPreferredSize() {
return new Dimension(1024, 600);
}
};
p.setLayout(new FlowLayout());
p.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent me) {
}
#Override
public void mousePressed(MouseEvent me) {
}
#Override
public void mouseReleased(MouseEvent me) {
//_state = State.IDLE;
_state = State.IDLE;
}
#Override
public void mouseEntered(MouseEvent me) {
}
#Override
public void mouseExited(MouseEvent me) {
}
});
p.addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent me) {
System.out.println("drag");
_state = State.DRAGGING;
_start = me.getPoint();
_end = _start;
if (_state == State.DRAGGING) {
Graphics2D g2 = _bufImage.createGraphics();
g2.setColor(Color.red);
g2.setStroke(new BasicStroke(90));
g2.fillOval(_start.x, _start.y, 10, 10);
p.repaint();
}
}
#Override
public void mouseMoved(MouseEvent me) {
System.out.println("move");
}
});
JButton pm = new JButton("+");
pm.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
}
});
p.add(pm);
p.setOpaque(true);
}
}
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Annotation {
// Image
private static Image backgroundImage;
private static BufferedImage _bufImage = null;
// Enum
public static enum Shape { RECTANGLE, OVAL, LINE }
private static enum State { IDLE, DRAGGING }
private static final Shape INIIIAL_SHAPE = Shape.RECTANGLE;
private static final Color INITIAL_COLOR = Color.RED;
private static Shape _shape = INIIIAL_SHAPE;
private static Color _color = INITIAL_COLOR;
private static State _state = State.IDLE;
private static Point _start = null;
private static Point _end = null;
// JPanel
private static JPanel p;
private static JPanel mp;
/* Run: */
public static void main(String args[]) {
c();
}
/* GUI */
public static void c() {
try {
URL url = new URL("http://pscode.org/media/stromlo2.jpg");
backgroundImage = ImageIO.read(url);
} catch (Exception e) {
e.printStackTrace();
}
loadAnnotation();
loadBackground();
JFrame f;
f = new JFrame();
f.setLayout(new BorderLayout());
f.add(mp);
f.pack();
f.setVisible(true);
}
/* Layer 0:
* Load background picture */
public static void loadBackground() {
mp = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), null);
}
public Dimension getPreferredSize() {
return new Dimension(backgroundImage.getWidth(this), backgroundImage.getHeight(this));
}
};
mp.add(p);
}
/* Layer 1:
* Annotation: Draw on top of background picture anything! */
public static void loadAnnotation() {
p = new JPanel() {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.RED);
if (_bufImage == null) {
int w = this.getWidth();
int h = this.getHeight();
_bufImage = new BufferedImage(1024,600, BufferedImage.TRANSLUCENT);
Graphics2D gc = _bufImage.createGraphics();
}
g2.drawImage(_bufImage, null, 0, 0);
if (_state == State.DRAGGING) {
g2.drawLine(_start.x, _start.y, _end.x , _end.y);
}
}
public Dimension getPreferredSize() {
return new Dimension(1024, 600);
}
};
p.setLayout(new FlowLayout());
p.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent me) {
}
#Override
public void mousePressed(MouseEvent me) {
}
#Override
public void mouseReleased(MouseEvent me) {
//_state = State.IDLE;
_state = State.IDLE;
}
#Override
public void mouseEntered(MouseEvent me) {
}
#Override
public void mouseExited(MouseEvent me) {
}
});
p.addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent me) {
_state = State.DRAGGING;
_end = me.getPoint();
if (_state == State.DRAGGING) {
Graphics2D g2 = _bufImage.createGraphics();
g2.setColor(Color.red);
g2.setStroke(new BasicStroke(2));
g2.drawLine(_start.x, _start.y, _end.x, _end.y);
p.repaint();
}
_start = _end;
}
#Override
public void mouseMoved(MouseEvent me) {
//System.out.println("move");
_start = me.getPoint();
}
});
JButton pm = new JButton("+");
pm.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
}
});
p.add(pm);
p.setOpaque(true);
}
}
I solved this problem by drawing rectangles between points, using the Stroke size (Basic Stroke) for height. It sounds like an icky solution but it does pretty well in reality

problem displaying mouse coordinates on the screen in java

I'm trying to display mouse coordinates (math coordinates) in my JPanel , but i get each coordinates on top of the other ,can' figure out why .
here's my code :
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.applet.*;
import javax.swing.JPanel;
import javax.swing.event.MouseInputAdapter;
public class drawarea extends JPanel {
int n;
private Point mouseCoords = null;
int UNIT = 20;
drawarea() {
super();
setBackground(Color.white);
addMouseMotionListener(new MouseInputAdapter() {
public void mouseMoved(MouseEvent e) {
super.mouseMoved(e);
mouseCoords = new Point(e.getX(), e.getY());
repaint();
}
/**
* #see java.awt.event.MouseListener#mouseExited(MouseEvent)
*/
public void mouseExited(MouseEvent e) {
super.mouseExited(e);
mouseCoords = null;
repaint();
}
});
setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
}
public void paint(Graphics g) {
//draw axis x and y
g.setColor(Color.red);
g.drawLine(0, r.height / 2, r.width, r.height / 2);
g.drawLine(r.width / 2, 0, r.width / 2, r.height);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
dessinBoule(g2);
}
private void dessinBoule(Graphics2D g) {
// if mouse isnt inside the ara where
// i want the coordinates to bes displayed
if (mouseCoords == null) {
return;
}
g.setColor(Color.BLACK);
int decPolice = 15;
g.drawString("x = " + getFormatedString("" + mouseCoords.x)
+ " , y = " + getFormatedString("" + mouseCoords.y), 2, 15);
}
private String getFormatedString(String s) {
if (s.length() > 4) {
return s.substring(0, 3);
}
return s;
}
}
thanks.
You're drawing on your graphics area, so g.drawString(...) draws a string on top of what is already there. You must either erase what is there first, by drawing a rectangle in the background colour, or use a separate component that you can manage with a separate paint(...) method.
An example of #richj's suggestion is shown below. Note that in Swing you should override paintComponent(). Also, the implementation of MouseInputAdapter is empty, so you don't need to invoke super().
import java.awt.*;
import java.awt.event.MouseEvent;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
public class DrawArea extends JPanel {
private Point mouseCoords = new Point();
DrawArea() {
super();
this.setPreferredSize(new Dimension(320, 240));
setBackground(Color.white);
addMouseMotionListener(new MouseInputAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
mouseCoords = e.getPoint();
repaint();
}
#Override
public void mouseExited(MouseEvent e) {
mouseCoords = null;
repaint();
}
});
setCursor(new Cursor(Cursor.CROSSHAIR_CURSOR));
}
#Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.clearRect(0, 0, getWidth(), getHeight());
g2.setColor(Color.red);
if (!(mouseCoords == null)) {
g2.drawString(mouseCoords.toString(), 10, getHeight() - 10);
}
}
private static void create() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new DrawArea());
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
create();
}
});
}
}

Categories