java學習整理五


1.創建一個具有關閉功能的空白窗口(如圖5-1)。

(知識點:在Eclipse下創建窗體,事件處理)

import java.awt.*;

import java.awt.event.*;

import javax.swing.JFrame;

public class SY5_1_JFrame 【代碼1{//繼承JFrame

public static void main(String[] args) {

new SY5_1_JFrame();

}

    //構造函數

public SY5_1_JFrame() {

   【代碼2;// 創建標題為“JFrame窗口”窗口對象

   【代碼3;// 設置窗口大小為400 x 200

   【代碼4;// 設置窗口是可視的

//為窗口添加窗口事件適配用來關閉窗體,這里大家暫時照用就是

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {// 關閉窗口事件的方法

System.exit(0);

}

});

}

}

 

5-1 JFrame窗口

 

 

 

 

5-2 帶組件的窗口

 

 

SY5_1_JFrame extends JFrame

 

2.在窗體界面上添加相應組件,程序運行結果如圖5-2。

(知識點:在NetBeans/Eclipse下創建窗體,基本組件的使用,事件處理)

 

SY5_1_1_JFrame extends JFrame

 

3.編寫窗體程序SY5_2_CalMoney,如圖5-3所示,界面上設置三個文本框,第一個文本框給用戶輸入商品單價,第二個則是給用戶輸入商品數量,第三個用於顯示總金額。

要求:①單價框和商品數量框中要求輸入的只能數字;②當在單價框中按“回車”時商品數量框獲得焦點,當在數量框中按“回車”時完成計算並在總金額框中顯示總金額。

 

 

 

 

5-3 計算金額窗口

 

 

 

 

        

 

 

 

 

5-4 輸入錯誤時提示

(知識點:在NetBeans/Eclipse下創建窗體,基本組件的使用,鍵盤事件處理,對話框)

package Exp05_03_20170566134;
import java.awt.Button;
import java.awt.KeyboardFocusManager;
import java.awt.event.*;
import java.io.Console;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class SY5_2_CalMoney extends JFrame implements ActionListener,KeyListener{//繼承JFrame類
    private JLabel name;
    private JTextField nameField;
    private JLabel call;
    private JTextField nameField2;
    private JLabel money;
    private JTextField moneyField;
    public static void main(String[] args) {
        new SY5_2_CalMoney();
    }
    //構造函數
    public SY5_2_CalMoney() {
       super("JFrame");// 創建標題為“JFrame窗口”窗口對象
       setSize(250,150);// 設置窗口大小為400 x 200
       this.setLocationRelativeTo(null);//窗體居中顯示
       
       name = new JLabel("商品單價");
       nameField = new JTextField("4.5");
       call = new JLabel("購買數量");
       nameField2 = new JTextField("20");
       money =new JLabel("應付金額");
       moneyField =new JTextField();
       
       this.setVisible(true);// 設置窗口是可視的
        //為窗口添加窗口事件適配用來關閉窗體,這里大家暫時照用就是
        addWindowListener(new WindowAdapter() {   //
            public void windowClosing(WindowEvent e) {// 關閉窗口事件的方法
                System.exit(0);
            }
        });
        setLayout(null);
        name.setBounds(30,10,80,20);
        nameField.setBounds(100,10,80,20);
        nameField.addActionListener(this);//數據綁定  以下兩種方式均可
        nameField.addKeyListener(this);//數據綁定
        call.setBounds(30,45,80,20);
        nameField2.setBounds(100, 45, 80, 20);
        nameField2.addActionListener(this);//數據綁定  以下兩種方式均可
        nameField2.addKeyListener(this);//數據綁定
        money.setBounds(30, 70, 80, 20);
        moneyField.setBounds(100, 75, 80, 20);
        moneyField.addActionListener(this);
        moneyField.setEditable(false);
        add(name);
        add(nameField);
        add(call);
        add(nameField2);
        add(money);
        add(moneyField);
        
        /*
         this.addKeyListener(new KeyAdapter()//這種方式也是的,但此時不使用  放在結構體里
           {
               public void keyPressed(KeyEvent e)
               {
                   if (e.getKeyCode() == KeyEvent.VK_ENTER)
                   {
                       e.consume();
                       KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent();
                       
                   }
               }
           });
          */
    }
    boolean isDouble(String str)
    {
       try
       {
          Double.parseDouble(str);
          return true;
       }
       catch(NumberFormatException ex){}
       return false;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        if (e.getSource()==nameField) {
            boolean isNum=nameField.getText().matches("[0-9]+");
            isNum = isDouble(nameField.getText());
            if (isNum) {
                
            } else {
                Object[] options = { "確定" }; 
                JOptionPane.showOptionDialog(null, "Click OK to continue", "Warning", 
                JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, 
                null, options, options[0]); 
                nameField.setText("");
            }
            nameField2.requestFocus();
        }
        if(e.getSource()==nameField2){
            //moneyField.requestFocus();
            Float mon = Float.parseFloat(nameField.getText())*Float.parseFloat(nameField2.getText());
            moneyField.setText(String.valueOf(mon));
        }
        
    }
    @Override
    public void keyPressed(KeyEvent e) {
        // TODO Auto-generated method stub
//        if (e.getKeyCode()==KeyEvent.VK_ENTER) {
//            nameField2.requestFocus();
//        } else if (e.getKeyCode()==KeyEvent.VK_ENTER) {
//            moneyField.requestFocus();
//        }else {
//            
//        }
    }
    @Override
    public void keyReleased(KeyEvent e) {}
    @Override
    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub
        
    }
    
    
    
}
/*
 其他類型轉String
String s = String.valueOf( value); // 其中 value 為任意一種數字類型。 
字符串型轉換成各種數字類型:
String s = "169"; 


byte b = Byte.parseByte( s ); 


short t = Short.parseShort( s ); 


int i = Integer.parseInt( s ); 


long l = Long.parseLong( s ); 


Float f = Float.parseFloat( s ); 


Double d = Double.parseDouble( s );
 
 
 * */
