newbie programmer here.
I'm making a program that renders user-inputted equations in a Cartesian coordinate system. At the moment I'm having some issues with letting the user move the view around freely in the coordinate. Currently with mouseDragged the user can drag the view around a bit, but once the user releases the mouse and tries to move the view again the origin snaps back to the current position of the mouse cursor. What is the best way to let the user move around freely? Thanks in advance!
Here's the code for the drawing area.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import javax.swing.JPanel;
public class DrawingArea extends JPanel implements MouseMotionListener {
private final int x_panel = 350; // width of the panel
private final int y_panel = 400; // height of the panel
private int div_x; // width of one square
private int div_y; // height of one square
private int real_y;
private int real_x;
private Point origin; // the origin of the coordinate
private Point temp; // temporary point
private static int y = 0;
private static int x = 0;
DrawingArea() {
setBackground(Color.WHITE);
real_x = x_panel;
real_y = y_panel;
setDivisionDefault();
setOrigin(new Point((real_x / 2), (real_y / 2)));
setSize(x_panel, y_panel);
addMouseMotionListener(this);
}
DrawingArea(Point origin, Point destination) {
this.origin = origin;
this.destination = destination;
panel = new JPanel();
panel.setSize(destination.x, destination.y);
panel.setLocation(origin);
this.panel.setBackground(Color.red);
panel.setLayout(null);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D line = (Graphics2D) g;
temp = new Point(origin.x, origin.y);
line.setColor(Color.red);
drawHelpLines(line);
line.setColor(Color.blue);
drawOrigin(line);
line.setColor(Color.green);
for (int i = 0; i < 100; i++) { // This is a test line
//temp = this.suora();
temp.x++;
temp.y++;
line.drawLine(temp.x, temp.y, temp.x, temp.y);
}
}
public void setOrigin(Point p) {
origin = p;
}
public void drawOrigin(Graphics2D line) {
line.drawLine(origin.x, 0, origin.x, y_panel);
line.drawLine(0, origin.y, x_panel, origin.y);
}
public void drawHelpLines(Graphics2D line) {
int xhelp= origin.x;
int yhelp= origin.y;
for (int i = 0; i < 20; i++) {
xhelp+= div_x;
line.drawLine(xhelp, 0, xhelp, y_panel);
}
xhelp= origin.x;
for (int i = 0; i < 20; i++) {
xhelp-= div_x;
line.drawLine(xhelp, 0, xhelp, y_panel);
}
for (int i = 0; i < 20; i++) {
yhelp-= div_y;
line.drawLine(0, yhelp,x_panel, yhelp);
}
yhelp= origin.y;
for (int i = 0; i < 20; i++) {
yhelp+= div_y;
line.drawLine(0, yhelp, x_panel, yhelp);
}
}
public void setDivisionDefault() {
div_x = 20;
div_y = 20;
}
#Override
public void mouseDragged(MouseEvent e) {
//Point temp_point = new Point(mouse_x,mouse_y);
Point coords = new Point(e.getX(), e.getY());
setOrigin(coords);
repaint();
}
#Override
public void mouseMoved(MouseEvent e) {
}
}
Based on this example, the following program allows the user to drag the axes' intersection to an arbitrary point, origin, which starts at the center of the panel.
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.EventQueue;
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/15576413/230513
* #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 origin = new Point(W / 2, H / 2);
private Point mousePt;
public MouseDragTest() {
this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
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;
origin.setLocation(origin.x + dx, origin.y + dy);
mousePt = e.getPoint();
repaint();
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(W, H);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawLine(0, origin.y, getWidth(), origin.y);
g.drawLine(origin.x, 0, origin.x, getHeight());
}
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);
}
});
}
}
Related
In the code below, when I move the wheel of the mouse, the square is zooming in or out and I always detect the square position everywhere in the screen if my mouse go inside it, even if the map is scrolling.
That's really great :)
If I change the boolean "centerScreen" to true, I can zoom and the square is always in the center of the screen.
It is really very great ...
... but the mouse detection is not good :(
How can I modify my code to zoom in or out with the Render still in center of screen but with a perfect mouse detection with the square ?
Thanks for your help !
Here is my full "clean code" -- work with copy paste (in 3 class) --
Main Class
package main;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ZoomDemo extends JPanel
{
private static final long serialVersionUID = 1L;
private Rectangle2D square;
private Mouse mouse;
private ScrollMap scrollMap;
private static int screenWidth;
private static int screenHeight;
private static int centerScreenWidth;
private static int centerScreenHeight;
private static boolean centerScreen;
private List<Point> listStar = new ArrayList<Point>();
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 800);
frame.setLocationRelativeTo(null);
screenWidth = frame.getWidth();
screenHeight = frame.getHeight();
centerScreenWidth = screenWidth / 2;
centerScreenHeight = screenHeight / 2;
centerScreen = false;
ZoomDemo zoomDemo = new ZoomDemo();
frame.add(zoomDemo);
frame.setVisible(true);
}
public ZoomDemo()
{
mouse = new Mouse();
addMouseListener(mouse);
addMouseMotionListener(mouse);
addMouseWheelListener(mouse);
scrollMap = new ScrollMap(mouse, screenWidth, screenHeight);
int centerX = (int) getCenter(0, screenWidth, 50, true);
int centerY = (int) getCenter(0, screenHeight, 50, true);
square = new Rectangle2D.Double(centerX, centerY, 50, 50);
Random rand = new Random();
for (int i = 0; i < 50; i++)
{
int x = rand.nextInt(screenWidth);
int y = rand.nextInt(screenHeight);
listStar.add(new Point(x, y));
}
}
#Override
public void paint(Graphics g)
{
Graphics2D g2d = (Graphics2D) g.create();
/* Optimization */
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED);
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_OFF);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
/* Background */
g2d.setColor(Color.GRAY);
g2d.fillRect(0, 0, this.getWidth(), this.getHeight());
/* Translatation center -- it is working, but mouse detection is not good */
if (centerScreen)
g2d.translate(centerScreenWidth, centerScreenHeight);
/* Listener Wheel Mouse for zooming and translation */
mouse.zoom(g2d);
/* Restore Translatation center */
if (centerScreen)
g2d.translate(-centerScreenWidth, -centerScreenHeight);
render(g2d);
g2d.dispose();
//#formatter:off
try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); }
//#formatter:on
repaint();
}
public void render(Graphics2D g2d)
{
/* Ask for scroll */
isScrolling(g2d);
/* Mouse Detection */
int xMouse = (int) (mouse.pMousePosition.x - scrollMap.getMapX());
int yMouse = (int) (mouse.pMousePosition.y - scrollMap.getMapY());
boolean detection = square.contains(xMouse, yMouse);
/* Graphic render */
g2d.setColor(Color.WHITE);
for (int i = 0; i < listStar.size(); i++)
g2d.fillRect(listStar.get(i).x, listStar.get(i).y, 4, 4);
g2d.setColor(detection ? Color.red : Color.black);
g2d.fill(square);
/* End of Scroll */
endScrolling(g2d);
}
private void isScrolling(Graphics2D g2d)
{
/* If Mouse on edge, so change value for scrolling */
scrollMap.scrolling();
/* Translation scrolling */
g2d.translate(scrollMap.getMapX(), scrollMap.getMapY());
}
private void endScrolling(Graphics2D g2d)
{
g2d.translate(-scrollMap.getMapX(), -scrollMap.getMapY());
}
public float getCenter(float startXZone, float longueurZone, float longueurElem, boolean round)
{
float s = startXZone + (longueurZone - longueurElem) / 2f;
return (round) ? Math.round(s) : s;
}
}
Mouse Class
package main;
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.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
public class Mouse implements MouseMotionListener, MouseWheelListener, MouseListener
{
public Point pMousePosition = new Point();
public double scaleCoef;
public double inverseScaleCoef;
public boolean clic;
private AffineTransform affineScale;
private AffineTransform inverseScale;
public Mouse()
{
scaleCoef = 1;
inverseScaleCoef = 1;
transform();
}
private void transform()
{
affineScale = AffineTransform.getScaleInstance(scaleCoef, scaleCoef);
//#formatter:off
try { inverseScale = affineScale.createInverse(); } catch (NoninvertibleTransformException e) { }
//#formatter:on
}
public void zoom(Graphics2D g2)
{
transform();
g2.transform(affineScale);
}
#Override
public void mouseWheelMoved(MouseWheelEvent e)
{
if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL)
{
scaleCoef -= (0.1 * e.getWheelRotation());
scaleCoef = Math.max(0.1, scaleCoef);
inverseScaleCoef = 1d / scaleCoef;
}
}
#Override
public void mouseMoved(MouseEvent e)
{
pMousePosition = e.getPoint();
inverseScale.transform(pMousePosition, pMousePosition);
}
#Override
public void mousePressed(MouseEvent e)
{
clic = true;
}
#Override
public void mouseReleased(MouseEvent e)
{
clic = false;
}
#Override
public void mouseClicked(MouseEvent e)
{
}
#Override
public void mouseEntered(MouseEvent e)
{
}
#Override
public void mouseExited(MouseEvent e)
{
}
#Override
public void mouseDragged(MouseEvent e)
{
}
}
(Optional)
Scroll class
package main;
public class ScrollMap
{
private float mapX = 0;
private float mapY = 0;
private int speedScroll = 1;
private int edgeDetection = 70;
private int screenWidth;
private int screenHeight;
private Mouse mouse;
public ScrollMap(Mouse mouse, int screenWidth, int screenHeight)
{
this.mouse = mouse;
this.screenWidth = screenWidth;
this.screenHeight = screenHeight;
}
/**
* Scrolling ecran
*/
public void scrolling()
{
double scale = mouse.inverseScaleCoef;
/* Mouse to Right */
if ((mouse.pMousePosition.x > screenWidth * scale - edgeDetection))
{
for (int k = 0; k < speedScroll; k++)
moveMapToRight();
}
/* Mouse to Left */
else if ((mouse.pMousePosition.x < edgeDetection * scale))
{
for (int k = 0; k < speedScroll; k++)
moveMapToLeft();
}
/* Mouse to Down */
if ((mouse.pMousePosition.y < edgeDetection * scale))
{
for (int k = 0; k < speedScroll; k++)
moveMaptoDown();
}
/* Mouse to Up */
else if ((mouse.pMousePosition.y > screenHeight * scale - edgeDetection))
{
for (int k = 0; k < speedScroll; k++)
moveMapToUp();
}
}
public float moveMapToRight()
{
return mapX--;
}
public float moveMapToLeft()
{
return mapX++;
}
public float moveMapToUp()
{
return mapY--;
}
public float moveMaptoDown()
{
return mapY++;
}
public float getMapY()
{
return mapY;
}
public float getMapX()
{
return mapX;
}
}
The paintcomponent works fine, the image shows up, no problems on that end or with the JFrame. I want to implement zooming and panning but not getting any luck as the added mouse listener isn't responding.
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseAdapter;
import javax.swing.JPanel;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
public class map extends JPanel {
public int moz = 100;
public void map()
{
addMouseListener(
new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent e)
{
moz = moz +100;
repaint();
}
}
);
}
public void paintComponent(Graphics g){
.....
g.drawLine( 0, moz, 100, 0 );
}
}
Your class doesn't have a real constructor but rather has a "pseudo" constructor since it has a return type -- yes void counts. So get rid of the void return type by changing:
// this is not a constructor
public void map()
to:
// this is a real constructor
public map()
Also as a side recommendation, change your variable and class names to conform with Java naming conventions: class names all start with an upper-case letter and method/variable names with a lower-case letter.
So in your case you'd name your class Map, and in playing with the code could have something like:
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.Rectangle;
import java.awt.Stroke;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.*;
public class Map extends JPanel {
private static final int PREF_W = 800;
private static final int PREF_H = 650;
private static final Color DRAW_RECT_COLOR = new Color(200, 200, 255);
public static final Stroke IMAGE_STROKE = new BasicStroke(3f);
public static final Color IMAGE_COLOR = Color.RED;
private BufferedImage image = new BufferedImage(PREF_W, PREF_H, BufferedImage.TYPE_INT_ARGB);
private Rectangle drawRectangle = null;
private List<Color> colors = new ArrayList<>();
private Random random = new Random();
public Map() {
MyMouse myMouse = new MyMouse();
addMouseListener(myMouse);
addMouseMotionListener(myMouse);
for (int r = 0; r < 4; r++) {
int r1 = (r * 255) / 3;
for (int g = 0; g < 4; g++) {
int g1 = (g * 255) / 3;
for (int b = 0; b < 4; b++) {
int b1 = (b * 255) / 3;
colors.add(new Color(r1, g1, b1));
}
}
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
Graphics2D g2 = (Graphics2D) g;
if (drawRectangle != null) {
g.setColor(DRAW_RECT_COLOR);
g2.draw(drawRectangle);
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class MyMouse extends MouseAdapter {
Point p1 = null;
#Override
public void mousePressed(MouseEvent e) {
p1 = e.getPoint();
}
#Override
public void mouseDragged(MouseEvent e) {
if (p1 == null) {
return;
}
Point p2 = e.getPoint();
drawRectangle = createDrawRect(p2);
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
Rectangle rectangle = createDrawRect(e.getPoint());
Graphics2D g2 = image.createGraphics();
g2.setStroke(IMAGE_STROKE);
Color c = colors.get(random.nextInt(colors.size()));
g2.setColor(c);
g2.draw(rectangle);
g2.dispose();
p1 = null;
drawRectangle = null;
repaint();
}
private Rectangle createDrawRect(Point p2) {
int x = Math.min(p1.x, p2.x);
int y = Math.min(p1.y, p2.y);
int w = Math.abs(p1.x - p2.x);
int h = Math.abs(p1.y - p2.y);
return new Rectangle(x, y, w, h);
}
}
private static void createAndShowGui() {
Map mainPanel = new Map();
JFrame frame = new JFrame("Map");
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(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
So I'm trying to draw 2 circles on top of each other (kinda like a snowman) and move the snowman to the right when the user clicks on the "Start" button and stop moving the snowman when the user clicks on the "Stop" button. However, the only thing that I am able to come up with is 2 snowmen drawn next to each other that don't react to the buttons.
Here is what I've come up with:
import java.awt.Graphics2D;
public interface MoveableShape {
void draw(Graphics2D g);
void translate(int dx, int dy);
}
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
public class SnowmanShape implements MoveableShape {
private int x;
private int y;
private int width;
public SnowmanShape(int x, int y, int width){
this.x = x;
this.y = y;
this.width = width;
}
#Override
public void draw(Graphics2D g2) {
// TODO Auto-generated method stub
Ellipse2D.Double head = new Ellipse2D.Double(0, 0, 10, 10);
Ellipse2D.Double body = new Ellipse2D.Double(0, 11, 10, 10);
g2.draw(head);
g2.draw(body);
}
#Override
public void translate(int dx, int dy) {
// TODO Auto-generated method stub
x += dx;
y += dy;
}
}
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class MyPanel extends JPanel{
MoveableShape s;
public MyPanel (MoveableShape m){
s = m;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
s.draw((Graphics2D)g);
}
}
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class AnimationTester {
private static final int DEFAULT_WIDTH = 400;
private static final int DEFAULT_HEIGHT = 200;
private static final int SNOWMAN_WIDTH = 50;
final static MoveableShape shape = new SnowmanShape(0, 0, SNOWMAN_WIDTH);
final static JPanel panel = new MyPanel(shape);
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame = new JFrame();
frame.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
JButton startButton = new JButton("Start");
JButton stopButton = new JButton("Stop");
frame.setLayout(new BorderLayout());
frame.add(panel);
frame.add(startButton, BorderLayout.NORTH);
frame.add(stopButton, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
final int DELAY = 100;
// Milliseconds between timer ticks
Timer t = new Timer(DELAY, translateSnowman());
startButton.addActionListener(startTimer(t));
stopButton.addActionListener(stopTimer(t));
}
public static ActionListener translateSnowman(){
return new ActionListener(){
public void actionPerformed(ActionEvent event){
shape.translate(1, 0);
panel.repaint();
}
};
}
public static ActionListener startTimer(final Timer t){
return new ActionListener(){
public void actionPerformed(ActionEvent event){
t.start();
}
};
}
public static ActionListener stopTimer(final Timer t){
return new ActionListener(){
public void actionPerformed(ActionEvent event){
t.stop();
}
};
}
}
Could someone please let me know where I went wrong or point me in the right direction?
EDIT: I fixed up the AnimationListener so now it doesn't draw 2 snowmans. The snowman still won't move however. I updated the code in the post as well.
Add g2.translate(x, y); to SnowmanShape#draw, before you are painting:
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Ellipse2D;
class SnowmanShape implements MoveableShape {
static final Color headColor = new Color(0xFFE9C9);
static final Color bodyColor = new Color(0xEAF6FF);
static final Color outlineColor = new Color(0x252525);
int x;
int y;
int size;
Ellipse2D.Double head;
Ellipse2D.Double body;
SnowmanShape(int x, int y, int size) {
this.x = x;
this.y = y;
this.size = size;
initModel();
}
void initModel() {
head = new Ellipse2D.Double(0, 0, size, size);
body = new Ellipse2D.Double(0, head.height, size * 1.3d, size * 1.5d);
body.x -= (body.width - head.width) * (1 / 2d);
}
#Override
public void draw(Graphics2D g2) {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2.translate(x, y);
g2.setColor(headColor);
g2.fill(head);
g2.setColor(outlineColor);
g2.draw(head);
g2.setColor(bodyColor);
g2.fill(body);
g2.setColor(outlineColor);
g2.draw(body);
}
#Override
public void translate(int dx, int dy) {
x += dx;
y += dy;
}
}
I not an expert on doing things like this, but if I were you I would use the timer to move the objects and then call the paint to repaint the objects in a new position. Therefore, your ShapeIcon class would just keep track of the position of your objects. That probably wasn't all that helpful, so to point you in right direction, you can check out some code in this tutorial here.
I'm doing a program involving the Pythagorean theorem, and wanted to leave a triangle in the middle, with three JTextField around three sides of it. I did it, but the problem is that when I create the JTextField and add it to the desired container, it is immense. It is a very large white rectangle that when I click to enter, get a small letter. So, my question is: How can I change the size of this JTextField to decrease it and avoid unnecessary sizes?
P.S:.'m Using Swing and AWT library for free!
Example of code:
Container content = window.getContentPane();
Contaiiner grid = new JPanel();
grid.setLayout(new GridLayout(3,3));
grid.add(new JTextField());
Well, this simple code, gives to you one example of the JTextField, when i executes than (with main method and more...) the JTextField is very very big, so, i want to decrease it.
Admittedly, it involves some guesses about your intention, but here is an example of what I think that you want to achieve:
It's a program that contains a panel with some points, and between each pair of points, it places a text field. The text fields are arranged so that their upper left corner remains at the center of the respective edge. When the points are dragged with the mouse, the locations of the text fields are updated accordingly. (In this example, the text fields contain the distance between the points - that is, the edge lengths - but this is just for illustration).
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TriangleTextFieldsTest
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new TriangleTextFieldsTest();
}
});
}
public TriangleTextFieldsTest()
{
JFrame frame = new JFrame();
frame.getContentPane().add(new TriangleTextFieldsPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800,800);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class TriangleTextFieldsPanel extends JPanel
implements MouseListener, MouseMotionListener
{
private final List<Point2D> points;
private final List<JTextField> textFields;
private Point2D draggedPoint = null;
TriangleTextFieldsPanel()
{
super(null);
points = new ArrayList<Point2D>();
points.add(new Point2D.Double(250,250));
points.add(new Point2D.Double(750,250));
points.add(new Point2D.Double(500,500));
textFields = new ArrayList<JTextField>();
for (int i=0; i<points.size(); i++)
{
JTextField t = new JTextField(10);
textFields.add(t);
add(t);
}
updateTextFieldPositions();
updateTextFieldContents();
addMouseListener(this);
addMouseMotionListener(this);
}
private void updateTextFieldPositions()
{
for (int i=0; i<points.size(); i++)
{
Point2D p0 = points.get(i);
Point2D p1 = points.get((i+1)%points.size());
JTextField textField = textFields.get(i);
int cx = (int)(0.5 * (p1.getX() + p0.getX()));
int cy = (int)(0.5 * (p1.getY() + p0.getY()));
Dimension d = textField.getPreferredSize();
textField.setBounds(cx, cy, d.width, d.height);
}
}
private void updateTextFieldContents()
{
for (int i=0; i<points.size(); i++)
{
Point2D p0 = points.get(i);
Point2D p1 = points.get((i+1)%points.size());
JTextField textField = textFields.get(i);
double d = p0.distance(p1);
textField.setText(String.format("%.2f", d));
}
}
#Override
protected void paintComponent(Graphics gr)
{
super.paintComponent(gr);
Graphics2D g = (Graphics2D)gr;
g.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.BLUE);
drawPoints(g, points);
g.setColor(Color.BLACK);
for (int i=0; i<points.size(); i++)
{
Point2D p0 = points.get(i);
Point2D p1 = points.get((i+1)%points.size());
g.draw(new Line2D.Double(p0,p1));
}
}
static void drawPoints(Graphics2D g, List<Point2D> points)
{
double r = 3;
for (Point2D point : points)
{
double x = point.getX();
double y = point.getY();
g.fill(new Ellipse2D.Double(
x-r, y-r, r+r, r+r));
}
}
#Override
public void mouseDragged(MouseEvent e)
{
if (draggedPoint != null)
{
draggedPoint.setLocation(e.getPoint());
updateTextFieldPositions();
updateTextFieldContents();
repaint();
}
}
#Override
public void mouseMoved(MouseEvent e)
{
}
#Override
public void mouseClicked(MouseEvent e)
{
}
#Override
public void mousePressed(MouseEvent e)
{
draggedPoint = null;
double thresholdSquared = 10*10;
double minDs = Double.MAX_VALUE;
for (Point2D point : points)
{
double ds = point.distanceSq(e.getPoint());
if (ds < thresholdSquared && ds < minDs)
{
minDs = ds;
draggedPoint = point;
}
}
}
#Override
public void mouseReleased(MouseEvent e)
{
draggedPoint = null;
}
#Override
public void mouseEntered(MouseEvent e)
{
}
#Override
public void mouseExited(MouseEvent e)
{
}
}
i am try to make chorded keyboard simulation.
I cannot resolve why KeyboardButtons in Keyboard are not painting. I have more KeyboardButtons in Keyboard. Mouse is listened properly, but polygons are not painted.
When i call paint to each KeyboardButton in the Keyboard's paintComponent(), polygons are painted, but not changing color on mousePressed.
Keyboard.java
package keyboard;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JComponent;
import javax.swing.JPanel;
public class Keyboard extends JPanel implements MouseListener{
Point[] leftFingers;
Point leftCenter = new Point(300, 600);
KeyboardButton[] buttons;
public Keyboard(Point left1, Point left2, Point left3, Point left4, Point left5) {
leftFingers = new Point[5];
leftFingers[0] = left1;
leftFingers[1] = left2;
leftFingers[2] = left3;
leftFingers[3] = left4;
leftFingers[4] = left5;
buttons = registerKeys();
addMouseListener(this);
}
public KeyboardButton[] registerKeys() {
Polygon[] polygons = generateKeyPolygons(calculateBordersOfKeys(leftFingers));
KeyboardButton[] buttons = new KeyboardButton[5];
for (int i = 0; i < polygons.length; i++) {
buttons[i] = new KeyboardButton(polygons[i]);
}
return buttons;
}
private Point[] calculateBordersOfKeys(Point[] fingers) {
Point[] centers = calculateCentersBetweenEachTwoFingers(fingers);
Point[] result = new Point[6];
result[0] = calculateCentralSymmetry(centers[0], fingers[0]);
System.arraycopy(centers, 0, result, 1, centers.length);
result[5] = calculateCentralSymmetry(centers[3], fingers[4]);
return result;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.drawOval(leftCenter.x - 25, leftCenter.y - 25, 50, 50);
for (int i = 0; i < leftFingers.length; i++) {
g.drawOval(leftFingers[i].x, leftFingers[i].y, 10, 10);
}
}
private Polygon[] generateKeyPolygons(Point[] borders) {
Polygon[] polygons = new Polygon[5];
for (int i = 0; i < borders.length - 1; i++) {
Polygon p = new Polygon();
p.addPoint(leftCenter.x, leftCenter.y);
p.addPoint(borders[i].x, borders[i].y);
p.addPoint(borders[i + 1].x, borders[i + 1].y);
polygons[i] = p;
}
return polygons;
}
private Point[] calculateCentersBetweenEachTwoFingers(Point[] fingers) {
Point[] centers = new Point[4];
for (int i = 0; i < fingers.length - 1; i++) {
centers[i] = new Point(((fingers[i].x + fingers[i + 1].x) / 2), ((fingers[i].y + fingers[i + 1].y) / 2));
}
return centers;
}
private Point calculateCentralSymmetry(Point toReflected, Point center) {
Point reflection = new Point();
if (toReflected.x > center.x) {
reflection.x = center.x - Math.abs(center.x - toReflected.x);
} else {
reflection.x = center.x + Math.abs(center.x - toReflected.x);
}
if (toReflected.y > center.y) {
reflection.y = center.y - Math.abs(center.y - toReflected.y);
} else {
reflection.y = center.y + Math.abs(center.y - toReflected.y);
}
return reflection;
}
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
for (KeyboardButton button : buttons) {
button.checkMousePosition(e);
}
}
public void mouseReleased(MouseEvent e) {
for (KeyboardButton button : buttons) {
button.checkMousePosition(e);
}
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
}
KeyboardButton.java
package keyboard;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.event.*;
import javax.swing.JComponent;
import javax.swing.JPanel;
public class KeyboardButton extends JComponent {
Polygon polygon;
boolean isActive;
final Color ACTIVE_COLOR = Color.red;
final Color INACTIVE_COLOR = Color.blue;
public KeyboardButton(Polygon p) {
polygon = p;
}
public void checkMousePosition(MouseEvent e) {
if (polygon.contains(e.getX(), e.getY())) {
setState(true);
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(isActive ? ACTIVE_COLOR : INACTIVE_COLOR);
g.drawPolygon(polygon);
}
void setState(boolean state) {
isActive = state;
System.out.println(this.hashCode());
repaint();
}
}
As far as I can tell, the KeyboardButton components are never added to the Keyboard. So, when they call repaint(), it has no effect because they are not part of the view hierarchy.