目前分類:TQC+ 物件導向視窗及資料庫程式設計認證指南 Java 6 進階 (13)

瀏覽方式: 標題列表 簡短摘要

參考答案

import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class JDD02 extends Frame implements ItemListener
{
  BufferedWriter bw = null;
  BufferedReader br = null;
  
  //護士名字
  String name[] =new  String[4];
  String weekDay[] = {"週一","週二","週三","週四","週五"};

  //Panel pn1 包含了 Panel pn1a 及 Panel pn1b
  Panel pn1 = new Panel();

  //pn1a 用來放排班表
  Panel pn1a = new Panel();
  Choice chAM[] = new Choice[5];   //週一至週五早班
  Choice chPM[] = new Choice[5];   //週一至週五晚班
  Choice chNigh[] = new Choice[5]; //週一至週五夜班

  //pn1b 放的是每位護士的班次統計表
  Panel pn1b = new Panel();
  Label lname[]  = new Label[4];    //顯示每位護士名字
  int AM[] = new int[4];            //每一位護士早班次數
  int PM[] = new int[4];            //每一位護士晚班次數
  int Nigh[] = new int[4];            //每一位護士夜班次數
  Label lbAM[]   = new Label[4];    //顯示每一位護士早班次數
  Label lbPM[]   = new Label[4];    //顯示每一位護士晚班次數
  Label lbNigh[] = new Label[4];    //顯示每一位護士夜班次數

  //pn3 是最下方的按鈕區
  Panel pn3 = new Panel();
  Button b1 = new Button("輸出");
  Button b2 = new Button("離開");

  public JDD02()
  {
    super("急診科護士排班表");
    addWindowListener(new WinListener());
  } 
  public static void main(String[] args)
  {
    JDD02 JD02 = new JDD02();
    JD02.setup();
    JD02.setSize(400,300);
    JD02.setVisible(true);
  }

  void setup()
  {
    //請將護士的名單讀入
      try{
    br = new BufferedReader(new FileReader("list.txt"));
    int i=0;
    while(br.ready()){
        name[i++] = br.readLine().trim();
    }
    br.close();
      }catch(Exception ex)
      {
          ex.printStackTrace();
      }
      
    setpn1();
    setpn3();
    add(pn1);
    add(pn3,BorderLayout.SOUTH);
  }

  //設定排班表內容
  void setpn1()
  {
    pn1a.setLayout(new GridLayout(4,0));
    pn1a.add(new Label(" "));
    pn1a.add(new Label(weekDay[0]));
    pn1a.add(new Label(weekDay[1]));
    pn1a.add(new Label(weekDay[2]));
    pn1a.add(new Label(weekDay[3]));
    pn1a.add(new Label(weekDay[4]));
    pn1a.add(new Label("早班"));

    for(int h=0; h<chAM.length; h++)
    {
       chAM[h] = new Choice();
       chPM[h] = new Choice();
       chNigh[h] = new Choice(); //週一至週五夜班
       //請將名單放入下拉式選單
       for(int i=0;i<name.length;i++)
       {
           chAM[h].add(name[i]);
           chPM[h].add(name[i]);
           chNigh[h].add(name[i]);
       }
       chAM[h].addItemListener(this);
       chPM[h].addItemListener(this);
       chNigh[h].addItemListener(this);
    }

    pn1a.add(chAM[0]);
    pn1a.add(chAM[1]);
    pn1a.add(chAM[2]);
    pn1a.add(chAM[3]);
    pn1a.add(chAM[4]);
    pn1a.add(new Label("晚班"));
    pn1a.add(chPM[0]);
    pn1a.add(chPM[1]);
    pn1a.add(chPM[2]);
    pn1a.add(chPM[3]);
    pn1a.add(chPM[4]);
    pn1a.add(new Label("夜班"));
    pn1a.add(chNigh[0]);
    pn1a.add(chNigh[1]);
    pn1a.add(chNigh[2]);
    pn1a.add(chNigh[3]);
    pn1a.add(chNigh[4]);
    //設定班別統計表
    pn1b.setLayout(new GridLayout(4,4));
    for(int a=0; a<lname.length; a++)
    {
      lname[a] = new Label(name[a]);
    }
    pn1b.add(new Label(" "));
    pn1b.add(lname[0]);
    pn1b.add(lname[1]);
    pn1b.add(lname[2]);
    pn1b.add(lname[3]);
    pn1b.add(new Label("早班"));
    lbAM[0] = new Label("");
    lbAM[1] = new Label("");
    lbAM[2] = new Label("");
    lbAM[3] = new Label("");
    pn1b.add(lbAM[0]);
    pn1b.add(lbAM[1]);
    pn1b.add(lbAM[2]);
    pn1b.add(lbAM[3]);
    pn1b.add(new Label("晚班"));
    lbPM[0] = new Label("");
    lbPM[1] = new Label("");
    lbPM[2] = new Label("");
    lbPM[3] = new Label("");
    pn1b.add(lbPM[0]);
    pn1b.add(lbPM[1]);
    pn1b.add(lbPM[2]);
    pn1b.add(lbPM[3]);
    pn1b.add(new Label("夜班"));
    lbNigh[0] = new Label("");
    lbNigh[1] = new Label("");
    lbNigh[2] = new Label("");
    lbNigh[3] = new Label("");
    pn1b.add(lbNigh[0]);
    pn1b.add(lbNigh[1]);
    pn1b.add(lbNigh[2]);
    pn1b.add(lbNigh[3]);
    pn1.setLayout(new GridLayout(0,1));
    pn1.add(pn1a);
    pn1.add(pn1b);
  }

  void setpn3()
  {
     b1.addActionListener(new act());
     pn3.add(b1);

     b2.addActionListener(new act());
     pn3.add(b2);
  }

  //對Item的變動作出即時反應
  public void itemStateChanged(ItemEvent e)
  {
    //先將資料清空
    for(int i=0; i<AM.length; i++)
    {
      AM[i] =0;
      PM[i] =0;
      Nigh[i] = 0;
    }
    //請計算每一位護士早班次數
    for(int i=0;i<chAM.length;i++)
        for(int j=0;j<name.length;j++)
            if(chAM[i].getSelectedItem().equals(name[j]))
                AM[j]++;

    //請計算每一位護士晚班次數
    for(int i=0;i<chPM.length;i++)
        for(int j=0;j<name.length;j++)
            if(chPM[i].getSelectedItem().equals(name[j]))
                PM[j]++;

    //請計算每一位護士夜班次數
    for(int i=0;i<chNigh.length;i++)
        for(int j=0;j<name.length;j++)
            if(chNigh[i].getSelectedItem().equals(name[j]))
                Nigh[j]++;

    //將資料填入畫面
    for(int i=0; i<AM.length; i++)
    {
      lbAM[i].setText("" + AM[i]);
      lbPM[i].setText("" + PM[i]);
      lbNigh[i].setText("" + Nigh[i]);
    }
  }

  //建立一個用來處理按鈕的 ActionListener inner class
  class act implements ActionListener
  {
    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource() == b2)
        {
           System.exit(0);
        }
        else if(e.getSource() == b1)
        {
           StringBuffer sbAM = new StringBuffer("");
           StringBuffer sbPM = new StringBuffer("");
           StringBuffer sbNight = new StringBuffer("");
           //請撰寫這部份,將排班資料寫入檔案
           try
           {
                   System.out.println("Writing JDA02.txt");
                   
                   bw = new BufferedWriter(new FileWriter("JDA02.txt"));
                   bw.write("值班通知書");
                   bw.newLine();
                   bw.newLine();
                   
                   for(int h=0;h<name.length;h++){
                       sbAM= new StringBuffer("");
                       sbPM=new StringBuffer("");
                       sbNight=new StringBuffer("");
                       bw.write(name[h]+".");
                       bw.newLine();
                       bw.newLine();
                       
                       for(int i = 0;i<chAM.length;i++)
                           if(chAM[i].getSelectedItem().equals(name[h]))
                               sbAM.append(" ").append(weekDay[i]);
                       
                       bw.write("早班"+sbAM);
                       bw.newLine();
                       
                       for(int i = 0;i<chPM.length;i++)
                           if(chPM[i].getSelectedItem().equals(name[h]))
                               sbPM.append(" ").append(weekDay[i]);
                       
                       bw.write("晚班"+sbPM);
                       bw.newLine();
                       
                       for(int i = 0;i<chNigh.length;i++)
                           if(chNigh[i].getSelectedItem().equals(name[h]))
                               sbNight.append(" ").append(weekDay[i]);
                       
                       bw.write("夜班"+sbNight);
                       bw.newLine();
                       bw.newLine();
                   }
                   bw.close();
           }
           catch (Exception ex) {
              ex.printStackTrace();
           }
        }
     }
  }

  /* 覆寫 WindowAdapter 中的 windowClosing()
     讓關閉視窗的按鈕有作用
  */
  class WinListener extends WindowAdapter
  {
    public void windowClosing(WindowEvent e)
    {
      e.getWindow().dispose();
      System.exit(0);
    }
  }
}

 

