Swing

课程:14、Swing之JFrame窗体_哔哩哔哩_bilibili 

 一.JFrame和容器

构造方法
Constructor and Description
JFrame()

构造一个最初不可见的新框架。

JFrame(GraphicsConfiguration gc)

在屏幕设备的指定 GraphicsConfiguration中创建一个 Frame和一个空白标题。

JFrame(String title)

创建一个新的,最初不可见的 Frame与指定的标题。

JFrame(String title, GraphicsConfiguration gc)

创建 JFrame具有指定标题和指定 GraphicsConfiguration屏幕设备的。

                                                                        方法                         

protected voidaddImpl(Component comp, Object constraints, int index)

添加指定的孩子 Component 。

protected JRootPanecreateRootPane()

由构造函数调用方法创建默认值 rootPane 。

protected voidframeInit()

由构造函数调用正确地初始化 JFrame 。

AccessibleContextgetAccessibleContext()

获取与此JFrame关联的AccessibleContext。

ContainergetContentPane()

返回此框架的 contentPane对象。

intgetDefaultCloseOperation()

返回当用户在此框架上启动“关闭”时发生的操作。

ComponentgetGlassPane()

返回此框架的 glassPane对象。

GraphicsgetGraphics()

为此组件创建图形上下文。

JMenuBargetJMenuBar()

返回在此框架上设置的菜单栏。

JLayeredPanegetLayeredPane()

返回此框架的 layeredPane对象。

JRootPanegetRootPane()

返回此框架的 rootPane对象。

TransferHandlergetTransferHandler()

获取 transferHandler属性。

static booleanisDefaultLookAndFeelDecorated()

如果新创建的 JFrame应该具有当前外观提供的窗口装饰,则返回true。

protected booleanisRootPaneCheckingEnabled()

add和 setLayout是否转接到 contentPane 。

protected StringparamString()

返回此 JFrame的字符串表示 JFrame 。

protected voidprocessWindowEvent(WindowEvent e)

处理在此组件上发生的窗口事件。

voidremove(Component comp)

从容器中删除指定的组件。

voidrepaint(long time, int x, int y, int width, int height)

在time毫秒内 time绘制该组件的 time矩形。

voidsetContentPane(Container contentPane)

设置 contentPane属性。

voidsetDefaultCloseOperation(int operation)

设置用户在此框架上启动“关闭”时默认执行的操作。

static voidsetDefaultLookAndFeelDecorated(boolean defaultLookAndFeelDecorated)

提供关于新创建的 JFrame是否应该具有由当前外观提供的窗口装饰(例如边框,窗口小部件以关闭窗口,标题...)的提示。

voidsetGlassPane(Component glassPane)

设置 glassPane属性。

voidsetIconImage(Image image)

将要显示的图像设置为此窗口的图标。

voidsetJMenuBar(JMenuBar menubar)

设置此帧的菜单栏。

voidsetLayeredPane(JLayeredPane layeredPane)

设置 layeredPane属性。

voidsetLayout(LayoutManager manager)

设置 LayoutManager 。

protected voidsetRootPane(JRootPane root)

设置 rootPane属性。

protected voidsetRootPaneCheckingEnabled(boolean enabled)

设置是否向 add和 setLayout的 contentPane 。

voidsetTransferHandler(TransferHandler newHandler)

设置 transferHandler属性,这是一种支持将数据传输到此组件中的机制。

voidupdate(Graphics g)

只要打 paint(g) 。

构造方法
Constructor and Description
Container()

构造一个新的容器。

                                                                        方法 

Modifier and TypeMethod and Description
Componentadd(Component comp)

将指定的组件附加到此容器的末尾。

Componentadd(Component comp, int index)

在给定的位置将指定的组件添加到此容器。

voidadd(Component comp, Object constraints)

将指定的组件添加到此容器的末尾。

voidadd(Component comp, Object constraints, int index)

将指定的组件添加到指定索引处的指定约束的容器中。

Componentadd(String name, Component comp)

将指定的组件添加到此容器。

voidaddContainerListener(ContainerListener l)

添加指定的容器侦听器以从此容器接收容器事件。

protected voidaddImpl(Component comp, Object constraints, int index)

在指定的索引处将指定的组件添加到此容器。

voidaddNotify()

通过将此容器连接到本机屏幕资源来使此容器显示。

voidaddPropertyChangeListener(PropertyChangeListener listener)

将PropertyChangeListener添加到侦听器列表。

voidaddPropertyChangeListener(String propertyName, PropertyChangeListener listener)

将PropertyChangeListener添加到特定属性的侦听器列表中。

voidapplyComponentOrientation(ComponentOrientation o)

设置此 ComponentOrientation属性及其中包含的所有组件。

booleanareFocusTraversalKeysSet(int id)

返回是否为此容器显式定义了给定焦点遍历操作的聚焦遍历键集。

intcountComponents()已弃用

从JDK 1.1版开始,由getComponentCount()替换。

voiddeliverEvent(Event e)已弃用

截至JDK 1.1版,由dispatchEvent(AWTEvent e)取代

voiddoLayout()

使此容器布置其组件。

ComponentfindComponentAt(int x, int y)

找到包含指定位置的可见子组件。

ComponentfindComponentAt(Point p)

找到包含指定点的可见子组件。

floatgetAlignmentX()

返回沿x轴的对齐方式。

floatgetAlignmentY()

返回沿着y轴的对齐。

ComponentgetComponent(int n)

获取此容器中的第n个组件。

ComponentgetComponentAt(int x, int y)

找到包含x,y位置的组件。

ComponentgetComponentAt(Point p)

获取包含指定点的组件。

intgetComponentCount()

获取此面板中的组件数量。

Component[]getComponents()

获取此容器中的所有组件。

intgetComponentZOrder(Component comp)

返回容器内组件的z-order索引。

ContainerListener[]getContainerListeners()

返回在此容器上注册的所有容器侦听器的数组。

Set<AWTKeyStroke>getFocusTraversalKeys(int id)

返回此Container的给定遍历操作的聚焦遍历键集。

FocusTraversalPolicygetFocusTraversalPolicy()

返回将管理此Container的子项的键盘遍历的焦点遍历策略,如果此Container不是焦点循环根,则返回null。

InsetsgetInsets()

确定此容器的插入,这表示容器边框的大小。

LayoutManagergetLayout()

获取此容器的布局管理器。

<T extends EventListener>
T[]
getListeners(<T> listenerType)

返回当前注册为 FooListener的所有对象的数组,在此 Container 。

DimensiongetMaximumSize()

返回此容器的最大大小。

DimensiongetMinimumSize()

返回此容器的最小大小。

PointgetMousePosition(boolean allowChildren)

如果 Container位于鼠标指针下,则返回该指针位于该 Container的坐标空间中,否则返回 null 。

DimensiongetPreferredSize()

返回此容器的首选大小。

Insetsinsets()已弃用

从JDK 1.1版开始,由getInsets() 。

voidinvalidate()

使容器无效。

booleanisAncestorOf(Component c)

检查组件是否包含在此容器的组件层次结构中。

booleanisFocusCycleRoot()

返回此容器是否是焦点遍历循环的根。

booleanisFocusCycleRoot(Container container)

返回指定的Container是否是此Container的焦点遍历循环的焦点循环根。

booleanisFocusTraversalPolicyProvider()

返回此容器是否提供焦点遍历策略。

booleanisFocusTraversalPolicySet()

返回是否为此Container显式设置了重点遍历策略。

booleanisValidateRoot()

指示此容器是否为 验证根 。

voidlayout()已弃用

从JDK 1.1版开始,由doLayout() 。

voidlist(PrintStream out, int indent)

将此容器的列表打印到指定的输出流。

voidlist(PrintWriter out, int indent)

从指定的缩进开始列出指定的打印作者的列表。

Componentlocate(int x, int y)已弃用

自JDK版本1.1起,由getComponentAt(int, int) 。

DimensionminimumSize()已弃用

截至JDK 1.1版,由getMinimumSize()取代。

voidpaint(Graphics g)

涂上容器

voidpaintComponents(Graphics g)

涂抹此容器中的每个组件。

protected StringparamString()

返回一个表示此 Container状态的字符串。

