javaswinguser-interfacejbuttonjlabel

Why components doesn't show on my shape. I want to place them on a rectangle it disappears and the rectangle only shows?


I'm having a really big issue in which when ether I create a JLabel, Jbutton and so on, it works in terms of showing on screen however when I want to place them on a rectangle it disappears and the rectangle only shows?

With JLabel I opted to use drawstring instead but now I'm stuck with trying to get JTextField on. I don't know what I am missing.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.*;
import javax.swing.event.*;

class main
{   
    public static void main (String Args [])
    {
        GUIwindow guiW = new GUIwindow();
    }
}

class GUIwindow extends JFrame
{
    JPanel grid = new JPanel();
    JTextArea screenArea = new JTextArea("", 10, 20);
    JScrollPane scrollBar = new JScrollPane(screenArea);
    
    GUIwindow()
    {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500,800);
        setTitle("Title here");
        setLocationRelativeTo(null);
        
        screenArea.setLineWrap(true);
        screenArea.setEditable(false);
        
        
        grid.add(scrollBar);
        add(grid);
        setVisible(true);
    }
    
    public void paint (Graphics g)
    {
        g.setColor(Color.decode("#0232ac"));
        g.fillRoundRect(100, 50, 300, 600, 50, 50);
        g.setColor(Color.white);
        g.drawString("TitleonRect", 220, 80);
    }  
    
}

Solution

  • Do not override the method paint() of JFrame.

    Override the method paintComponent() of an element.

    If you subclass JPanel, you can override its paintComponent method:

    class GridPanel extends JPanel {
        GridPanel() {
            super();
        }
    
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.decode("#0232ac"));
            g.fillRoundRect(100, 50, 300, 600, 50, 50);
            g.setColor(Color.white);
            g.drawString("TitleonRect", 220, 80);
        }
    }