Jpanel error repainting - java

I've created my own extended JPanel to able the user to sign on it, after that save the signature and delete from the panel:
public class PanelParaFirmar extends JPanel
{
private MouseHandler mouseHandler = new MouseHandler();
private int index = 0;
private Point[] arr = new Point[100000];
public PanelParaFirmar()
{
this.setBackground(Color.WHITE);
this.addMouseListener(mouseHandler);
this.addMouseMotionListener(mouseHandler);
}
protected void paintComponent(Graphics g)
{
this.paintComponents(g);
for (int i = 0; i < index - 1; i++)
g.drawLine(arr[i].x, arr[i].y, arr[i + 1].x, arr[i + 1].y);
}
private class MouseHandler extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
arr[index] = new Point(e.getX(), e.getY());
index++;
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
arr = new Point[100000];
index = 0;
}
#Override
public void mouseDragged(MouseEvent e) {
//updateUI();
//save();
arr[index] = new Point(e.getX(), e.getY());
index++;
repaint();
}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
}
};
Before click on it all it's right:
But when I started to sign, it repaints the rootPane:
How can I paint just the line?

In addition to the fact that you should override paintComponent and not paintComponents , and call its super implementation, here is how you could manage multiple lines for one signature .
Create a list of lines ( a line is nothing else than a list of Point) to represent the signature.
When the mouse is pressed, add a new line to the list, and add the current point to this line.
When the mouse is dragged, add the current point to the current line.
Finally, your paint method will paint each line one after the other, without making junctions between them :
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class PanelParaFirmar extends JPanel {
private final MouseHandler mouseHandler = new MouseHandler();
private final List<List<Point>> lines = new ArrayList<>();
private List<Point> currentLine;
public static void main(final String[] args) {
JFrame fr = new JFrame();
fr.setSize(400, 200);
fr.getContentPane().add(new PanelParaFirmar());
fr.setVisible(true);
}
public PanelParaFirmar() {
this.setBackground(Color.WHITE);
this.addMouseListener(mouseHandler);
this.addMouseMotionListener(mouseHandler);
}
protected void paintComponent(final Graphics g) {
super.paintComponent(g);
for (List<Point> line : lines) {
for (int i = 0; i < line.size() - 1; i++) {
Point thisPoint = line.get(i);
Point nextPoint = line.get(i + 1);
g.drawLine(thisPoint.x, thisPoint.y, nextPoint.x, nextPoint.y);
}
}
}
private class MouseHandler extends MouseAdapter {
#Override
public void mousePressed(final MouseEvent e) {
currentLine = new ArrayList<Point>();
currentLine.add(new Point(e.getX(), e.getY()));
lines.add(currentLine);
repaint();
}
#Override
public void mouseDragged(final MouseEvent e) {
Point p = new Point(e.getX(), e.getY());
currentLine.add(p);
repaint();
}
}
}
Also note that since you are using a MouseAdapter , you don't have to implement the methods you don't need (like mouseClicked).

Related

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();
});
}
}

Why are drawn lines automatically erased?