DimensionpreferredSize()已弃用

从JDK 1.1版开始,替换为getPreferredSize() 。

voidprint(Graphics g)

打印容器。

voidprintComponents(Graphics g)

打印此容器中的每个组件。

protected voidprocessContainerEvent(ContainerEvent e)

通过将容器事件发送到任何已注册的ContainerListener对象来处理容器事件。

protected voidprocessEvent(AWTEvent e)

处理此容器上的事件。

voidremove(Component comp)

从此容器中删除指定的组件。

voidremove(int index)

去除组件,通过指定 index ,从这个容器。

voidremoveAll()

从此容器中删除所有组件。

voidremoveContainerListener(ContainerListener l)

删除指定的容器侦听器,使其不再从此容器接收容器事件。

voidremoveNotify()

通过删除其与其本机屏幕资源的连接,使此容器不可显示。

voidsetComponentZOrder(Component comp, int index)

将指定的组件移动到容器中指定的z顺序索引。

voidsetFocusCycleRoot(boolean focusCycleRoot)

设置此容器是否是焦点遍历循环的根。

voidsetFocusTraversalKeys(int id, Set<? extends AWTKeyStroke> keystrokes)

设置此容器的给定遍历操作的焦点遍历键。

voidsetFocusTraversalPolicy(FocusTraversalPolicy policy)

设置焦点遍历策略,将管理此Container的子项的键盘遍历,如果此Container是焦点循环根。

voidsetFocusTraversalPolicyProvider(boolean provider)

设置此容器是否将用于提供焦点遍历策略。

voidsetFont(Font f)

设置此容器的字体。

voidsetLayout(LayoutManager mgr)

设置此容器的布局管理器。

voidtransferFocusDownCycle()

将焦点转移到一个焦点遍历周期。

voidupdate(Graphics g)

更新容器。

voidvalidate()

验证此容器及其所有子组件。

protected voidvalidateTree()

递归地下降容器树,并重新计算标记为需要的任何子树(标记为无效的)的布局。

package com.demo.panel;

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

public class JFrameTest {
    public static void main(String[] args) {

        new MyJFrame().init();
    }
}


class MyJFrame extends JFrame{
    // 使用init初始化窗口
    public void init() {

        // 由于继承关系,有些设置是一样的
        setTitle("fuck");
        setBounds(200,200,200,200);
        setVisible(true);

        // 设置字体,后面参数是设置为居中显示
        JLabel jLabel = new JLabel("Fuck",SwingConstants.CENTER);

        // 将字体添加到窗口
        add(jLabel);

        // 获取一个容器,容器的颜色才是真正的颜色,这点与Frame不同
        Container container = this.getContentPane();
        container.setBackground(Color.yellow);


        // 关闭事件
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }
}

二.JDialog弹窗

构造方法
Constructor and Description
JDialog()

创建一个没有标题的无模式对话框,没有指定的 Frame所有者。

JDialog(Dialog owner)

使用指定的 Dialog作为其所有者创建无模式对话框,并创建一个空的标题。

JDialog(Dialog owner, boolean modal)

创建一个具有空标题和指定模态的对话框,并以其所有者为 Dialog 。

JDialog(Dialog owner, String title)

使用指定的标题和指定的所有者对话框创建无模式对话框。

JDialog(Dialog owner, String title, boolean modal)

创建一个具有指定标题,模态和指定所有者的 Dialog 。

JDialog(Dialog owner, String title, boolean modal, GraphicsConfiguration gc)

创建一个具有指定标题的对话框,所有者为 Dialog ,模式和 GraphicsConfiguration 。

JDialog(Frame owner)

创建一个无模式对话框,其中指定的是 Frame作为其所有者,并且是一个空的标题。

JDialog(Frame owner, boolean modal)

创建一个具有空标题和指定模态的对话框,并以 Frame作为其所有者。

JDialog(Frame owner, String title)

使用指定的标题和指定的所有者框架创建无模式对话框。

JDialog(Frame owner, String title, boolean modal)

创建一个具有指定标题的对话框,所有者为 Frame和模态。

JDialog(Frame owner, String title, boolean modal, GraphicsConfiguration gc)

创建一个具有指定标题的对话框,所有者为 Frame ,模态和 GraphicsConfiguration 。

JDialog(Window owner)

创建一个无模式的对话框,其中指定的是 Window作为其所有者,并且是一个空的标题。

JDialog(Window owner, Dialog.ModalityType modalityType)

创建一个具有空标题和指定模式的对话框,并以其所有者身份创建 Window 。

JDialog(Window owner, String title)

使用指定的标题和所有者创建一个无模式对话框 Window 。

JDialog(Window owner, String title, Dialog.ModalityType modalityType)

创建一个具有指定标题的对话框,所有者为 Window和模态。

JDialog(Window owner, String title, Dialog.ModalityType modalityType, GraphicsConfiguration gc)

创建一个具有指定标题的对话框,所有者为 Window ,模态和 GraphicsConfiguration 。

                                                          方法 

Modifier and TypeMethod and Description
protected voidaddImpl(Component comp, Object constraints, int index)

添加指定的小孩 Component 。

protected JRootPanecreateRootPane()

由构造函数调用方法创建默认值 rootPane 。

protected voiddialogInit()

由构造函数调用正确地初始化 JDialog 。

AccessibleContextgetAccessibleContext()

获取与此JDialog关联的AccessibleContext。

ContainergetContentPane()

返回此对话框的 contentPane对象。

intgetDefaultCloseOperation()

返回用户在此对话框上启动“关闭”时发生的操作。

ComponentgetGlassPane()

返回此对话框的 glassPane对象。

GraphicsgetGraphics()

为此组件创建图形上下文。

JMenuBargetJMenuBar()

返回此对话框上的菜单栏。

JLayeredPanegetLayeredPane()

返回此对话框的 layeredPane对象。

JRootPanegetRootPane()

返回此对话框的 rootPane对象。

TransferHandlergetTransferHandler()

获取 transferHandler财产。

static booleanisDefaultLookAndFeelDecorated()

如果新创建的 JDialog应该具有当前外观提供的窗口装饰,则返回true。

protected booleanisRootPaneCheckingEnabled()

返回是否向 add和 setLayout的 contentPane 。

protected StringparamString()

返回此 JDialog的字符串表示 JDialog 。

protected voidprocessWindowEvent(WindowEvent e)

根据 defaultCloseOperation属性的状态处理窗口事件。

voidremove(Component comp)

从容器中删除指定的组件。

voidrepaint(long time, int x, int y, int width, int height)

在time毫秒内 time绘制该组件的 time矩形。

voidsetContentPane(Container contentPane)

设置 contentPane属性。

voidsetDefaultCloseOperation(int operation)

设置用户在此对话框上启动“关闭”时默认执行的操作。

static voidsetDefaultLookAndFeelDecorated(boolean defaultLookAndFeelDecorated)

提供一个提示,即新创建的 JDialog是否应该具有当前的外观和感觉提供的窗口装饰(如边框,关闭窗口,标题...)。

voidsetGlassPane(Component glassPane)

设置 glassPane属性。

voidsetJMenuBar(JMenuBar menu)

设置此对话框的菜单栏。

voidsetLayeredPane(JLayeredPane layeredPane)

设置 layeredPane属性。

voidsetLayout(LayoutManager manager)

设置 LayoutManager 。

protected voidsetRootPane(JRootPane root)

设置 rootPane属性。

protected voidsetRootPaneCheckingEnabled(boolean enabled)

设置是否向 add和 setLayout的 contentPane 。

voidsetTransferHandler(TransferHandler newHandler)

设置 transferHandler属性,这是一种支持将数据传输到此组件的机制。

voidupdate(Graphics g)

致电 paint(g) 。

用来被弹出,默认有关闭事件 

package com.demo.panel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JDialogTest {
    public static void main(String[] args) {

        new JDialogSwingTest();
    }
}

