微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java滑动JPanels

我有一个显示各种按钮的菜单,我可以让按钮在点击时调用各自的JPanels.事情是我想让Jpanel在调用时滑入而不是瞬间弹出.我尝试使用补间引擎和 Java初学者,我发现它真的很难,所以我决定使用定时动画.我能够让Jpanel在顶部滑到一边,但由于某种原因,下一个面板不想显示,我真的很累,有人可以帮忙!代码如下:
public class Listener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {

        new Timer(0,new ActionListener() {
           public void actionPerformed(ActionEvent e) {                

              mainpane.setLocation(mainpane.getX() - 10,0);
              if (mainpane.getX() + mainpane.getWidth() == 0) 
              {
                 ((Timer) e.getSource()).stop();
                   System.out.println("Timer stopped");
              } 
           }
        }).start();   
   } 
}

解决方法

滑动面板可能很棘手.这是一些入门代码.修改以适应
您的需求.根据需要添加错误检查和异常处理.

此示例使用JButtons和JTree作为内容,但您可以使用几乎任何类型的内容.

用法

static public void main(final String[] args) throws Exception {
    SwingUtilities.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            final JFrame jFrame = new JFrame() {
                {
                    final PanelSlider42<JFrame> slider = new PanelSlider42<JFrame>(this);
                    final JPanel jPanel = slider.getBasePanel();

                    slider.addComponent(new JButton("1"));
                    slider.addComponent(new JButton("22"));
                    slider.addComponent(new JButton("333"));
                    slider.addComponent(new JButton("4444"));

                    getContentPane().add(jPanel);
                    setSize(300,300);
                    setLocationRelativeto(null);
                    setDefaultCloSEOperation(JFrame.disPOSE_ON_CLOSE);
                    setVisible(true);
                }
            };
        }
    });
}

impl很冗长……

package com.java42.example.code;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseMotionAdapter;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.jdialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JWindow;
import javax.swing.SwingUtilities;

public class PanelSlider42<ParentType extends Container> {

private static final int           RIGHT             = 0x01;
private static final int           LEFT              = 0x02;
private static final int           TOP               = 0x03;
private static final int           BottOM            = 0x04;
private final JPanel               basePanel         = new JPanel();
private final ParentType           parent;
private final Object               lock              = new Object();
private final ArrayList<Component> jPanels           = new ArrayList<Component>();
private final boolean              useSlideButton    = true;
private boolean                    isSlideInProgress = false;

private final JPanel               glasspane;
{
    glasspane = new JPanel();
    glasspane.setopaque(false);
    glasspane.addMouseListener(new MouseAdapter() {
    });
    glasspane.addMouseMotionListener(new MouseMotionAdapter() {
    });
    glasspane.addKeyListener(new KeyAdapter() {
    });
}

public PanelSlider42(final ParentType parent) {
    if (parent == null) {
        throw new RuntimeException("ProgramCheck: Parent can not be null.");
    }
    if ((parent instanceof JFrame) || (parent instanceof jdialog) || (parent instanceof JWindow) || (parent instanceof JPanel)) {
    }
    else {
        throw new RuntimeException("ProgramCheck: Parent type not supported. " + parent.getClass().getSimpleName());
    }
    this.parent = parent;
    attach();
    basePanel.setSize(parent.getSize());
    basePanel.setLayout(new BorderLayout());
    if (useSlideButton) {
        final JPanel statusPanel = new JPanel();
        basePanel.add(statusPanel,BorderLayout.soUTH);
        statusPanel.add(new JButton("Slide Left") {
            private static final long serialVersionUID = 9204819004142223529L;
            {
                setMargin(new Insets(0,0));
            }
            {
                addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(final ActionEvent e) {
                        slideLeft();
                    }
                });
            }
        });
        statusPanel.add(new JButton("Slide Right") {
            {
                setMargin(new Insets(0,0));
            }
            private static final long serialVersionUID = 9204819004142223529L;
            {
                addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(final ActionEvent e) {
                        slideRight();
                    }
                });
            }
        });
        statusPanel.add(new JButton("Slide Up") {
            {
                setMargin(new Insets(0,0));
            }
            private static final long serialVersionUID = 9204819004142223529L;
            {
                addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(final ActionEvent e) {
                        slidetop();
                    }
                });
            }
        });
        statusPanel.add(new JButton("Slide Down") {
            {
                setMargin(new Insets(0,0));
            }
            private static final long serialVersionUID = 9204819004142223529L;
            {
                addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(final ActionEvent e) {
                        slideBottom();
                    }
                });
            }
        });
    }
}

public JPanel getBasePanel() {
    return basePanel;
}

private void attach() {
    final ParentType w = this.parent;
    if (w instanceof JFrame) {
        final JFrame j = (JFrame) w;
        if (j.getContentPane().getComponents().length > 0) {
            throw new RuntimeException("ProgramCheck: Parent already contains content.");
        }
        j.getContentPane().add(basePanel);
    }
    if (w instanceof jdialog) {
        final jdialog j = (jdialog) w;
        if (j.getContentPane().getComponents().length > 0) {
            throw new RuntimeException("ProgramCheck: Parent already contains content.");
        }
        j.getContentPane().add(basePanel);
    }
    if (w instanceof JWindow) {
        final JWindow j = (JWindow) w;
        if (j.getContentPane().getComponents().length > 0) {
            throw new RuntimeException("ProgramCheck: Parent already contains content.");
        }
        j.getContentPane().add(basePanel);
    }
    if (w instanceof JPanel) {
        final JPanel j = (JPanel) w;
        if (j.getComponents().length > 0) {
            throw new RuntimeException("ProgramCheck: Parent already contains content.");
        }
        j.add(basePanel);
    }
}

