关于Swing构件的使用---一个完整的卡片设计和播放的例程

一、卡片信息类

public class QuizCard {
	private String question;
	private String answer;
	
	/**
	 * 
	 * @param q
	 * @param a
	 */
	public QuizCard(String q, String a)
	{
		question = q;
		answer = a;
	}
	
	/**
	 * 
	 * @return
	 */
	public String getQuestion()
	{
		return question;
	}
	
	/**
	 * 
	 * @return
	 */
	public String getAnswer()
	{
		return answer;
	}
}

二、卡片设计

import java.io.*;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.Panel;
import java.awt.event.*;
import java.util.*;

public class QuizCardBuilder {
	private JTextArea question;
	private JTextArea answer;
	private ArrayList cardList;
	private JFrame frame ;
	
	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		QuizCardBuilder builder = new QuizCardBuilder();
		builder.go();
	}
	
	/**
	 * 
	 */
	public void go()
	{
		//创建问题和答案文本框
		frame = new JFrame("卡片生成器");
		JPanel mainPanel = new JPanel();
		Font bigFont = new Font("sanserif",Font.BOLD,24);
		question = new JTextArea(6, 20);
		question.setLineWrap(true);
		question.setWrapStyleWord(true);//
		question.setFont(bigFont);
		
		JScrollPane qScroller = new JScrollPane(question);
		qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		
		answer = new JTextArea(6, 20);
		answer.setLineWrap(true);
		answer.setWrapStyleWord(true);//
		answer.setFont(bigFont);
		
		JScrollPane aScroller = new JScrollPane(answer);
		aScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		aScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		
		//创建按键
		JButton nextButton = new JButton("next card");
		
		cardList = new ArrayList();
		
		//创建问题和答案提示文本
		JLabel qLable = new JLabel("问题");
		JLabel aLable = new JLabel("答案");
		
		//将上述东西加到面板上去
		mainPanel.add(qLable);
		mainPanel.add(qScroller);
		mainPanel.add(aLable);
		mainPanel.add(aScroller);
		mainPanel.add(nextButton);
		
		//给按键添加监听响应
		nextButton.addActionListener(new NextCardListener());//容易忘记写new
		
		//创建菜单栏及选项
		JMenuBar menuBar = new JMenuBar();
		JMenu fileMenu = new JMenu("文件");
		JMenuItem newMenuItem = new JMenuItem("新建");
		JMenuItem saveMenuItem = new JMenuItem("保存");
		
		JMenu windowMenu = new JMenu("窗口");
		
		//给新建、保存选项天剑监听响应
		newMenuItem.addActionListener(new NewMenuLister());
		saveMenuItem.addActionListener(new SaveMenuListener());
		
		//将创建的菜单栏及选项串联起来
		fileMenu.add(newMenuItem);
		fileMenu.add(saveMenuItem);
		menuBar.add(fileMenu);
		menuBar.add(windowMenu);
		
		frame.setJMenuBar(menuBar);
		
		frame.getContentPane().add(BorderLayout.CENTER,mainPanel);
		frame.setSize(500,600);
		frame.setVisible(true);
	}
	
	/**
	 * 
	 * @author Administrator
	 *
	 */
	public class NextCardListener implements ActionListener{
		public void actionPerformed(ActionEvent ev)
		{
			//如果问题或者答案是空白,则弹出对话框提示
			if (question.getText().isEmpty())
			{
				JOptionPane.showMessageDialog(null, "问题不能为空","格式错误",JOptionPane.ERROR_MESSAGE);
			}
			else if(answer.getText().isEmpty())
			{
				JOptionPane.showMessageDialog(null, "答案不能为空","格式错误",JOptionPane.ERROR_MESSAGE);
			}
			else
			{
				QuizCard card = new QuizCard(question.getText(),answer.getText());
				cardList.add(card);
				clearCard();
			}
			
		}
	}
	
	/**
	 * 
	 * @author Administrator
	 *
	 */
	public class SaveMenuListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO 自动生成的方法存根
			QuizCard card = new QuizCard(question.getText(),answer.getText());
			cardList.add(card);
			
			//弹出对话框,可以选择文件,System.getProperty("user.dir")用于设置默认路径为工程所在文件夹
			JFileChooser fileSave = new JFileChooser();//(System.getProperty("user.dir"));

			//设置默认打开的路径
			//先判断是否存在用于存放数据的文件夹,如果不存在就创建该文件夹
			//创建文件使用“file.createNewFile()”
			File testDir = new File("./DataTmp");
			if(!testDir.exists())
			{
				testDir.mkdir();//创建文件夹
			}
			
			fileSave.setCurrentDirectory(testDir);//切换到对应文件夹目录下
			
			/*
			 可是设置对话打开的方式,有如下打开方式:
			FILES_ONLY 只选文件;
			DIRECTORIES_ONLY  只选文件夹;
			FILES_AND_DIRECTORIES 可选文件或文件夹
			 **/
			fileSave.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
			
			//设置是否允许多选
			fileSave.setMultiSelectionEnabled(false);
			
			//向用户可选择的文件过滤器列表添加一个过滤器
			fileSave.addChoosableFileFilter(new FileNameExtensionFilter("zip(*.zip,*.rar)", ".zip",".rar"));
			
			//过滤可以选择窗口中哪些后缀的文件,将这些后缀名称文件过滤不显示
			fileSave.setFileFilter(new FileNameExtensionFilter("image(*.jpg,*.png,*gif)", ".jpg",".png",".gif"));
			
			fileSave.showSaveDialog(frame);
			saveFile(fileSave.getSelectedFile());
		}
		
	}
	
	public class NewMenuLister implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO 自动生成的方法存根
			cardList.clear();//将缓存进行清空,一遍重新输入
			clearCard();   //清空屏幕
		}
		
	}
	
	/**
	 * 
	 */
	public void clearCard()
	{
		question.setText("");
		answer.setText("");
		question.requestFocus();//
	}

	/**
	 * 
	 * @param file
	 */
	public void saveFile(File file)
	{
		try{
			System.out.println(file);
			BufferedWriter Write = new BufferedWriter(new FileWriter(file));
			for(QuizCard card:cardList)
			{
				String q = card.getQuestion();
				//System.out.println(q);
				String a = card.getAnswer();
				//System.out.println(a);
				if ((!q.isEmpty()) && (!a.isEmpty()))//只有问题不为空才去存
				{
					Write.write(q+"/");
					Write.write(a + "\n");
				}
				
				//Write.write(card.getQuestion()+"/");
				//Write.write(card.getAnswer() + "\n");
				
			}
			Write.close();
		}catch(IOException ex){
			System.out.println("存储失败");
			ex.printStackTrace();
		}
	}
}

