1

我有这个 GUI 类:

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);
    }
}

连同这个主要课程:

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

但是 JButtonbutton1仅在我将鼠标移到它应该在的位置后才会出现。我究竟做错了什么?

4

2 回答 2

4

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

于 2013-05-13T15:18:15.447 回答
2

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

于 2013-05-13T15:18:12.393 回答