Dino 發表在 痞客邦 留言(0) 人氣()

參考答案

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JDD02 extends JFrame implements ActionListener
{
  //第一個JPanel用來放置所選取檔案
  JPanel pn1 = new JPanel();
  //顯示訊息的標籤
  JLabel msg = new JLabel("請選取兩個 txt 檔來做合併");
  //按鈕上的圖示
  ImageIcon image1=new ImageIcon("JDD02-1.gif");
  ImageIcon image2=new ImageIcon("JDD02-1.gif");
  ImageIcon image3=new ImageIcon("JDD02-2.gif");
  //選取檔案的按鈕
  JButton bn1=new JButton("選取要合併的第一個檔案",image1);
  JButton bn2=new JButton("選取要合併的第二個檔案",image2);
  JButton bn3=new JButton("選取合併後要存入的檔案",image3);
  //顯示所選取檔案名稱
  JTextField tfIn[]={new JTextField(),new JTextField()};
  //顯示所要輸出的檔案名稱
  JTextField tf3=new JTextField(3);


  //第二個JPanel用來放置按鈕
  JPanel pn2 = new JPanel();
  JButton bnOK   = new JButton("確定");
  JButton bnExit = new JButton("離開");

  //合併檔案所用的 IO 類別
  JFileChooser jfc = new JFileChooser(".");
  InputStream is;
  SequenceInputStream sis;
  File outputFile;
  FileOutputStream out;

  public JDD02( ) { addWindowListener(new WinListener()); }

  public static void main(String[] args) throws IOException
  {
    JDD02 test = new JDD02();
    test.setTitle("文字檔合併器");
    test.setup();
    test.setSize(300,200);
    test.setVisible(true);
  }

  //設定畫面元件及 Listener
  void setup()
  {
    Container content = this.getContentPane();
    pn1.setLayout(new GridLayout(0,1));
    pn1.add(msg);
    bn1.addMouseListener(new MouseListen());
    bn2.addMouseListener(new MouseListen());
    bn3.addMouseListener(new MouseListen());
    bn1.addActionListener(this);
    bn2.addActionListener(this);
    bn3.addActionListener(this);
    pn1.add(bn1);
    pn1.add(tfIn[0]);
    pn1.add(bn2);
    pn1.add(tfIn[1]);
    pn1.add(bn3);
    pn1.add(tf3);
    content.add(pn1);
    bnOK.addMouseListener(new MouseListen());
    bnExit.addMouseListener(new MouseListen());
    bnOK.addActionListener(this);
    bnExit.addActionListener(this);
    pn2.add(bnOK);
    pn2.add(bnExit);
    content.add(pn2,BorderLayout.SOUTH);
  }

  // 顯示開啟檔案對話方塊,並將所選取的檔案名稱放入 JTextField tfIn[] 中
  void selectInFile(int i)
  {
     //回傳值為 0 代表使用者不是選擇 Cancel
     if(jfc.showOpenDialog(this)==0){
         tfIn[i-1].setText(jfc.getSelectedFile().toString());
     }

  }

  // 顯示開啟檔案對話方塊,並將所選取的檔案名稱放入 JTextField tf3 中
  void selectOutFile()
  {
     //回傳值為 0 代表使用者不是選擇 Cancel
     if(jfc.showOpenDialog(this)==0){
         tf3.setText(jfc.getSelectedFile().toString());
     }


  }

  //進行檔案合併的動作
  void combineFiles()
  {
    try
    {
       InputStream in0 = new FileInputStream(tfIn[0].getText().trim());
       InputStream in1 = new FileInputStream(tfIn[1].getText().trim());
       
       sis = new SequenceInputStream(in0,in1);
       
       outputFile = new File(tf3.getText().trim());
       out=new FileOutputStream(outputFile);
       int c;
       while((c=sis.read())!=-1)
       {
           System.out.write(c);
           out.write(c);
       }
       sis.close();
       out.close();
       msg.setText("檔案合併完成");
       tfIn[0].setText("");
       tfIn[1].setText("");
       tf3.setText("");
    }
    catch (Exception ex)
    {
       msg.setText("檔案合併失敗"); 
    }
  }

  //對按鈕的動作做出回應
  public void actionPerformed(ActionEvent e)
  {
     if(e.getSource() == bnExit)
       {
          //結束程式
          dispose();
          System.exit(0);
       }
     else if(e.getSource() == bnOK)
       {
    //進行檔案合併
         combineFiles();
       }
     else if(e.getSource() == bn1)
       {
           // 顯示開啟檔案對話方塊,並將所選取的檔案名稱放入 JTextField tf[0] 中
         selectInFile(1);
       }
     else if(e.getSource() == bn2)
     {
         selectInFile(2);
     }
     else if(e.getSource() == bn3)
     {
         selectOutFile();
     }

  }

  //用來讓JFrame可以正常結束
  class WinListener extends WindowAdapter
  {
      public void windowClosing(WindowEvent e)
      {
        e.getWindow().dispose();
        System.exit(0);
      }
   }


  //讓按鈕在滑鼠進入會變色
  class MouseListen extends MouseAdapter
  {
    public void mouseEntered(MouseEvent e)
    {
       ((JButton)(e.getSource())).setBackground(Color.YELLOW);
    }
    public void mouseExited(MouseEvent e)
    {
       ((JButton)e.getSource()).setBackground(new Color(204,204,204));
    }
  }

}


 

