/***************************************** 展示JOptionPane用法:投票 *************************************************/ import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.*; public class ui33 extends JFrame implements ActionListener { Container c; JButton bot0,bot1; String[] cname={"1.白色","2.銀色","3.黑色","4.粉紅色","5.彩色"} ; Object[][] card =new String[1][5]; JComboBox cbox; JTable dsp; public ui33() { super("JOptionPane用法:投票"); int i,j; int x; c=getContentPane(); c.setLayout(new FlowLayout(FlowLayout.CENTER)); bot0=new JButton("結束"); bot1=new JButton("投票"); dsp=new JTable(card,cname); //設定JTable for (j=0;j<5;j=j+1) card[0][j]=new String(Integer.toString(0)); c.add(bot0); c.add(bot1); c.add(dsp.getTableHeader()); c.add(dsp); bot0.addActionListener(this); bot1.addActionListener(this); setSize(400,500); setVisible(true); } public void paint(Graphics g) { super.paint(g); } /***按鈕事件的傾聽方法****/ public void actionPerformed(ActionEvent e) //按鈕事件的處理方法 { if (e.getSource()==bot0) { String message="真的要離開嗎?"; int messageType=JOptionPane.QUESTION_MESSAGE; int optionType= JOptionPane.YES_NO_OPTION ; String[] option={"確定","取消"}; int YN=JOptionPane.showOptionDialog(this,message, "離開確認",optionType,messageType,null,option, option[0]); if (YN==JOptionPane.YES_OPTION) System.exit(0); } else if (e.getSource()==bot1)//投票 { int x; String svote = JOptionPane.showInputDialog("請輸入你希望的電腦顏色編號:"); int vote=Integer.parseInt(svote); if (vote>1 && vote <5) { vote=vote-1; x=Integer.parseInt(card[0][vote].toString()); x=x+1; dsp.setValueAt(Integer.toString(x),0,vote); } }//else if repaint(); } public static void main(String args[]) //程式起點 { ui33 app=new ui33(); //畫圖 //處理視窗關閉要求 app.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0);} }); } }