SY5_2_CalMoney extends JFrame implements ActionListener,KeyListener

 

package Exp05_03_20170566134;

import java.applet.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class test extends Applet implements ActionListener {
TextField userText, passText;
Button loginButton;
public void init() {
userText = new TextField(10);
passText = new TextField(10);
loginButton = new Button("login");
add(userText);
add(passText);
add(loginButton);
userText.addActionListener(this);
passText.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == userText)
passText.requestFocus();
else if (e.getSource() == passText)
loginButton.requestFocus();
}
}
test extends Applet implements ActionListener

 

4.編寫菜單程序SY5_3_Menu,如圖9-5所示,在窗口中添加菜單欄,在菜單欄添加菜單項,並添加下拉菜單和2 級菜單,通過選擇菜單項可以執行不同操作,如“打開”可打開SY9_3_Menu類生成的窗口。(知識點:在NetBeans/Eclipse下創建窗體,菜單,事件處理)

 

 

 

                                                               5-5 菜單應用窗口

 

 

package Exp05_04_20170566134;
import java.awt.Button;
import java.awt.event.*;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.filechooser.FileSystemView;
public class SY5_3_Menu extends JFrame implements ActionListener{//繼承JFrame類
    JMenu jm1,jm2,twojm1;
    JMenuBar jmb;
    JMenuItem jmt1,jmt2,jmt3;
    
    JMenuItem two01,two02,two03;
    
    private Button exitButton;
    public static void main(String[] args) {
        new SY5_3_Menu();
    }
    //構造函數
    public SY5_3_Menu() {
       super("菜單應用");// 創建標題為“JFrame窗口”窗口對象
       setSize(400,200);// 設置窗口大小為400 x 200
       this.setLocationRelativeTo(null);//窗體居中顯示
       jmb=new JMenuBar();
       jm1=new JMenu("文件");
       jm2=new JMenu("幫助");
       jmb.add(jm1);
       jmb.add(jm2);
       
       jmt1=new JMenuItem("打開");
       jmt2=new JMenuItem("關閉");
       jmt3=new JMenuItem("退出");
       
       twojm1=new JMenu("編輯");
       two01=new JMenuItem("復制");
       two02=new JMenuItem("剪切");
       two03=new JMenuItem("粘貼");
       twojm1.add(two01);
       twojm1.add(two02);
       twojm1.add(two03);
       
       jm1.add(jmt1);
       jm1.add(jmt2);
       jm1.add(twojm1);
       jm1.add(jmt3);
       this.add(jmb,"North");
       
       exitButton =new Button("退出");
       this.setVisible(true);// 設置窗口是可視的
        //為窗口添加窗口事件適配用來關閉窗體,這里大家暫時照用就是
        addWindowListener(new WindowAdapter() {   //
            public void windowClosing(WindowEvent e) {// 關閉窗口事件的方法
                System.exit(0);
            }
        });
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(null);
        jmt1.addActionListener(this);
        jmt2.addActionListener(this);
        jmt3.addActionListener(this);
        
        two01.addActionListener(this);
        two02.addActionListener(this);    
        two03.addActionListener(this);
        
        add(jmb,"North");
        exitButton.setBounds(160, 135, 50, 20);
        exitButton.addActionListener(this);
        add(exitButton);
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        if (e.getSource() == jmt1) {  //打開
            JFileChooser chooser = new JFileChooser(new File(System.getProperty("user.dir")+"/src/Exp05_04_20170566134"));
            chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            chooser.showDialog(new JLabel(), "選擇");
            System.out.println(System.getProperty("user.dir"));
            
            //File file = chooser.getSelectedFile();
            //textField.setText(file.getAbsoluteFile().toString());//importent
        }else if (e.getSource() == jmt2) {  //關閉
            
        }else if (e.getSource() == jmt3) {  //退出
            System.exit(0);
        }else if (e.getSource() == two01) {   //復制
            
        }else if (e.getSource() == two02) {   //剪切
            
        }else if (e.getSource() == two03) {   //粘貼
            
        }else if (e.getSource() == exitButton) {
            System.exit(0);
        } else {
            
        }
    }
}


