package com.company; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Main extends JFrame { public Main(){ setBounds(100,100,500,300);//设置窗体坐标和大小 setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); Container c=getContentPane(); c.setLayout(new GridLayout(3,2,5,5)); JButton btn[]=new JButton[6]; for(int i=0;i<btn.length;i++){ btn[i]=new JButton(); c.add(btn[i]); } btn[0].setText("不可用");//设置文本 btn[0].setEnabled(false);//设置组建不可用 btn[1].setText("有背景色"); btn[1].setBackground(Color.YELLOW); btn[2].setText("不显示边框"); btn[2].setBorderPainted(false);//不显示边框 btn[3].setText("有边框"); btn[3].setBorder(BorderFactory.createLineBorder(Color.RED));//设置边框 ImageIcon cion=new ImageIcon("src/com/company/jbutton.PNG");//获取按钮 btn[4].setIcon(cion);//给按钮设置图片 btn[4].setToolTipText("我 喜 欢 你");//鼠标悬停提示 btn[5].setText("可点击"); btn[5].addActionListener(new ActionListener() {//添加事件监听 @Override public void actionPerformed(ActionEvent e) {//监听触发事件 JOptionPane.showMessageDialog(Main.this,"我喜欢你");//弹出小对话框 } }); setVisible(true);//设置窗体为可见 } public static void main(String[] args) { new Main(); // write your code here } }
通过两周的学习JFrame,小小的总结一下:
以终极目标邮箱为例,首先学习了窗体及其关闭规则,容器更好的承接了在窗体里插入文字和按钮,接着学习了流,边界,网格,绝对布局,其中绝对布局中设置按钮不随窗体大小改变而改变,通过学习在窗体里插入图片让窗体更漂亮,美观更加吸引人的眼球,滚动条让容器中的文本域查看更加便利,设置了六种按钮,中有其中有给按钮设置不可用,背景色,不显示边框,给边框添加颜色,图片,点击弹出对话框,这让按钮美观不失风采。