Dino 發表在 痞客邦 留言(0) 人氣()

參考答案

import java.awt.*;
import java.awt.event.*;
class JDD02 extends Frame
implements MouseListener, MouseMotionListener {
    
    String msg="", info="";
    int mouseX=0, mouseY=0 ;
    
    public static void main(String arg[])
    {
        JDD02 mew=new JDD02();
    }
    
    //ctor
    JDD02() {
        super("滑鼠感應視窗");
        addMouseListener(this);
        addMouseMotionListener(this);
        addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent we) {
                dispose();
            }
        });
        setBackground(Color.white);
        setSize(250,200);
        //setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
    public void mouseClicked(MouseEvent me) {
        
    }

    public void mouseEntered(MouseEvent me) {
         //請在此撰寫滑鼠移入事件
        this.setBackground(Color.yellow);
        this.repaint();
    }
    public void mouseExited(MouseEvent me) {
         //請在此撰寫滑鼠移出視窗事件
        this.setBackground(Color.white);
        mouseX=me.getX();
        mouseY=me.getY();
        info = "Mouse just left the window from ";
        repaint();

    }
    public void mousePressed(MouseEvent me) {
         //請在此撰寫滑鼠按下事件
        mouseX=me.getX();
        mouseY=me.getY();
        msg="Down";
        info="Mouse is pressed at ";
        repaint();
        
    }
    public void mouseReleased(MouseEvent me) {
         //請在此撰寫滑鼠放開事件
        mouseX=me.getX();
        mouseY=me.getY();
        msg="Up";
        info="Mouse is released from ";
        repaint();

    }
    public void mouseDragged(MouseEvent me) {
         //請在此撰寫滑鼠拖曳事件
        mouseX=me.getX();
        mouseY=me.getY();
        msg="Dragging";
        info="Mouse is Dragging at ";
        repaint();

    }
    public void mouseMoved(MouseEvent me) {
         //請在此撰寫滑鼠移動事件
        mouseX=me.getX();
        mouseY=me.getY();
        msg="";
        info="Mouse is moving to ";
        repaint();

    }
    public void paint(Graphics g) {
         //請在此撰寫撰寫程式取得滑鼠座標
        g.drawString(msg, mouseX, mouseY);
        g.drawString(info+mouseX+","+mouseY, 10, 40);

    }
}

 

