Java Swing基础(顶层容器,中间层容器,原子组件)

Swing基础

Swing顶层容器

Swing的3个顶层容器类

  • JFrame、JApplet、JDialog
  • 都是重量级组件,分别继承了AWT组件Frame、Applet和Dialog
  • 每个顶层容器都有一个内容面板,通常直接或间接的容纳别的可视组件。
  • 可以有选择的为顶层容器添加菜单,菜单被放置再顶层容器上,但是在内容面板外。

JFrame使用举例

package swing;

import java.awt.BorderLayout;
import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class FrameDemo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JFrame frame = new JFrame("FrameDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JLabel emptyLabel = new JLabel("Hello World!!!");
        emptyLabel.setPreferredSize(new Dimension(175,100));
        frame.getContentPane().add(emptyLabel,BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
    }
}

就直接定义一个顶层容器的实例就可以了

对话框使用:通过静态方法showxxxDialog,可以产生四种简单的对话框,它们的方法参数绝大多数都要提供父窗口组件ParentComponent,只有关闭这些简单的对话框后,才能返回其父窗口,也就是说,它们绝大多数是模态的

对话框使用举例

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class JOptionPaneDemo extends JFrame implements ActionListener{
    public JOptionPaneDemo()
    {
        super("简单对话框");
        Container c = getContentPane();
        JButton button = new JButton("退出");
        button.addActionListener(this);
        //添加事件监听器
        c.setLayout(new FlowLayout());
        c.add(button);
    }
    public void actionPerformed(ActionEvent e)
    {
        int select = JOptionPane.showConfirmDialog(this, "确定退出吗?",
                "确定",JOptionPane.OK_CANCEL_OPTION,JOptionPane.WARNING_MESSAGE);
        if(select == JOptionPane.OK_OPTION);
            System.exit(0);
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JFrame frame = new JOptionPaneDemo();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(200,100);
        frame.setVisible(true);
    }
}

中间层容器

中间层容器是为了容纳其他组件而存在的

中间层容器

  • 一般用途的

    • Jpanel
    • JScrollPane
  • 特殊用途

    • JInternalFrame
    • JRootPane(可以直接从顶层容器中获得)

在这里插入图片描述

只要了解了中间层容器的基本概念就可以了,关于各种容器的用法可以到https://docs.oracle.com/javase/tutorial/这里去看

原子组件

直接与用户交互的组件

le.com/javase/tutorial/](https://docs.oracle.com/javase/tutorial/)这里去看

原子组件

直接与用户交互的组件

各种原子组件的用法可以到上面的网站去看

猜你喜欢

转载自blog.csdn.net/jump_into_zehe/article/details/106787338