using button click event to update variables in java - java

i have drawn a graph and placed a 20*20 pixel box in it and i am trying to move the box around with a bunch of buttons. the trouble is, i cant seem to change the X-axis and Y-axis values of the box from within the action listener. this is my first graphics application, help!
GrapMain.java
import java.awt.BorderLayout;
import javax.swing.JFrame;
import java.awt.Color;
import javax.swing.JTextField;
public class GraphMain {
public static void main(String [] args){
Display nashDisplay = new Display();
nashDisplay.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Graph.java
import java.awt.*;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Graph extends JPanel {
int x = 5, y = 100;
Graph (int x, int y){
this.x = x;
this.y = y;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
this.setBackground(Color.WHITE);
//horizontal lines
g.setColor(Color.RED);
for (int height=20; height<200; height+=20){
g.drawLine(5, height, 480, height);
}
//verticle lines
g.setColor(Color.RED);
for (int height=5; height<400; height+=20){
g.drawLine(height,200,height,10);
}
//the box
g.setColor(Color.BLACK);
g.fillRect(this.x, this.y, 20, 20);
//g.fillRect((+20 to move right one box),(+20 to move down one box), 20, 20);
//g.fillRect((-20 to move left one box),(-20 to move up one box), 20, 20);
}
}
Display.java
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Display extends JFrame {
int X = 5, Y = 100;
private JButton left, right, up, down;
Graph dude = new Graph(X, Y);
public Display() {
super("nash's graph(moving the box!)");
JButton left = new JButton("move left");
add(left, BorderLayout.WEST);
left.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
X = X - 20;
}
});
JButton right = new JButton("move right");
add(right, BorderLayout.EAST);
right.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
X = X + 20;
}
});
JButton up = new JButton("move up");
add(up, BorderLayout.NORTH);
up.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
Y = Y - 20;
}
});
JButton down = new JButton("move down");
add(down, BorderLayout.SOUTH);
down.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
Y = Y + 20;
}
});
setSize(500, 300);
setVisible(true);
add(dude, BorderLayout.CENTER);
}
}

You need To repaint after you cange the x and y value Like this :
JButton left = new JButton("move left");
add(left, BorderLayout.WEST);
left.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
X = X - 20;
dude.x = X;
dude.y = Y;
repaint();
}
});
JButton right = new JButton("move right");
add(right, BorderLayout.EAST);
right.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
X = X + 20;
dude.x = X;
dude.y = Y;
repaint();
}
});
JButton up = new JButton("move up");
add(up, BorderLayout.NORTH);
up.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
Y = Y - 20;
dude.x = X;
dude.y = Y;
repaint();
}
});
JButton down = new JButton("move down");
add(down, BorderLayout.SOUTH);
down.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
Y = Y + 20;
dude.x = X;
dude.y = Y;
repaint();
}
});

Related

I want to be applied paintComponent individually