I am building up a system with a canvas where user can draw lines by dragging the mouse in Java. I want all the strokes to be stored and displayed. However, when I press the mouse to draw a new line, previous lines are automatically erased, which is not what I was expecting. How can I solve this problem?
Here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FreeDrawing extends JPanel implements MouseListener, MouseMotionListener {
private int indexOfStroke = 0;
private int indexOfPoint = 0;
private Stroke[] strokes = new Stroke[50];
private Point[] currentPoints = new Point[500];
public FreeDrawing(String name) {
super();
this.addMouseListener(this);
this.addMouseMotionListener(this);
JFrame fr = new JFrame(name);
fr.add(this);
fr.setSize(500, 500);
setBackground(Color.GRAY);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.setVisible(true);
}
public void paintComponent(Graphics g) {
System.out.println("Paint");
super.paintComponents(g);
strokes[indexOfStroke] = new Stroke();
for (int i = 0; i < indexOfPoint - 1; i++) {
System.out.println("Really draw");
g.drawLine(currentPoints[i].x, currentPoints[i].y, currentPoints[i + 1].x, currentPoints[i + 1].y);
}
}
public void mouseDragged(MouseEvent e) {
System.out.println("Drag");
currentPoints[indexOfPoint] = new Point(e.getX(), e.getY());
indexOfPoint++;
repaint();
}
public void mousePressed(MouseEvent e) {
System.out.println("Press");
currentPoints[indexOfPoint] = new Point(e.getX(), e.getY());
indexOfPoint = 0;
repaint();
}
public void mouseReleased(MouseEvent e) {
indexOfPoint = 0;
indexOfStroke++;
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
public static void main(String[] args) {
FreeDrawing canvas = new FreeDrawing("Mouse");
}
}
class Stroke {
public Stroke() {
System.out.println("Stroke initiated");
points = new Point[500];
}
Point[] points;
}
Because, that's how painting works, see Painting in AWT and Swing and Performing Custom Painting for more details.
Basically, painting is destructive, meaning that each time paintComponent is called, you are expected to repaint the entire state of the component from scratch
One thing you might consider doing, is creating a class which contains the stroke, color and points you need to each line and store that in a List each time you click
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Stroke;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.Line2D;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
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 List<Drawing> drawings;
private Drawing current;
private Random rnd = new Random();
public TestPane() {
drawings = new ArrayList<>(25);
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
Stroke stroke = new BasicStroke(rnd.nextInt(9) + 1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
Color color = new Color(rnd.nextInt(255), rnd.nextInt(255), rnd.nextInt(255));
current = new Drawing(stroke, color);
current.addPoint(e.getPoint());
drawings.add(current);
}
});
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
current.addPoint(e.getPoint());
repaint();
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
for (Drawing drawing : drawings) {
drawing.paint(g2d);
}
g2d.dispose();
}
}
public class Drawing {
private Stroke stroke;
private Color color;
private List<Point> points;
public Drawing(Stroke stroke, Color color) {
this.stroke = stroke;
this.color = color;
this.points = new ArrayList<>(25);
}
public void addPoint(Point p) {
points.add(p);
}
public void paint(Graphics2D g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(color);
g2d.setStroke(stroke);
if (!points.isEmpty()) {
Point from = points.get(0);
for (Point to : points.subList(1, points.size())) {
g2d.draw(new Line2D.Double(from, to));
from = to;
}
}
g2d.dispose();
}
}
}

Java panel interface

Im trying to make a pline drawing program. when I try to repaint all of the lines(after creating a new one) only the last one is draw out.The problem might be in repainting.
Can someone see what I am doing wrong?
Code is here:
public class Kimp extends JFrame {
private ArrayList<Point[]> pointsArray = new ArrayList<>();
private Point points[] = new Point[10000];
private int pointCounter = 0;
public Kimp () {
panel paintArea = new panel();
add(paintArea, BorderLayout.CENTER);
}
private class panel extends JPanel {
public panel () {
HandlerClass handler = new HandlerClass();
this.addMouseListener(handler);
this.addMouseMotionListener(handler);
}
#Override
void paintComponent(Graphics g) {
super.paintComponent(g);
try {
for (Point[] p : pointsArray) {
for(int i = 0; i < p.length; i++) {
if (p[i].x == 0) {
continue;
} else {
if (p[i + 1].x == 0) {
g.setColor(Color.BLUE);
g.drawLine(p[i].x, p[i].y, p[i].x, p[i].y);
} else {
g.setColor(Color.BLUE);
g.drawLine(p[i].x, p[i].y, p[i + 1].x, p[i + 1].y);
}
}
}
}
points = preFill(points);
} catch (NullPointerException e) {
}
}
}
private class HandlerClass implements MouseListener , MouseMotionListener {
#Override
public void mouseDragged(MouseEvent e) {
points[pointCounter++] = e.getPoint();
}
#Override
public void mousePressed(MouseEvent e) {
points[pointCounter] = e.getPoint();
}
#Override
public void mouseMoved(MouseEvent e) {
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
}
public static Point[] preFill (Point[] points) {
for (int i = 0; i < points.length; i++) {
points[i] = new Point(-999,-999);
}
return points;
}
}
I quickly rewrote your code to simplify it as much as possible. You may be able to better understand the concepts behind it.
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Color;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class Kimp {
public static void main(String[] args) {
JFrame frame = new JFrame("Kimp!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.add(new CanvasPanel());
frame.setVisible(true);
}
}
class CanvasPanel extends JPanel {
private final List<List<Point>> lines = new LinkedList<List<Point>>();
private List<Point> points = new LinkedList<Point>();
public CanvasPanel() {
addMouseListener(mouseAdapter);
addMouseMotionListener(mouseAdapter);
}
#Override
public void paintComponent(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
for (List<Point> line : lines)
drawLine(line, g);
drawLine(points, g);
}
private void drawLine(List<Point> points, Graphics g) {
if (points.size() < 2) return;
Point p1 = points.get(0);
for (int i=1, n=points.size(); i<n; i++) {
Point p2 = points.get(i);
g.setColor(Color.BLUE);
g.drawLine(p1.x, p1.y, p2.x, p2.y);
p1 = p2;
}
}
private MouseAdapter mouseAdapter = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
points.add(e.getPoint());
repaint();
}
#Override
public void mouseDragged(MouseEvent e) {
points.add(e.getPoint());
repaint();
}
#Override
public void mouseReleased(MouseEvent e) {
if (points.size() > 1) {
lines.add(points);
points = new LinkedList<Point>();
}
}
};
}
private ArrayList<Point[]> pointsArray = new ArrayList<>();
This is a list of Point[]. Here only one private Point points[] = new Point[10000]; is allocated. Which means that each time you add points into pointArray, you are adding the same instance of points.
When you change the elements of points, all the existing Point[] in pointArray is updated. Since all the elements are referring to the same points.
Allocate new Point[] when drawing a new line.
You are resetting your points array every time you painted it (preFillPoints() is called in paint()). Your pointsArray (which should be called pointsList for gods sake) is completely meaninless, you add the same points[] array each time the mouse is released.
The code makes no sense. You only need the list or the array. Not both. Declare a List<Point> (not Point[]) and just add a new Point every time the mouse moves.

