swing面板和其他组件
面板
JPanel
可以在大布局里设计另一种布局
JScrollPane 滚动面板
它可以显示在文本较多的时候显示水平或垂直滚动条。如JTextArea或JTextField(水平滚动)或JList等可以使用滚动面板
JScrollPane内有一个ViewPort(视口),表示JScrollPane的显示区域,视口内包含一个需要滚动的组件。
构造方法:
- JScrollPane(Component view, int vsbPolicy, int hsbPolicy): view是需要加入视口的组件,vsb和hsb是水平和垂直滚动策略。
 
策略取值  | 
方法:
- setViewportView(Component view): 设置滚动条内组件(最好不要用add,容易出问题)
 - setVerticalScrollBarPolicy(int policy): 垂直滚动条显示策略
 - setHorizontalScrollBarPolicy(int policy): 水平滚动条显示策略
 - setWheelScrollingEnabled(boolean handleWheel):是否响应鼠标,默认响应
 
JSplitPane 分隔面板
分隔面板可以分隔两个组件。组件位置可以是上下或者左右。并且两个组件的分割线可以拉伸。
构造方法:
- JSplitPane(int orientation, boolean continuousLayout, Component leftComponent, Component rightComponent): orientation是分割方向,可以取JSplitPane.HORIZONTAL_SPLIT或JSplitPane.VERTICAL_SPLIT。continuousLayout是拖动分割线时是否重绘组件。如果是false,那么拖动完了才会重绘。后面两个参数时两个组件
 
方法:
- setOrientation(int orientation):设置分割方向
 - setLeftComponent(Component comp):设置左边/上面组件
 - setRightComponent(Component comp)
 - setContinuousLayout(boolean continuousLayout)
 - setOneTouchExpandable(boolean newValue): 分隔条上快速折叠/展开组件小按钮
 - setDividerSize(int newSize): 分隔条宽度
 - setDividerLocation(int location):分隔条位置,相对于左边/上面的像素值
 - setDividerLocation(double proportionalLocation): 这个是在0到1间取值,也是位置。
 
JTabbedPane 选项卡面板
可以通过点击在组件之间进行切换。
构造方法:
- JTabbedPane(int tabPlacement, int tabLayoutPolicy): 选项卡标题的位置, 值为 JTabbedPane.TOP、JTabbedPane.BOTTOM、JTabbedPane.LEFT 或 JTabbedPane.RIGHT, 默认为 TOP。tabLayoutPolicy是选项放不下时放置选项策略。有JTabbedPane.WRAP_TAB_LAYOUT 或 JTabbedPane.SCROLL_TAB_LAYOUT。
 
方法:
- void addTab(String title, Icon icon, Component component, String tip):添加选项,tip是焦点在选项卡时显示的文本。
 - insertTab(String title, Icon icon, Component component, String tip, int index): 指定位置插入选项卡
 - removeTabAt(int index):移除选项卡
 - remove(int index)
 - remove(Component component)
 - removeAll()
 - setSelectedIndex(int index): 设置选中的选项卡
 - getSelectedIndex(): 获得选中的选项卡索引
 - Component getSelectedComponent(): 获得选项卡组件
 - setTitleAt(int index, String title): 设置选项卡标题
 - setIconAt(int index, Icon icon): 设置选项卡图标
 - setEnabledAt(int index, boolean enabled): 设置选项是否可用
 - setComponentAt(int index, Component component):设置组件
 - getTabCount(): 获得选项卡数量
 - setTabComponentAt(int index, Component titleComponent):把一个组件放到标题位置(其他是标题位置就是标题,组件在下面)
 
监听器: addChangeListener(ChangeListener l)
public class Calculate extends JFrame  | 
JLayerPane 层级面板
层级面板允许组件重叠出现,并且把组件分成若干层。层取值-1到n-1
每一层组件位置可以设置编号,编号决定前后。层之间编号越大在前面,层中编号越大越接近底部。
加入层的组件必须要设置位置和大小(width和height),否则不予显示
构造方法:
- JLayerPane()
 
方法:
- add(Component comp, Object layer, int position):因为layer是object,说明不能直接用整型,而是要用Integer类。
 - add(Component comp, Object layer)
 - setLayer(Component c, int layer, int position)
 - setLayer(Component c, int layer)
 - moveToFront(Component c): 把组件移到最顶端的位置
 - moveToBack(Component c)
 - setPosition(Component c, int position):设置组件所在层
 
