【例6.1】一个简单的JFrame。
Example6_1.java
public class Example6_1 {
public static void main(String[] args) {
new MyJFrame();
}
}
MyJFrame.java
import java.awt.*;
import javax.swing.*;
public class MyJFrame extends JFrame {
public MyJFrame(){
super("框架示例"); //窗口名字
this.setBounds(200,200,200,200); //窗口长度
this.getContentPane().setBackground(Color.white); //背景颜色
this.setDefaultCloseOperation(EXIT_ON_CLOSE); //
this.setVisible(true);
}
}
【例6.2】流布局管理器示例。
Example6_2.java
public class Example6_2 {
public static void main(String[] args) {
new MyFlowLayout();
}
}
MyFlowLayout.java
import java.awt.*;
import javax.swing.*;
public class MyFlowLayout extends JFrame {
public MyFlowLayout(){
super("FlowLayout流布局示例");
this.setBounds(100,100,300,200);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.getContentPane().setLayout(new FlowLayout());
this.getContentPane().add(new JButton("button1"));//添加按钮
this.getContentPane().add(new JButton("button2"));
this.getContentPane().add(new JButton("button3"));
this.setVisible(true); //设置框架的可见性
}
}
【例6.3】边布局管理器示例
Example6_3.java
public class Example6_3 {
public static void main(String[] args) {
new MyBorderLayout();
}
}
MyBorderLayout.java
import java.awt.*;
import javax.swing.*;
public class MyBorderLayout extends JFrame {
public MyBorderLayout() {
super("BorderLayout边布局示例");
this.setBounds(100,100,500,200);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.getContentPane().add(new JButton("button_north"),"North");
this.getContentPane().add(new JButton("button_south"),"South");
this.getContentPane().add(new JButton("button_west"),"West");
this.getContentPane().add(new JButton("button_east"),"East");
this.getContentPane().add(new JButton("button_center"),"Center");
this.setVisible(true);
}
}
【例6.4】网格布局管理器示例
Example6_4.java
public class Example6_4 {
public static void main(String [] args) {
new MyGridLayout();
}
}
MyGridLayout.java
import java.awt.*;
import javax.swing.*;
public class MyGridLayout extends JFrame{
public MyGridLayout() {
super("GirdLayout网格布局示例");
this.setBounds(100,100,300,200);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.getContentPane().setLayout(new GridLayout(3,1));
this.getContentPane().add(new JButton("button1"));
JPanel jp=new JPanel();
jp.setLayout(new FlowLayout());
jp.add(new JButton("button2"));
jp.add(new JButton("button3"));
this.getContentPane().add(jp);
this.getContentPane().add(new JButton("button4"));
this.setVisible(true);
}
}
【例6.5】文本编辑组件示例
Example6_5.java
public class Example6_5 {
public static void main(String[] args) {
new TextComponents();
}
}
TextComponents.java
import java.awt.*;
import javax.swing.*;
public class TextComponents extends JFrame{
public TextComponents(){
super("文本显示和文本编辑示例");
this.setBounds(100,100,310,220);
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
this.setLayout(new FlowLayout(FlowLayout.RIGHT));
this. add(new JLabel("user"));
this. add(new JTextField(20));
this. add(new JLabel("password"));
this. add(new JPasswordField(20));
this. add(new JLabel("description"));
this. add(new JTextArea("my information:",5,20));
this.setVisible(true);
}
}
【例6.6】菜单示例
Example6_6.java
public class Example6_6 {
public static void main(String[] args) {
new MenuDemo();
}
}
MenuDemo.java
import java.awt.*;
import javax.swing.*;
public class MenuDemo extends JFrame {
public MenuDemo(){
super("菜单示例");
this.setBounds(100,100,200,200);
this.setDefaultCloseOperation (EXIT_ON_CLOSE);
//添加菜单栏
JMenuBar menubar=new JMenuBar();
this.setJMenuBar(menubar);
//添加菜单
JMenu menu_file=new JMenu("文件");
JMenu menu_help=new JMenu("帮助");
menubar.add(menu_file);
menubar.add(menu_help);
// 添加菜单项
JMenuItem mi1=new JMenuItem("打开");
JMenuItem mi2=new JMenuItem("保存");
JMenuItem mi3=new JMenuItem("关闭");
JCheckBoxMenuItem mi4=new JCheckBoxMenuItem("工具1");
JCheckBoxMenuItem mi5=new JCheckBoxMenuItem("工具2");
JRadioButtonMenuItem mi6=new JRadioButtonMenuItem("格式1");
JRadioButtonMenuItem mi7=new JRadioButtonMenuItem("格式2");
ButtonGroup bg=new ButtonGroup();
bg.add(mi6);
bg.add(mi7);
menu_file.add(mi1);
menu_file.add(mi2);
menu_file.add(mi3);
menu_file.addSeparator();
menu_file.add(mi4);
menu_file.add(mi5);
menu_file.addSeparator();
menu_file.add(mi6);
menu_file.add(mi7);
this.setVisible(true);
}
}
【例6.7】当鼠标进入到窗口时,背景色变为红色;鼠标移出窗口后,背景色变成白色
Example6_7.java
public class Example6_7 {
public static void main(String [] args) {
new MyJFrame();
}
}
MyJFrame.java
import java.awt.*;
import javax.swing.*;
public class MyJFrame extends JFrame{
public MyJFrame(){
super("事件监听器接口的简单例子");
this.setBounds(100,100,200,200);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
Container c=this.getContentPane(); //框架的内容窗格作为事件源
c.addMouseListener(new MyMouseListener2(c)); //注册监听器
this.setVisible(true);
}
}
MyMouseListener.java
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class MyMouseListener implements MouseListener{ //实现监听器接口的类
Container c;
public MyMouseListener(Container c){ //构造函数,用于传入事件源
this.c=c;
}
public void mouseEntered(MouseEvent e) { //鼠标进入时的事件处理方法
c.setBackground(Color.RED);
}
public void mouseExited(MouseEvent e) { //鼠标移出时的事件处理方法
c.setBackground(Color.WHITE);
}
public void mouseClicked(MouseEvent e) { } //监听器接口的其它方法未调用,但需要给出空实现
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
}
【例6.8】用事件适配器类改写例6_7。
Example6_8.java
public class Example6_8 {
public static void main(String[] args) {
new MyJFrame2();
}
}
MyJFrame2.java
import javax.swing.*;//组件与响应类仍然各自一个类
import java.awt.*;
public class MyJFrame2 extends JFrame {
public MyJFrame2(){
super("事件监听器接口的简单例子");
this.setBounds(100,100,200,200);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
Container c=this.getContentPane();
c.addMouseListener(new MyMouseListener2(c));
this.setVisible(true);
}
}
MyMouseListener2.java
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class MyMouseListener2 extends MouseAdapter{ //监听器继承自事件适配器类
Container c;
public MyMouseListener2(Container c){
this.c=c;
}
public void mouseEntered(MouseEvent e) {
c.setBackground(Color.RED);
}
public void mouseExited(MouseEvent e) {
c.setBackground(Color.WHITE);
}
}
【例6.9】按钮组件示例
Example6_9.java
public class Example6_9 {
public static void main(String[] args) {
new ButtonComponents();
}
}
ButtonComponents.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;//组件类自己完成组件布局和//响应两个功能,但两个功能分别具有自己的方法.业主自己装修,要实现接口
public class ButtonComponents extends JFrame implements ActionListener{
JTextArea text; // 组合
JButton btn_ok;
JTextField text_name;
JRadioButton rb[];
JCheckBox cb[];
String str="";
public ButtonComponents(){
super("按钮组件示例");
String[] sex={"male","female"};//用于生成一组单选按钮上的文字
String[] hobbies={"sport","music"}; //用于生成多个复选框上的文字
this.setBounds(100,100,300,180);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
text=new JTextArea(5,10);
this. add(text,"West");
JPanel panel=new JPanel(new FlowLayout());//效果图中右半部分的布局
this. add(panel);
panel.add(new JLabel("name:"));
text_name=new JTextField(12);
panel.add(text_name);
panel.add(new JLabel("sex:"));
//用循环语句产生多个单选按钮,将其加入同一个按钮组,并添加到面板中
ButtonGroup bg=new ButtonGroup();
rb=new JRadioButton[sex.length];//一个数组的长度作为另一个数组的长度
for (int i=0;i<sex.length;i++){//用字符串数组生成单选按钮数组
rb[i]=new JRadioButton(sex[i]);
bg.add(rb[i]);//数组元素作为方法的参数
panel.add(rb[i]);
}
panel.add(new JLabel("hobbies:"));
cb=new JCheckBox[hobbies.length];
for (int i=0;i<hobbies.length;i++){
cb[i]=new JCheckBox(hobbies[i]);
panel.add(cb[i]);
}
btn_ok=new JButton("ok");
btn_ok.addActionListener(this);
panel.add(btn_ok);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==btn_ok){
str+=" name:\n"+text_name.getText()+"\n sex: \n";
for (int i=0;i<rb.length;i++)
if (rb[i].isSelected())
str+=rb[i].getText(); //查看各单选按钮的选中状态
str+="\n hobbies: ";
for(int i=0;i<cb.length;i++)
if (cb[i].isSelected())
str+="\n"+cb[i].getText();
text.append(str);
}
}
}
【例6.10】列表框和组合框示例
Example6_10.java
public class Example6_10 {
public static void main(String[] args) {
new ItemComponents();
}
}
ItemComponents.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class ItemComponents extends JFrame{
JComboBox cb_channel;
JList list_shows;
JLabel label;
Object[] channel={"中央一台","中央二台"}; //用来作为组合框的条目
Object[][] shows={{"新闻联播","焦点访谈"},{"交换空间","经济与法","经济半小时"}};
//用来作为列表框的条目
public ItemComponents(){
super("按钮组件示例");
this.setBounds(100,100,250,180);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this. setLayout(new FlowLayout());
//添加组合框、列表框、标签
cb_channel=new JComboBox(channel);
this. add(cb_channel);
list_shows=new JList(shows[0]);
this. add(list_shows);
label=new JLabel("");
this. add(label);
//为组合框注册监听器ItemListener
cb_channel.addItemListener(new ItemListener(){
//匿名内部类,静态组件与动态响应的功能在一个方法中实现,不是在两个方法中实现,更不是在两个类中实现.
public void itemStateChanged(ItemEvent e) {
int i=cb_channel.getSelectedIndex();
list_shows.setListData(shows[i]);
}
});
//为列表框注册事件监听器ListSelectionListener
list_shows.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e) {
String str=cb_channel.getSelectedItem().toString();
if (!list_shows.isSelectionEmpty()) //如果有选中的选项,则在label中显示该值
str+=" "+list_shows.getSelectedValue();
label.setText("您选择的是:"+str);
}
});
this.setVisible(true);
}
}
【例6.11】对话框示例
Example6_11.java
public class Example6_11 {
public static void main(String[] args) {
// TODO Auto-generated method stub
new DialogDemo();
}
}
DialogDemo.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class DialogDemo extends JFrame {
private JButton btn;
private MyJDialog dialog;
public DialogDemo() {
super("对话框示例");
this.setBounds(100,100,200,200);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
btn=new JButton("打开对话框");
this.getContentPane().add(btn);
dialog=new MyJDialog(this);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btn)
dialog.setVisible(true);
}
});
this.setVisible(true);
}
class MyJDialog extends JDialog{
public MyJDialog(JFrame jframe) {
super(jframe,"我的对话框",true);
this.setBounds(jframe.getX()+jframe.getWidth()+10,jframe.getY(),150,150);
this.setDefaultCloseOperation(HIDE_ON_CLOSE);
this.getContentPane().setLayout(new FlowLayout());
this.getContentPane().add(new JButton("学习"));
this.getContentPane().add(new JButton("休息"));
}
}
}
【例6.12】弹出菜单示例
Example6_12.java
public class Example6_12 {
public static void main(String[] args) {
new PopupMenuDemo();
}
}
PopupMenuDemo.java
import java.awt.*;
import javax.swing.*;
public class PopupMenuDemo extends JFrame{
private JTextArea text;
private JPopupMenu popmenu;
public PopupMenuDemo() {
super("菜单示例");
this.setBounds(100,100,200,200);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.text=new JTextArea("我是中国人");
this.getContentPane().add(this.text);
this.popmenu=new JPopupMenu();
String popstr[]= {"剪切","复制","粘贴"};
JMenuItem popmenuitthis[]=new JMenuItem[popstr.length];
MyActionListener3 mal=new MyActionListener3(text);
for(int i=0;i<popstr.length;i++) {
popmenuitthis[i]=new JMenuItem(popstr[i]);
this.popmenu.add(popmenuitthis[i]);
popmenuitthis[i].addActionListener(mal);
}
this.text.add(this.popmenu); //快捷菜单依附于组件
MyMouseListener mml=new MyMouseListener(text,popmenu);
this.text.addMouseListener(mml);
this.setVisible(true);
}
}
MyActionListener3.java
import java.awt.event.*;
import javax.swing.*;
public class MyActionListener3 implements ActionListener {
private JTextArea text;
public MyActionListener3 (JTextArea text) {
this.text=text;
}
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand()=="复制") {text.copy();}
if(e.getActionCommand()=="粘贴") {text.paste();}
if(e.getActionCommand()=="剪切") {text.cut();}
}
}
MyMouseListener.java
import java.awt.event.*;
import javax.swing.*;
public class MyMouseListener implements MouseListener {
private JTextArea text;
private JPopupMenu popmenu;
public MyMouseListener(JTextArea text,JPopupMenu popmenu) {
this.text=text;
this.popmenu=popmenu;
}
public void mouseClicked(MouseEvent e) {
if(e.getModifiers()==MouseEvent.BUTTON3_MASK)
popmenu.show(text,e.getX(),e.getY());
}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}
【例6.13】本例设计一个简单的文本编辑器,可实现对文本区中的字符串进行字号大小、字形、字体颜色的设置。文本编辑器中设置菜单栏,且右击文本区,可弹出快捷菜单。
Example6_13.java
public class Example6_13 {
public static void main(String[] args) {
new TextJFrame();
}
}
TextJFrame.java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TextJFrame extends JFrame{
private JFrame jf;
private JTextArea text;
private JComboBox jcb;
private JCheckBox check_bold,check_italic;
private JRadioButton radio_red,radio_green,radio_blue;
private JPopupMenu popmenu;
public TextJFrame() {
jf=new JFrame("文本编辑器");
jf.setBounds(100,100,500,200);
jf.setDefaultCloseOperation(EXIT_ON_CLOSE);
jf.setVisible(true);
JMenuBar menubar=new JMenuBar();
jf.setJMenuBar(menubar);
String str[]= {"文件","编辑","帮助"};
JMenu menu[]=new JMenu[str.length];
for(int i=0;i<str.length;i++) {
menu[i]=new JMenu(str[i]);
menubar.add(menu[i]);
}
text=new JTextArea("示例文本");
jf.getContentPane().add(text);
JToolBar toolbar=new JToolBar();
toolbar.setLayout(new FlowLayout());
jf.getContentPane().add(toolbar,"North");
jcb=new JComboBox();
jcb.setEditable (true);
toolbar.add(jcb);
String[] str_size={"20","30","40","50","60"};
String str_file[]= {"打开","保存","退出"};
JMenuItem menuitem[]=new JMenuItem[str_file.length];
for(int j=0; j<str_file.length;j++) {
menuitem[j]=new JMenuItem(str_file[j]);
menu[0].add(menuitem[j]);
menu[0].addSeparator();
menuitem[j].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() instanceof JMenuItem) {
if(e.getActionCommand()=="退出") {
if(JOptionPane.showConfirmDialog(jf,"你确定退出么?")==0)
System.exit(0);
}
}
}
});
}
check_bold=new JCheckBox("粗体");
check_italic=new JCheckBox("斜体");
toolbar.add(check_bold);
toolbar.add(check_italic);
check_bold.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() instanceof JCheckBox) {
if(e.getActionCommand()=="粗体") {
Font f=text.getFont();
text.setFont(new Font(f.getFontName(),Font.BOLD,f.getSize()));
}
}
}
});
check_italic.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() instanceof JCheckBox) {
if(e.getActionCommand()=="斜体") {
Font f=text.getFont();
text.setFont(new Font(f.getFontName(),Font.ITALIC,f.getSize()));
}
}
}
});
radio_red=new JRadioButton("红色");
radio_green=new JRadioButton("绿色");
radio_blue=new JRadioButton("蓝色");
ButtonGroup bg= new ButtonGroup();
bg.add(radio_red);
bg.add(radio_green);
bg.add(radio_blue);
radio_red.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if(e.getSource() instanceof JRadioButton) {
if(e.getActionCommand()=="红色") {
text.setForeground(Color.red);
}
}
}
});
radio_green.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if(e.getSource() instanceof JRadioButton) {
if(e.getActionCommand()=="绿色") {
text.setForeground(Color.green);
}
}
}
});
radio_blue.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
if(e.getSource() instanceof JRadioButton) {
if(e.getActionCommand()=="蓝色") {
text.setForeground(Color.blue);
}
}
}
});
popmenu=new JPopupMenu();
String popstr[]= {"剪切","复制","粘贴"};
JMenuItem popmenuitem[]=new JMenuItem[popstr.length];
for(int i=0;i<popstr.length;i++) {
popmenuitem[i]=new JMenuItem(popstr[i]);
popmenu.add(popmenuitem[i]);
popmenuitem[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() instanceof JMenuItem) {
if(e.getActionCommand()=="复制") {
text.copy();
}
if(e.getActionCommand()=="粘贴") {
text.paste();
}
if(e.getActionCommand()=="剪切") {
text.cut();
}
}
}
});
}
text.add(popmenu);
text.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
if (e.getModifiers()==MouseEvent.BUTTON3_MASK)
popmenu.show(text,e.getX(),e.getY());
}
public void mouseEntered(MouseEvent e) {};
public void mouseExited(MouseEvent e) {};
public void mousePressed(MouseEvent e) {};
public void mouseReleased(MouseEvent e) {};
});
for (int i=0;i<str_size.length;i++) {
jcb.addItem(str_size[i]);
jcb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource() instanceof JComboBox) {
Font f=text.getFont();
try {
int i=Integer.parseInt((String) jcb.getSelectedItem());
text.setFont(new Font(f.getFontName(),f.getStyle(),i));
} catch(Exception ex) {
JOptionPane.showMessageDialog(jf, "字号大小不合适,请重新输入");
jcb.setSelectedItem(String.valueOf(f.getSize()));
}
String size=(String) jcb.getSelectedItem();
int i=0,n=jcb.getItemCount();
while(i<n && size.compareTo((String)jcb.getItemAt(i))>=0) {
if(size.compareTo((String)jcb.getItemAt(i))==0)
return;
i++;
}
jcb.insertItemAt(size,i);
}
}
});
}
}
}
【例6.14】首先编写一个封装矩形的类,然后再编写一个窗口。要求窗口使用两个标签表示矩形的长和宽,两个文本行可以输入矩形的长和宽,一个文本区输出矩形的面积,一个按钮,单击后计算矩形的面积。要求有判断矩形是否为正方形的代码,即长和宽相等。要求编写3个类,一个主类RectangleMVC.java,一个图形界面类WindowRectangle.java,一个完成求矩形面积以及判断矩形是否为正方形的类Rectangle.java,即业务要与视图分离。
RectangleAreaMVC.java
public class RectangleAreaMVC {
public static void main(String[] args) {
WindowRectangel win=new WindowRectangel();
win.setTitle("使用MVC结构计算矩形或正方形的面积");
win.setBounds(100,100,400,200);
}
}
WindowRectangel.java
//import java.awt.*;
//import javax.swing.*;
//import java.awt.event.*;
public class WindowRectangel extends JFrame implements ActionListener {
JTextField tf_width,tf_length;
JButton btn_area;
JTextArea text;
Rectangle r;
public WindowRectangel() {
r=new Rectangle();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel p1=new JPanel();
p1.add(new JLabel("长度"));
tf_length=new JTextField(5);
p1.add(tf_length);
p1.add(new JLabel("宽度"));
tf_width=new JTextField(5);
p1.add(tf_width);
btn_area=new JButton("计算面积");
btn_area.addActionListener(this);
p1.add(btn_area);
this.getContentPane().add(p1,"North");
text=new JTextArea(5,20);
this.getContentPane().add(text);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try {
int length=Integer.parseInt(tf_length.getText());
int width=Integer.parseInt(tf_width.getText());
r.setLength(length);
r.setWidth(width);
if(r.isSquare())
text.append("正方形的边长:"+length+",面积:"+r.area()+"\n");
else text.append("长方形的长:"+length+", 宽:"+width+",面积:"+r.area()+"\n");
}
catch(Exception ex) {
text.append("无法计算面积:"+ex.toString()+"\n");
}
}
}
Rectangle.java
public class Rectangle {
private int length;
private int width;
public Rectangle() {}
public void setLength(int length) {
this.length=length;
}
public void setWidth(int width) {
this.width=width;
}
public boolean isSquare() {
return width==length?true:false;
}
public int area() {
return width*length;
}
}