I make a PaintBrush.
I want to apply the line in a different color, but all the lines change to the same color.
I painted it white to create the eraser function, and when I use the eraser, all the lines become white, and when I select a different color, the lines reappear with the color I chose.
//choose the color
public void ColorBox() {
ArrayList<Color> clist = new ArrayList<>();
clist.add(Color.RED);
clist.add(Color.ORANGE);
clist.add(Color.YELLOW);
clist.add(Color.GREEN);
clist.add(Color.BLUE);
clist.add(Color.MAGENTA);
clist.add(Color.WHITE);
clist.add(Color.BLACK);
for (int i = 0; i < clist.size(); i++) {
JButton cbutton = new JButton();
cbutton.setBackground(clist.get(i));
cbutton.setBounds(500+50*i, 10, 37, 37); add(cbutton);
cbutton.addActionListener(e -> {
colour = cbutton.getBackground();
});
add(cbutton);
}
}
public void Pencil() {
JButton pen = new JButton(new ImageIcon("icon\\pencil.png"));
pen.setBounds(200, 10, 37, 37); add(pen);
pen.addActionListener(e -> {
draw = true; erase = false;
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
super.mouseDragged(e);
x = e.getX();
y = e.getY();
plist.add(new Point(x, y));
repaint();
}
});
});
}
public void Eraser() {
JButton eraser = new JButton(new ImageIcon("icon\\eraser.png"));
eraser.setBounds(250, 10, 37, 37); add(eraser);
eraser.addActionListener(e -> {
draw = false; erase = true;
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
super.mouseDragged(e);
x = e.getX();
y = e.getY();
elist.add(new Point(x, y));
repaint();
}
});
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (draw == true)
g.setColor(colour);
for (Point p : plist) {
g.fillOval(p.x, p.y, 5, 5);
}
if (erase == true)
g.setColor(Color.WHITE);
for (Point p : plist) {
g.fillOval(p.x, p.y, 5, 5);
}
}
Full Code
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionAdapter;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
class Point {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
class Board extends JPanel {
int x, y;
Color colour;
boolean draw = false; boolean erase = false;
Vector<Point> plist = new Vector<>();
Vector<Point> elist = new Vector<>();
public void ColorBox() {
ArrayList<Color> clist = new ArrayList<>();
clist.add(Color.RED);
clist.add(Color.ORANGE);
clist.add(Color.YELLOW);
clist.add(Color.GREEN);
clist.add(Color.BLUE);
clist.add(Color.MAGENTA);
clist.add(Color.WHITE);
clist.add(Color.BLACK);
for (int i = 0; i < clist.size(); i++) {
JButton cbutton = new JButton();
cbutton.setBackground(clist.get(i));
cbutton.setBounds(500+50*i, 10, 37, 37); add(cbutton);
cbutton.addActionListener(e -> {
colour = cbutton.getBackground();
});
add(cbutton);
}
}
public void Pencil() {
JButton pen = new JButton(new ImageIcon("icon\\pencil.png"));
pen.setBounds(200, 10, 37, 37); add(pen);
pen.addActionListener(e -> {
draw = true; erase = false;
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
super.mouseDragged(e);
x = e.getX();
y = e.getY();
plist.add(new Point(x, y));
repaint();
}
});
});
}
public void Eraser() {
JButton eraser = new JButton(new ImageIcon("icon\\eraser.png"));
eraser.setBounds(250, 10, 37, 37); add(eraser);
eraser.addActionListener(e -> {
draw = false; erase = true;
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
super.mouseDragged(e);
x = e.getX();
y = e.getY();
elist.add(new Point(x, y));
repaint();
}
});
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (draw == true)
g.setColor(colour);
for (Point p : plist) {
g.fillOval(p.x, p.y, 5, 5);
}
if (erase == true)
g.setColor(Color.WHITE);
for (Point p : plist) {
g.fillOval(p.x, p.y, 5, 5);
}
}
public Board() {
setLayout(null);
this.Pencil();
this.Eraser();
this.ColorBox();
setBackground(Color.WHITE);
}
}
public class PaintBrush extends JFrame {
public PaintBrush() {
setSize(1200, 600);
setTitle("그림판");
add(new Board());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
PaintBrush p = new PaintBrush();
}
}
How can I do?
So, the basic idea is, you need to keep track of the color each "pixel" is meant to be painted with.
I'd start by creating some kind of "drawing" entity to track this, for example...
public class Pixel {
private Point point;
private Color color;
public Pixel(Point point, Color color) {
this.point = point;
this.color = color;
}
public Point getPoint() {
return point;
}
public Color getColor() {
return color;
}
}
When the user selects a color, you apply it to an instance field and when the user drags the mouse, you create a new instance of Pixel with the selected color, for example...
int x = e.getX();
int y = e.getY();
Pixel pixel = new Pixel(e.getPoint(), getPixelColor());
pixels.add(pixel);
repaint();
Runnable example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
public final class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new MainPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class Pixel {
private Point point;
private Color color;
public Pixel(Point point, Color color) {
this.point = point;
this.color = color;
}
public Point getPoint() {
return point;
}
public Color getColor() {
return color;
}
}
public class MainPane extends JPanel {
private CanvasPane canvasPane;
public MainPane() {
setLayout(new BorderLayout());
canvasPane = new CanvasPane();
add(canvasPane);
Color[] colors = new Color[]{
Color.RED,
Color.ORANGE,
Color.YELLOW,
Color.GREEN,
Color.BLUE,
Color.MAGENTA,
Color.WHITE,
Color.BLACK
};
JPanel colorSelectionPane = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 4, 4, 4);
gbc.weightx = 1;
ButtonGroup bg = new ButtonGroup();
for (Color color : colors) {
JToggleButton btn = new JToggleButton();
btn.setContentAreaFilled(false);
btn.setBorderPainted(false);
btn.setForeground(color);
btn.setBackground(color);
btn.setOpaque(true);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
canvasPane.setPixelColor(color);
}
});
colorSelectionPane.add(btn, gbc);
bg.add(btn);
}
add(colorSelectionPane, BorderLayout.NORTH);
}
}
public class CanvasPane extends JPanel {
private List<Pixel> pixels = new ArrayList<>(128);
private Color pixelColor = Color.BLACK;
public CanvasPane() {
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
int x = e.getX();
int y = e.getY();
Pixel pixel = new Pixel(e.getPoint(), getPixelColor());
pixels.add(pixel);
repaint();
}
});
}
public Color getPixelColor() {
return pixelColor;
}
public void setPixelColor(Color pixelColor) {
this.pixelColor = pixelColor;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
for (Pixel pixel : pixels) {
g2d.setColor(pixel.getColor());
Point p = pixel.getPoint();
g2d.fillOval(p.x - 2, p.y - 2, 4, 4);
}
g2d.dispose();
}
}
}
Feedback...
This (and the eraser work flow)...
pen.addActionListener(e -> {
draw = true; erase = false;
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
super.mouseDragged(e);
x = e.getX();
y = e.getY();
plist.add(new Point(x, y));
repaint();
}
});
});
is a bad idea. Every time you action either of these two, you are adding ANOTHER mouse listener, this is going to be become messy very quickly.
I would, personally, make a simple enum with DRAW and ERASE and maintain a simple instance field which described the current "pen action".
When erasing, instead of drawing "white" pixels, I would use a "collision detection" workflow and remove the pixels from the List if you run over them, but that's me.

