重绘时JButton复制了吗?

Luc*_*ius 5 java swing jpanel repaint jbutton

我有一个JFrame2 JPanel: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();           
    }
}
Run Code Online (Sandbox Code Playgroud)

这可以重现我的问题(对于奇怪的代码标记感到遗憾,似乎无法正确).

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

aym*_*ric 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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 对于paintComponent和super.paintCompont,为+1.你需要记住@aymeric,重复使用Graphics对象,所以如果你没有花时间确保你先清理它,你最终会得到意想不到的油漆文物 (2认同)
  • +1使用`super.paintComponent()`来兑现[不透明度](http://java.sun.com/products/jfc/tsc/articles/painting/index.html#props)属性. (2认同)