Custom JComponent not showing up in custom JPanel

I tried the add () method, but when I try to add Test to GraphicsTest nothing is displayed. How to add it? Can someone show me? I have included the code that I am using.

This is my way and it does not work. Can someone show me or tell me what the problem really is?

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;

public class Test extends JComponent
{
    @Override
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setColor(Color.red);
        g2d.drawString("Hello", 50, 50);
        g2d.dispose();
    }
}

Here is another class:

   import java.awt.Color;
   import java.awt.Graphics;
   import java.awt.Graphics2D;
   import java.awt.geom.Rectangle2D;
   import javax.swing.JPanel;

   public class GraphicsTest extends JPanel
   {
       private Graphics2D g2d;
       private String state;
       private int x, y;

   GraphicsTest()
   {
       Test t = new Test();
       t.setVisible(true);
       add(t);
   }

   @Override
   public void paintComponent(Graphics g)
   {
       super.paintComponent(g);
       g2d = (Graphics2D) g;

       g2d.setColor(Color.BLACK);
       g2d.drawString("STATE: " + state, 5, 15);
       g2d.drawString("Mouse Position: " + x + ", " + y, 5, 30);

       g2d.setColor(Color.red);
       Rectangle2D r2d = new Rectangle2D.Double(x, y, 10, 10);
       g2d.draw(r2d);

       g2d.dispose();
    }

    public void setState(String state) { this.state = state; }
    public String getState() { return state; }
    public void setX(int x) { this.x = x; repaint(); }
    public void setY(int y) { this.y = y; repaint(); }
}
+3
source share
1 answer

- g2d.dispose(). , . , jvms. , g2d GraphicsTest. g2d Test, , . , g2d.dispose(), .

, , , :

setLayout(new BorderLayout());
add(t, BorderLayout.CENTER);

Flow Layout. , Flow Layout.

+1

Source: https://habr.com/ru/post/1736831/


All Articles