paintComponent method not being called in Java - java

I'm doing this very basic and simple Swing tutorial as the first assignment from my software engineering course, and for some very strange reason, the paintComponent method isn't being invoked in my JPanel. Now I've worked with Java Swing in the past and I've never had any issues like this.
The tutorial I am using is found right on the Oracle site(easier to go to the site and look at the code since it's the same code I have).
Tutorial Link
Can anyone please explain to me why it isn't working for me?
My code:
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.Graphics;
public class PaintDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createGUI();
}
});
}
private static void createGUI() {
System.out.println("Created GUI on EDT? "+
SwingUtilities.isEventDispatchThread());
JFrame frame = new JFrame("Yay, first 2102 lab!!");
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE); // allows to close the program
DemoPanel panel = new DemoPanel();
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
class DemoPanel extends JPanel {
public DemoPanel() {
setBorder(BorderFactory.createLineBorder(Color.BLACK));
}
public Dimension getPreferredSize() {
return new Dimension(250,200);
}
public void paintComponenet(Graphics g) {
super.paintComponent(g);
g.drawString("This is my custom panel!",10,20);
}
}

It is paintComponent(Graphics g), not paintComponenet(Graphics g).
At least you are calling the super.paintComponent(g) correctly.
If you annotate your paint* method with the #Override annotation, you will get a compile error that will help you understand what is going on.

Related

MouseListener overriding Paint Component

I'm trying to make a a program in MVC architecture which simply opens a frame (JFrame) with some certain design and when clicked somewhere with a mouse simply prints to the console : "sth" notifying that the action went through successfully but it seems that the Input.java class when added to the frame before the Ouput.java class is overridden by the latter and disables MouseListener, or the former overrides the latter where you're able to activate MouseListener executing a certain program when clicked on the frame but doesn't show the design made in Output
Here are the mentioned class files:
input.java:
package MouseListenerTest;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JPanel;
public class Input extends JPanel implements MouseListener
{
Input()
{
addMouseListener(this);
}
public void mouseClicked(MouseEvent e) {
System.out.println("Ej Adiiiii");
}
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
}
Output.java
package MouseListenerTest;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Output extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(0, 0, 500, 500);
}
}
Frame.java
package MouseListenerTest;
import javax.swing.*;
public class Frame
{
Frame()
{
JFrame frame = new JFrame();
frame.getContentPane().add(new Output());
frame.getContentPane().add(new Input());
frame.setSize(500,500);
frame.setVisible(true);
frame.setTitle("MouseListener test");
}
}
Controller.java
package MouseListenerTest;
public class Controller
{
public static void main(String[] args)
{
new Frame();
}
}
How do I fix this problem?
the problem in your code is because the way you added the elements to frame and I changed to a GridLayout and added them to frame to see both:
frame.setLayout(new GridLayout(2, 1));
frame.getContentPane().add(new Output());
frame.getContentPane().add(new Input());
more info about Layout Manager
You will have to learn at least the basics about laying out components.

Java swing: i called once drawString and it printed my string multiple times

I'm new in java swing programming. What i'm trying to do is paint a string to a specific location in a JPanel. The JPanel is very large and so i add it to a JScrollpane, but when i draw the string it is printed not just in the specified location but also in others.
The first image represents the bottom of the panel where i decided to draw the string and this is correct. But if you observe whole the panel you can find the string too in others locations (see second image).
Can someone tell me why this happen? How can i prevent it?
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
class Example extends JFrame
{
private MyPanel gg=new MyPanel();
Example(){
add(new JScrollPane(gg));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setExtendedState(MAXIMIZED_BOTH);
}
public static void main(String argv[]){
EventQueue.invokeLater(new Runnable() {
public void run() {
Example test=new Example();
test.setVisible(true);
}
});
return;
}
}
class MyPanel extends JPanel
{
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d=(Graphics2D)g;
g2d.drawString("HI I LOVE ELON MUSK", 90, 300035);
return;
}
public Dimension getPreferredSize() {
return new Dimension(500, 300060);
}
}
Your code ran fine on my Windows 10 system. I have a Java 13 JDK that I compile at Java 8.
I made a few changes to your main class. Maybe these changes stabilized the display. Run my code on your system and see.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class LongJPanelExample {
public LongJPanelExample() {
JFrame frame = new JFrame("Long JPanel Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyPanel gg = new MyPanel();
frame.add(new JScrollPane(gg));
frame.pack();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
}
public static void main(String argv[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new LongJPanelExample();
}
});
}
}
class MyPanel extends JPanel {
private static final long serialVersionUID = 1L;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawString("HI I LOVE ELON MUSK", 90, 300035);
return;
}
public Dimension getPreferredSize() {
return new Dimension(500, 300060);
}
}

Drawing a rectangle that moves slowly towards the point of the mouse click rather than jumping to it (JAVA)