How do I repaint every second a component?

I'm trying to create a little game where the user need to click on squares for x seconds. The square should dissapear on mouse click or after 1 sec and at the end I should display the final score he achieved. I'm having troubles making the square repaint every second.
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class RectangleDemo extends JPanel{
JLabel label;
void buildUI(Container container) {
container.setLayout(new BoxLayout(container,BoxLayout.Y_AXIS));
RectangleArea rectangleArea = new RectangleArea(this);
container.add(rectangleArea);
label = new JLabel("Click within the framed area.");
container.add(label);
//Align the left edges of the components.
rectangleArea.setAlignmentX(LEFT_ALIGNMENT);
label.setAlignmentX(LEFT_ALIGNMENT); //unnecessary, but doesn't hurt
}
public void updateLabel(Point point) {
label.setText("Click occurred at coordinate ("
+ point.x + ", " + point.y + ").");
}
//Called only when this is run as an application.
public static void main(String[] args) {
JFrame f = new JFrame();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
RectangleDemo controller = new RectangleDemo();
controller.buildUI(f.getContentPane());
f.pack();
f.setVisible(true);
}
}
class RectangleArea extends JPanel implements ActionListener{
Random rand = new Random();
int a = rand.nextInt(400);
int b = rand.nextInt(400);
Point point = new Point(a,b);
RectangleDemo controller;
Dimension preferredSize = new Dimension(500,500);
int rectWidth = 50;
int rectHeight = 50;
Timer t;
public void actionPerformed (ActionEvent e)
{
}
//final Container panou;
public RectangleArea(RectangleDemo controller) {
this.controller = controller;
t=new Timer(1000, this); t.start();
Border raisedBevel = BorderFactory.createRaisedBevelBorder();
Border loweredBevel = BorderFactory.createLoweredBevelBorder();
Border compound = BorderFactory.createCompoundBorder
(raisedBevel, loweredBevel);
setBorder(compound);
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
if ((point.x<=x)&&(x<=point.x+50)&&(point.y<=y)&&(y<=point.y+50))
{point=null;t.stop();}
repaint();
}
});
}
public Dimension getPreferredSize() {
return preferredSize;
}
public void paintComponent(Graphics g) {
super.paintComponent(g); //paint background
//Paint a filled rectangle at user's chosen point.
if (point != null) {
g.drawRect(point.x, point.y,
rectWidth - 1, rectHeight - 1);
g.setColor(Color.yellow);
g.fillRect(point.x + 1, point.y + 1,
rectWidth - 2, rectHeight - 2);
controller.updateLabel(point);
}
}
}
Also after I click the first square I get get this error message:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at RectangleArea$1.mousePressed(RectangleDemo.java:82)

How to clear in jframe

