Java 在JPanel中左右移动

Java 在JPanel中左右移动,java,swing,jpanel,toolbar,Java,Swing,Jpanel,Toolbar,我想动态地向JPanel添加一些按钮,当我添加它时,它只显示固定数量的按钮 因此,我想添加一个左右移动来查看所有按钮 我们如何做到这一点,是否有java组件可以做到这一点 public class TestJPanel extends JFrame { JPanel statusBar; public TestJPanel() { setLayout(new BorderLayout()); statusBar = new JPanel(); statusBar.se

我想动态地向JPanel添加一些按钮,当我添加它时,它只显示固定数量的按钮

因此,我想添加一个左右移动来查看所有按钮

我们如何做到这一点,是否有java组件可以做到这一点

public class TestJPanel extends JFrame {
JPanel statusBar;
public TestJPanel() {
    setLayout(new BorderLayout());
    statusBar = new JPanel();
    statusBar.setLayout(new BoxLayout(statusBar, BoxLayout.LINE_AXIS));
    add("South", statusBar);
    for (int i = 1; i < 20; i++) {
        statusBar.add(new Button("Button" + i));
    }
} }
公共类TestJPanel扩展了JFrame{
JPanel状态栏;
公共测试面板(){
setLayout(新的BorderLayout());
statusBar=新的JPanel();
statusBar.setLayout(新的BoxLayout(statusBar,BoxLayout.LINE_轴));
添加(“南”,状态栏);
对于(int i=1;i<20;i++){
添加(新按钮(“按钮”+i));
}
} }
公共测试面板()
{
setLayout(新的BorderLayout());
statusBar=新的JPanel();
statusBar.setLayout(新的BoxLayout(statusBar,BoxLayout.LINE_轴));
JScrollPane scrollPane=新的JScrollPane();
scrollPane.setViewportView(状态栏)
添加(滚动窗格,BorderLayout.SOUTH);
对于(int i=1;i<20;i++){
添加(新按钮(“按钮”+i));
}
} 

如果外观不满足您的要求,请参见示例并阅读有关自定义外观和感觉的内容

以下是我使用的一些旧代码,它们将根据需要自动添加/删除左/右按钮:

import java.awt.*;
import java.util.List;
import java.util.ArrayList;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.basic.*;


public class ScrollContainer extends JPanel
    implements ActionListener, ComponentListener
{
    private Container container;
    private List<Component> removedComponents = new ArrayList<Component>();
    private JButton forwardButton;
    private JButton backwardButton;

    public ScrollContainer(Container container)
    {
        this.container = container;
        setLayout( new BorderLayout(5, 0) );
        addComponentListener( this );

        //  Create buttons to control scrolling

        backwardButton = new BasicArrowButton( BasicArrowButton.WEST );
        configureButton( backwardButton );
        forwardButton = new BasicArrowButton( BasicArrowButton.EAST);
        configureButton( forwardButton );

        //  Layout the panel

        add( backwardButton, BorderLayout.WEST );
        add( container );
        add( forwardButton, BorderLayout.EAST );
    }

    //  Implement the ComponentListener

    public void componentResized(ComponentEvent e)
    {
        //  When all components cannot be shown, add the forward button

        int freeSpace = getSize().width - container.getPreferredSize().width;

        if (backwardButton.isVisible())
            freeSpace -= backwardButton.getPreferredSize().width;

        forwardButton.setVisible( freeSpace < 0 );

        //  We have free space, redisplay removed components

        while (freeSpace > 0 && ! removedComponents.isEmpty())
        {
            if (removedComponents.size() == 1)
                freeSpace += backwardButton.getPreferredSize().width;

            Object o = removedComponents.get(removedComponents.size() - 1);
            Component c = (Component)o;
            freeSpace -= c.getSize().width;

            if (freeSpace >= 0)
            {
                container.add(c, 0);
                removedComponents.remove(removedComponents.size() - 1);
            }
        }

        //  Some components still not shown, add the backward button

        backwardButton.setVisible( !removedComponents.isEmpty() );

//      repaint();

    }

    public void componentMoved(ComponentEvent e) {}
    public void componentShown(ComponentEvent e) {}
    public void componentHidden(ComponentEvent e) {}

    //  Implement the ActionListener

    public void actionPerformed(ActionEvent e)
    {
        Object source = e.getSource();

        //  Scroll the components in the container

        if (source == forwardButton)
            scrollForward();
        else
            scrollBackward();
    }

    /*
     *  Simulate scrolling forward
     *  by remove the first component from the container
     */
    private void scrollForward()
    {
        if (container.getComponentCount() == 1)
            return;

        //  Remove and save the first component

        Component c = container.getComponent(0);
        container.remove( c );
        removedComponents.add( c );

        //  Allow for backwards scrolling

        backwardButton.setVisible( true );

        //  All components are showing, hide the forward button

        int backwardButtonWidth = backwardButton.getPreferredSize().width;
        int containerWidth = container.getPreferredSize().width;
        int panelWidth = getSize().width;

        if (backwardButtonWidth + containerWidth <= panelWidth)
            forwardButton.setVisible( false );

        //  Force a repaint of the panel

        revalidate();
        repaint();
    }

    /*
     *  Simulate scrolling backward
     *  by adding a removed component back to the container
     */
    private void scrollBackward()
    {
        if (removedComponents.isEmpty())
            return;

        //  Add a removed component back to the container

        Object o = removedComponents.remove(removedComponents.size() - 1);
        Component c = (Component)o;
        container.add(c, 0);

        //  Display scroll buttons when necessary

        if (removedComponents.isEmpty())
            backwardButton.setVisible( false );

        forwardButton.setVisible( true );
        revalidate();
        repaint();
    }

    private void configureButton(JButton button)
    {
        button.setVisible( false );
        button.addActionListener( this );
    }

    private static void createAndShowGUI()
    {
        JToolBar toolBar = new JToolBar();
        toolBar.setFloatable(false);
        toolBar.add( new JButton("one") );
        toolBar.add( new JButton("two222222") );
        toolBar.add( new JButton("three") );
        toolBar.add( new JButton("four") );
        toolBar.add( new JButton("five") );
        toolBar.add( new JButton("six666666666") );
        toolBar.add( new JButton("seven") );
        toolBar.add( new JButton("eight") );
        toolBar.add( new JButton("nine9999999") );
        toolBar.add( new JButton("ten") );
        ScrollContainer container = new ScrollContainer(toolBar);

        JFrame frame = new JFrame("Scroll Container");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(container, BorderLayout.NORTH);
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
    }
}
import java.awt.*;
导入java.util.List;
导入java.util.ArrayList;
导入java.awt.event.*;
导入javax.swing.*;
导入javax.swing.plaf.basic.*;
公共类ScrollContainer扩展了JPanel
实现ActionListener、ComponentListener
{
私人货柜;
private List removedComponents=new ArrayList();
私有JButton转发按钮;
私有JButton backwardButton;
公共滚动容器(容器)
{
this.container=容器;
setLayout(新边界布局(5,0));
addComponentListener(此);
//创建按钮以控制滚动
backwardButton=新的BasicArrowButton(BasicArrowButton.WEST);
配置按钮(后退按钮);
forwardButton=新的BasicArrowButton(BasicArrowButton.EAST);
配置按钮(转发按钮);
//布局面板
添加(后退按钮,BorderLayout.WEST);
添加(容器);
添加(前进按钮,BorderLayout.EAST);
}
//实现ComponentListener
公共无效组件已恢复(组件事件e)
{
//当无法显示所有组件时,添加前进按钮
int freeSpace=getSize().width-container.getPreferredSize().width;
if(backwardButton.isVisible())
freeSpace-=backwardButton.getPreferredSize().width;
forwardButton.setVisible(自由空间<0);
//我们有自由空间,重新显示移除的组件
while(freeSpace>0&!removedComponents.isEmpty())
{
如果(removedComponents.size()==1)
freeSpace+=backwardButton.getPreferredSize().width;
对象o=removedComponents.get(removedComponents.size()-1);
组分c=(组分)o;
freeSpace-=c.getSize().width;
如果(自由空间>=0)
{
容器。添加(c,0);
removedComponents.remove(removedComponents.size()-1);
}
}
//某些组件仍未显示,请添加“后退”按钮
backwardButton.setVisible(!removedComponents.isEmpty());
//重新油漆();
}
public void componentMoved(ComponentEvent e){}
显示的公共无效组件(组件事件e){}
public void componentHidden(ComponentEvent e){}
//实现ActionListener
已执行的公共无效操作(操作事件e)
{
对象源=e.getSource();
//滚动容器中的组件
如果(源==forwardButton)
前滚();
其他的
向后滚动();
}
/*
*模拟向前滚动
*通过从容器中移除第一个组件
*/
私有void scrollForward()
{
if(container.getComponentCount()==1)
返回;
//删除并保存第一个组件
组件c=容器.getComponent(0);
容器。移除(c);
移除的组件。添加(c);
//允许向后滚动
backwardButton.setVisible(真);
//显示所有组件,隐藏“前进”按钮
int backwardButtonWidth=backwardButton.getPreferredSize().width;
int containerWidth=container.getPreferredSize().width;
intpanelwidth=getSize().width;

如果(backwardButtonWidth+containerWidth我得到了一个解决方案,我们可以使用JViewport实现左右导航

public class StatusBar extends JFrame {
private final JPanel statusBar; 
private final JPanel leftrightPanel;
private final JPanel myPane;
private final JButton rightButton;
private final JButton leftButton;
private final JViewport viewport;
private final JPanel iconsPanel;
private JButton button;   
public StatusBar() {
    setLayout(new BorderLayout());
    statusBar = new JPanel();
    statusBar.setLayout(new BorderLayout());
    iconsPanel = new JPanel();
    iconsPanel.setLayout(new BoxLayout(iconsPanel, BoxLayout.LINE_AXIS));
    iconsPanel.setBackground(Color.LIGHT_GRAY);
    viewport = new JViewport();
    viewport.setView(iconsPanel);
    leftrightPanel = new JPanel();
    leftrightPanel.setBackground(Color.WHITE);
    rightButton = new BasicArrowButton(BasicArrowButton.WEST);
    rightButton.addActionListener((ActionEvent e) -> {
        int iconsPanelStartX = iconsPanel.getX();
        if (iconsPanelStartX < 0) {
            Point origin = viewport.getViewPosition();
            if (Math.abs(iconsPanelStartX) < 20) {
                origin.x -= Math.abs(iconsPanelStartX);
            } else {
                origin.x -= 20;
            }
            viewport.setViewPosition(origin);
        }
    });
    leftButton = new BasicArrowButton(BasicArrowButton.EAST);
    leftButton.addActionListener((ActionEvent e) -> {
        Point origin = viewport.getViewPosition();
        origin.x += 20;
        viewport.setViewPosition(origin);
    });
    leftrightPanel.add(rightButton);
    leftrightPanel.add(leftButton);
    statusBar.add(viewport);
    statusBar.add(leftrightPanel, BorderLayout.LINE_END);
    add(statusBar,BorderLayout.SOUTH);
    myPane = new JPanel();
    add(myPane, BorderLayout.CENTER);
    for (int i = 1; i < 20; i++) {
        button =new JButton("Button " + i);
        iconsPanel.add(button);
    }
}}
公共类状态栏扩展JFrame{
专用最终JPanel状态栏;
私人最终JPanel leftrightPanel;
私人最终JPanel myPane;
私有最终JButton rightButton;
私有最终JButton leftButton;
私有最终视口;
私人最终JPanel iconsPanel;
私人按钮;
公共状态栏(){
setLayout(新的BorderLayout());
statusBar=新的JPanel();
statusBar.setLayout(新的BorderLayout());
IConPanel=新的JPanel();
IConPanel.setLayout(新的BoxLayout(IConPanel,BoxLayout.LINE_轴));
iconsPanel.挫折背景(颜色:浅灰色);
viewport=newjviewport();
viewport.setView(IConPanel);
leftrightPanel=新的JPanel();
leftrightPanel.setBackground(颜色:白色);
rightButton=新的BasicArrowButton(BasicArrowButton.WEST);
rightButton.addActionListener((ActionEvent e)->{
int IConPanelStartX=IConPanel.getX();
如果(IConPanelStartX<0){
点原点=viewport.getViewPosition();
如果(数学abs(IConPanelStartX)<20){
origin.x-=Math.abs(IConPanelStartx);
}否则{
原点x-=20;
}
viewport.setViewPosition(原点);
}
});
leftButton=新车
public class StatusBar extends JFrame {
private final JPanel statusBar; 
private final JPanel leftrightPanel;
private final JPanel myPane;
private final JButton rightButton;
private final JButton leftButton;
private final JViewport viewport;
private final JPanel iconsPanel;
private JButton button;   
public StatusBar() {
    setLayout(new BorderLayout());
    statusBar = new JPanel();
    statusBar.setLayout(new BorderLayout());
    iconsPanel = new JPanel();
    iconsPanel.setLayout(new BoxLayout(iconsPanel, BoxLayout.LINE_AXIS));
    iconsPanel.setBackground(Color.LIGHT_GRAY);
    viewport = new JViewport();
    viewport.setView(iconsPanel);
    leftrightPanel = new JPanel();
    leftrightPanel.setBackground(Color.WHITE);
    rightButton = new BasicArrowButton(BasicArrowButton.WEST);
    rightButton.addActionListener((ActionEvent e) -> {
        int iconsPanelStartX = iconsPanel.getX();
        if (iconsPanelStartX < 0) {
            Point origin = viewport.getViewPosition();
            if (Math.abs(iconsPanelStartX) < 20) {
                origin.x -= Math.abs(iconsPanelStartX);
            } else {
                origin.x -= 20;
            }
            viewport.setViewPosition(origin);
        }
    });
    leftButton = new BasicArrowButton(BasicArrowButton.EAST);
    leftButton.addActionListener((ActionEvent e) -> {
        Point origin = viewport.getViewPosition();
        origin.x += 20;
        viewport.setViewPosition(origin);
    });
    leftrightPanel.add(rightButton);
    leftrightPanel.add(leftButton);
    statusBar.add(viewport);
    statusBar.add(leftrightPanel, BorderLayout.LINE_END);
    add(statusBar,BorderLayout.SOUTH);
    myPane = new JPanel();
    add(myPane, BorderLayout.CENTER);
    for (int i = 1; i < 20; i++) {
        button =new JButton("Button " + i);
        iconsPanel.add(button);
    }
}}