Dino 發表在 痞客邦 留言(0) 人氣()

參考答案

import java.awt.event.*;
import javax.swing.*;

 
class JDD01
{   
        public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MyJFrame().setVisible(true);
            }
        });
    }
}

class MyJFrame extends javax.swing.JFrame {
    private ButtonGroup answers;
    private JRadioButton baseball;
    private JRadioButton basketball;
    private JRadioButton tennis;
    private JRadioButton other;
    private JButton okBtn;
    private JTextField otherBallGame;
    private JLabel question;
    private String favoriteBallGame="棒球"; 
    
    public MyJFrame() {
        answers = new ButtonGroup();
        okBtn = new JButton();
        question = new JLabel();
        baseball = new JRadioButton();
        basketball = new JRadioButton();
        tennis = new JRadioButton();
        other = new JRadioButton();
        otherBallGame = new JTextField();

        setSize(340,290);
        setLocationRelativeTo(null);
        setLayout(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setTitle("問卷調查");
        

        okBtn.setText("確定");
        okBtn.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                String tmp;
                
                if(favoriteBallGame.equals(""))
                    tmp = otherBallGame.getText();
                else
                    tmp = favoriteBallGame;
                JOptionPane.showMessageDialog(MyJFrame.this, "你最喜好的球類運動是"+tmp,"test",JOptionPane.INFORMATION_MESSAGE);
                
            }
        });
        
        question.setText("下列何者是您最喜好的球類運動?(單選)");

        answers.add(baseball);
        baseball.setText("棒球");
        baseball.setSelected(true);
        
        baseball.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                otherBallGame.setEnabled(false);
                favoriteBallGame="棒球";
            }
        });

        answers.add(basketball);
        basketball.setText("籃球");
        basketball.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt)
            {
                otherBallGame.setEnabled(false);
                favoriteBallGame="籃球";
            }
        });    

        answers.add(tennis);
        tennis.setText("網球");
        tennis.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                otherBallGame.setEnabled(false);
                favoriteBallGame="網球";
            }
        });

        answers.add(other);
        other.setText("其它");
        other.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                otherBallGame.setEnabled(true);
                favoriteBallGame = "";
            }
        });
        
        otherBallGame.setEnabled(false);
        
        question.setSize(240, 30);
        question.setLocation(50,20);        
        baseball.setSize(100,30);
        baseball.setLocation(50,50);
        basketball.setSize(100,30);
        basketball.setLocation(50,80);
        tennis.setSize(100,30);
        tennis.setLocation(50,110);
        other.setSize(70,30);
        other.setLocation(50, 140);
        otherBallGame.setSize(100,20);
        otherBallGame.setLocation(120, 145);
        
        okBtn.setSize(100,20);
        okBtn.setLocation(120, 200);
        
        getContentPane().add(question);
        getContentPane().add(baseball);
        getContentPane().add(basketball);
        getContentPane().add(tennis);
        getContentPane().add(other);
        getContentPane().add(otherBallGame);
        getContentPane().add(okBtn);        
    }
}

 

