JAVA面向对象程序设计基础教程第六章例子

【例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;
	}

}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: Java面向对象程序设计是一种使用Java语言进行编程的方法。它基于面向对象的编程范式,强调将问题划分为多个独立的对象,并通过对象之间的交互解决问题。 Java是一种通用的、跨平台的高级编程语言,广泛用于各个领域的软件开发。面向对象程序设计Java的核心特性之一,也是其成功的关键因素之一。通过使用面向对象程序设计,开发人员可以将复杂的问题分解为多个简单的对象,每个对象负责特定的功能,从而提高代码的复用性和可维护性。 Java面向对象程序设计的主要特点包括封装、继承和多态。封装可以将对象的实现细节隐藏起来,只暴露必要的接口给其他对象使用,增加了代码的安全性和可读性。继承允许一个类继承另一个类的属性和方法,从而减少了代码的重复编写,提高了代码的可重用性。多态允许一个对象以不同的形态呈现,提供了更灵活的代码设计和扩展能力。 Java面向对象程序设计的核心概念包括类、对象、方法和属性。类是创建对象的模板,它包含了对象的特征和行为。对象是类的实例,具有类定义的属性和方法。方法是类和对象的行为,用于实现特定的功能。属性是类和对象的特征,描述了它们的状态。 对于初学者来说,掌握Java面向对象程序设计是非常重要的。它不仅能帮助他们理解程序的结构和组织,还能提高他们的问题分析和解决能力。Java面向对象程序设计的基本概念和技巧也适用于其他面向对象的编程语言,为进一步学习和掌握其他编程语言奠定了良好的基础。 总而言之,Java面向对象程序设计是一种强大且灵活的编程方法,它能够帮助开发人员构建可维护和可扩展的软件系统。通过深入学习和应用Java面向对象程序设计的原理和技术,开发人员能够更好地理解和利用Java语言的特性,提高自己的编程水平。 ### 回答2: 《Java面向对象程序设计PDF》是一本关于Java编程语言面向对象程序设计的电子书。它涵盖了Java编程语言的基础知识和面向对象编程的核心概念。该书主要分为以下几个部分: 首先,它介绍了Java语言的基本语法,包括变量、数据类型、运算符等。这些基础知识对于理解后续的面向对象编程非常重要。 其次,它详细介绍了面向对象编程的核心概念,如类、对象、继承、多态等。通过实例和案例分析,读者可以深入理解这些概念的原理和应用。 此外,该书还介绍了Java的常用类库和API,如集合框架、输入输出流等。这些类库和API为Java开发者提供了丰富的功能和工具,能够提高开发效率和代码质量。 最后,该书还涵盖了一些高级主题,如异常处理、多线程编程、网络编程等。这些主题对于开发具有复杂功能和高性能要求的应用程序非常重要。 总体而言,该书全面而系统地介绍了Java面向对象程序设计的基础知识和高级应用。它适合初学者入门以及有一定Java编程经验的开发者进一步提高自己的编程能力。读者可以通过学习该书,掌握Java面向对象编程的核心概念和技术,从而能够设计和开发出功能强大、灵活性好的Java应用程序。 ### 回答3: Java面向对象程序设计(Object-oriented Programming,简称OOP)是一种应用广泛的程序设计模式,使用Java编程语言进行实现。Java语言将数据和操作封装在对象中,通过定义类和对象之间的关系来实现程序的设计和开发。 在Java面向对象程序设计中,开发者将问题抽象为对象模型,将问题的属性和行为封装在类中。通过创建对象,可以实例化类,并使用类提供的方法进行操作和交互。这种设计思想使得程序具有更高的可重用性和可维护性。 Java面向对象程序设计的优点之一是封装性。通过将数据和方法封装在对象中,可以隐藏内部实现的细节。这样的设计可以有效地保护数据的完整性和安全性,同时提供更加清晰的接口,方便其他对象与之交互。 另一个优点是继承性。Java面向对象程序设计通过继承机制,实现类与类之间的关联和扩展。继承可以使得代码的重用更加方便,提高了程序的可扩展性。同时,借助多态性的特性,可以进行更灵活的编程和适应不同的需求。 此外,Java面向对象程序设计还具有多线程、异常处理和异常处理等特性,使得程序开发更加灵活和稳定。 总的来说,Java面向对象程序设计是一种强大的编程模式,通过封装、继承、多态等基本特性,使得程序更加模块化、可维护性强、可扩展性高。同时,Java面向对象程序设计还提供了很多其他特性,如多线程和异常处理等,使得程序开发变得更加方便和稳定。对于想要学习Java编程或进行软件开发的人来说,掌握Java面向对象程序设计是非常重要的一部分。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值