我有一个带有2个JFrameJPanel:一个PaintPanel(带有paint()方法)和一个ButtonPanel(带有按钮)。当我调用repaint()PaintPanel(但单击按钮)时,ButtonPanel的按钮被绘制在PaintPanel中!它是不可点击的或其他任何东西,仅存在于此。

我尝试使用以下代码重新创建问题:

public class Main {

    public static void main(String[] args) {
        JFrame frame = new JFrame("frame");
        frame.setSize(400,400);
        frame.setLayout(new GridLayout(2,1));
        PaintPanel paint = new PaintPanel();
        ButtonPanel buttons = new ButtonPanel(paint);
        frame.add(paint);
        frame.add(buttons);
        frame.setVisible(true);
    }
}

public class PaintPanel extends JPanel{
    public void paint(Graphics g){
        g.drawRect(10, 10, 10, 10);
    }
}

public class ButtonPanel extends JPanel implements ActionListener{

    private PaintPanel paintPanel;

    public ButtonPanel(PaintPanel paintPanel){
        this.paintPanel=paintPanel;
        JButton button = new JButton("button");
        button.addActionListener(this);
        add(button);
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        paintPanel.repaint();
    }
}

这重现了我遇到的问题(对奇数代码标记感到抱歉,似乎无法正确解决)。

我真的希望你们中的一个知道这里发生了什么,因为我不知道...

最佳答案

首先,您应该覆盖paintComponent()而不是paint()。在进行某些面板定制时,这是Swing最佳实践的一部分。

其次,以下是对我有用的代码(我不知道为什么您的代码不是:S):

public class Main {

    public static void main(String[] args) {

        JFrame frame = new JFrame("frame");
        frame.setSize(400, 400);
        // frame.setLayout(new GridLayout(2, 1));
        PaintPanel paint = new PaintPanel();
        ButtonPanel buttons = new ButtonPanel(paint);
        // frame.add(paint);
        // frame.add(buttons);
        frame.setVisible(true);

        JPanel pan = new JPanel(new BorderLayout());
        pan.add(paint);
        pan.add(buttons, BorderLayout.SOUTH);
        frame.add(pan);

    }
}

class PaintPanel extends JPanel {

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(new Color(new Random().nextInt()));
        g.drawRect(10, 10, 10, 10);
    }
}

class ButtonPanel extends JPanel implements ActionListener {

    private final PaintPanel paintPanel;

    public ButtonPanel(PaintPanel paintPanel) {

        this.paintPanel = paintPanel;
        JButton button = new JButton("button");
        button.addActionListener(this);
        add(button);
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
        if (getParent() != null) {
            getParent().repaint();
        }
    }
}

09-05 14:51