Swing常用容器

3、Swing(AWT的子类)

3.1窗口、面板

public class myJFrame extends JFrame {
    //JFrame是一个顶级窗口
    public myJFrame() {
        setBounds(100, 100, 400, 400);
        setVisible(true);
        //swing关闭窗口的方法
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}
//JFrame是Frame的子类
class Demo01JFrame extends myJFrame{
    //JFrame是一个顶级窗口
    public Demo01JFrame(){

        //组件都是在容器中设置
        //获得容器
        Container container = this.getContentPane(); //JFrame也属于一个容器,需要将容器实例化
        container.setBackground(new Color(172, 26, 9));
        container.setLayout(null);

        //添加面板
        JPanel jP = new JPanel();
        jP.setBackground(new Color(1,50,1));
        jP.setBounds(100,100,200,200);

        add(jP);
    }
}

//有一定的偏移,因为将顶部高度也算在其中了

3.2弹窗

class Demo02Frame extends myJFrame{
    public Demo02Frame(){
        //容器
        Container contentPane = this.getContentPane();
        //绝对布局
        contentPane.setLayout(null);
        Button btn1 = new Button("btn1");
        btn1.setBounds(100,100,70,30);
        btn1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new myJDialog();
            }
        });
        contentPane.add(btn1);
    }
}

//弹窗属性和frame类似
class myJDialog extends JDialog {
    public myJDialog() {
        setVisible(true);
        setBounds(500,500,300,300);
        this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

        //任何组件都需要放到容器当中,否则无效
        Container container = this.getContentPane();
        //container.setLayout(new FlowLayout(FlowLayout.CENTER));

        Label label = new Label("成功弹出弹窗");
        //如果显示中文只能设置为MS Song字体,否则的话就会显示方框状的乱码
        label.setFont(new Font("MS Song", Font.PLAIN, 9));
        container.add(label);
    }
}

3.3 imageIcon

public class IconJFrame extends myJFrame {
        public IconJFrame(){
            setSize(1000,1000);

            //图片在标签上显示
            JLabel jlabel = new JLabel();
            URL url = IconJFrame.class.getResource("tp.png");//直接获取同级目录下的图片地址
            ImageIcon imageIcon = new ImageIcon(url);
            //设置图片
            jlabel.setIcon(imageIcon);
            add(jlabel);
            setVisible(true);
        }
        public static void main(String[] args) {
        new IconJFrame();
    }
}

3.4 JScrollPane 滚动条面板

public class JScrollDemo extends myJFrame{
    public JScrollDemo(){
        //获取容器
        Container container = this.getContentPane();

        //创建文本域
        JTextArea jtArea = new JTextArea(50,50);
        jtArea.setText("hello");

        //创建一个滚动条面板
        JScrollPane scrollPane = new JScrollPane(jtArea);//添加了文本域
        scrollPane.setBounds(100,100,200,100);

        container.add(scrollPane);
        setVisible(true);
    }


    public static void main(String[] args) {
        new JScrollDemo();
    }
}
原文地址:https://www.cnblogs.com/shimmernight/p/13441717.html