三、卡片播放

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.*;
import javax.swing.*;

public class QuizCardPlayer {
	private JTextArea display;
	private JTextArea answer;
	private ArrayList cardList;
	private QuizCard currentCard;
	private int currentCardIndex;
	private JFrame frame;
	private JButton nextButton;
	private boolean isShowAnswer;
	private int loadCartCnt;
	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		QuizCardPlayer reader = new QuizCardPlayer();
		reader.go();
	}
	
	public void go()
	{
		frame = new JFrame("知识练习机");
		JPanel mainPanel = new JPanel();
		//mainPanel.setLayout(new BoxLayout(mainPanel,BoxLayout.Y_AXIS));
		Font bigFont = new Font("sanserif", Font.BOLD, 24);
		
		display = new JTextArea(10, 20);
		display.setFont(bigFont);
		
		display.setLineWrap(true);
		display.setEditable(false); //文本内容不允许被编辑
		
		JScrollPane qscrollPane = new JScrollPane(display);
		qscrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		qscrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		
		nextButton = new JButton("显示答案");
		nextButton.setEnabled(false);//开始没有数据时按键无效
		//nextButton.getHideActionText();
		//nextButton.setHorizontalAlignment(SwingConstants.CENTER);
		mainPanel.add(qscrollPane);
		mainPanel.add(nextButton);
		
		nextButton.addActionListener(new NextCardListener());
		
		JMenuBar menuBar = new JMenuBar();
		JMenu fileMenu = new JMenu("文件");
		JMenuItem loadMenuItem = new JMenuItem("加载卡片");
		loadMenuItem.addActionListener(new OpenMenListener());
		fileMenu.add(loadMenuItem);
		menuBar.add(fileMenu);
		
		frame.setJMenuBar(menuBar);
		frame.getContentPane().add(BorderLayout.CENTER,mainPanel);
		frame.setSize(640,500);
		frame.setVisible(true);

	}
	
	/**
	 * 
	 * @author Administrator
	 *
	 */
	public class NextCardListener implements ActionListener{
		
		public void actionPerformed(ActionEvent ev)
		{
			if(isShowAnswer)
			{
				display.setText(currentCard.getAnswer());
				nextButton.setText("下一张");
				isShowAnswer = false;
			}
			else
			{
				if (currentCardIndex < cardList.size())//注意这里是通过size()方法来获取元素格式
				{
					showNextCard();
				}
				else
				{
					display.setText("地主家没有余粮了!");
					nextButton.setEnabled(false);//禁止按键监听
				}
			}
		}
	}
	
	public class OpenMenListener implements ActionListener
	{
		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO 自动生成的方法存根
			JFileChooser fileOpen = new JFileChooser();
			File file = new File(".");
			fileOpen.setCurrentDirectory(file);
			fileOpen.showOpenDialog(frame);
			loadFile(fileOpen.getSelectedFile());
		}
	}

	
	
	/**
	 * 
	 * @param file
	 */
	private void loadFile(File file)
	{
		//System.out.println(file);
		cardList = new ArrayList();
		try{
			BufferedReader reader = new BufferedReader(new FileReader(file));
			String line = null;
			loadCartCnt =0;
			while((line = reader.readLine()) != null)
			{
				System.out.println(line);
				makeCard(line);
			}
			reader.close();
			//一旦加载了卡片,就有效按键
			nextButton.setEnabled(true);
		}catch(Exception ex){
			System.out.println("加载失败");
			ex.printStackTrace();
		}
		showNextCard();
	}
	
	/**
	 * 
	 * @param line
	 */
	private void makeCard(String line)
	{
		String[] result = line.split("/");//遇到设定符号就拆分, * ^ : | . \这些字符要转义
		QuizCard card = new QuizCard(result[0], result[1]);
		cardList.add(card);
		loadCartCnt++;
		System.out.println("加载第"+ loadCartCnt+"卡片");
	}
	
	/**
	 * 
	 */
	private void showNextCard()
	{
		currentCard = cardList.get(currentCardIndex);
		currentCardIndex++;
		display.setText(currentCard.getQuestion());
		nextButton.setText("显示答案");
		isShowAnswer = true;
	}

}

关于Swing构件的使用---一个完整的卡片设计和播放的例程_第1张图片

关于Swing构件的使用---一个完整的卡片设计和播放的例程_第2张图片

你可能感兴趣的:(01_JAVA)