class JDialogSwingTest extends JFrame {
    public JDialogSwingTest()  {

        // 基础设置
        setTitle("主窗口");
        setVisible(true);
        setBounds(100,100,400,800);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // 容器:放东西
        Container container = getContentPane();
        // 设置为绝对布局:组件大小固定,不可改变,组件的大小必须设置
        container.setLayout(null);

        // 按钮启动弹出
        JButton jButton = new JButton("Fuck");
        jButton.setBounds(30,30,100,50);
        // 监听器
        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                new MyDialog();
            }
        });

        // 将按钮放进容器
        container.add(jButton);

    }

    // 弹窗
    private class MyDialog extends JDialog {
        public MyDialog() {
            // 弹窗的基础设置
            setTitle("fuck");
            setVisible(true);
            setBounds(200,500,300,300);
            // 对于弹窗来说不用再设置退出监听了,默认可以直接退出

            // 设置了绝对布局,组件就必须设置大小
            Container container = getContentPane();
            container.setLayout(null);

            // 将字体放进容器 
            JLabel jLabel1=new JLabel("JDialog弹窗",SwingConstants.CENTER);
            jLabel1.setBounds(0,0,400,400);
            container.add(jLabel1);
        }
    }
}

三.图标标签ICON

构造方法
Constructor and Description
JLabel()

创建一个没有图像的 JLabel实例,标题为空字符串。

JLabel(Icon image)

使用指定的图像创建一个 JLabel实例。

JLabel(Icon image, int horizontalAlignment)

创建一个具有指定图像和水平对齐的 JLabel实例。

JLabel(String text)

使用指定的文本创建一个 JLabel实例。

JLabel(String text, Icon icon, int horizontalAlignment)

创建具有 JLabel文本,图像和水平对齐的JLabel实例。

JLabel(String text, int horizontalAlignment)

创建一个具有指定文本和水平对齐的 JLabel实例。

                                                                        方法 

protected intcheckHorizontalKey(int key, String message)

验证该键是horizontalAlignment属性的合法值。

protected intcheckVerticalKey(int key, String message)

验证该键是verticalAlignment或verticalTextPosition属性的合法值。

AccessibleContextgetAccessibleContext()

获取此对象的AccessibleContext

IcongetDisabledIcon()

返回标签禁用时使用的图标。

intgetDisplayedMnemonic()

返回指示助记键的键码。

intgetDisplayedMnemonicIndex()

返回字符,作为索引,外观和感觉应提供装饰用于表示助记符。

intgetHorizontalAlignment()

返回标签内容沿X轴的对齐方式。

intgetHorizontalTextPosition()

返回标签相对于其图像的文本的水平位置。

IcongetIcon()

返回标签显示的图形图像(字形,图标)。

intgetIconTextGap()

返回文本与此标签中显示的图标之间的空间量。

ComponentgetLabelFor()

获取此标签的组件。

StringgetText()

返回标签显示的文本字符串。

LabelUIgetUI()

返回渲染此组件的L&F对象。

StringgetUIClassID()

返回一个字符串,指定呈现此组件的l&f类的名称。

intgetVerticalAlignment()

返回标签内容沿着Y轴的对齐方式。

intgetVerticalTextPosition()

返回标签相对于其图像的文本的垂直位置。

booleanimageUpdate(Image img, int infoflags, int x, int y, int w, int h)

如果当前图标的图像不等于图像 img传递的图像,则这被覆盖以返回false。

protected StringparamString()

返回该JLabel的字符串表示形式。

voidsetDisabledIcon(Icon disabledIcon)

如果此JLabel为“禁用”(JLabel.setEnabled(false)),请设置要显示的图标。

voidsetDisplayedMnemonic(char aChar)

指定显示的助记符为char值。

voidsetDisplayedMnemonic(int key)

指定一个指示助记键的键码。

voidsetDisplayedMnemonicIndex(int index)

提供关于文字中哪个字符应该被装饰以表示助记符的外观和感觉的提示。

voidsetHorizontalAlignment(int alignment)

设置标签内容沿着X轴的对齐方式。

voidsetHorizontalTextPosition(int textPosition)

设置标签文本相对于其图像的水平位置。

voidsetIcon(Icon icon)

定义该组件将显示的图标。

voidsetIconTextGap(int iconTextGap)

如果设置了图标和文本属性,则此属性定义它们之间的空格。

voidsetLabelFor(Component c)

设置标签的组件。

voidsetText(String text)

定义该组件将显示的单行文本。

voidsetUI(LabelUI ui)

设置渲染此组件的L&F对象。

voidsetVerticalAlignment(int alignment)

设置标签内容沿着Y轴的对齐方式。

voidsetVerticalTextPosition(int textPosition)

设置标签文本相对于其图像的垂直位置。

voidupdateUI()

将UI属性重置为当前外观的值。

package com.demo.panel;

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

public class IconTest extends JFrame implements Icon {


    private int width,height;

    public IconTest() {
    }