Dino 發表在 痞客邦 留言(0) 人氣()

參考答案

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
class JDD01
{   
    public static void main(String[] args)
    {
        new MyFrame();
    }
}

class MyFrame extends JFrame
{
    Color curColor;
    
    MyFrame() 
    {   
        //視窗大小、標題、位置與關閉事件設定
        setSize(640,480);
        setTitle("畫筆功能");
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        
        //加入自訂容器至中央區塊
        setLayout(new BorderLayout()); 
        add(new MyPanel(this), BorderLayout.CENTER); 
        setVisible(true);
        } 
}

class MyPanel extends Panel 
{   
    MyFrame parent;
    int curX,curY,lastX=-1,lastY=-1;
    
    
    public MyPanel(MyFrame p) 
    {   
        parent = p;
        setSize(600,480);
        setBackground(Color.WHITE);
        
        //當滑鼠按下時
        this.addMouseListener(new MouseAdapter(){
            public void mousePressed(MouseEvent e){
                lastX=e.getX();
                lastY=e.getY();//紀錄目前座標
            }
        });
        
        //當滑鼠拖曳時
        this.addMouseMotionListener(new MouseAdapter(){
            public void mouseDragged(MouseEvent e){
                Graphics g = MyPanel.this.getGraphics();
                g.setColor(parent.curColor);
                curX=e.getX();
                curY=e.getY();
                //從最後紀錄的座標畫至目前座標
                g.drawLine(lastX, lastY, curX, curY);
                //繪製完畢後,目前的座標成為下次繪製的起始座標
                lastX=curX;
                lastY=curY;
            }
        });
    }
}

 