JDialog和JOptionPane
JOpintionPane是已经实现好的JDialog,以静态方法的形式提供调用。
JOpintionPane提供的调用:
| 方法名 | 描述 | 
|---|---|
| showMessageDialog | 消息对话框,向用户展示一个消息,没有返回值。 | 
| showConfirmDialog | 确认对话框,询问一个问题是否执行。 | 
| showInputDialog | 输入对话框,要求用户提供某些输入。 | 
| showOptionDialog | 选项对话框,上述三项的大统一,自定义按钮文本,询问用户需要点击哪个按钮。 | 
静态方法中的参数:(1) parentComponent: 对话框的父级组件,决定对话框显示的位置,对话框的显示会尽量紧靠组件的中心,如果传 null,则显示在屏幕的中心。
(2) title: 对话框标题。
(3) message: 消息内容。
(4) messageType: 消息类型,主要是提供默认的对话框图标。可能的值为:
JOptionPane.PLAIN_MESSAGE 简单消息(不使用图标)
JOptionPane.INFORMATION_MESSAGE 信息消息(默认)
JOptionPane.QUESTION_MESSAGE 问题消息
JOptionPane.WARNING_MESSAGE 警告消息
JOptionPane.ERROR_MESSAGE 错误消息
(5) icon: 自定义的对话框图标,如果传 null,则图标类型由 messageType 决定。
(6) optionType: 选项按钮的类型。
(7) options、initialValue: 自定义的选项按钮(如果穿 null,则选项按钮由 optionType 决定),以及默认选中的选项按钮。
(8) selectionValues、initialSelectionValue: 提供的输入选项,以及默认选中的选项。
但是不是每种选项都拥有所有参数,下面是每个方法最多的选项
static void showMessageDialog(Component parentComponent,  | 
其中showconfirmDialog的messageType参数可以是JOptionPane.YES_OPTION(是)或JOptionPane.NO_OPTION(否)或JOptionPane.CANCEL_OPTION(取消)或JOptionPane.CLOSED_OPTION(关闭)。也可以是JOptionPane.YES_NO_CANCEL_OPTION;等组合选项。
public class Calculate extends JFrame  | 
注意:showOptionDialog如果后面没有Object[],那么下面的选项是YES_NO_CANCEL_OPTION。并且它的返回值是一个int型,如果点了叉那么返回值是-1.
showInputDialog返回值是输入的信息,
JFileChooser 文件选择器
可以用来打开和保存文件。
构造方法:
- JFileChooser(File currentDirectory):打开文件时默认显示的文件夹。可以使用绝对目录
 
方法:
- setCurrentDirectory(File dir): 设置当前文件夹
 - setFileSelectionMode(int mode):有三种模式。JFileChooser.FILES_ONLY: 只能选文件 或 JFileChooser.DIRECTORIES_ONLY: 只能选文件夹 或 JFileChooser.FILES_AND_DIRECTORIES: 文件和文件夹都可以选。
 - setMultiSelectionEnabled(boolean b):是否可以选多个(默认不允许)
 - addChoosableFileFilter(FileFilter filter): 添加文件类型选择。例如
fileChooser.setFileFilter(new FileNameExtensionFilter("image(*.jpg, *.png, *.gif)", "jpg", "png", "gif"));前面是描述,后面是选择类型。 - setFileFilter(FileFilter filter): 设置默认使用的过滤器
 - setSelectedFile(File file): 设置默认被选中的文件
 - setSelectedFiles(File[] selectedFiles)
 - showOpenDialog(Component parent): 打开对话框(线程会被阻塞),parent是父组件,设置会让对话框显示在父组件中心,如果是null显示在屏幕中心。返回值有JFileChooser.CANCEL_OPTION: 点击了取消或关闭 或 JFileChooser.APPROVE_OPTION: 点击了确认或保存 或 JFileChooser.ERROR_OPTION: 出现错误
 - File getSelectedFile(): 获得选择的文件
 
例:public class Calculate extends JFrame
{
    private File files;
    private FileReader fileReader;
    public Calculate(String name) throws IOException
    {
        super(name);
        JFileChooser fileChooser = new JFileChooser("F:\\系统设置\\Desktop\\我的文档");
        fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("*.zip","zip"));
        fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("*.txt", "txt"));
        fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        fileChooser.setMultiSelectionEnabled(false);
        JButton button = new JButton("open to copy");
        JTextArea textArea = new JTextArea( 40, 40);
        textArea.setSelectedTextColor(Color.YELLOW);
        textArea.setSelectionColor(Color.RED);
        textArea.setCaretColor(Color.BLUE);
        textArea.setWrapStyleWord(false);
        textArea.setFont(new Font(null, Font.PLAIN, 20));
        textArea.setEditable(true);
        JTextField textField = new JTextField("The content of the file will show here");
        textField.setEditable(false);
        textArea.setForeground(Color.RED);
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        JPanel panel1 = new JPanel();
        panel1.setLayout(new BorderLayout());
        panel1.add(button, BorderLayout.NORTH);
        panel1.add(textField, BorderLayout.CENTER);
        panel.add(panel1, BorderLayout.NORTH);
        panel.add(textArea, BorderLayout.CENTER);
        button.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent actionEvent)
            {
                if(fileChooser.showOpenDialog(panel) == JFileChooser.APPROVE_OPTION)
                {
                    files = fileChooser.getSelectedFile();
                }
                else if(fileChooser.showOpenDialog(panel) == JFileChooser.ERROR_OPTION)
                {
                    showMessageDialog(fileChooser, "something wrong", "hello", ERROR_MESSAGE, null);
                }
                try
                {
                    fileReader = new FileReader(files);
                    int c;
                    while((c=fileReader.read()) != -1)
                    {
                        textArea.append(String.valueOf((char) c));
                    }
                    fileReader.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        });
        add(panel);
        setVisible(true);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        pack();
    }
    public static void main(String[] args) throws IOException
    {
        new Calculate("hello");
    }
}
如果想使用系统的ui可以用java.awt.FileDialog
JColorChooser 颜色选择器
提供一个让用户选择颜色的对话框。
构造方法:
- public static Color showDialog(Component component, String title, Color initialColor): 这是JColorChooser的静态方法。Component是父组件,title标题。
 