    public IconTest(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public static void main(String[] args) {
        new IconTest().init();
    }


    public void init(){
        // 设置标签
        JLabel label = new JLabel("标签图标", new IconTest(10, 10), SwingConstants.CENTER);
        // 放进容器
        Container container = this.getContentPane();
        container.add(label);
        // 设置窗口
        this.setBounds(10,10,400,800);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    // 参数为组件,画笔,大小
    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {

        //画笔  画图标  创建对象后,默认自动画一次
        g.fillOval(x,y,width,height);
    }

    @Override
    public int getIconWidth() {
        return this.width;
    }

    @Override
    public int getIconHeight() {
        return this.height;
    }
}

二.将图片放进标签 

package com.demo.panel;

import javax.swing.*;
import java.awt.*;
import java.net.URL;

public class IconDemoTest extends JFrame {

    public IconDemoTest(){
        // 标签设置
        JLabel label = new JLabel("ImageIcon",SwingConstants.CENTER);
        // 获取图片的地址,找到ImageIcon_类的同级目录下的1.jpg文件
        URL url = IconDemoTest.class.getResource("one.jpg");
        ImageIcon imageIcon = new ImageIcon(url);
        label.setIcon(imageIcon);
        // 容器
        Container container = getContentPane();
        container.add(label);
        // 面板
        setBounds(100,100,400,400);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    }
    public static void main(String[] args) {
        new IconDemoTest();
    }
}

类加载器问题:ClassLoader的getResourceAsStream方法使用及在java和web项目中的路径问题_loader.getresourceasstream-CSDN博客

四.面板

1.Jpanel

构造方法
Constructor and Description
JPanel()

创建一个新的 JPanel双缓冲区和流布局。

JPanel(boolean isDoubleBuffered)

创建一个新的 JPanel与 FlowLayout和指定的缓冲策略。

JPanel(LayoutManager layout)

使用指定的布局管理器创建一个新的缓冲JPanel

JPanel(LayoutManager layout, boolean isDoubleBuffered)

使用指定的布局管理器和缓冲策略创建一个新的JPanel。

                                                                        方法 

Modifier and TypeMethod and Description
AccessibleContextgetAccessibleContext()

获取与此JPanel关联的AccessibleContext。

PanelUIgetUI()

返回渲染此组件的外观和感觉(L&amp; F)对象。

StringgetUIClassID()

返回一个字符串,它指定呈现此组件的L&F类的名称。

protected StringparamString()

返回此JPanel的字符串表示形式。

voidsetUI(PanelUI ui)

设置渲染此组件的外观和感觉(L&F)对象。

voidupdateUI()

将UI属性重新设置为来自当前外观的值。

package com.demo.panel;

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

public class JPanelTest extends JFrame {

    public JPanelTest() {
        // 容器
        Container container = this.getContentPane();
        container.setLayout(new GridLayout(2,1,10,10));
        // 四个面板与添加按钮
        JPanel panel1 = new JPanel(new GridLayout(1, 3));
        JPanel panel2 = new JPanel(new GridLayout(1, 2));
        JPanel panel3 = new JPanel(new GridLayout(2, 1));
        JPanel panel4 = new JPanel(new GridLayout(3,2));
        panel1.add(new JButton("1"));
        panel1.add(new JButton("1"));
        panel1.add(new JButton("1"));
        container.add(panel1);
        panel2.add(new JButton("2"));
        panel2.add(new JButton("2"));
        container.add(panel2);
        panel3.add(new JButton("3"));
        panel3.add(new JButton("3"));
        container.add(panel3);
        panel4.add(new JButton("4"));
        panel4.add(new JButton("4"));
        panel4.add(new JButton("4"));
        panel4.add(new JButton("4"));
        panel4.add(new JButton("4"));
        panel4.add(new JButton("4"));
        container.add(panel4);
        // 窗口
        this.setVisible(true);
        this.setSize(800,800);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JPanelTest();
    }
}

 2.滑动面板JScrollPane

构造方法
Constructor and Description
JScrollPane()

创建一个空( JScrollPane口视图) JScrollPane ,其中水平和垂直滚动条在需要时出现。

JScrollPane(Component view)

创建一个 JScrollPane ,它显示指定组件的内容,当组件的内容大于视图时,水平和垂直滚动条都会显示。

JScrollPane(Component view, int vsbPolicy, int hsbPolicy)

创建一个 JScrollPane ,它可以在一个视口中显示视图组件,其视图位置可以通过一对滚动条来控制。

JScrollPane(int vsbPolicy, int hsbPolicy)

使用指定的滚动条策略创建一个空( JScrollPane口视图) JScrollPane 。

                                                                         方法

Modifier and TypeMethod and Description
JScrollBarcreateHorizontalScrollBar()

默认情况下返回 JScrollPane.ScrollBar 。

JScrollBarcreateVerticalScrollBar()

默认返回 JScrollPane.ScrollBar 。

protected JViewportcreateViewport()

默认情况下返回一个新的 JViewport 。

AccessibleContextgetAccessibleContext()

获取与此JScrollPane关联的AccessibleContext。

JViewportgetColumnHeader()

返回列标题。

ComponentgetCorner(String key)

返回指定角落的组件。

JScrollBargetHorizontalScrollBar()

返回控制视口水平视图位置的水平滚动条。

intgetHorizontalScrollBarPolicy()

返回水平滚动条策略值。

JViewportgetRowHeader()

返回行标题。

ScrollPaneUIgetUI()

返回渲染此组件的外观和感觉(L&F)对象。

StringgetUIClassID()

返回用于构造用于呈现此组件的L&F类的名称的后缀。

JScrollBargetVerticalScrollBar()

返回控制视口垂直视图位置的垂直滚动条。

intgetVerticalScrollBarPolicy()

返回垂直滚动条策略值。

JViewportgetViewport()

返回当前的 JViewport 。

BordergetViewportBorder()

返回视口 Border对象。

RectanglegetViewportBorderBounds()

返回视口边框的边界。

booleanisValidateRoot()

重写以返回true,这样任何电话 revalidate这个的任何后代 JScrollPane会造成这个开始的整棵树 JScrollPane进行验证。

booleanisWheelScrollingEnabled()

指示是否会响应于鼠标滚轮进行滚动。

protected StringparamString()

返回此 JScrollPane的字符串表示 JScrollPane 。

voidsetColumnHeader(JViewport columnHeader)

删除旧的columnHeader(如果存在) 如果新的columnHeader不是null ,则将其viewPosition的x坐标与视口(如果有的话)同步,然后将其添加到滚动窗格。

voidsetColumnHeaderView(Component view)

如果需要,创建列标题视口,设置其视图,然后将列标题视口添加到滚动页面。

voidsetComponentOrientation(ComponentOrientation co)

设置由ComponentOrientation参数确定的垂直和水平滚动条的 ComponentOrientation 。

voidsetCorner(String key, Component corner)

添加一个孩子,出现在一个滚动窗格的角落,如果有空间。

voidsetHorizontalScrollBar(JScrollBar horizontalScrollBar)

将控制视口的水平视图位置的滚动条添加到滚动条。

voidsetHorizontalScrollBarPolicy(int policy)

确定水平滚动条何时出现在滚动条中。

voidsetLayout(LayoutManager layout)

设置此 JScrollPane的布局管理器。

voidsetRowHeader(JViewport rowHeader)

删除旧的行阅读器(如果存在) 如果新的rowHeader不是null ,则将其viewPosition的y坐标与视口同步(如果有),然后将其添加到滚动窗格。

voidsetRowHeaderView(Component view)

如果需要,创建行标题视口,设置其视图,然后将行标题视口添加到滚动条。

voidsetUI(ScrollPaneUI ui)

设置为该 ScrollPaneUI提供外观和感觉(L&F)的ScrollPaneUI对象。

voidsetVerticalScrollBar(JScrollBar verticalScrollBar)

将控制视口垂直视图位置的滚动条添加到滚动条。

voidsetVerticalScrollBarPolicy(int policy)

确定滚动条中何时出现垂直滚动条。

voidsetViewport(JViewport viewport)

删除旧的视口(如果有的话); 迫使新视口的观点位于+ x,+ y象限中; 使用新的视口同步行和列标题(如果有的话); 最后使用新的视口同步滚动条和标题。

voidsetViewportBorder(Border viewportBorder)

在视口周围添加一个边框。

voidsetViewportView(Component view)

如果需要,创建一个视口,然后设置它的视图。

voidsetWheelScrollingEnabled(boolean handleWheel)

响应于鼠标滚轮的移动启用/禁用滚动。

voidupdateUI()

将当前的 ScrollPaneUI对象替换为当前默认外观的版本。

package com.demo.panel;

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

public class JScrollPaneTest extends JFrame {

    public JScrollPaneTest() throws HeadlessException {
        // 容器
        Container container = this.getContentPane();
        // 设置一个文本域  文本域可以换行,而文本框不行
        // 设置起始行列数,行列可变化
        JTextArea textArea = new JTextArea(20,30);
        textArea.setText("滑动面板的文本域,有换行功能");
        // JScrollPane面板
        JScrollPane scrollPane = new JScrollPane(textArea);
        container.add(scrollPane);
        // 窗口
        setVisible(true);
        setBounds(100,100,200,300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JScrollPaneTest();
    }

}

五.按钮

1.图标按钮

把一个图标变为一个按钮图标 

构造方法
Constructor and Description
JButton()

创建一个没有设置文本或图标的按钮。

JButton(Action a)

创建一个按钮,其中的属性取自提供的 Action 。

JButton(Icon icon)

创建一个带有图标的按钮。

JButton(String text)

创建一个带文本的按钮。

JButton(String text, Icon icon)

创建一个带有初始文本和图标的按钮。

                                                                方法 

Modifier and TypeMethod and Description
AccessibleContextgetAccessibleContext()

获取 AccessibleContext与此相关 JButton 。

StringgetUIClassID()

返回一个字符串,它指定呈现此组件的L&F类的名称。

booleanisDefaultButton()

获取 defaultButton属性的值,如果 true意味着此按钮是其 JRootPane的当前默认按钮。

booleanisDefaultCapable()

获取 defaultCapable属性的值。

protected StringparamString()

返回此 JButton的字符串表示 JButton 。

voidremoveNotify()

覆盖 JComponent.removeNotify ,以检查此按钮当前被设置为在默认按钮 RootPane ,如果是的话,设置 RootPane的默认按钮 null ,以确保 RootPane不继续停留在无效的按钮引用。

voidsetDefaultCapable(boolean defaultCapable)

设置 defaultCapable属性,它确定此按钮是否可以成为其根窗格的默认按钮。

voidupdateUI()

将UI属性重置为当前外观的值。

package com.demo.panel;


import javax.swing.*;
import java.awt.*;
import java.net.URL;
/**
 * 设置一个图标按钮  加了一个按钮提示方法
 * 将一个图片变为图标
 */
public class JButtonIconTest extends JFrame {
    public JButtonIconTest() throws HeadlessException {
        Container container = getContentPane();
        //将一个图片变成图标
        URL url = JButtonIconTest.class.getResource("one.jpg");
        ImageIcon imageIcon = new ImageIcon(url);
        //把这个图标放在按钮上
        JButton button = new JButton();
        button.setIcon(imageIcon);
        //设置提示按钮,鼠标放到按钮上面会弹出一些提示
        button.setToolTipText("图片按钮");
        container.add(button);

        setSize(500,300);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JButtonIconTest();
    }
}

2.单选按钮

构造方法
Constructor and Description
JRadioButton()

创建一个没有设置文本的最初未选择的单选按钮。

JRadioButton(Action a)

创建一个单选按钮,其中从提供的Action提取属性。

JRadioButton(Icon icon)

创建一个初始未选择的单选按钮与指定的图像,但没有文字。

JRadioButton(Icon icon, boolean selected)

创建具有指定图像和选择状态的单选按钮,但不包含文本。

JRadioButton(String text)

使用指定的文本创建一个未选择的单选按钮。

JRadioButton(String text, boolean selected)

创建具有指定文本和选择状态的单选按钮。

JRadioButton(String text, Icon icon)

创建具有指定文本和图像的单选按钮,最初未被选择。

JRadioButton(String text, Icon icon, boolean selected)

创建具有指定文本,图像和选择状态的单选按钮。

                                                                方法 

Modifier and TypeMethod and Description
AccessibleContextgetAccessibleContext()

获取与此JRadioButton关联的AccessibleContext。

StringgetUIClassID()

返回呈现此组件的L&F类的名称。

protected StringparamString()

返回此JRadioButton的字符串表示形式。

voidupdateUI()

将UI属性重置为当前外观的值。

构造方法
Constructor and Description
ButtonGroup()

创建一个新的 ButtonGroup 。

                                                                方法 

Modifier and TypeMethod and Description
voidadd(AbstractButton b)

将按钮添加到组。

voidclearSelection()

清除选择,使得没有选择 ButtonGroup中的按钮。

intgetButtonCount()

返回组中按钮的数量。

Enumeration<AbstractButton>getElements()

返回参与此组的所有按钮。

ButtonModelgetSelection()

返回所选按钮的型号。

booleanisSelected(ButtonModel m)

返回是否选择 ButtonModel 。

voidremove(AbstractButton b)

从组中删除按钮。

voidsetSelected(ButtonModel m, boolean b)

设置 ButtonModel的选定值。

package com.demo.panel;

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

public class JButtonOneTest extends JFrame {

    public void init(){
        Container container = getContentPane();
        //单选框
        JRadioButton radioButton1 = new JRadioButton("JRdioButton1");
        JRadioButton radioButton2 = new JRadioButton("JRdioButton2");
        JRadioButton radioButton3 = new JRadioButton("JRdioButton3");
        //由于是单选框,需要准备一个组,让三个按钮在这组内实现单选功能
        ButtonGroup group = new ButtonGroup();
        group.add(radioButton1);
        group.add(radioButton2);
        group.add(radioButton3);
        //将按钮添加进来,不是将组添加进来!! 要设置按钮的位置,避免出现覆盖现象
        container.add(radioButton1,BorderLayout.NORTH);
        container.add(radioButton2,BorderLayout.CENTER);
        container.add(radioButton3,BorderLayout.SOUTH);
        
        setSize(500,300);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JButtonOneTest().init();
    }
}

3. 复选按钮

构造方法
Constructor and Description
JCheckBox()

创建一个最初未选择的复选框按钮,没有文字,没有图标。

JCheckBox(Action a)

创建一个复选框,其中从提供的操作中获取属性。

JCheckBox(Icon icon)

创建一个带有图标的最初未选中的复选框。

JCheckBox(Icon icon, boolean selected)

创建一个带有图标的复选框,并指定是否最初选择它。

JCheckBox(String text)

创建一个最初未选择的复选框与文本。

JCheckBox(String text, boolean selected)

创建一个带有文本的复选框,并指定是否最初选择它。

JCheckBox(String text, Icon icon)

使用指定的文本和图标创建最初未选择的复选框。

JCheckBox(String text, Icon icon, boolean selected)

创建一个带有文本和图标的复选框,并指定是否最初选择它。

                                                                方法 

Modifier and TypeMethod and Description
AccessibleContextgetAccessibleContext()

获取与此JCheckBox关联的AccessibleContext。

StringgetUIClassID()

返回一个字符串,它指定呈现此组件的L&F类的名称。

booleanisBorderPaintedFlat()

获取 borderPaintedFlat属性的值。

protected StringparamString()

返回此JCheckBox的字符串表示形式。

voidsetBorderPaintedFlat(boolean b)

设置 borderPaintedFlat属性,它提供了对复选框边框外观的看法和感觉。

voidupdateUI()

将UI属性重置为当前外观的值。

package com.demo.panel;

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

public class JButtonTwoTest extends JFrame {

    public void init(){
        Container container = getContentPane();
        //多选框
        JCheckBox checkBox1 = new JCheckBox("checkBox1");
        JCheckBox checkBox2 = new JCheckBox("checkBox2");
        JCheckBox checkBox3 = new JCheckBox("checkBox3");

        container.add(checkBox1,BorderLayout.NORTH);
        container.add(checkBox2,BorderLayout.CENTER);
        container.add(checkBox3,BorderLayout.SOUTH);
        
        setSize(500,300);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JButtonTwoTest().init();
    }
}

六.列表

1.下拉框 

构造方法
Constructor and Description
JComboBox()

使用默认数据模型创建 JComboBox 。

JComboBox(ComboBoxModel<E> aModel)

创建一个 JComboBox ,从现有的 ComboBoxModel获取其项目。

JComboBox(E[] items)

创建 JComboBox包含指定数组中的元素。

JComboBox(Vector<E> items)

创建一个 JComboBox包含指定Vector中的元素。

                                                                方法 

Modifier and TypeMethod and Description
voidactionPerformed(ActionEvent e)

这种方法是公共的,作为实现的副作用。

protected voidactionPropertyChanged(Action action, String propertyName)

响应关联操作中的属性更改更新组合框的状态。

voidaddActionListener(ActionListener l)

添加一个 ActionListener 。

voidaddItem(E item)

将项目添加到项目列表。

voidaddItemListener(ItemListener aListener)

添加一个 ItemListener 。

voidaddPopupMenuListener(PopupMenuListener l)

添加一个 PopupMenu监听器,它将从组合框的弹出窗口中收听通知消息。

voidconfigureEditor(ComboBoxEditor anEditor, Object anItem)

用指定的项目初始化编辑器。

protected voidconfigurePropertiesFromAction(Action a)

设置此组合框上的属性,以匹配指定的Action中的 Action 。

voidcontentsChanged(ListDataEvent e)

这种方法是公共的,作为实现的副作用。

protected PropertyChangeListenercreateActionPropertyChangeListener(Action a)

创建并返回一个 PropertyChangeListener ,负责监听来自指定的变化 Action和更新相应的属性。

protected JComboBox.KeySelectionManagercreateDefaultKeySelectionManager()

返回默认密钥选择管理器的一个实例。

protected voidfireActionEvent()

通知所有在此事件类型上通知有兴趣的听众。

protected voidfireItemStateChanged(ItemEvent e)

通知所有在此事件类型上通知有兴趣的听众。

voidfirePopupMenuCanceled()

通知 PopupMenuListener s组合框的弹出部分已被取消。

voidfirePopupMenuWillBecomeInvisible()

通知 PopupMenuListener s组合框的弹出部分已经变得不可见。

voidfirePopupMenuWillBecomeVisible()

通知 PopupMenuListener s组合框的弹出部分将变得可见。

AccessibleContextgetAccessibleContext()

获取与此JComboBox关联的AccessibleContext。

ActiongetAction()

返回当前设置 Action这个 ActionEvent来源,或 null如果没有 Action设置。

StringgetActionCommand()

返回发送到动作侦听器的事件中包含的动作命令。

ActionListener[]getActionListeners()

返回使用addActionListener()添加到此JComboBox的所有 ActionListener的数组。

ComboBoxEditorgetEditor()

返回在 JComboBox字段中用于绘制和编辑所选项目的编辑器。

EgetItemAt(int index)

返回指定索引处的列表项。

intgetItemCount()

返回列表中的项目数。

ItemListener[]getItemListeners()

返回使用addItemListener()添加到此JComboBox的所有 ItemListener的数组。

JComboBox.KeySelectionManagergetKeySelectionManager()

返回列表的密钥选择管理器。

intgetMaximumRowCount()

返回在没有滚动条的情况下组合框可以显示的最大项数

ComboBoxModel<E>getModel()

返回当前使用的数据模型 JComboBox 。

PopupMenuListener[]getPopupMenuListeners()

返回使用addPopupMenuListener()添加到此JComboBox的所有 PopupMenuListener的数组。

EgetPrototypeDisplayValue()

返回“原型显示”值 - 用于计算显示高度和宽度的对象。

ListCellRenderer<? super E>getRenderer()

返回用于在 JComboBox字段中显示所选项目的渲染器。

intgetSelectedIndex()

返回列表中与给定项目匹配的第一个项目。

ObjectgetSelectedItem()

返回当前所选项目。

Object[]getSelectedObjects()

返回一个包含所选项目的数组。

ComboBoxUIgetUI()

返回渲染此组件的L&F对象。

StringgetUIClassID()

返回呈现此组件的L&F类的名称。

voidhidePopup()

导致组合框关闭其弹出窗口。

voidinsertItemAt(E item, int index)

在给定索引的项目列表中插入项目。

protected voidinstallAncestorListener() 
voidintervalAdded(ListDataEvent e)

这种方法是公共的,作为实现的副作用。

voidintervalRemoved(ListDataEvent e)

这种方法是公共的,作为实现的副作用。

booleanisEditable()

如果 JComboBox是可编辑的,则返回true。

booleanisLightWeightPopupEnabled()

获取 lightWeightPopupEnabled属性的值。

booleanisPopupVisible()

确定弹出窗口的可见性。

protected StringparamString()

返回此 JComboBox的字符串表示 JComboBox 。

voidprocessKeyEvent(KeyEvent e)

手柄 KeyEvent s,寻找Tab键。

voidremoveActionListener(ActionListener l)

删除 ActionListener 。

voidremoveAllItems()

从项目列表中删除所有项目。

voidremoveItem(Object anObject)

从项目列表中删除一个项目。

voidremoveItemAt(int anIndex)

anIndex删除该项目此方法仅在 JComboBox使用可变数据模型时有效。

voidremoveItemListener(ItemListener aListener)

删除 ItemListener 。

voidremovePopupMenuListener(PopupMenuListener l)

删除 PopupMenuListener 。

protected voidselectedItemChanged()

这种受保护的方法是具体的实现。

booleanselectWithKeyChar(char keyChar)

选择与指定键盘字符相对应的列表项,如果存在与该字符相对应的项,则返回true。

voidsetAction(Action a)

为 Action设置 ActionEvent源。

voidsetActionCommand(String aCommand)

设置应该包含在发送到action监听器的事件中的action命令。

voidsetEditable(boolean aFlag)

确定 JComboBox字段是否可编辑。

voidsetEditor(ComboBoxEditor anEditor)

设置用于在 JComboBox字段中绘制和编辑所选项目的编辑器。

voidsetEnabled(boolean b)

启用组合框,以便可以选择项目。

voidsetKeySelectionManager(JComboBox.KeySelectionManager aManager)

设置将键盘字符转换为列表选择的对象。

voidsetLightWeightPopupEnabled(boolean aFlag)

设置 lightWeightPopupEnabled属性,它提供了一个提示,一个轻量级的 Component是否应该用于包含 JComboBox ,而重量级 Component ,如 Panel或 Window 。

voidsetMaximumRowCount(int count)

设置 JComboBox显示的最大行数。

voidsetModel(ComboBoxModel<E> aModel)

设置 JComboBox用于获取项目列表的数据模型。

voidsetPopupVisible(boolean v)

设置弹出窗口的可见性。

voidsetPrototypeDisplayValue(E prototypeDisplayValue)

设置用于计算UI部分显示大小的原型显示值。

voidsetRenderer(ListCellRenderer<? super E> aRenderer)

设置绘制列表项目的渲染器和从JComboBox字段中的列表中选择的项目。

voidsetSelectedIndex(int anIndex)

选择索引为 anIndex的项目。

voidsetSelectedItem(Object anObject)

将组合框显示区域中的选定项目设置为参数中的对象。

voidsetUI(ComboBoxUI ui)

设置渲染此组件的L&F对象。

voidshowPopup()

导致组合框显示其弹出窗口。

voidupdateUI()

将UI属性重置为当前外观的值。

package com.demo.panel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
 * 下拉框  JComboBox类
 * System.out.println(comboBox.getSelectedIndex());//返回当前项的位置
 * System.out.println(comboBox.getSelectedItem());//返回当前项的内容
 */
public class ComboboxTest extends JFrame {
    public ComboboxTest() {
        Container container = this.getContentPane();
        // 下拉框 
        JComboBox comboBox = new JComboBox();
        comboBox.addItem("正在热映");
        comboBox.addItem(null);
        comboBox.addItem("即将上映");
        comboBox.addItem("下架");

        container.add(comboBox,BorderLayout.NORTH);
        // 监听
        comboBox.addActionListener(new MyActionListener());

        this.setVisible(true);
        this.setBounds(100,100,400,400);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new ComboboxTest();
    }
}
// 监听
class MyActionListener implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        JComboBox comboBox = (JComboBox)e.getSource();
        //返回当前项的位置
        System.out.println(comboBox.getSelectedIndex());
        //返回当前项的内容
        System.out.println(comboBox.getSelectedItem());
    }
}

2.列表框

构造方法
Constructor and Description
JList()

构造一个空的只读模型的 JList 。

JList(E[] listData)

构造一个 JList ,显示指定数组中的元素。

JList(ListModel<E> dataModel)

构造一个 JList ,其显示从指定的,元件 non-null ,模型。

JList(Vector<? extends E> listData)

构造一个 JList ,显示在指定的元素 Vector 。

