Cursor disappears while calling repaint in mouseMoved? - java

I have a problem with drawing horizontal and vertical lines from the cursor position while the cursor is moving. The cursor seem to disappear.
I've attached a MouseInputAdapter to my swing component, which has a mouseMoved method which call repaint();
Calling repaint will cause a paintComponent(Graphics g) to be called. In paintComponent i paint the horizontal and vertical line:
Dimension dim = getSize();
g2.setColor(Color.white);
g2.fillRect(0, 0, dim.width, dim.height);
g2.setColor(Color.black);
Point pos = this.getMousePosition();
g2.draw(new Line2D.Double(0, pos.y, dim.getWidth(), pos.y));
g2.draw(new Line2D.Double(pos.x, 0, pos.x, dim.getHeight()));
Here is a screenshot:
The cursor should be in the white area that exists between the big horizontal line and the vertical one and should be at the left of the big number 1.2434307...
When i move the cursor with my mouse i can see the cursor (crosshair) flickering which makes me believe my paint method is painting over the cursor.
Anyone know where the problem may lie?
As requested i've added a little test code.
public class TestApp extends JFrame {
public TestApp() {
super("TestApp");
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(new CustomComponent(), BorderLayout.CENTER);
this.setSize(300, 300);
this.setVisible(true);
}
class CustomComponent extends JComponent {
public CustomComponent() {
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
MouseInputAdapter mia = new MouseInputAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
repaint();
}
};
addMouseMotionListener(mia);
addMouseListener(mia);
}
#Override
public void paintComponent(Graphics g) {
Dimension dim = getSize();
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.white);
g2.fillRect(0, 0, dim.width, dim.height);
g2.setColor(Color.black);
Point pos = this.getMousePosition();
if (pos != null) {
g2.draw(new Line2D.Double(0, pos.y, dim.getWidth(), pos.y));
g2.draw(new Line2D.Double(pos.x, 0, pos.x, dim.getHeight()));
g2.drawString("where is my cursor?", pos.x, pos.y);
}
}
}
public static void main(String[] args) {
new TestApp();
}
}

Related

Drawing in JPanel disappears when scrolling or ressizing the main frame

I draw many shapes in panel and it works, but when I scroll the panel or when I resize the frame the drawings disappears.
I looked at other questions on this topic, but did not find a solution to the problem.
The screenshots:
The code:
public class ZoomPane {
public static void main(String[] args) {
new ZoomPane();
}
public ZoomPane() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
. . .
}
});
}
public class TestPane extends JPanel {
private float scale = 1;
public TestPane() {
addMouseWheelListener(new MouseAdapter() {
#Override
public void mouseWheelMoved(MouseWheelEvent e) {
double delta = 0.05f * e.getPreciseWheelRotation();
scale += delta;
revalidate();
repaint();
}
});
}
#Override
public Dimension getPreferredSize() {
Dimension size = new Dimension(200, 200);
size.width = Math.round(size.width * scale);
size.height = Math.round(size.height * scale);
return size;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
AffineTransform at = new AffineTransform();
at.scale(scale, scale);
g2d.setTransform(at);
g2d.setColor(Color.RED);
gr.draw(new Line2D.Double((int)this.getWidth() / 2, 0, (int)this.getWidth() / 2, this.getHeight()));
gr.draw(new Line2D.Double(0, (int)this.getHeight() / 2, this.getWidth(), (int)this.getHeight() / 2));
g2d.dispose();
}
}
}
How can I fix this bug?
You are clobbering the Graphics2D transform put in place by Swing. JScrollPane relies on it.
Instead of replacing the transform, you need to append to it. Replace this:
AffineTransform at = new AffineTransform();
at.scale(scale, scale);
g2d.setTransform(at);
with this:
AffineTransform at = new AffineTransform();
at.scale(scale, scale);
g2d.transform(at);
The setTransform replaces the transform; the transform method appends to it.
A cleaner solution is to replace all three lines with this:
g2d.scale(scale, scale);

Is it possible to write paint on screen program in java/swing?

