LazySloth13
LazySloth13

Reputation: 2487

JButton only appears after mouse rolls over it

I have this GUI class:

import java.awt.*;
import javax.swing.*;
public class Exp2 extends JFrame {
    public Exp2 () {
        setLayout(new FlowLayout());
        setSize(360, 360);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel panel1 = new JPanel();
        JPanel panel2 = new JPanel();
        add(panel2);
        add(panel1);
        panel1.paint(null);
        JButton button1 = new JButton("Run");
        panel2.add(button1, BorderLayout.PAGE_END);
    }
    public void paint(Graphics g) {
        g.setColor(Color.green);
        g.fillRect(50, 50, 20, 20);
    }
}

along with this main class:

import javax.swing.JFrame;
class Exp1 extends JFrame {
    public static void main(String[] args) {
        Exp2 box = new Exp2();
    }
}

But the JButton button1 only appears after I roll my mouse over where it should be. What am I doing wrong?

Upvotes: 1

Views: 607

Answers (2)

Reimeus
Reimeus

Reputation: 159754

You never call

super.paint(g);

which paints the containers child components.

Don't do custom painting in a top level container such as JFrame. Rather move the paint functionality to a subclass of JComponent. There override paintComponent rather than paint and invoke super.paintComponent(g). This takes advantage of the improved performance of Swing double buffering mechanism.

See: Performing Custom Painting

Upvotes: 4

christopher
christopher

Reputation: 27346

Call a repaint on the JFrame after you've added everything. Additionally, you need to call super.paint(g) from your paint method.

Upvotes: 2

Related Questions