                                                                        方法 

Modifier and TypeMethod and Description
voidaddListSelectionListener(ListSelectionListener listener)

将一个监听器添加到列表中,每次发生更改时都会被通知; 倾听选择状态变化的首选方式。

voidaddSelectionInterval(int anchor, int lead)

将选择设置为指定间隔与当前选择的并集。

voidclearSelection()

清除选择; 调用此方法后, isSelectionEmpty将返回true 。

protected ListSelectionModelcreateSelectionModel()

返回一个DefaultListSelectionModel的实例; 在建设期间呼吁初始化列表的选择模型属性。

voidensureIndexIsVisible(int index)

在封闭的视口中滚动列表,使指定的单元格完全可见。

protected voidfireSelectionValueChanged(int firstIndex, int lastIndex, boolean isAdjusting)

通知 ListSelectionListener s直接添加到选择模型所做的选择更改列表中。

AccessibleContextgetAccessibleContext()

获取 AccessibleContext与此相关 JList 。

intgetAnchorSelectionIndex()

返回锚选择索引。

RectanglegetCellBounds(int index0, int index1)

返回列表坐标系中由两个索引指定的单元格范围的边界矩形。

ListCellRenderer<? super E>getCellRenderer()

返回负责绘画列表项的对象。

booleangetDragEnabled()

返回是否启用自动拖动处理。

JList.DropLocationgetDropLocation()

返回该组件应在视觉上作为放置位置的DnD操作期间组件上方指示,或位置 null如果没有位置是当前被显示。

DropModegetDropMode()

返回此组件的放置模式。

intgetFirstVisibleIndex()

返回当前可见的最小列表索引。

intgetFixedCellHeight()

返回 fixedCellHeight属性的值。

intgetFixedCellWidth()

返回 fixedCellWidth属性的值。

intgetLastVisibleIndex()

返回当前可见的最大列表索引。

intgetLayoutOrientation()

返回列表的布局方向属性: VERTICAL如果布局是单列单元格, VERTICAL_WRAP如果布局是“报纸样式”,内容垂直然后水平流动,或 HORIZONTAL_WRAP如果布局是“报纸样式”与内容水平流动然后垂直。

intgetLeadSelectionIndex()

返回引导选择索引。

ListSelectionListener[]getListSelectionListeners()

返回所有的数组 ListSelectionListener加入到这个S JList途经 addListSelectionListener 。

intgetMaxSelectionIndex()

返回最大的所选单元 -1引,如果选择为空,则返回-1。

intgetMinSelectionIndex()

返回最小选择的单元 -1引,如果选择为空,则返回-1。

ListModel<E>getModel()

返回保存由 JList组件显示的项目列表的数据模型。

intgetNextMatch(String prefix, int startIndex, Position.Bias bias)

返回下一个列表元素,其中 toString值以给定的前缀开始。

DimensiongetPreferredScrollableViewportSize()

计算显示 visibleRowCount行所需的视口大小。

EgetPrototypeCellValue()

返回“原型”单元格值 - 用于计算单元格的固定宽度和高度的值。

intgetScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction)