I'm writing paint on screen program using Java Swing. It working on ubuntu linux. But windows shows black screen instead of transparent panel. I included similar example code. What is wrong in my code?
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Example {
public static final Color COLOR_TRANSPARENT = new Color(0,0,0,0);
public Example() {
Canvas drawArea = new Canvas();
drawArea.setBackground(COLOR_TRANSPARENT);
drawArea.setOpaque(true);
JWindow drawingFrame = new JWindow();
drawingFrame.setBackground(COLOR_TRANSPARENT);
drawingFrame.setContentPane(drawArea);
drawingFrame.pack();
drawingFrame.setSize(640, 460);
drawingFrame.setVisible(true);
drawingFrame.setLocationRelativeTo(null);
drawingFrame.setAlwaysOnTop(true);
}
public static void main(String[] args){
SwingUtilities.invokeLater(Example::new);
}
class Canvas extends JPanel{
private Image image;
private Graphics2D g2;
public Canvas() {
super();
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
g2.setPaint(Color.RED);
g2.fillOval(x-10, y-10, 20, 20);
repaint(x-10, y-10, 20, 20);
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image == null){
image = createImage(getWidth(), getHeight());
g2 = (Graphics2D) image.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setBackground(COLOR_TRANSPARENT);
clear();
}
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(image, 0,0, null);
}
public void clear(){
System.out.println("clearing canvas ");
g2.setComposite(AlphaComposite.Clear);
g2.setBackground(COLOR_TRANSPARENT);
g2.setColor(COLOR_TRANSPARENT);
g2.fillRect(0, 0, getWidth(), getHeight());
g2.clearRect(0, 0, getWidth(), getHeight());
g2.setPaint(Color.RED);
g2.setComposite(AlphaComposite.SrcOver);
repaint();
}
}
}
Here is screenshot what I wanted.
Example code updated. Now code should work without any other additional code.
For windows I made a couple of changes:
image = createImage(getWidth(), getHeight());
image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
I used a BufferedImage to you can set the alpha values of the image to be transparent.
//public static final Color COLOR_TRANSPARENT = new Color(0,0,0,0);
public static final Color COLOR_TRANSPARENT = new Color(0,0,0,1);
I made the alpha value non-zero, because a value of zero means the Java application won't receive the MouseEvent because it is passed to the application under the window.

How can I fix this NullPointerException when trying to render on a JPanel with Graphics2D? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I've been trying to make a shop for my game.
This has been unsuccessful.
I've tried drawComponent, didn't work.
No errors, code executed, but didn't work.
Now i'm trying to do:
private void render() {
Graphics2D g = (Graphics2D) graphics.getGraphics();
/////////////////////
g.drawImage(img, 0, 0, WIDTH, HEIGHT, null);
/////////////////////
g.dispose();
Graphics2D g2d = (Graphics2D) getGraphics();
g2d.drawImage(img, 0, 0, null);
g2d.dispose();
}
Now i get a NullPointerException on g2d.
I've tried everything.
`Exception in thread "game" java.lang.NullPointerException
at com.johnythecarrot.game.Shop$DrawPane.access$2(Shop.java:123)
at com.johnythecarrot.game.Shop.render(Shop.java:154)
at com.johnythecarrot.game.Game.render(Game.java:75)
at com.johnythecarrot.game.Game.run(Game.java:112)
at java.lang.Thread.run(Unknown Source)`
My goals are to be able to have clickable buttons.
It DID work. But i had to restart almost everytime. Because mostly of the time to code wasn't even executed. So i tried to fix it. Now it's all messed up.
This is the code to it.
(DoubleInt is a part of my library it's nothing more than just x and y. )
public class Shop {
public BuildWindow window;
public static JWindow w;
private int WIDTH = 860, HEIGHT = 440;
private BufferedImage graphics = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
public DrawPane drawPane;
public Shop() {
//window = new BuildWindow().setSize(new DoubleInt(100, 100)).at(wi, he).setTitle("Shop").setOpacity(1).setDragable(false).showEmpty(true);
w = new JWindow();
w.setOpacity(1);
w.setSize(WIDTH, HEIGHT);
w.setLocation(800, 800);
w.setVisible(false);
w.setAlwaysOnTop(true);
//graphics = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
}
private void createShop() {
/***Graphics2D g = (Graphics2D) graphics.getGraphics();
g.setColor(Color.blue);
g.drawString("hey", WIDTH-50, HEIGHT-50);
g.fillRect(0, 0, WIDTH, HEIGHT);*/
}
public class DrawPane extends JPanel {
int width = WIDTH;
int height = HEIGHT;
private ArrayList<Shape> buttons;
private Shape btn1 = new Rectangle2D.Double(20, 60, width/2, height-20);
private Shape btnClose = new Rectangle2D.Double(width-25, 5, 20, 20);
Point wCoords;
Point mCoords;
public DrawPane() {
buttons = new ArrayList<>();
buttons.add(btn1);
buttons.add(btnClose);
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
for(Shape s : buttons) {
if(s.contains(e.getPoint())) {
System.out.println("Clicked " + s.getBounds());
if(s == btnClose) {
w.dispose();
}
}
}
}
#Override
public void mousePressed(MouseEvent e) {
mCoords = e.getPoint();
}
#Override
public void mouseReleased(MouseEvent arg0) {
mCoords = null;
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
wCoords = e.getLocationOnScreen();
w.setLocation(wCoords.x - mCoords.x, wCoords.y - mCoords.y);
}
});
}
void repaintThis() {
repaint();
}
BufferedImage img = loadImageFrom.LoadImageFrom(Shop.class, "bar.png");
Graphics gb;
/**
* super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g.setColor(Color.red);
//g.fillRect(0, 0, width, 50);
g.drawImage(img, 0, 0, width, 50, null);
g.setColor(Color.WHITE);
g.drawString("SHOP", 15, 30);
g.drawString("X", width-20, 20);
for(Shape b : buttons) {
g2d.draw(b);
}
System.out.println("Built");
gb = g;
*/
private void render() {
Graphics2D g = (Graphics2D) graphics.getGraphics();
/////////////////////
g.drawImage(img, 0, 0, WIDTH, HEIGHT, null);
/////////////////////
g.dispose();
Graphics2D g2d = (Graphics2D) getGraphics();
g2d.drawImage(img, 0, 0, null);
g2d.dispose();
}
public void Build() {
Graphics g = gb;
Graphics2D g2d = (Graphics2D) g;
g.setColor(Color.red);
//g.fillRect(0, 0, width, 50);
g.drawImage(img, 0, 0, width, 50, null);
g.setColor(Color.WHITE);
g.drawString("SHOP", 15, 30);
g.drawString("X", width-20, 20);
for(Shape b : buttons) {
g2d.draw(b);
}
System.out.println("Built");
}
}
public void render(Graphics2D g) {
drawPane.render();
}
public void addDrawPane() {
drawPane = new DrawPane();
w.add(drawPane);
}
}
If you need access to more code, just ask me.
You should override the paintComponent method like this:
public class DrawPane extends JPanel {
// all your variables and other things
#Override
paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
// Your code goes here, use the g2d
}
}
then if you need to repaint your component, simply call repaint() on it.

