5

我有一个JFrame带有 2JPanel的:a PaintPanel(带有paint()方法)和 a 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();           
    }
}

这会重现我遇到的问题(对不起,奇怪的代码标记,似乎无法正确处理)。

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

4

1 回答 1

6

首先,您应该覆盖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();
        }
    }
}
于 2012-08-31T20:46:16.187 回答