Java图形界面的编写

旧街凉风 提交于 2019-12-24 04:20:39

Java学习笔记十

图形化用户界面

AWT库

extends
extends
extends
extends
extends
extends
extends
extends
extends
extends
JButton
JComponent
JPanel
JLabel
JList
...
Container
Windows
JFrame
JDialog
Component
implements
implements
implements
implements
implements
implements
implements
MouseEvent
InputEvent
KeyEvent
WindowsEvent
ComponentEvent
FoucusEvent
ContainEvent
AWTEvent

常用的几个类

  • JFrame
  • JList
  • JLabel
  • JButton
  • JPanel

我们使用JFrame来创建一个图形化界面,我们可以自定义其的大小,布局,标题,初始化位置,还有其内部的组件布局,注意在创建一了JFrame类时,我们把这些除组件布局外的基本初始化写在构造函数的后面,不然在实例化窗口对象时会出现组件不可见的情况

public class MyFrame extends JFrame{
    private Container container;
    private JButton button;
    
    public MyFrame(){
        container = this.getContentPane();
        button = new JButton("My Button");
        container.add(button);
        container.setLayout(New FlowLayout());
        
        this.setTitle("My Frame");
        this.setSize(600,800);
        this.setDefaluteCloseOperation(JFrame.Exit_On_Close);
        this.setVisible(true);
    }
}

这样一个最简单的窗口就构建完毕了,如果你想要在窗口关闭时执行一些操作,你可以

addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
                //the operation you want to do
            }
        });

JList时功能非常强大的一个组件,你可以对其任意一个单位添加监控,操作如下

list.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if(e.getClickCount()==2){
                        //···
                    }
                }
            });

你还可以给Jlist组件添加一个scrollPanel

JScrollPane scrollPane = new JScrollPane();
            scrollPane.setBounds(80,132,369,213);
            scrollPane.setViewportView(list);
            panel.add(scrollPane);//the panel is a component which the list attached to;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!