public void addComponent(final Component component) {
    if (jPanels.contains(component)) {
    }
    else {
        jPanels.add(component);
        if (jPanels.size() == 1) {
            basePanel.add(component);
        }
        component.setSize(basePanel.getSize());
        component.setLocation(0,0);
    }
}

public void removeComponent(final Component component) {
    if (jPanels.contains(component)) {
        jPanels.remove(component);
    }
}

public void slideLeft() {
    slide(LEFT);
}

public void slideRight() {
    slide(RIGHT);
}

public void slidetop() {
    slide(TOP);
}

public void slideBottom() {
    slide(BottOM);
}

private void enableuserInput(final ParentType w) {
    if (w instanceof JFrame) {
        ((JFrame) w).getGlasspane().setVisible(false);
    }
    if (w instanceof jdialog) {
        ((jdialog) w).getGlasspane().setVisible(false);
    }
    if (w instanceof JWindow) {
        ((JWindow) w).getGlasspane().setVisible(false);
    }
}

private void disableuserInput(final ParentType w) {
    if (w instanceof JFrame) {
        ((JFrame) w).setGlasspane(glasspane);
    }
    if (w instanceof jdialog) {
        ((jdialog) w).setGlasspane(glasspane);
    }
    if (w instanceof JWindow) {
        ((JWindow) w).setGlasspane(glasspane);
    }
    glasspane.setVisible(true);
}

private void enableTransparentOverylay() {
    if (parent instanceof JFrame) {
        ((JFrame) parent).getContentPane().setBackground(jPanels.get(0).getBackground());
        parent.remove(basePanel);
        parent.validate();
    }
    if (parent instanceof jdialog) {
        ((jdialog) parent).getContentPane().setBackground(jPanels.get(0).getBackground());
        parent.remove(basePanel);
        parent.validate();
    }
    if (parent instanceof JWindow) {
        ((JWindow) parent).getContentPane().setBackground(jPanels.get(0).getBackground());
        parent.remove(basePanel);
        parent.validate();
    }
}

private void slide(final int slideType) {
    if (!isSlideInProgress) {
        isSlideInProgress = true;
        final Thread t0 = new Thread(new Runnable() {
            @Override
            public void run() {
                parent.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                disableuserInput(parent);
                slide(true,slideType);
                enableuserInput(parent);
                parent.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                isSlideInProgress = false;
            }
        });
        t0.setDaemon(true);
        t0.start();
    }
    else {
        Toolkit.getDefaultToolkit().beep();
    }
}

private void slide(final boolean useLoop,final int slideType) {
    if (jPanels.size() < 2) {
        System.err.println("Not enough panels");
        return;
    }
    synchronized (lock) {
        Component componentOld = null;
        Component componentNew = null;
        if ((slideType == LEFT) || (slideType == TOP)) {
            componentNew = jPanels.remove(jPanels.size() - 1);
            componentOld = jPanels.get(0);
            jPanels.add(0,componentNew);
        }
        if ((slideType == RIGHT) || (slideType == BottOM)) {
            componentOld = jPanels.remove(0);
            jPanels.add(componentOld);
            componentNew = jPanels.get(0);
        }
        final int w = componentOld.getWidth();
        final int h = componentOld.getHeight();
        final Point p1 = componentOld.getLocation();
        final Point p2 = new Point(0,0);
        if (slideType == LEFT) {
            p2.x += w;
        }
        if (slideType == RIGHT) {
            p2.x -= w;
        }
        if (slideType == TOP) {
            p2.y += h;
        }
        if (slideType == BottOM) {
            p2.y -= h;
        }
        componentNew.setLocation(p2);
        int step = 0;
        if ((slideType == LEFT) || (slideType == RIGHT)) {
            step = (int) (((float) parent.getWidth() / (float) Toolkit.getDefaultToolkit().getScreenSize().width) * 40.f);
        }
        else {
            step = (int) (((float) parent.getHeight() / (float) Toolkit.getDefaultToolkit().getScreenSize().height) * 20.f);
        }
        step = step < 5 ? 5 : step;
        basePanel.add(componentNew);
        basePanel.revalidate();
        if (useLoop) {
            final int max = (slideType == LEFT) || (slideType == RIGHT) ? w : h;
            final long t0 = System.currentTimeMillis();
            for (int i = 0; i != (max / step); i++) {
                switch (slideType) {
                    case LEFT: {
                        p1.x -= step;
                        componentOld.setLocation(p1);
                        p2.x -= step;
                        componentNew.setLocation(p2);
                        break;
                    }
                    case RIGHT: {
                        p1.x += step;
                        componentOld.setLocation(p1);
                        p2.x += step;
                        componentNew.setLocation(p2);
                        break;
                    }
                    case TOP: {
                        p1.y -= step;
                        componentOld.setLocation(p1);
                        p2.y -= step;
                        componentNew.setLocation(p2);
                        break;
                    }
                    case BottOM: {
                        p1.y += step;
                        componentOld.setLocation(p1);
                        p2.y += step;
                        componentNew.setLocation(p2);
                        break;
                    }
                    default:
                        new RuntimeException("ProgramCheck").printstacktrace();
                        break;
                }

                try {
                    Thread.sleep(500 / (max / step));
                } catch (final Exception e) {
                    e.printstacktrace();
                }
            }
            final long t1 = System.currentTimeMillis();
        }
        componentOld.setLocation(-10000,-10000);
        componentNew.setLocation(0,0);
    }
}
}

原文地址:https://www.jb51.cc/java/128291.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