返回要滚动以显示下一个或上一个块的距离。

booleangetScrollableTracksViewportHeight()

返回true如果JList显示在JViewport和视口比列表的首选高度更高,或者布局方向为VERTICAL_WRAPvisibleRowCount <= 0 ; 否则返回false 。

booleangetScrollableTracksViewportWidth()

返回true如果此JList被显示在JViewport和视口比所述列表的优选宽度,或者如果布局方向为HORIZONTAL_WRAPvisibleRowCount <= 0 ; 否则返回false 。

intgetScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)

返回滚动的距离以显示下一行或上一行(垂直滚动)或列(用于水平滚动)。

intgetSelectedIndex()

返回最小的选定单元格索引; 在列表中仅选择单个项目时的选择。

int[]getSelectedIndices()

以递增的顺序返回所有选定索引的数组。

EgetSelectedValue()

返回最小选定单元索引的值; 在列表中仅选择单个项目时的选定值 。

Object[]getSelectedValues()已弃用

截至JDK 1.7,由getSelectedValuesList()替代

List<E>getSelectedValuesList()

根据列表中的索引,按照增加的顺序返回所有选定项目的列表。

ColorgetSelectionBackground()

返回用于绘制所选项目背景的颜色。

ColorgetSelectionForeground()

返回用于绘制所选项目前景的颜色。

