[Solved] How to use the JComponent [closed]


This is a rather perplexing way to start programming in Java. Even so, in this instance why would you not use a JLabel rather than creating your own JComponent?

In any case, as some of the comments already said, you need to add your JComponent to a JFrame.

An example below:

Example JFrame class
This class extends JFrame rather than creating and using a JFrame object. It also includes the main method as well, just to avoid another class. The main method runs the GUI on the event dispatch thread. This part is important, but not so much for a beginner.

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class ExampleFrame extends JFrame {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                ExampleFrame frame = new ExampleFrame();
                frame.createAndShow();
            }
        });
    }

    public void createAndShow() {
        getContentPane().add(new HelloComponent());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Hello World Example");
        pack();
        setVisible(true);
    }

}

HelloComponent

As before with your version, but sets the preferred size so that when the JFrame is ‘packed’ it sizes to the component. Additionally, I’ve used the Graphic font height metric to position the y-coordinate, since the drawString method places the y coordinate at the bottom left.

import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JComponent;

public class HelloComponent extends JComponent {

    private final int COMPONENT_WIDTH = 100;
    private final int COMPONENT_HEIGHT = 30;

    public HelloComponent() {
        setPreferredSize(new Dimension(COMPONENT_WIDTH, COMPONENT_HEIGHT));
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawString("Hello World", 0, g.getFontMetrics().getHeight());
    }
}

solved How to use the JComponent [closed]