Dino 發表在 痞客邦 留言(0) 人氣()

參考答案:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
class JDD01
{   
    public static void main(String[] args)
    {
        new MyFrame();
    }
}

class MyFrame extends JFrame
{
    Color curColor;
    
    MyFrame() 
    {   
        Panel toolbar;
        Button redBtn, blueBtn; 
        
        //設定視窗標題、大小、位置、排版方式
        this.setTitle("繪製圓形");
        this.setSize(640,480);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setLayout(new BorderLayout());
        
        // 加入自訂容器至中央區塊
        this.add(new MyPanel(this),BorderLayout.CENTER); 
        toolbar = new Panel();
        curColor = Color.red; //預設繪製顏色為紅色
        redBtn = new Button("Red");
        blueBtn = new Button("Blue");
        
        //按下RED按鈕時,設定目前顏色為紅色
        redBtn.addMouseListener(new MouseAdapter(){
            public void mousePressed(MouseEvent e){
                MyFrame.this.curColor=Color.red;
            }
        });
        
        //按下BLUE按鈕時,設定目前顏色為藍色
        blueBtn.addMouseListener(new MouseAdapter(){
            public void mousePressed(MouseEvent e){
                MyFrame.this.curColor=Color.blue;
            }
        });
        
        //配置下方的工具按鈕
        toolbar.setLayout(new FlowLayout());
        toolbar.add(redBtn);
        toolbar.add(blueBtn);
        this.add(toolbar, BorderLayout.SOUTH);
        setVisible(true);  
    } 
}

class MyPanel extends Panel 
{   
    MyFrame parent;
    
    public MyPanel(MyFrame p) 
    {   
        parent = p;
        this.setSize(600,480);
        this.setBackground(Color.WHITE);
        
        //當滑鼠按下時,在目前位置以繪圖顏色畫一個20x20的圓形
        addMouseListener(new MouseAdapter(){
            public void mousePressed(MouseEvent e){
                Graphics g = MyPanel.this.getGraphics();
                g.setColor(parent.curColor);
                g.fillOval(e.getX()-10, e.getY()-10, 20, 20);
            }
        });
        
    }
}

 

Dino 發表在 痞客邦 留言(0) 人氣()

1.題目說明:

2.設計說明:

Dino 發表在 痞客邦 留言(0) 人氣()

參考答案:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;

 
class JDD01
{   
        public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MyJFrame().setVisible(true);
            }
        });
    }
}

class MyJFrame extends javax.swing.JFrame {
 
