GUI基础编程 Day 05
swing
窗口 面板
import javax.swing.*;
import java.awt.*;
public class JFrameDemo01 {
//init(); 初始化
public void init(){
//顶级窗口
JFrame jFrame = new JFrame("这是一个JFrame窗口!");
jFrame.setVisible(true);
jFrame.setBounds(200,200,500,500);
jFrame.setBackground(Color.cyan);
//设置文字 Jlabel
JLabel jLabel = new JLabel("欢迎来到GUI基础!");
jFrame.add(jLabel);
//关闭事件
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
//建立一个窗口
new JFrameDemo01().init();
}
}
优化 标签居中
import javax.swing.*;
import java.awt.*;
public class JFrameDemo02 {
public static void main(String[] args) {
new MyJFrame02().init();
}
}
class MyJFrame02 extends JFrame{
public void init(){
this.setVisible(true);
this.setBounds(200,200,600,600);
JLabel jLabel = new JLabel("居中");
this.add(jLabel);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//让文本标签居中 设置水平对齐
jLabel.setHorizontalAlignment(SwingConstants.CENTER);
//获得一个容器
Container container = this.getContentPane();
container.setBackground(Color.YELLOW);
}
}
弹窗
注意:弹窗自带关闭事件,可以不写
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//主窗口
public class DialogDemo extends JFrame {
public DialogDemo(){
this.setVisible(true);
this.setBounds(100,100,500,500);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//JFrame 放东西 容器
Container container = this.getContentPane();
//绝对布局
container.setLayout(null);
//按钮
JButton button = new JButton("点击出现一个窗口!"); //创建一个对象
button.setBounds(50,50,200,50);
//点击按钮的时候出现一个弹窗 弹窗默认就有关闭事件
button.addActionListener(new ActionListener() { //监听事件
@Override
public void actionPerformed(ActionEvent e) {
new MyDialog();
}
});
container.add(button);
}
public static void main(String[] args) {
new DialogDemo();
}
}
class MyDialog extends JDialog{
public MyDialog() {
this.setVisible(true);
this.setBounds(100,100,200,200);
Container container = this.getContentPane();
container.setLayout(null);
container.add(new Label("第一个弹窗!"));
}
}
问题:弹窗中的文字不显示!
修改:
class MyDialog extends JDialog{
public MyDialog() {
this.setVisible(true);
this.setBounds(100,100,200,200);
Container container = this.getContentPane();
//container.setLayout(null);
//container.add(new JLabel("第一个弹窗!"));
JLabel label = new JLabel("第一个弹窗!");
//1.居中
//add(label);
//label.setHorizontalAlignment(SwingConstants.CENTER);
//2.
container.add(label);
label.setHorizontalAlignment(SwingConstants.CENTER);
}
}