Draw Lines with mouseevent in java

I have a problem with my project, my project is draw lines (likes paint in windows). I want to draw more one line with mouseDragged,mousePressed and mouseReleased. But when I run to test, it showed a lot of errors, here my code
package image;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Point;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class paint extends JFrame{
private Point points[] = new Point[10000];
private Point pointends[] = new Point[10000];
private int pointCount = 0;
public paint()
{
panel paint2 = new panel();
add(paint2,BorderLayout.CENTER);
}
private class panel extends JPanel
{
public panel()
{
setBackground(Color.BLUE);
MouseHandler handler = new MouseHandler();
this.addMouseMotionListener(handler);
this.addMouseListener(handler);
}
#Override
protected void paintComponent(Graphics g)
{
// TODO Auto-generated method stub
super.paintComponent(g);
for(int i = 0;i < pointCount;i++)
{
g.setColor(Color.RED);
g.drawLine(points[pointCount].x, points[pointCount].y, pointends[pointCount].x, pointends[pointCount].y);
}
}
}
private class MouseHandler extends MouseAdapter
{
#Override
public void mouseDragged(MouseEvent e)
{
// TODO Auto-generated method stub
pointends[ pointCount ] = e.getPoint();
repaint();
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
super.mousePressed(e);
if(pointCount < points.length)
{
points[ pointCount ] = e.getPoint();
}
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
super.mouseReleased(e);
pointends[pointCount]=e.getPoint();
repaint();
pointCount++;
}
}
}
and here's my void main
package image;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.BorderLayout;
public class test
{
public static void main(String[] args) {
paint paint1 = new paint();
/*paintP.add(paint1, BorderLayout.CENTER);
paintP.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
paintP.setSize(400,400);
paintP.setVisible(true);*/
paint1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
paint1.setSize(400,400);
paint1.setVisible(true);
}
}
In your paintComponentmethod, change the line
g.drawLine(points[pointCount].x, points[pointCount].y, pointends[pointCount].x, pointends[pointCount].y);
to this:
g.drawLine(points[i].x, points[i].y, pointends[i].x, pointends[i].y);
This will get rid of the NullPointerException and the lines will be drawn correctly once you release the mouse button. (Before, you were not only trying to paint the same line in each iteration of the loop, but also a line that did not exist yet, thus the NullPointerException.)
There's another problem: In your releaseMouse and mouseDragged methods, you are setting the end points for the line at index pointCount, but you are drawing only up to pointCount - 1. You have to increment the pointCount counter when you start drawing the lines, otherwise the new line will only be drawn when the mouse is released. One way to fix this would be to change your mouse listener to this:
private class MouseHandler extends MouseAdapter {
public void mouseDragged(MouseEvent e) {
pointends[ pointCount - 1 ] = e.getPoint(); // note the "- 1"
repaint();
}
public void mousePressed(MouseEvent e) {
if(pointCount < points.length) {
points[ pointCount ] = e.getPoint();
pointends[ pointCount ] = e.getPoint(); // add end point
pointCount++;
repaint();
}
}
public void mouseReleased(MouseEvent e) { // do nothing
}
}
You may try this:
public class myDrawLine extends JPanel {
private static final long serialVersionUID = 1L;
// These ArrayList will save all Points of Pressed and Released
ArrayList<Point> pointStart = new ArrayList<Point>();
ArrayList<Point> pointEnd = new ArrayList<Point>();
// These single Points will save the point of Dragged
Point startSinglePoint = new Point();
Point endSinglePoint = new Point();
public void paint(Graphics g) {
super.paint(g);
g.drawLine(startSinglePoint.x, startSinglePoint.y, endSinglePoint.x,
endSinglePoint.y);
for (int i = 0; i < pointStart.size() && i < pointEnd.size(); i++) {
g.drawLine(pointStart.get(i).x, pointStart.get(i).y,
pointEnd.get(i).x, pointEnd.get(i).y);
}// end for
}// end paint
{// start Block of Listeners
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
startSinglePoint = e.getPoint(); // used to the draw line when
// you drag
pointStart.add(e.getPoint()); // used to save all drew lines
}// end mousePressed
public void mouseReleased(MouseEvent e) {
pointEnd.add(e.getPoint()); // used to save all drew lines
repaint();
}// end mouseReleased
});// end addMouseListener
addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
endSinglePoint = e.getPoint(); // used to draw the line when you
// drag
repaint();
}// end mouseDragged
});// end addMouseMotionListener
}// end Block of Listeners
}// end Class
and the main method:
public static void main(String[] args){
JFrame frame = new JFrame("Draw Line");
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
myDrawLine draw = new myDrawLine();
frame.getContentPane().add(draw);
}//end main