I am very new to JAVA and i am just a hobbyist,Just recently I have been following some tutorials on making UI and all thee looking in to learn about this, any code snippets are welcome but also more what is this function / process called so i can look deeper into different parts of swing from the ORACLE DOCS which is really informative, I am still working my way through the components.
I do not have an overall goal at present and am just finding my feet, but i want to try and make a small top-down 2d maze game to learn.
One part got my attention and it was this demo at the bottom of the page
https://docs.oracle.com/javase/tutorial/uiswing/painting/step3.html
Basically this is the code and I am trying to make it so when I click inside the frame the rectangle moves slowly towards the point of the mouse click rather than jumping to it (and later on if possible to click in another location and it would change its course before reaching its destination.
What kind of area do i need to be looking in to learn about this, any code snippets are welcome but also more what is this function / process called so i can look deeper into it.
WORKING DEMO CODE BELOW
package painting;
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.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseMotionAdapter;
public class SwingPaintDemo3 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() { I am Trying to make it so when I click inside the
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
System.out.println("Created GUI on EDT? "+
SwingUtilities.isEventDispatchThread());
JFrame f = new JFrame("Swing Paint Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new MyPanel());
f.pack();
f.setVisible(true);
}
}
class MyPanel extends JPanel {
private int squareX = 50;
private int squareY = 50;
private int squareW = 20;
private int squareH = 20;
public MyPanel() {
setBorder(BorderFactory.createLineBorder(Color.black));
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
moveSquare(e.getX(),e.getY());
}
});
addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
moveSquare(e.getX(),e.getY());
}
});
}
private void moveSquare(int x, int y) {
int OFFSET = 1;
if ((squareX!=x) || (squareY!=y)) {
repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
squareX=x;
squareY=y;
repaint(squareX,squareY,squareW+OFFSET,squareH+OFFSET);
}
}
public Dimension getPreferredSize() {
return new Dimension(250,200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("This is my custom Panel!",10,20);
g.setColor(Color.RED);
g.fillRect(squareX,squareY,squareW,squareH);
g.setColor(Color.BLACK);
g.drawRect(squareX,squareY,squareW,squareH);
}
}
Thanks for any advice ;)

Java Frame shows my screen

I am starting to learn how to make graphics in Java. But if I draw something in my Frame and I run the program. those parts of the Frame where I did not draw anything there is the picture of the Frame running behind my Program. hw can I avoid this?
package de.sarah;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
public class Framemg extends JFrame{
public Framemg() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Zeichnen mit Java");
setSize(400, 300);
setBackground(Color.yellow);
setVisible(true);
}
public void paint(Graphics g) {
g.drawString( "Hellooo", 120, 60 );
}
}
package de.sarah;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Insets;
public class Main{
public static void main(String[] args) {
Framemg Frame = new Framemg();
}
}
Don't override paint() of a JFrame.
Custom painting is done by overriding the paintComponent(...) method of a JPanel. Then you add the panel to the frame.
Read the section from the Swing tutorial on Custom Painting for more information and working examples to get you started.

How to implement .png pics in a JFrame?

Hi I want to make a window, a GUI, and put an image in it.
I watched a YT tutorial (https://www.youtube.com/watch?v=Ap20Qw77TzY) and copied everything similar but the Window I make has no image at all. I tried different file types like .jpg and different window sizes, matching the picture size but it doesn't help.
That's my code, I get no real errors, except a warning of:
The serializable class main does not declare a static final serialVersionUID field of type long,line 8
This method has a constructor,line 25
Code
package main;
import java.awt.Graphics;
import java.awt.Toolkit;
import javax.swing.*;
public class main extends JFrame {
/**
* author jan
*/
public main(String title){
super (title);
}
public void paint(Graphics gr) {
super.paint(gr);
gr.drawImage(Toolkit.getDefaultToolkit().getImage("Koppenhagen\\Pictures\\Herz.png"), 0, 0, this);
}
public static void main(String[] args) {
main window = new main("Mein Test!");
window.setSize(160,160);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
}
Use ImageIO.read over Toolkit.getImage, it will throw a IOException of the image can't be load for some reason
Check the location of the image. Your example is looking for a file in Koppenhagen\\Pictures, relative to the execution context of the program. You could use File#exists to check if the file actually exists where you think it is
Don't load resources within the any paint method, loading images can take time and painting should run as fast as possible
I'd discourage you from overriding paint of top level containers like JFrame. A JFrame contains a JRootPane, which contains, amongst other things, a contentPane all of which can be painted independently of its parent container. Instead, start with a JPanel and override its paintComponent method instead, then add this to an instance of JFrame
Here's a simple Swing application that draws an image.
You have to put the image in the same directory as the Java code.
package com.ggl.testing;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public class DrawImage implements Runnable {
#Override
public void run() {
JFrame frame = new JFrame("Image");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane(new ImagePanel(getImage()));
frame.add(scrollPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private Image getImage() {
try {
return ImageIO.read(getClass().getResourceAsStream(
"StockMarket.png"));
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new DrawImage());
}
public class ImagePanel extends JPanel {
private static final long serialVersionUID = -2668799915861031723L;
private Image image;
public ImagePanel(Image image) {
this.image = image;
this.setPreferredSize(new Dimension(image.getWidth(null), image
.getHeight(null)));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
}
}

Categories

Resources