繁体   English   中英

如果JPanel填满整个屏幕,它将不会移动

[英]JPanel won't move if it fills the screen

首先,对模糊的标题感到抱歉,我不知道如何用句子表达问题。

我有一个简单的程序,当单击一个按钮时,一个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);
    }       
}

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

希望有人可以帮助:)

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

您不应该是:

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

如果要为组件设置动画,则当计时器触发时,可以使用setLocation(...)或setSize()或setBounds()。 该组件将自动重新粉刷。

我不知道解决此问题是否可以解决您的问题,但是当前的方法是错误的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM