3.Swing
3.1窗口 、 容器
public class JFrameDemo {
//init(); 初始化
public void init(){
JFrame frame = new JFrame("这是第一个JFrame窗口");
frame.setVisible(true);
frame.setBounds(100,100,200,200);
//设置文字
JLabel label = new JLabel("欢迎来到相亲大会");
//让文本标签居中 设置水平对齐
label.setHorizontalAlignment(SwingConstants.CENTER);
frame.add(label);
Container contentPane = frame.getContentPane();
contentPane.setBackground(Color.cyan);
//关闭事件
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
//创建一个窗口
new JFrameDemo().init();
}
}
3.2弹窗
JDialog,,用来被弹出,默认就有关闭事件
//主方法
public class DialogDemo extends JFrame {
public DialogDemo(){
setVisible(true);
setBounds(100,100,700,500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//JFrame放东西 容器
Container container = getContentPane();
container.setLayout(null);
//按钮
JButton button = new JButton("点击弹出一个对话框");
button.setBounds(30,30,200,50);
//点击按钮触发弹窗
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new MyDialogDemo();
}
});
container.add(button);
}
public static void main(String[] args) {
new DialogDemo();
}
}
//弹出窗口
class MyDialogDemo extends JDialog{
public MyDialogDemo() {
this.setVisible(true);
this.setBounds(100,100,500,500);
//this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Container container = this.getContentPane();
container.setLayout(null);
container.add(new JLabel("狂神最帅"));
}
}
3.3 标签
lable
JLable lable = new JLable("xxxx");
图标Icon
//图标需要实现类,Frame继承
public class IconDemo extends JFrame implements Icon {
private int width;
private int height;
public IconDemo(){
}
public IconDemo(int width, int height) {
this.width = width;
this.height = height;
}
public void init(){
IconDemo iconDemo = new IconDemo(15,15);
//图标可以放在标签上,也可以放在按钮上
JLabel label = new JLabel("icontest", iconDemo, SwingConstants.CENTER);
Container container = getContentPane();
container.add(label);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.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 width;
}
@Override
public int getIconHeight() {
return height;
}
public static void main(String[] args) {
new IconDemo().init();
}
}
图片Icon
public class ImageIconDemo extends JFrame {
public ImageIconDemo(){
//获取图片地址
JLabel label = new JLabel("ImageIcon");
URL url = ImageIconDemo.class.getResource("male.gif");
ImageIcon icon = new ImageIcon(url);
label.setIcon(icon);
label.setHorizontalAlignment(SwingConstants.CENTER);
Container container = getContentPane();
container.add(label);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setBounds(100,100,200,200);
}
public static void main(String[] args) {
new ImageIconDemo();
}
}