1

首先,对于模糊的标题对不起我不知道如何用一句话来表达这个问题。

我有一个简单的程序,当单击按钮时,当另一个 JPanel 被推出时,它会将一个 JPanel 滑入视图。

如果第一个 JPanel 的宽度设置为,getWidth()那么当单击按钮时 JPanel 将不会移动,但是如果我将宽度更改为getWidth() - 1它工作得很好!?!

一个简单的例子如下所示

public class SlidingJPanel extends JFrame{

    public JPanel panel = new JPanel();
    public JPanel panel2 = new JPanel();
    public JLabel label = new JLabel(" SUCCESS!!!!!!!");
    public JButton button = new JButton("TESTING"); 

    public class MyJPanel extends JPanel implements ActionListener{
        public int x = 0;
        public int delay = 70;
        final Timer timer = new Timer(delay,this);

        public MyJPanel(){};

        public void paintComponent(Graphics g)
        {
            super.paintComponent(g);

            button.setBounds(10, 20, 100, 50);
            button.addActionListener(this);
            panel.setBorder(BorderFactory.createLineBorder(Color.black));
            panel.setBounds(x, 0, getWidth(), getHeight());
            panel.add(button);
            panel2.setBorder(BorderFactory.createLineBorder(Color.blue));
            panel2.setBounds(x - getWidth(), 0, getWidth(), getHeight());
            panel2.add(label);
            add(panel);
            add(panel2);
        }

        @Override
        public void actionPerformed(ActionEvent arg0) {
            timer.addActionListener(move);
            timer.start();
        }

        ActionListener move = new ActionListener(){
            public void actionPerformed(ActionEvent e){
                repaint();
                x++;
            }
        };

    }

    public static void main(String args [])
    {         
        new SlidingJPanel();        
    }

    SlidingJPanel()
    {
        Container container = getContentPane();
        MyJPanel panel = new MyJPanel();
        container.add(panel);           
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(500,500);
        setTitle("JPanel Draw Rect Animation");
        setVisible(true);
    }       
}

忽略我可能忽略或错过的任何编码约定这只是一个粗略的草稿。

希望有人可以提供帮助:)

4

1 回答 1

2

paintComponent() 方法仅用于绘画!您无需重写此方法。

你不应该:

  1. 更新组件的属性(即边界、边框)
  2. 向容器中添加组件

如果您想为组件设置动画,那么当计时器触发时,您可以使用 setLocation(...) 或 setSize() 或 setBounds()。该组件将自动重新绘制。

我不知道解决这个问题是否能解决你的问题,但目前的方法是错误的。

于 2013-06-13T17:57:53.967 回答