I have a situation where I'm moving a ball. However, after struggling with the queue that repaint() places paintComponent(Graphics g) in. I resorted to using paintImmediately. The problem now is that without access to super.paintComponent(g), I don't know how to clear the canvas each time before I paint. So one possible answer to my question would be a way to clear the canvas by itself. I also found that Threads could be a possible solution but after a great many attempts to implement that idea, I still don't understand that so if someone could show correct implementation for that I would be very grateful.
Here is my code:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JButton;
public class PhysicsEngine extends JPanel {
double x, y;
JPanel pan;
JButton b1;
JButton b2;
JButton b3;
JButton b4;
JButton b5;
public static void main(String[] args) {
JFrame frame = new JFrame("Ball Engine");
PhysicsEngine gui = new PhysicsEngine();
frame.add(gui, BorderLayout.CENTER);
frame.setSize(600, 600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public PhysicsEngine() {
b1 = new JButton("1");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
try {
startFirst();
} catch (InterruptedException exception) {
}
}
});
this.add(b1);
b2 = new JButton("2");
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
startSecond();
} catch (InterruptedException exception) {
}
}
});
this.add(b2);
b3 = new JButton("3");
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
startThird();
} catch (InterruptedException exception) {
}
}
});
this.add(b3);
b4 = new JButton("4");
b4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
startFourth();
} catch (InterruptedException exception) {
}
}
});
this.add(b4);
b5 = new JButton("5");
b5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
startFifth();
} catch (InterruptedException exception) {
}
}
});
this.add(b5);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("" + y);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.fillOval((int) x, (int) y, 30, 30);
}
public void startFirst() throws InterruptedException {
x = 300;
y = 80;
// xPos= 0*t*t + 0*t + 300 this is constant at 300
for(int t = 1; t<70;t++){
y = .1 * t * t + 0 * t + 80; // parametric equation for y
repaint();
paintImmediately((int)x, (int)y, 30, 30);
Thread.sleep(10);
}
}
public void startSecond() throws InterruptedException {
x = 300;
y = 550;
for (int t = 1;t<150; t++) {
// xPos= 0*t*t + 0*t + 300 this is constant at 300
y = .1 * t * t - 15 * t + 550; // parametric equation for y
repaint();
paintImmediately((int)x, (int)y, 30, 30);
Thread.sleep(10);
}
}
public void startThird() throws InterruptedException {
y = 550;
x = 50;
for (int t = 1;t<150; t++) {
y = .1 * t * t - 15 * t + 550; // parametric equation for y
x = 0 * t * t + 3 * t + 50; // parametric equation for x
repaint();
paintImmediately((int)x, (int)y, 30, 30);
Thread.sleep(10);
}
}
public void startFourth() throws InterruptedException {
y = 50;
x = -4;
for (int t = 1;t<110; t++) {
// xPos= 0*t*t + 0*t + 300 this is constant at 300
y = .001*t * t * t + 50; // given parametric equation for y
x = t - 4; // given parametric equation for x
repaint();
paintImmediately((int)x, (int)y, 30, 30);
Thread.sleep(10);
}
}
public void startFifth() throws InterruptedException {
for (int t = 1; t < 130 /* goes for 1.5 seconds */; t++) {
y = 200 * Math.sin(.05*t) + 300; // given parametric equation for y
x = 200 * Math.cos(.05*t) + 300; // given parametric equation for x
repaint();
paintImmediately((int)x, (int)y, 30, 30);
Thread.sleep(10);
}
}
}
Your problem isn't the "paint queue", it's the fact that you're violating the single threaded nature of the API, by calling Thread.sleep within the context of the EDT.
Instead of using for-loops with Thread.sleep in them, you should make use of a Swing Timer which updates the state of the variables paintComponent relies on (and call repaint)
Swing Timer can be thought of a pseudo loop, whose ActionListener is called within the context of the EDT, making it safe to update the UI from
Start by having a look at Concurrency in Swing and How to Use Swing Timers for more details
As a conceptual example...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private PhysicsPane physicsPane;
public TestPane() {
physicsPane = new PhysicsPane();
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = gbc.REMAINDER;
JButton b1 = new JButton("1");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
startFirst();
}
});
this.add(b1, gbc);
this.add(physicsPane, gbc);
}
protected void startFirst() {
physicsPane.startFirst();
}
}
public class PhysicsPane extends JPanel {
private Timer timer;
private double xPos, yPos;
private int tick;
public PhysicsPane() {
setBackground(Color.BLUE);
}
protected void stopTimer() {
if (timer == null) {
return;
}
timer.stop();
timer = null;
}
public void startFirst() {
stopTimer();
xPos = 300;
yPos = 500;
tick = 0;
timer = new Timer(10, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (tick >= 150) {
stopTimer();
return;
}
yPos = .1 * tick * tick - 15 * tick + 550;
tick++;
repaint();
}
});
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(600, 600);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.RED);
g2d.fillOval((int) xPos, (int) yPos, 30, 30);
g2d.dispose();
}
}
}