intgetSelectionMode()

返回列表的当前选择模式。

ListSelectionModelgetSelectionModel()

返回当前的选择模型。

StringgetToolTipText(MouseEvent event)

返回用于给定事件的工具提示文本。

ListUIgetUI()

返回 ListUI ,呈现此组件的外观和感觉对象。

StringgetUIClassID()

返回 "ListUI" ,该 UIDefaults用于查找该名关键 javax.swing.plaf.ListUI类定义的外观和感觉这个组件。

booleangetValueIsAdjusting()

返回选择模型的 isAdjusting属性的值。

intgetVisibleRowCount()

返回 visibleRowCount属性的值。

PointindexToLocation(int index)

返回列表坐标系中指定项目的原点。

booleanisSelectedIndex(int index)

如果选择了指定的索引,则返回 true ,否则为 false 。

booleanisSelectionEmpty()

如果没有选择,返回 true ,否则 false 。

intlocationToIndex(Point location)

返回最接近列表坐标系中给定位置的单元格索引。

protected StringparamString()

返回 String如此表示 JList 。

voidremoveListSelectionListener(ListSelectionListener listener)

从列表中删除选择侦听器。

voidremoveSelectionInterval(int index0, int index1)

将选择设置为指定间隔和当前选择的设置差。

voidsetCellRenderer(ListCellRenderer<? super E> cellRenderer)

设置用于绘制列表中每个单元格的委托。

voidsetDragEnabled(boolean b)

打开或关闭自动拖动处理。

voidsetDropMode(DropMode dropMode)

设置此组件的下拉模式。

voidsetFixedCellHeight(int height)

设置要用于列表中每个单元格的高度的固定值。

voidsetFixedCellWidth(int width)

设置要用于列表中每个单元格宽度的固定值。

voidsetLayoutOrientation(int layoutOrientation)

定义列表单元格的布局方式。

voidsetListData(E[] listData)

构造一个只读 ListModel从项目的数组,并调用 setModel这种模式。

voidsetListData(Vector<? extends E> listData)

构造一个只读 ListModel从 Vector并调用 setModel这种模式。

voidsetModel(ListModel<E> model)

设置表示列表的内容或“值”的模型,通知属性更改侦听器,然后清除列表的选择。

voidsetPrototypeCellValue(E prototypeCellValue)

设置 prototypeCellValue属性,然后(如果新值为 non-null ),通过从单元格渲染器请求单元格渲染器组件给定值(和索引0),并使用该组件的首选大小来计算 fixedCellWidth和 fixedCellHeight属性。

voidsetSelectedIndex(int index)

选择单个单元格。

voidsetSelectedIndices(int[] indices)

将选择更改为给定数组指定的索引集。

voidsetSelectedValue(Object anObject, boolean shouldScroll)

从列表中选择指定的对象。

voidsetSelectionBackground(Color selectionBackground)

设置用于绘制所选项目背景的颜色,哪些单元格渲染器可以使用填充所选单元格。

voidsetSelectionForeground(Color selectionForeground)

设置用于绘制所选项目的前景的颜色,哪些单元格渲染器可用于渲染文本和图形。

voidsetSelectionInterval(int anchor, int lead)

选择指定的间隔。

voidsetSelectionMode(int selectionMode)

设置列表的选择模式。

voidsetSelectionModel(ListSelectionModel selectionModel)

将该列表的 selectionModel设置为非 null ListSelectionModel实现。

voidsetUI(ListUI ui)

设置 ListUI ,呈现此组件的外观和感觉对象。

voidsetValueIsAdjusting(boolean b)

设置选择模型的 valueIsAdjusting属性。

voidsetVisibleRowCount(int visibleRowCount)

设置visibleRowCount属性,具有不同的含义,具体取决于布局方向:对于VERTICAL布局方向,这将设置要显示的首选行数,而不需要滚动; 对于其他取向,它影响细胞的包裹。

voidupdateUI()

将 ListUI属性重新设置为当前外观所提供的值。

                                                   

package com.demo.panel;

import javax.swing.*;
import java.awt.*;
import java.util.Vector;
/**
 * 列表框  JList
 * 每一项都是可点击的
 */
public class ComboboxDemoTest extends JFrame {
    public ComboboxDemoTest() {

        // 列表的内容
        // 动态变量 动态集合
        Vector vector = new Vector();
        vector.add("正在热映");
        //与下拉框不同,动态集合自动排除掉为空的内容,所以这里显示的就两个项
        vector.add(null);
        vector.add("已下架");
        // 列表中需要放入内容
        JList list = new JList(vector);

        Container container = this.getContentPane();
        container.add(list);


        this.setVisible(true);
        this.setBounds(100,100,400,400);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new ComboboxDemoTest();
    }
}

  • 应用场景

    • 选择地区,或者一些单个选项 (选项只有两个的话建议使用单选框,三个以上建议使用下拉框)
    • 列表框,展示项信息,一般都是动态扩容

 七.文本框 

1.文本框 

构造方法
Constructor and Description
JTextField()

构造新的 TextField 。

JTextField(Document doc, String text, int columns)

构造一个新的 JTextField ,它使用给定的文本存储模型和给定的列数。

JTextField(int columns)

构造一个新的空的 TextField与指定的列数。

JTextField(String text)

构造一个新的 TextField ,用指定的文本初始化。

JTextField(String text, int columns)

构造一个新的 TextField ,用指定的文本和列初始化。

                                                                方法 

Modifier and TypeMethod and Description
protected voidactionPropertyChanged(Action action, String propertyName)

响应相关操作中的属性更改更新文本框的状态。

voidaddActionListener(ActionListener l)

添加指定的动作侦听器以从此文本字段接收动作事件。

protected voidconfigurePropertiesFromAction(Action a)

设置此文本字段上的属性以匹配指定的Action中的 Action 。

protected PropertyChangeListenercreateActionPropertyChangeListener(Action a)

创建并返回一个 PropertyChangeListener ,负责监听来自指定的变化 Action和更新相应的属性。

protected DocumentcreateDefaultModel()

如果没有明确给出,则创建要在构建中使用的模型的默认实现。

protected voidfireActionPerformed()

通知所有在此事件类型上通知有兴趣的听众。

AccessibleContextgetAccessibleContext()

获取 AccessibleContext与此相关 JTextField 。

ActiongetAction()

返回当前设置的 Action为 ActionEvent源,或 null如果没有设置 Action 。

ActionListener[]getActionListeners()

返回使用addActionListener()添加到此JTextField的所有 ActionListener的数组。

Action[]getActions()

获取编辑器命令列表。

intgetColumns()