Window going blank during MouseWheelMotion event

I've written this simple program which displays key presses, draws the phrase "Hello World," where one's cursor moves (with a trail mode when clicked) and also cycles through the Colors in which "Hello World," is picked out when the mouse wheel is scrolled. However there is a problem with this: When the mouse wheel scrolls the entire window goes blank (showing the default grey color from when you first make a component visible) and will then be redrawn with the color change (a very small change only to the "Hello World," which doesn't seem to require that the whole frame be redrawn.
The time for which the blankness occurs seems to correlate with the force with which the mouse wheel is scrolled, if I scroll very lightly there is only a very tiny moment where everything is not displayed, however scrolling very hard can make the window go blank for 2-3 seconds.
I've tried double buffering - thinking that this might be some sort of screen flicker - but it has made no change and I'm at a loss as to what could be causing this weird effect. It's as if the frame image is loading while the Wheel motion event is happening. (Is there perhaps a way to exit from the wheel event immediately so as to reduce loading time? (This is just my guesses as to possible solutions)).
The code is below. Any ideas would be greatly appreciated.
package keymouse;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferStrategy;
import java.util.LinkedList;
import javax.swing.JFrame;
public class KeyMouse implements KeyListener,
MouseMotionListener, MouseListener, MouseWheelListener, Runnable {
boolean trailMode = false;
boolean exists = false;
display window;
LinkedList wordList;
LinkedList trailList;
LinkedList colorList;
Point mousePoint;
int TRAIL_SIZE = 10;
boolean init = true;
int FONT_SIZE = 32;
int mouseY;
int mouseX;
int y;
int colorCount = 0;
public static void main(String[] args) {
KeyMouse k = new KeyMouse();
k.run();
}
public KeyMouse() {
window = new display();
window.addKeyListener(this);
window.addMouseMotionListener(this);
window.addMouseListener(this);
window.addMouseWheelListener(this);
window.setBackground(Color.WHITE);
window.setForeground(Color.BLACK);
wordList = new LinkedList();
trailList = new LinkedList();
colorList = new LinkedList();
colorList.add(Color.BLACK);
colorList.add(Color.BLUE);
colorList.add(Color.YELLOW);
colorList.add(Color.GREEN);
colorList.add(Color.PINK);
}
#Override
public void keyTyped(KeyEvent e) {
// do nothing
}
#Override
public void keyPressed(KeyEvent e) {
int keyCode;
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
stop();
}
keyCode = e.getKeyCode();
addMessage("Pressed:" + e.getKeyText(keyCode));
}
#Override
public void keyReleased(KeyEvent e) {
//do nothing
}
#Override
public void mouseDragged(MouseEvent e) {
Point p = new Point(e.getX(), e.getY());
addLocation(p);
}
#Override
public void mouseMoved(MouseEvent e) {
Point p = new Point(e.getX(), e.getY());
addLocation(p);
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
trailMode = true;
}
#Override
public void mouseReleased(MouseEvent e) {
trailMode = false;
}
#Override
public void mouseEntered(MouseEvent e) {
//do nothing
}
#Override
public void mouseExited(MouseEvent e) {
//do nothing
}
#Override
public void mouseWheelMoved(MouseWheelEvent e) {
System.out.println(e.getWheelRotation());
colorCount++;
if (colorCount > 4) {
colorCount = 0;
}
window.setForeground((Color) colorList.get(colorCount));
}
#Override
public void run() {
window.createBufferStrategy(2);
BufferStrategy strategy = window.getBufferStrategy();
while (true) {
draw(strategy.getDrawGraphics());
strategy.show();
try {
Thread.sleep(20);
} catch (Exception ex) {
}
}
}
public void draw(Graphics g) {
//draw background
g.setColor(window.getBackground());
g.fillRect(0, 0, window.getWidth(), window.getHeight());
//draw Text
g.setColor(window.getForeground());
g.setFont(new Font("sansserif", Font.BOLD, 32));
int count = trailList.size();
if (trailList.size() > 1 && trailMode == false) {
count = 1;
}
if (exists == true) {
for (int i = 0; i < count; i++) {
Point p = (Point) trailList.get(i);
g.drawString("Hello World", p.x, p.y);
}
}
g.setColor(Color.BLACK);
y = 56;
for (int i = 0; i < wordList.size(); i++) {
String word = (String) wordList.get(i);
g.drawString((String) wordList.get(i), 100, y);
y += 32;
}
}
public void addMessage(String message) {
if (y >= window.getHeight()) {
wordList.remove(0);
}
wordList.add(message);
}
public void addLocation(Point h) {
exists = true;
trailList.addFirst(h);
if (trailList.size() > TRAIL_SIZE) {
trailList.removeLast();
}
}
public void printMessages() {
for (int i = 0; i < wordList.size(); i++) {
System.out.println(wordList.get(i));
}
}
private void stop() {
System.exit(0);
}
Absent a complete example, I can't reproduce the effect you describe. You might compare your code to this example, which exhibits no apparent blanking.
In general,
JPanel is double buffered by default; it's unusual to need a different buffer strategy.
AnimationTest illustrates a Swing Timer and how to display your average paint period.
MouseAdapter is convenient for overriding a small number of methods.
When possible, use generic parameters for type safety.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseWheelEvent;
import java.util.LinkedList;
import java.util.Queue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
* #see https://stackoverflow.com/a/10970892/230513
*/
public class ColorWheel extends JPanel {
private static final int N = 32;
private final Queue<Color> clut = new LinkedList<Color>();
private final JLabel label = new JLabel();
public ColorWheel() {
for (int i = 0; i < N; i++) {
clut.add(Color.getHSBColor((float) i / N, 1, 1));
}
this.setBackground(clut.peek());
label.setText(getBackground().toString());
this.add(label);
this.addMouseWheelListener(new MouseAdapter() {
#Override
public void mouseWheelMoved(MouseWheelEvent e) {
setBackground(clut.peek());
label.setText(getBackground().toString());
clut.add(clut.remove());
}
});
}
#Override
public Dimension getPreferredSize() {
return new Dimension(320, 240);
}
private void display() {
JFrame f = new JFrame("ColorWheel");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new ColorWheel().display();
}
});
}
}

Categories