在使用JAVA SWING做界面的时候,不同的场景我们需要使用不同的菜单栏等功能。在其他的界面插件或框架中想做出菜单栏的按钮切换工具栏的功能很简单,然而在Swing中却不能直接做出这样的功能。下面,我将给大家介绍一下如何用Java swing做出菜单栏控制工具栏切换的两种方法。
一:Java Swing Ribbon(Flamingo)
Ribbon即功能区,是新的 Microsoft Office Fluent 用户界面 (UI) 的一部分。功能区包含一些用于创建、编辑和导出仪表板及其元素的上下文工具。它是一个收藏了命令按钮和图示的面板。它把命令组织成一组"标签",每一组包含了相关的命令。每一个应用程序都有一个不同的标签组,展示了程序所提供的功能。在每个标签里,各种的相关的选项被组在一起。Windows Ribbon是一个Windows Vista或Windows 7自带的GUI构架,外形更加华丽。(该段文字来自于百度百科)
Ribbon可以做出office风格的UI界面。对这个框架有兴趣的可以转到(https://blog.csdn.net/ghuil/article/details/40687023)有对Java Swing Ribbon(Flamingo)的详细描述。ribbon做出的界面风格如下图所示。
然而用ribbon做界面的话,主框架Frame必须要继承JRibbonFrame,整体的框架必须是在JRibbonFrame上的。那么如果我们不想用这个JRibbonFrame,我们怎么在Java swing中做出菜单栏控制工具栏的效果呢,这就需要用到我们的第二种方法。
二:用选项卡窗格JTabbedPane
实现效果:
代码实现:
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
public class test {
public static JPanel p_1 = null;
public static void main(String[] args) {
JFrame jf = new JFrame("测试窗口");
jf.setSize(600, 600);
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jf.setLocationRelativeTo(null);
p_1 = new JPanel(new BorderLayout());
// 创建选项卡面板
JTabbedPane tabbedPane = new JTabbedPane();
JToolBar toolBar3 = new JToolBar();
toolBar3.setLayout(new FlowLayout(FlowLayout.LEFT, 15, 10));
JToolBar toolBar1 = new JToolBar();
toolBar1.setLayout(new FlowLayout(FlowLayout.LEFT, 15, 10));
JToolBar toolBar2 = new JToolBar();
toolBar2.setLayout(new FlowLayout(FlowLayout.LEFT,15, 10));
tabbedPane.addTab("菜单1", toolBar1);
JButton vertical = new JButton("选项1");
JButton horizontal = new JButton("选项2");
toolBar1.add(vertical);
toolBar1.add(horizontal);
tabbedPane.addTab("菜单2", toolBar2);
JButton button8 = new JButton("选项1");
JButton button9 = new JButton("选项2");
JButton button10 = new JButton("选项3");
toolBar2.add(button8);
toolBar2.add(button9);
toolBar2.add(button10);
tabbedPane.addTab("菜单3", toolBar3);
JButton button1 = new JButton("选项1");
JButton button2 = new JButton("选项2");
toolBar3.add(button1);
toolBar3.add(button2);
jf.getContentPane().add(tabbedPane, BorderLayout.NORTH);
jf.getContentPane().add(p_1,BorderLayout.CENTER);
// 添加选项卡选中状态改变的监听器
tabbedPane.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
System.out.println("当前选中的选项卡: " + tabbedPane.getSelectedIndex());
}
});
// 设置默认选中的选项卡
tabbedPane.setSelectedIndex(1);
jf.setVisible(true);
}
}
下面是之前用此方法做的一个项目的主界面的菜单和工具栏部分。