Painting multiple JComponent on JPanel not working

I just don't get this. I want to add Highlight extends JComponent objects to a PdfPage extends JPanel but the Highlight components are simple not painted. I can see that their paint() and paintComponent() methods are getting called in correct order but they do not show. The only thing that fixes my problem is to add:
for(Component component : this.getComponents()) {
component.paint(g);
}
into the PdfPanel.paint() method but this is not how I want to do that. I want PdfPage extends JPanel to render any JComponent I'm adding but not override paint() if possible.
This is how I add Highlight components to PdfPage panels:
for (DatasheetError datasheetError : datasheetErrorList) {
int pageNumber = datasheetError.getPageNumber();
Highlight highlight = createErrorHighlight(datasheetError);
PdfPage pdfPage = pdfPages[pageNumber];
pdfPage.add(highlight);
}
This is how PdfPage looks like. Note that I am not using a LayoutManager as I am calling super(null);:
public class PdfPage extends JPanel {
private static final long serialVersionUID = 7756137054877582063L;
final Image pageImage;
public PdfPage(Image pageImage) {
// No need for a 'LayoutManager'
super(null);
this.pageImage = pageImage;
Rectangle bounds = new Rectangle(0, 0, pageImage.getWidth(null), pageImage.getHeight(null));
this.setBounds(bounds);
this.setLayout(null);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
paintPdfPage(g);
}
private void paintPdfPage(Graphics g) {
// For now transparent background to see if `Highlight` gets painted
g.setColor(new Color(1.0f, 1.0f, 1.0f, 0.0f));
g.fillRect(0, 0, getWidth(), getHeight());
}
}
In Highlight.java you can see that I call this.setBounds(bounds);
public class Highlight extends JComponent {
private static final long serialVersionUID = -1010170342883487727L;
private Color borderColor = new Color(0, 0, 0, 0);
private Color fillColor;
public Highlight(Rectangle bounds, Color fillColor) {
this.fillColor = fillColor;
this.setBounds(bounds);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Rectangle bounds = this.getBounds();
g.setColor(this.fillColor);
g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
g.setColor(this.borderColor);
g.drawRect(bounds.x, bounds.y, bounds.width, bounds.height);
}
}
Looks like problem is coordinate space
protected void paintComponent(Graphics g) {
...
Rectangle bounds = this.getBounds();
g.setColor(this.fillColor);
g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
...
}
The getBounds() returns the component's rectanle on parent container. So when you can call just g.fillRect(0, 0, bounds.width, bounds.height);

Drawing graphics2D java

I need to draw a circle between 2 lines. When I click on the panel, a line is drawn. When I click a second time, another line is drawn and the color of the line has changed. Also, at the 2nd click, a circle is drawn between the 2 lines. Then, there is a little animation with the circle. Someone helped me yesterday with this code :
List<Integer> yClicks = new ArrayList<>(); {
addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
yClicks.add(e.getY());
repaint();
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g.create();
for(int y : yClicks) {
g2d.draw(new Line2D.Double(0, y, getWidth(), y));
}
g2d.dispose();
}
I added this:
for(int y : yClicks) {
line1= new Line2D.Double(0, y, getWidth(), y);
g2d.setColor(Color.blue);
g2d.draw(line1);
int l2= (yClicks.get(1));
int Diameter=l2-y;
g2d.setColor(Color.yellow);
g2d.draw(new Line2D.Double(0,l2,getWidth(),l2));
g2d.draw(new Ellipse2D.Double(getWidth()/2,(Diameter),10,10));
}
g2d.dispose();
}
But there is a problem withe the code and maybe circle are drawn. I never used this form of a for loop, so i don't know. how to add something on the loop. I also tried if(y==2) but it doesn't do anything.

Categories