返回此 TextField中的列数。

protected intgetColumnWidth()

返回列宽。

intgetHorizontalAlignment()

返回文本的水平对齐。

BoundedRangeModelgetHorizontalVisibility()

获取文本字段的可见性。

DimensiongetPreferredSize()

返回首选大小 Dimensions为此需要 TextField 。

intgetScrollOffset()

获取滚动偏移量,以像素为单位。

StringgetUIClassID()

获取UI的类ID。

booleanisValidateRoot()

呼叫 revalidate是来自文本字段本身内将通过验证文本字段,除非文本字段包含一个内处理 JViewport ,在这种情况下,这个返回false。

protected StringparamString()

返回此 JTextField的字符串表示 JTextField 。

voidpostActionEvent()

通过将这些事件发送到任何已注册的 ActionListener对象来处理在此文本字段上发生的操作事件。

voidremoveActionListener(ActionListener l)

删除指定的动作监听器,使其不再从此文本字段接收动作事件。

voidscrollRectToVisible(Rectangle r)

向左或向右滚动字段。

voidsetAction(Action a)

设置 Action为 ActionEvent源。

voidsetActionCommand(String command)

设置用于操作事件的命令字符串。

voidsetColumns(int columns)

设置此 TextField中的列数,然后使布局无效。

voidsetDocument(Document doc)

将编辑器与文本文档相关联。

voidsetFont(Font f)

设置当前字体。

voidsetHorizontalAlignment(int alignment)

设置文本的水平对齐方式。

voidsetScrollOffset(int scrollOffset)

设置滚动偏移量,以像素为单位。

package com.demo.panel;

import javax.swing.*;
import java.awt.*;
/**
 * 文本框 JTextField
 * 不能换行
 */
public class JTextFieldTest extends JFrame {
    public JTextFieldTest() throws HeadlessException {

        // 设置文本框 不能换行
        // 设置初始内容
        JTextField textField1 = new JTextField("hello");
        // 设置初始内容与起始字符数,行列可变化
        JTextField textField2 = new JTextField("world",20);

        Container container = this.getContentPane();
        container.add(textField1,BorderLayout.NORTH);
        container.add(textField2,BorderLayout.SOUTH);
        
        setVisible(true);
        setBounds(100,100,200,300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JTextFieldTest();
    }
}

2.密码框

构造方法
Constructor and Description
JPasswordField()

构造一个新的 JPasswordField ,默认文档为 null起始文本字符串和0列宽。

JPasswordField(Document doc, String txt, int columns)

构造一个新的 JPasswordField ,它使用给定的文本存储模型和给定的列数。

JPasswordField(int columns)

构造一个新的空的 JPasswordField与指定的列数。

JPasswordField(String text)

构造一个新 JPasswordField用指定文本初始化。

JPasswordField(String text, int columns)

构造一个新的 JPasswordField ,用指定的文本和列进行初始化。

                                                                方法 

Modifier and TypeMethod and Description
voidcopy()

调用 provideErrorFeedback当前的外观,通常会发出一个错误提示音。

voidcut()

调用 provideErrorFeedback当前的外观和感觉,通常会发出一个错误提示音。

booleanechoCharIsSet()

如果这个 JPasswordField具有一个用于回 JPasswordField的字符集,则返回true。

AccessibleContextgetAccessibleContext()

返回 AccessibleContext与此相关 JPasswordField 。

chargetEchoChar()

返回要用于回显的字符。

char[]getPassword()

返回包含在此文字 TextComponent 。

StringgetText()已弃用

从Java 2平台v1.2开始,由getPassword 。

StringgetText(int offs, int len)已弃用

从Java 2平台v1.2开始,由getPassword取代。

StringgetUIClassID()

返回呈现此组件的L&F类的名称。

protected StringparamString()

返回此 JPasswordField的字符串表示 JPasswordField 。

voidsetEchoChar(char c)

设置此 JPasswordField的回音 JPasswordField 。

voidupdateUI()

重新加载可插拔的UI。

package com.demo.panel;

import javax.swing.*;
import java.awt.*;
/**
 * 密码框 JPasswordField 在文本框中用一个字符隐藏内容
 * 是JTextField的子类  默认是一个小黑点隐藏
 */
public class JPasswordFieldTest extends JFrame {
    public JPasswordFieldTest() throws HeadlessException {

        // 设置文本框 不能换行
        // 设置初始内容
        JPasswordField passwordField = new JPasswordField("hello");
        // 设置用一个字符代替输入字符,实现隐藏作用
        passwordField.setEchoChar('*');
        // 得到文本框的内容
        System.out.println(passwordField.getPassword());


        Container container = this.getContentPane();
        container.add(passwordField,BorderLayout.NORTH);

        setVisible(true);
        setBounds(100,100,200,300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JPasswordFieldTest();
    }
}

3.文本域

构造方法
Constructor and Description
JTextArea()

构造一个新的TextArea。

JTextArea(Document doc)

使用给定的文档模型构造一个新的JTextArea,默认为所有其他参数(null,0,0)。

JTextArea(Document doc, String text, int rows, int columns)

构造具有指定行数和列数的新JTextArea以及给定模型。

JTextArea(int rows, int columns)

构造具有指定行数和列数的新的空TextArea。

JTextArea(String text)

构造一个新的TextArea,并显示指定的文本。

JTextArea(String text, int rows, int columns)

构造具有指定文本和行数和列数的新TextArea。

                                                        方法 

Modifier and TypeMethod and Description
voidappend(String str)

将给定的文本附加到文档的末尾。

protected DocumentcreateDefaultModel()

如果没有明确给出,则创建要在构建中使用的模型的默认实现。

AccessibleContextgetAccessibleContext()

获取与此JTextArea关联的AccessibleContext。

intgetColumns()

返回TextArea中的列数。

protected intgetColumnWidth()

获取列宽。

intgetLineCount()

确定该区域中包含的行数。

intgetLineEndOffset(int line)

确定给定行末端的偏移量。

intgetLineOfOffset(int offset)

将偏移量转换为组件文本为行号。

intgetLineStartOffset(int line)

确定给定行开始的偏移量。

booleangetLineWrap()

获取文本区域的换行政策。

DimensiongetPreferredScrollableViewportSize()

如果此组件嵌入在JScrollPane中,则返回视口的首选大小。

DimensiongetPreferredSize()

返回TextArea的首选大小。

protected intgetRowHeight()

定义一行高度的含义。

intgetRows()

返回TextArea中的行数。

booleangetScrollableTracksViewportWidth()

如果视口应始终强制此Scrollable的宽度与视口的宽度相匹配,则返回true。

intgetScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)

显示逻辑行或列的组件应计算将根据取向值完全暴露一个新行或列的滚动增量。

intgetTabSize()

获取用于扩展选项卡的字符数。

StringgetUIClassID()

返回UI的类ID。

booleangetWrapStyleWord()

如果文本区域是包装线,则获取使用的包装样式。

voidinsert(String str, int pos)

在指定的位置插入指定的文本。

protected StringparamString()

返回此JTextArea的字符串表示形式。

voidreplaceRange(String str, int start, int end)

用指定的新文本替换指定的开始到结束位置的文本。

voidsetColumns(int columns)

设置此TextArea的列数。

voidsetFont(Font f)

设置当前字体。

voidsetLineWrap(boolean wrap)

设置文本区域的换行策略。

voidsetRows(int rows)

设置此TextArea的行数。

voidsetTabSize(int size)

设置扩展标签的字符数。

voidsetWrapStyleWord(boolean word)

如果文本区域是包装线,则设置使用的包装样式。

package com.demo.panel;

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

public class JTextAreaTest extends JFrame {
    public JTextAreaTest() throws HeadlessException {

        // 设置一个文本域  文本域可以换行,而文本框不行
        // 设置起始行列数,行列可变化
        JTextArea textArea = new JTextArea(20,30);
        textArea.setText("滑动面板的文本域,有换行功能");
        // JScrollPane面板
        JScrollPane scrollPane = new JScrollPane(textArea);

        Container container = this.getContentPane();
        container.add(scrollPane);

        setVisible(true);
        setBounds(100,100,200,300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        new JTextAreaTest();
    }
}

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