Capture/Save JPanel image

I am new to java and now like to make an application for drawing images and capturing it through JPanel. I tried a lot but failed. The code I used is given below. Please help
Thanks in advance.
The program draws images by dragging the mouse. And type a character in the textbox provided the press scan
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.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;
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;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class SwingPaintDemo3 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
final JFrame f = new JFrame("Swing Paint Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(null);
f.setBounds(0,0,800,600);
JButton scanButton=new JButton("Scan");
scanButton.setBounds(0,0,75, 40);
f.add(scanButton);
JButton eraseButton=new JButton("Erase");
eraseButton.setBounds(0,50,75, 40);
f.add(eraseButton);
JLabel label1=new JLabel("Program developed by Gopakumar in connection with MCA project MCP 60");
label1.setBounds(0, 500, 600,50);
f.add(label1);
final JTextField textBox=new JTextField();
textBox.setBounds(510, 50,50,50);
f.add(textBox);
Font font=new Font(Font.SANS_SERIF,Font.BOLD,50);
textBox.setFont(font);
final JLabel label2=new JLabel("Please type the Character for training");
label2.setBounds(505, 110, 600,50);
f.add(label2);
final MyPanel pan=new MyPanel();
f.add(pan);
f.setVisible(true);
eraseButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
f.repaint();
}
});
scanButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
if(textBox.getDocument().getLength()<1){
label2.setText("Please type the Character for training");
label2.setForeground(Color.red);
}
else if(textBox.getDocument().getLength()>1){
label2.setText("please Enter only one character");
}
else{
label2.setForeground(Color.BLACK);
label2.setText("Please type the Character for training");
scan(pan);
}
}
});
}
private static void scan(MyPanel pan1) {
int i,j;
pan1.bi.getGraphics();
pan1.paint(pan1.gd);
// Save your screen shot with its label
File outputfile = new File("image.jpg");
try {
ImageIO.write(pan1.bi, "jpg", outputfile);
} catch (IOException ex) {
Logger.getLogger(SwingPaintDemo3.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
class MyPanel extends JPanel {
private int x = 0;
private int y = 0;
private int ox = 0;
private int oy = 0;
private Graphics graphicsForDrawing;
//private boolean dragging;
public BufferedImage bi=new BufferedImage(400,400,BufferedImage.TYPE_INT_RGB);
public Graphics gd;
public MyPanel() {
this.gd = bi.getGraphics();
this.paint(gd);
setBorder(BorderFactory.createLineBorder(Color.black));
this.setBackground(Color.WHITE);
this.setBounds(100, 50,400, 400);
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
x = e.getX();
y = e.getY();
ox = x;
oy = y;
// dragging = true;
setUpDrawingGraphics();
}
});
addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
graphicsForDrawing.drawLine(ox, oy, x, y);
gd.drawLine(ox, oy, x, y);
ox = x;
oy = y;
}
});
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e){
if(SwingUtilities.isRightMouseButton(e)){
clear();
}
}
});
}
private void setUpDrawingGraphics() {
graphicsForDrawing = getGraphics();
graphicsForDrawing.setColor(Color.black);
gd.setColor(Color.black);
}
public void clear(){
repaint();
}
public Dimension getPreferredSize() {
return new Dimension(400,300);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
gd.drawImage(bi,0, 0, this);
}
}
I would suggest only drawing to your buffered image at the time you draw on the panel.
So you could remove your whole paintComponent(...) method, change your mouse drag listener to this:
addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
Graphics g = bi.getGraphics();
g.setColor(Color.green);
g.drawLine(ox, oy, x, y);
getGraphics().drawLine(ox, oy, x, y);
ox = x;
oy = y;
}
});
And then change your scan method to this:
private static void scan(MyPanel pan1) {
int i,j;
// Save your screen shot with its label
File outputfile = new File("image.jpg");
try {
ImageIO.write(pan1.bi, "jpg", outputfile);
} catch (IOException ex) {
ex.printStackTrace();
}
}

Moving a JLabel Around JPanel