    private JButton btn1, btn2, btn3, btn4, btn5;
    private LayoutManager layout;
    
    public MyJFrame() {
      
        this.setSize(500,400);
        this.setLocationRelativeTo(null);
        this.setLayout(new BorderLayout());
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    
        JButton btn1 = new JButton("Button 1");
        JButton btn2 = new JButton("Button 2");
        JButton btn3 = new JButton("Button 3");
        JButton btn4 = new JButton("Button 4");
        JButton btn5 = new JButton("Button 5");

        this.getContentPane().add(btn1, BorderLayout.CENTER);
        this.getContentPane().add(btn2, BorderLayout.EAST);
        this.getContentPane().add(btn3, BorderLayout.SOUTH);
        this.getContentPane().add(btn4, BorderLayout.WEST);
        this.getContentPane().add(btn5, BorderLayout.NORTH);
    }
}

執行結果:

Dino 發表在 痞客邦 留言(0) 人氣()

參考答案:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;

public class JDD01
{
    public static void main(String args[])
    {
        new MyApp();
    }
}

class MyApp
{
    MyApp()
    {
        JFrame f = new JFrame();  //建立新視窗
        f.setSize(200, 200);  //設定寬高
        f.setVisible(true);  //讓視窗顯示在螢幕
        f.setLocationRelativeTo(null);  //設定視窗位置在螢幕中央
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    //設定當視窗被關閉時,執行關閉動作
        

        //建立選擇顏色視窗(在f視窗之上,標題,預設選擇的顏色是f視窗的背景色)
        Color c = JColorChooser.showDialog(f, "Choose Background Color", f.getContentPane().getBackground());
        
        f.getContentPane().setBackground(c); //改變背景色
    }
}

執行結果:

Dino 發表在 痞客邦 留言(0) 人氣()

參考答案:

import java.awt.event.*;
import javax.swing.*;
import java.io.*;

public class JDD01
{
    public static void main(String args[])
    {
        new MyApp();
    }
}

class MyApp
{
    MyApp()
    {
        JFrame f = new JFrame();
        f.setSize(300, 200);
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLocationRelativeTo(null);
        
        JFileChooser chooser = new JFileChooser();
        
        String[] exts={".java",".class"};
        AppFiles filter = new AppFiles(exts,"Java-Related Files");
        chooser.setFileFilter(filter);
        int returnVal = chooser.showOpenDialog(f);
        
        if(returnVal==JFileChooser.APPROVE_OPTION)
            f.setTitle(chooser.getSelectedFile().getName());  //如果使用者有選擇檔案,改變視窗標題
        else
            f.setTitle("You don`t choose any file");  //沒有回傳值代表沒有選擇
    }
}

class AppFiles extends javax.swing.filechooser.FileFilter  //建立繼承FileFilter的class,命名為AppFiles
{
    String[] extensions;
    String description;
    
    AppFiles(String[] exts,String descr)
    {
        extensions = exts;
        description = descr;
        
        for(int i=0;i<exts.length;i++)
            extensions[i] = exts[i].toLowerCase();
    }

    @Override  //此Function為FileFilter強制實作
    public boolean accept(File f) {
        // TODO Auto-generated method stub
        if(f.isDirectory())  
            return true;
        else
        {
            String fname = f.getName().toLowerCase();  //取得完整檔名,並全數轉為小寫
            for(String s:extensions)
            {
                if(fname.endsWith(s))  //看字串的尾端是否和extentions內的字串相等 (比對副檔名)
                return true; //如果其中一個相等回傳true
            }
        }
        
        return false; //找不到就會跳出迴圈,回傳false
    }

    @Override //此Function為FileFilter強制實作
    public String getDescription() {
        // TODO Auto-generated method stub
        return description;  
    }
    
    
}


執行結果:

Dino 發表在 痞客邦 留言(0) 人氣()

參考答案:

import javax.swing.*;

public class JDD01
{
    public static void main(String args[])
    {
        new MyApp();
    }
}