/*
 * 參考路徑選擇文檔

    https://blog.csdn.net/u010142437/article/details/78262895
*/
SY5_3_Menu extends JFrame implements ActionListener

 

5.[SY5_4.java]編寫一個算術測試小軟件,用來訓練小學生的算術能力。程序由3個類組成,其中GeneratorTM類對象負責給出算術題目,並判斷回答者的答案是否正確;ComputerFrame類對象負責為算術題目提供界面,程序運行結果如圖5-6所示。(知識點:在NetBeans/Eclipse下創建窗體,基本組件,事件處理,類與類之間關系,MVC初步了解)

 

 

 

 

5-6 算術測試小軟件

 

package Exp05_05_20170566134;
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;


public class ComputerFrame implements ActionListener{
    
    JFrame suanshu = new JFrame("算數測試小軟件");
    
    String[] num={"30","50","100"};
    JLabel nameLabel  = new JLabel("選擇算數范圍");
    JComboBox number = new JComboBox();
    JButton button = new JButton("獲取題目");
    JTextField beijianshu = new JTextField();
    JTextField jianshu = new JTextField();
    JTextField daan = new JTextField();
    JLabel jiahao = new JLabel("-");
    JLabel dengyu = new JLabel("=");
    JButton queren = new JButton("確認答案");
    JLabel jieguo = new JLabel("");
    
    int Answerjieguo;
    
    public ComputerFrame() {
        
        suanshu.setSize(480, 200);
        suanshu.setLayout(null);
        suanshu.setLocationRelativeTo(null);
        
        for (int i = 0; i < num.length; i++) {
            number.addItem(Integer.parseInt(num[i]) );
        }
        nameLabel.setBounds(15, 20, 80, 20);
        number.setBounds(110, 20, 50, 20);
        button.setBounds(180, 20, 100, 20);
        button.addActionListener(this);
        beijianshu.setBounds(20, 50, 80, 20);
        beijianshu.setEditable(false);
        jianshu.setBounds(150, 50, 80, 20);
        jianshu.setEditable(false);
        jiahao.setBounds(120, 50, 10, 20);
        dengyu.setBounds(240, 50, 20, 20);
        daan.setBounds(270, 50, 80, 20);
        queren.setBounds(350, 50, 90, 20);
        queren.addActionListener(this);
        jieguo.setBounds(240, 80, 100, 20);
        
        suanshu.add(nameLabel);
        suanshu.add(number);
        suanshu.add(button);
        suanshu.add(beijianshu);
        suanshu.add(jianshu);
        suanshu.add(jiahao);
        suanshu.add(dengyu);
        suanshu.add(daan);
        suanshu.add(queren);
        suanshu.add(jieguo);
        
        
        suanshu.setVisible(true);
        
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        if ("獲取題目".equals(e.getActionCommand())) {
            System.out.println(number.getSelectedItem());
            GeneratorTM naTm = new GeneratorTM((int)number.getSelectedItem().hashCode());    
            beijianshu.setText(naTm.beijianshu+"");
            jianshu.setText(naTm.jianshu+"");
            Answerjieguo = naTm.getDaan();
        }
        if("確認答案".equals(e.getActionCommand())) {
            
            System.out.println(daan.getText());
            
            try {
                if (Answerjieguo ==Integer.parseInt(daan.getText())) {
                    System.out.println("你回答正確");
                    jieguo.setText("你回答正確");
                }else {
                    System.out.println("你回答錯誤");
                    jieguo.setText("你回答錯誤");
                    daan.setText("");
                }
            } catch (Exception e2) {
                System.out.println("你的輸入格式有誤!");
                daan.setText("");
            }
        }
        
    }
    
}
ComputerFrame implements ActionListener

 

package Exp05_05_20170566134;

public class GeneratorTM {
    
    protected int beijianshu;
    protected int jianshu;
    protected int daan;
    
    public GeneratorTM(int max) {
        this.beijianshu = (int)(1+Math.random()*max);
        this.jianshu = (int)(1+Math.random()*max);
        this.daan = this.beijianshu-this.jianshu;
        
    }

    public int getDaan() {
        return daan;
    }
    
}
GeneratorTM

 

package Exp05_05_20170566134;

public class test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new ComputerFrame();
    }

}
test

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM