JavaSwing学习笔记(一)

2018-03-01  本文已影响0人  一杯清凉的水
一:JFrame(Swing框架类)
package n1;

import java.awt.Color;
import java.awt.Container;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

public class MyFrame1 extends JFrame{
    
    public void start() {
        JFrame jf=new JFrame("窗口");
        Container container=jf.getContentPane();
        container.setBackground(Color.white);
        JLabel jl=new JLabel("标签");
        jl.setHorizontalAlignment(SwingConstants.CENTER);
        container.add(jl);
        jf.setVisible(true);
        jf.setSize(300, 200);
        jf.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
        MyFrame1 myframe=new MyFrame1();
        myframe.start();
    }
}

运行结果:

image.png
二:JDialog(Java对话框)
package n1;

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

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;

class MyDialog extends JDialog{
    
    public MyDialog(MyFrame frame) {
        super(frame,"Dialog",true);
        Container container=getContentPane();
        container.add(new JLabel("Hello"));
        container.setBackground(Color.white);
        setBounds(120,120,100,100);
    }
}
public class MyFrame extends JFrame{
    public static void main(String[] args) {
        new MyFrame();
    }
    public MyFrame() {
        Container container=getContentPane();
        container.setLayout(null);
        container.setBackground(Color.white);
        JButton button=new JButton("按钮");
        button.setBounds(33, 33, 80, 30);
        button.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                new MyDialog(MyFrame.this).setVisible(true);
            }
        });
        container.add(button);
        setVisible(true);
        setSize(300, 200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
    
}

运行结果:

image.png
注意事项:

1. 我第一次的时候在一个文件中写了两个public类,报错,且无法执行,
后来百度一下,原来是这样:


参考资料:

上一篇 下一篇

猜你喜欢

热点阅读