class MyApp
{
    MyApp()
    {
        Object[] options = {"500*500","300*300","100*100"};
        
        int n = JOptionPane.showOptionDialog(null, 
                "What size window do you prefer?", "Window Size", 
                0, JOptionPane.QUESTION_MESSAGE, null, options, options[2]);
        
        JFrame f = new JFrame();
        
        if(n==0)
            f.setSize(500, 500);
        else if(n==1)
            f.setSize(300, 300);
        else
            f.setSize(100, 100);
        
        f.setLocationRelativeTo(null);
        f.setVisible(true);
        
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
    }
}

執行結果:

Dino 發表在 痞客邦 留言(0) 人氣()

參考答案:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JDD01
{
    public static void main(String args[])
    {
        new MyApp();
    }
}

class MyApp
{
        JFrame win;
        boolean firstTime=true;  //第一次按下關閉時,會拿來做判斷的Boolean變數


        MyApp()
        {
            win = new JFrame("Hello Swing!");  //建立視窗物件並增加標題
            win.setSize(350, 125);  //設定視窗大小
            win.setLocationRelativeTo(null);  //將視窗固定在螢幕中央
            
            win.getContentPane().setBackground(Color.GREEN);  //設定視窗背景色為:綠色
            win.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);  //當視窗關閉時動作:甚麼都不做
            
            win.addWindowListener(new WindowAdapter(){  //增加視窗監聽的事件
                public void windowClosing(WindowEvent e)
                {
                    if(firstTime)  //如果firstTime是true表示這是第一次按下關閉
                    {
                        MyApp.this.win.setTitle("再按一次關閉視窗以結束程式");  //更改標題顯示
                        firstTime=false;  //將firstTime改為False,這樣下次再按關閉的話,就會跳過這塊程式碼直接關閉
                    }else
                        System.exit(0);  //firstTime如果是False,就是直接執行這行
                }
            });
            
            win.setVisible(true);  //所有判斷設定完成,顯示視窗
        }
}

執行結果:

Dino 發表在 痞客邦 留言(0) 人氣()

參考答案:

import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class JDA01
{
    public static void main(String args[])
    {
        new MyApp();
    }
}

class MyApp
{
        Frame mainWin;
        int num=9;
        
        MyApp()
        {      
            //建立主視窗mainWin
            mainWin = new Frame("Nuber of Windows = 9"); //創造新視窗時,連帶設定標題為『Nuber of Windows = 9』
            mainWin.setSize(300,50);  //設定視窗大小 (寬300,高50)
            mainWin.setLocation(100,100);  //設定視窗位置,螢幕的最左上角為(0,0)
            mainWin.setVisible(true);  //上面幾行完成了屬性設定,設定視窗為可視,視窗就會顯示在螢幕上
            
            Frame f;  //建立視窗變數,準備建立子視窗
            for(int i=0;i<8;i++) //從0~7,總共8個子視窗
            {
                f = new Frame(); //建立視窗物件
                f.setSize(50,50);  //設定寬跟高
                f.setLocation(150*(i%4)+100, i<4 ? 200:300); //設定位置,依題目要求一列要四個視窗,兩列分別為i=0~3 和 i=4~7
                f.setVisible(true);  //顯示視窗
                f.addWindowListener(new WindowAdapter()  //增加視窗事件
                {
                    public void windowClosing(WindowEvent e)  //事件發生時要執行的Function
                    {
                        mainWin.setTitle("Number of Windows = "+(--num));  //更改主視窗標題,每關閉一個視窗就減一
                        e.getWindow().setVisible(false);  //e為觸發事件傳入的參數,取得觸發此事件的視窗 (就是使用者按下關閉的那個視窗) ,然後設定為不可視 (視窗就消失了)
                    }
                });
            }

            mainWin.addWindowListener(new WindowAdapter()  //添加主視窗的事件
            {
                public void windowClosing(WindowEvent e)  //如果觸發了視窗關閉事件
                {
                    System.exit(0);  //關閉此程式
                }
            });

        }
}

執行畫面:

Dino 發表在 痞客邦 留言(0) 人氣()