JMenuBar 菜单
把菜单添加到JFrame后,会在顶部出现。菜单有三种:
- JMenu: 菜单栏上的菜单
 - JMenuBar: 菜单栏
 - JMenuItem, JCheckBoxMenuItem, JRadioButtonMenuItem: 子菜单,表示子菜单\带复选框的子菜单\带单选按钮的子菜单。
 
JMenu、JCheckBoxMenuItem、JRadioButtonMenuItem 均继承自 JMenuItem。
JMenuItem的构造方法:
- JMenuItem(String title, Icon icon): icon是菜单显示的图标
 
把JMenuBar添加到JFrame是用setJmenuBar()方法
JMenuItem常用方法:
- setIcon(Icon defaultIcon)
 - setText(String text)
 - setMnemonic(int mnemonic): 设置快捷键助记符。也就是在标题后面会加一个下划线或其他标识然后再加上这个字母。它是用来提示你按下那个键触发快捷键的。例如: menuItem.setMnemonic(KeyEvent.VK_N);
 - setAccelerator(KeyStroke keyStroke): 设置快捷键。例如:menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.ALT_MASK));
 - setActionCommand(String actionCommand):设置菜单项的Action名称。如果多个菜单项使用同一个监听器就可以用这个方法设置名字用来辨别到底是哪一个触发了。
 
监听器: addActionListener(ActionListener l)
JCheckBoxMenuItem、JRadioButtonMenuItem 常用方法::
其实就是JCheckBoxButton类似的方法.它的监听器是addChangeListener(ChangeListener l)
JMenu常用方法:
- JMenuItem add(JMenuItem menuItem): 添加一个子菜单到JMenu中
 - addSeparator(): 添加一个子菜单分界线
 
public class Menu extends JFrame  | 
JToolBar 工具栏
工具栏显示了一些常用组件。它支持拖动,为了确保可以拖动,可以把它加入到BorderLayout的任意一边,并且不要再其他四边中加入子级
构造方法:
- JToolBar(String name, int orientation): orientation是工具栏方向,可以取SwingConstants.HORIZONTAL或SwingConstants.VERTICAL,默认水平
 
方法:
- Component add(Component comp):添加组件到工具栏
 - addSeparator():添加分割线
 - addSeparator(Dimension size)
 - Component getComponentAtIndex(int index):获取指定位置组件(包括分隔符)
 - setFloatable(boolean b):工具栏是否可以拖动
 - setOrientation(int o)
 - setMargin(Insets m): 设置内边距
 - setBorderPainted(boolean b): 是否绘制边框
 
public class tool extends JFrame  | 
把它拖到左上角又可以固定。
JPopupMenu 右键菜单
这个挺熟悉的,又叫弹出式菜单。它的使用和JToolBar类似。
JInternalFrame 内部窗口
内部窗口是在JFrame内部显示一个完整的子窗口。
在实际使用中,通常将 JInternalFrame 添加到 JDesktopPane 中,由其来维护和显示 JInternalFrame。
方法等和JFrame类似
private static JInternalFrame createInternalFrame() {  | 
DeskTop
DeskTop可以让java程序启动本机上注册的程序。一般程序有
- 打开浏览器
 - 打开邮件
 - 打开文件
 
方法:
- static boolean isDesktopSupported(): 当前平台是否支持此类
 - static Desktop getDesktop(): 获得DeskTop实例
 - browse(URI uri): 启用默认浏览器显示URI
 - open(File file): 启用默认应用程序打开文件
 - edit(File file): 启用默认编辑器编辑文件
 - print(File file): 打印
 - mail(): 启用邮件管理
 - mail(URI mailtoURI): 启用邮件管理并填充URI
 - isSupported(Desktop.Action action): 查看当前平台是否支持上述操作。取值是DeskTop.Action.xxx xxx是上面操作的大写
 
系统剪切板
获得系统剪切板:
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
使用:
  |