gpt4 book ai didi

java - 使用 swing 创建滑出工具面板

转载 作者:行者123 更新时间:2023-12-01 18:49:01 25 4
gpt4 key购买 nike

我真的不知道该怎么做。当用户单击按钮时,我希望有一个面板从当前面板下方“滑出”。然后,当他们再次单击该按钮时,它将滑回。

这是一个例子来说明我的意思。请注意它看起来如何位于左侧窗口的“下方”,以及它如何没有完全(但几乎)延伸到底部和顶部:

enter image description here

这是它未退出时的图片(背景中的第二个窗口只是第一个图像[上面的],因为当我拍摄屏幕截图时浏览器位于框架中): enter image description here

最佳答案

两种方法:

  1. 使用JLayeredPane。好处是您可以获得所需的重叠效果。缺点是 JLP 使用空布局,这意味着如果不付出额外的努力,您的 UI 将无法很好地调整大小。

  2. 使用CardLayout。好处是,如果调整大小,您的布局将按照您的要求运行。缺点是你不会获得重叠效果。您的滑出面板右侧只有空白区域。

编辑:我刚刚注意到您的滑出部分不是重叠的,而是向外延伸到右侧。我最初以为你指的是旧的 Outlook UI 之类的东西。在这种情况下,它可以是任何滑出式的,还是必须固定在框架上?

这是一个简单的演示,仅使用 BorderLayout 来实现效果。我发现这个演示和屏幕截图之间的最大区别是:

  1. 演示中框架的边框随着滑出而延伸
  2. 滑出式面板在演示中没有偏移。

代码:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class SlideOutPanelDemo
{
private JPanel pnlMain;
private JPanel pnlTools;
private JFrame frame;

public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new SlideOutPanelDemo().createAndShowGUI();
}
});
}

public void createAndShowGUI()
{
JButton button = new JButton("Tools");
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent event)
{
boolean visible = pnlTools.isVisible();
pnlTools.setVisible(! visible);
frame.pack();
}
});

pnlTools = createToolsPanel();
pnlMain = createMainPanel();

JToolBar toolBar = new JToolBar();
toolBar.add(button);

JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.setOpaque(true);
contentPane.add(toolBar, BorderLayout.NORTH);
contentPane.add(pnlMain, BorderLayout.WEST);
contentPane.add(pnlTools, BorderLayout.EAST);

pnlMain.setVisible(true);
pnlTools.setVisible(false);

JFrame.setDefaultLookAndFeelDecorated(true);
frame = new JFrame("Slide Out Panel Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

private JPanel createMainPanel()
{
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder("Main"));
panel.add(new JLabel("Field 1"));
panel.add(new JTextField(20));
panel.add(new JLabel("Field 2"));
panel.add(new JTextField(20));
panel.setSize(1000, 600);

return panel;
}

private JPanel createToolsPanel()
{
JPanel panel = new JPanel();
panel.setBackground(Color.YELLOW);
Border b1 = BorderFactory.createTitledBorder("Tools");
Border b2 = BorderFactory.createLineBorder(Color.BLUE, 2);
panel.setBorder(BorderFactory.createCompoundBorder(b2, b1));
panel.add(new JLabel("Thing 1"));
panel.add(new JLabel("Thing 2"));
panel.setSize(400, 600);

return panel;
}
}

关于java - 使用 swing 创建滑出工具面板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16484362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com