jay
jay

Reputation: 15

Paint component drawing not appearing on frame

I have the following class (panel class), and a main class (Main class), shown below the panel class. The code is suppose to display the text that is inside the paintComponent method. Although, the frame opens, showing the title I provided, it does not display the string from paintComponent. I wrote the code following a tutorial on Java website, and I don't know why it's not working.

panel

package com.learn.java;
import javax.swing.*;
import java.awt.*;

class panel extends JPanel {

    public void paintComponent(Graphics g) {

        super.paintComponents(g);
        g.drawString("From Paint Component Method ", 10, 20);

    }
}

Main

package com.learn.java;

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

public class Main {

    public static void main(String[] args) {
        JFrame Frame = new JFrame("The big Title");
        Frame.setLayout(new FlowLayout());
        Frame.setSize(850, 800);
        Frame.setVisible(true);
        Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Frame.add(new panel());
    }

}

Upvotes: 1

Views: 227

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168825

The code has a number of problems, and the solution suggested in comments is sub-optimal.

First, the paint chain in the custom painted component is broken. The overridden method needs to call the super method, but instead calls the 'plural' version. To fix it, change:

super.paintComponents(g);

To:

super.paintComponent(g);

Now onto the stated problem. Getting rid of the FlowLayout hides the problem because while flow layout respects the preferred size of components (and does not stretch them) the default layout of a JFrame (BorderLayout) does stretch components to fill the available space.

The correct approach is to have the custom painted component override the getPreferredSize() method. Then it will appear as expected in a flow layout.

Once that is taken care of, remove:

Frame.setSize(850, 800);

Since it is just a guess.. Then move..

Frame.setVisible(true);

To the last statement and immediately before it, put..

Frame.pack(); // make the GUI the correct size

A further tip: Please learn common Java nomenclature (naming conventions - e.g. EachWordUpperCaseClass, firstWordLowerCaseMethod(), firstWordLowerCaseAttribute unless it is an UPPER_CASE_CONSTANT) and use it consistently.

Upvotes: 1

Related Questions