import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import javax.swing.*; public class Test_17_5 extends JFrame{ private JPanel jpHold = new JPanel(); private JLabel jlb = new JLabel("Text file"); private JTextField jtf = new JTextField(10); private JP jp = new JP(); private File file; StringBuffer str = new StringBuffer(); public Test_17_5(){ jpHold.setLayout(new FlowLayout()); jpHold.add(jlb); jpHold.add(jtf); setLayout(new BorderLayout(5,5)); add(jpHold,BorderLayout.SOUTH); add(jp,BorderLayout.CENTER); jtf.addKeyListener(new KeyAdapter(){ @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub if(e.getKeyCode() == KeyEvent.VK_ENTER) { try { jp.showHistogram(countLetters()); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } }); } private String getTextContent() throws FileNotFoundException{ file = new File(jtf.getText()); Scanner input; if(file.exists() && file.canRead()){ input = new Scanner(file); while(input.hasNext()){ // string= input.nextLine(); str.append(input.nextLine()); } } return str.toString(); } private int[] countLetters() throws FileNotFoundException{ int[] count = new int[26]; String text = getTextContent(); for(int i = 0; i < text.length(); i++){ char character = text.charAt(i); if((character >= 'A') && (character <= 'Z')){ count[character - 'A']++; } else if((character >= 'a') && (character <= 'z')){ count[character - 'a']++; } } return count; } public static void main(String[] args) { // TODO Auto-generated method stub Test_17_5 frame = new Test_17_5(); frame.setTitle("Test_17_5"); frame.setSize(400,500); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } class JP extends JPanel{ private int[] count; public void showHistogram(int[] count){ this.count = count; repaint(); } protected void paintComponent(Graphics g){ if(count == null) return; super.paintComponent(g); int width = getWidth(); int height = getHeight(); int interval = (width - 40)/ count.length; int individualWidth = (int)(((width - 40) / 24) * 0.6); int maxCount = 0; for(int i = 0; i < count.length; i++){ if(maxCount < count[i]) maxCount = count[i]; } int x = 30; g.drawLine(10, height - 45, width - 10, height - 45); for(int i = 0; i < count.length; i++){ int barHeight = (int)(((double)count[i] / (double)maxCount) * (height - 55)); g.drawRect(x, height - 45 - barHeight, individualWidth, barHeight); g.drawString((char)(65 + i) + "", x, height - 30); x += interval; } } } }
效果图: 需要注意的地方:之前错误的使用了StringBuffer StringBuilder,导致程序一运行即错误,如下图: