Swing代码练习2

- 图标、按钮

JLabel标签,通过Icon接口创建图标(并给定图标大小颜色等)

//非正确代码233
import javax.swing.JLabel;

public class MyImage extends JFrame {
	public MyImage() {
		Container container = getContentPane();
		JLable jl = new JLabel("JAVA STUDY",JLabel.CENTER);//创建标签
		URL url = MyImage.class.getResource("imageButton.jpg");
		Icon icon = new ImageIcon(url);//实例化Icon对象
		jl.setlcon(icon);//为标签设置图片
		jl.setHorzontalAlignment(SwingConstants.CENTER);
		jl.setOpaque(true);////标签不透明
		container.add(jl);
		setSize(300,300);
		setVisble(true);//窗体可见
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
	}
	public static void main(String args[]) {
		new MyImage();
	}
}

布局管理器

绝对布局
绝对布局就是硬性指定组件位置。
使用之前需要取消布局管理器setLayout(null);//取消布局管理区

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

public class AbsolutePosition extends JFrame {
	public AbsolutePosition() {
		setTitle("JAVA Study");//窗体标题
		setLayout(null);//取消布局管理区
		setBounds(0,0,800,850);
		Container c = getContentPane();//创建容器对象
		JButton b1 = new JButton("Point me1");
		JButton b2 = new JButton("Point me2");
		b1.setBounds(10,30,80,30);//位置and大小
		b2.setBounds(60,70,100,20);
		c.add(b1);
		c.add(b2);
		setVisible(true);//使窗体可见
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
	}
	public static void main(String[] args) {
		new AbsolutePosition();
	}
}

运行结果,这里的JButton按了没laun用,233,还没搞东西。待下面加东西。
在这里插入图片描述
流布局管理器
默认剧中排列,也可设置为向左对齐(0),向右对齐(2);
在这里插入图片描述

import java.awt.Container;
import java.awt.*;
import javax.swing.*;
public class FLowLayoutPosition extends JFrame {
	public FLowLayoutPosition() {
		setTitle("吴明窗体");
		Container c = getContentPane();
		setLayout(new FlowLayout(2,10,10));//组件向右对齐,设置水平垂直间隔
		for(int i=0;i<10;i++)
		c.add(new JButton("button"+i));
		setSize(300,200);
		setVisible(true);
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);//关闭方式
	}
	public static void main(String[] args) {
		new FLowLayoutPosition();
	}
}

在这里插入图片描述
布局管理器还有:
边界布局管理器BorderLayout,边界布局管理器的特点使可以把组件安排在东南西北中五个地方
在这里插入图片描述网格布局管理器GridLayout
按行按列进行排列。每个组件的大小相同。

常用面板

JPanel面板
可以聚焦一些组件来布局。ddd
JScrollpane面板
这个面板在当我们的内容在窗体显示不下时使用,它带滚动条。但是只能放一个组件。
可以把多个组件放在JPanel上面然后把JPanel看作整体放在JScrollpane上面

import java.awt.*;
import javax.swing.*;
public class JSscroo extends JFrame {
	public JSscroo() {
		Container c = getContentPane();
		JTextArea ta = new JTextArea(20,50);
		JScrollPane sp =new JScrollPane(ta);
		c.add(sp);
		setTitle("随便叫个什么");
		setSize(300,300);
		setVisible(true);
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
	}
	public static void main(String[] args) {
		new JSscroo();
	}
}

在这里插入图片描述

发布了53 篇原创文章 · 获赞 6 · 访问量 4898

猜你喜欢

转载自blog.csdn.net/m0_46193982/article/details/104774736
今日推荐