I have a JPanel that has 2+ JLables on it, I would like to be able to grab a label then move it to a different location on the JPanel. How can I do that? The only things I can find on this are moving a label from component "A" to component "B", nothing about moving it around on a Panel.
Start playing with this:
public class ComponentDragger extends MouseAdapter {
private Component target;
/**
* {#inheritDoc}
*/
#Override
public void mousePressed(MouseEvent e) {
Container container = (Container) e.getComponent();
for (Component c : container.getComponents()) {
if (c.getBounds().contains(e.getPoint())) {
target = c;
break;
}
}
}
/**
* {#inheritDoc}
*/
#Override
public void mouseDragged(MouseEvent e) {
if (target != null) {
target.setBounds(e.getX(), e.getY(), target.getWidth(), target.getHeight());
e.getComponent().repaint();
}
}
/**
* {#inheritDoc}
*/
#Override
public void mouseReleased(MouseEvent e) {
target = null;
}
public static void main(String[] args) {
JLabel label = new JLabel("Drag Me");
JPanel panel = new JPanel();
panel.add(label);
ComponentDragger dragger = new ComponentDragger();
panel.addMouseListener(dragger);
panel.addMouseMotionListener(dragger);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(1024, 768);
f.add(panel);
f.setVisible(true);
panel.setLayout(null);
f.setState(Frame.MAXIMIZED_BOTH);
}
}
Here's another example of this where the MouseListener and MouseMotionListener are on the JLabels themselves. For this to work, it needs to know the mouse's location on the screen vs it's initial location on screen when the mouse was initially pressed.
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
public class MovingLabels {
private static final int PREF_W = 800;
private static final int PREF_H = 600;
private static void createAndShowGui() {
Random random = new Random();
final JPanel panel = new JPanel();
Color[] colors = {Color.red, Color.orange, Color.yellow, Color.green, Color.blue, Color.cyan};
panel.setPreferredSize(new Dimension(PREF_W, PREF_H)); // sorry kleopatra
panel.setLayout(null);
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
for (int i = 0; i < colors.length; i++) {
Color c = colors[i];
JLabel label = new JLabel("Label " + (i + 1));
Border outsideBorder = new LineBorder(Color.black);
int eb = 10;
Border insideBorder = new EmptyBorder(eb, eb, eb, eb);
label.setBorder(BorderFactory.createCompoundBorder(outsideBorder , insideBorder));
label.setSize(label.getPreferredSize());
label.setBackground(c);
label.setOpaque(true);
int x = random.nextInt(PREF_W - 200) + 100;
int y = random.nextInt(PREF_H - 200) + 100;
label.setLocation(x, y);
label.addMouseListener(myMouseAdapter);
label.addMouseMotionListener(myMouseAdapter);
panel.add(label);
}
JFrame frame = new JFrame("MovingLabels");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class MyMouseAdapter extends MouseAdapter {
private Point initialLoc;
private Point initialLocOnScreen;
#Override
public void mousePressed(MouseEvent e) {
Component comp = (Component)e.getSource();
initialLoc = comp.getLocation();
initialLocOnScreen = e.getLocationOnScreen();
}
#Override
public void mouseReleased(MouseEvent e) {
Component comp = (Component)e.getSource();
Point locOnScreen = e.getLocationOnScreen();
int x = locOnScreen.x - initialLocOnScreen.x + initialLoc.x;
int y = locOnScreen.y - initialLocOnScreen.y + initialLoc.y;
comp.setLocation(x, y);
}
#Override
public void mouseDragged(MouseEvent e) {
Component comp = (Component)e.getSource();
Point locOnScreen = e.getLocationOnScreen();
int x = locOnScreen.x - initialLocOnScreen.x + initialLoc.x;
int y = locOnScreen.y - initialLocOnScreen.y + initialLoc.y;
comp.setLocation(x, y);
}
}
You are probably getting it for the label itself. Try observing the coordinates of the panel. It should work
Here is what I wanted:
public class LayerItem extends JLabel{
protected int lblYPt = 0;
public LayerItem(JPanel layers){
this.addMouseListener(new MouseAdapter(){
#Override
public void mousePressed(MouseEvent evt){
lblMousePressed(evt);
}
});
this.addMouseMotionListener(new MouseAdapter(){
#Override
public void mouseDragged(MouseEvent evt){
lblMouseDragged(evt);
}
});
}
public void lblMousePressed(MouseEvent evt){
lblYPt = evt.getY();
}
public void lblMouseDragged(MouseEvent evt){
Component parent = evt.getComponent().getParent();
Point mouse = parent.getMousePosition();
try{
if(mouse.y - lblYPt >= 30){
this.setBounds(0, mouse.y - lblYPt, 198, 50);
}
}catch(Exception e){
}
}
}

Categories