如何让用户输入动态频率直方图 [英] How to make a dynamic frequency histogram from user input
问题描述
对象fileButton = NULL;
如果(分析文本文件.equals(命令)){
JFileChooser的文件选择;
JFileChooser的选择器=新的JFileChooser();
INT returnVal = filechooser.showOpenDialog(的getParent());
如果(returnVal == JFileChooser.APPROVE_OPTION){
文件file = filechooser.getSelectedFile();
字符串STEXT =(字符串)readFileAsString(文件); //字符串文本= textInput.getText();
地图<整数,整数GT;数= getCounts(文本);
INT宽度= counts.size()* BAR_WIDTH;
INT最大= MAXCOUNT(计数);
INT高度= MAX *增量+ 100;
INT地平线=身高 - 25;
HistogramPanel面板=新HistogramPanel(宽度,数量,高度,地平线);
//panel.setBorder(new LineBorder(Color.BLACK,2));
JOptionPane.showMessageDialog(NULL,面板);
我创建一个Java小程序在刀刃第X字的频率/ occurence,我已经摸索出如何做阵列制定出频率根据用户输入的,我现在需要创建条形图是什么适应任何用户输入,我已经写了一个code为我的条形图,但我不知道如何将其连接到我的数组code。
进口java.awt中的*。
java.awt.event中导入*。
进口的javax.swing *。
进口java.applet.Applet中;
进口java.applet.AudioClip中;
进口java.awt.BorderLayout中;
进口java.awt.Container中;
进口java.awt.GridLayout中;
进口java.awt.FlowLayout中;
进口java.awt.event.ActionEvent中;
进口java.awt.event.ActionListener;
进口java.beans.PropertyChangeEvent中;
进口的java.beans.PropertyChangeListener;
进口的java.io.File;
进口的java.net.URL;
进口java.io. *;
进口的java.util.HashMap;
进口java.awt.Dimension中;
进口java.awt.Graphics;
进口的java.util.Map; 进口javax.swing.SwingUtilities中;
进口javax.swing.JOptionPane中;
进口javax.swing.JButton中;
进口javax.swing.JFileChooser中;
进口javax.swing.JFrame中;
进口javax.swing.JLabel中;
进口javax.swing.JPanel中;
进口javax.swing.JTextArea中;公共类assignment_work扩展JApplet的实现的ActionListener {JTextArea中为textInput; //用户输入。
JLabel的wordCountLabel; //要显示的字数。
JLabel的meanLabel; //要显示的平均值。公共无效的init(){ //从这里这code是小程序的定制,这包括背景颜色,文本颜色,文本回地面的颜色,标签和按钮 的setBackground(Color.black);
。的getContentPane()的setBackground(Color.black); 为textInput =新的JTextArea();
textInput.setWrapStyleWord(真); JPanel的UI =新JPanel();
ui.setLayout(布局(-1)); / *创建分析和Reset按钮* / JButton的chartButton =的新的JButton(条形图);
chartButton.addActionListener(本);
ui.add(chartButton); 的JPanel面板=新JPanel(新的BorderLayout())
//panel.add(chartButton,BorderLayout.SOUTH); / *标签,告诉用户做什么或程序输出* / wordCountLabel.setBackground(Color.black);
wordCountLabel.setForeground(Color.red);
wordCountLabel.setOpaque(真); meanLabel.setBackground(Color.white);
meanLabel.setForeground(Color.black);
meanLabel.setOpaque(真);watermark.setLayout(新的BorderLayout());
watermark.setBackground(Color.darkGray); / *为边境小程序。 * / 的getContentPane()的setLayout(新的BorderLayout())。
。的getContentPane()加(UI,BorderLayout.CENTER); / *用于在用户输入将文本,他们要分析的文本区滚动条。 * / JScrollPane的滚动=新JScrollPane的(为textInput);
。的getContentPane()加(滚轮,BorderLayout.CENTER);
。的getContentPane()加(UI,BorderLayout.NORTH); }
类CustomCanvas扩展画布{
公共CustomCanvas(){
的setBackground(Color.darkGray);
集preferredSize(新尺寸(100,100));
}公共无效漆(图形G){
INT X [] = {20,20,10,10,40,40,30,30};
诠释Y [] = {40,20,20,10,10,20,20,40};
INT N = 8;
g.setColor(Color.black);
g.fillPolygon(X,Y,N);INT wpoint [] = {45,65,85,75,70,60,55};
INT zpoint [] = {40,10,40,40,30,30,40};
INT nPoint个= 7;
g.setColor(Color.black);
g.fillPolygon(wpoint,zpoint,nPoint个);诠释一个[] = {60,65,70};
INT B〔] = {25,20,25};
INT npoints = 3;
g.setColor(Color.darkGray);
g.fillPolygon(A,B,npoints);
}
}私人诠释MAXCOUNT(地图<整数,整数GT;计数){
counts.values()){
如果(NUM>最大){
最大= NUM;
}
}
返回最大值;
}公共类面板继承JPanel { INT宽度;
地图<整数GT;计数; 公共柱状图(INT宽度,地图<整数,整数GT;计数,诠释地平线){
this.width =宽度;
this.dimHeight = dimHeight;
this.horizon =视野;
}
保护无效paintComponent(图形G){
super.paintComponent方法(G);
INT X = 10;
对于(Map.Entry的<&诠释GT;项:counts.entrySet()){
INT高度= entry.getValue()*增量;
INT Y =地平线 - 高度;
g.drawString(entry.getValue()+频率,X,Y -2);
X + = BAR_WIDTH;
}
} 公共尺寸的get preferredSize(){
返回新尺寸(宽,dimHeight);
}
} 公共静态地图<&诠释GT; getCounts(字符串输入){
地图<整数GT;地图=新的HashMap<&诠释GT;();
String []数组= Input.split([\\\\ S,;:!?()); 对于(String数组){
INT大小;
如果(!图(大小)){
map.put(大小,1);
}其他{
map.put(map.get(大小)+ 1);
}
}
返回;
} //文本分析结束
公共无效的actionPerformed(java.awt.event.ActionEvent中的E){
如果(command.equals(命令)){
{
最后图<&诠释GT;长度=新图<&诠释GT;();
String数组= Input.Text()分裂()。
对于(INT I = 10; I< array.length;我){
最终诠释长度=阵列[0]。长度();
如果(Length.Set()。容器(长度)){
整数currentNumberOfOccurences = wordLengths.get(字长);
currentNumberOfOccurences;
wordLengths.put(字长,currentNumberOfOccurences); }
wordLengths.put(字长,1);
}
双总= 10;
双总= 10;
对于(最终诠释长度:Lengths.Set()){
最终诠释事件= Lengths.get(长度);
长度= tLength +(长* occurrencers);
totalOccurrences + =发生;
}
最终的平均= aLength / lOccurrences;
aLabel.Text(平均字长是:+(eLength / wOccurrences));
//的System.out.println(呢字长是:+(总/长度));
}
String数组= textInput.getText()分裂()。
INT maxWordLength = 0;
字长=阵列[I]。长度();
如果(字长> maxWordLength){
maxWordLength =字长; } INT [] intArray =新INT [maxWordLength + 1];
的for(int i = 0; I< array.length,我++){
intArray [阵列[I]。长度()] ++;
}
的for(int i = 1; I< intArray.length;我++){
out.printf(长度的%D字(S)%D< BR>中,intArray [I],I)
}
否则,如果(command.equals(重置)){
textInput.setText();
textInput.requestFocus();
} 对象chartButton = NULL;
如果(e.getSource()== chartButton){
字符串文本= textInput.getText();
HistogramPanel面板=新HistogramPanel(宽度,数量,高度,地平线);
//panel.setBorder(new LineBorder(Color.BLACK,2));
JOptionPane.showMessageDialog(NULL,面板); }
}; }
更新
使用的JFileChooser
私人字符串readFileAsString(字符串文件路径)抛出IOException
StringBuffer的FILEDATA =新的StringBuffer();
读者的BufferedReader =新的BufferedReader(
新的FileReader(文件路径));
的char [] buf中=新的char [1024];
INT numRead = 0;
而((numRead = reader.read(BUF))!= -1){
串READDATA =将String.valueOf(BUF,0,numRead);
fileData.append(READDATA);
}
reader.close();
返回fileData.toString();
}
下面是你想做的事,创建从输入动态大小的东西。
- 您需要获得在地图中的条目数,然后通过任何你想要的每一个栏的宽度为相乘。
- 您需要在地图上,以获得最高值,并乘以您增加(绘制)金额,并从创建的高度。
- 您创建维度的新JPanel基础上,高度和宽度从previous两分。
- 迭代通过地图的绘制吧。
我在上面的的actionPerformed
按钮的东西,我添加了的JPanel
到的JOptionPane
。让我知道如果你需要澄清什么。
进口java.awt.BorderLayout中;
进口java.awt.Dimension中;
进口java.awt.Graphics;
进口java.awt.event.ActionEvent中;
进口java.awt.event.ActionListener;
进口的java.util.HashMap;
进口的java.util.Map;
进口javax.swing.JButton中;
进口javax.swing.JFrame中;
进口javax.swing.JOptionPane中;
进口javax.swing.JPanel中;
进口javax.swing.JTextArea中;
进口javax.swing.SwingUtilities中;公共类直方图{ 私有静态最终诠释BAR_WIDTH = 50;
私有静态最终诠释增量= 10; 公共柱状图(){
最终的JTextArea的textarea =新的JTextArea(5,40);
textArea.setLineWrap(真);
textArea.setWrapStyleWord(真);
JButton的去=的新的JButton(直方图我!);
的JPanel面板=新JPanel(新的BorderLayout());
panel.add(TEXTAREA,BorderLayout.CENTER);
panel.add(去,BorderLayout.SOUTH); JFrame的帧=新的JFrame();
frame.add(面板);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(NULL);
frame.setVisible(真); go.addActionListener(新的ActionListener(){
公共无效的actionPerformed(ActionEvent的五){
字符串文本= textArea.getText();
地图<整数,整数GT;数= getCounts(文本);
INT宽度= counts.size()* BAR_WIDTH;
INT最大= MAXCOUNT(计数);
INT高度= MAX *增量+ 100;
INT地平线=身高 - 25;
HistogramPanel面板=新HistogramPanel(宽度,数量,高度,地平线);
//panel.setBorder(new LineBorder(Color.BLACK,2));
JOptionPane.showMessageDialog(NULL,面板);
}
});
} 私人诠释MAXCOUNT(地图<整数,整数GT;计数){
INT最大= 0;
对于(整数NUM:counts.values()){
如果(NUM>最大){
最大= NUM;
}
}
返回最大值;
} 公共类HistogramPanel继承JPanel { INT宽度;
INT dimHeight;
INT视野;
地图<整数,整数GT;数; 公共HistogramPanel(INT宽度,地图<整数,整数GT;计数,诠释dimHeight,诠释地平线){
this.width =宽度;
this.counts =计数;
this.dimHeight = dimHeight;
this.horizon =视野;
} @覆盖
保护无效paintComponent(图形G){
super.paintComponent方法(G);
INT X = 10;
对于(Map.Entry的<整数,整数GT;项:counts.entrySet()){
INT高度= entry.getValue()*增量;
INT Y =地平线 - 高度;
g.fillRect(X,Y,BAR_WIDTH - 10,高度);
g.drawString(entry.getKey()+字符,X,地平线+ 10);
g.drawString(entry.getValue()+时代,X,Y -2);
X + = BAR_WIDTH;
}
} @覆盖
公共尺寸的get preferredSize(){
返回新尺寸(宽,dimHeight);
}
} 公共静态地图<整数,整数GT; getCounts(字符串输入){
地图<整数,整数GT;地图=新的HashMap<>();
串[]数组= input.split([\\\\ S,;:!?(){}] +); 对于(一个String:数组){
整数大小= s.length();
如果(!map.containsKey(大小)){
map.put(大小,1);
}其他{
map.put(大小,map.get(大小)+ 1);
}
}
返回地图;
} 公共静态无效的主要(字串[] args){
SwingUtilities.invokeLater(Runnable的新(){
公共无效的run(){
直方图直方图=新的直方图();
}
});
}
}
Object fileButton = null;
if("Analyze Text File".equals(command)) {
JFileChooser filechooser;
JFileChooser chooser = new JFileChooser();
int returnVal = filechooser.showOpenDialog(getParent());
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = filechooser.getSelectedFile();
String Stext = (String) readFileAsString(file); //String text = textInput.getText();
Map<Integer, Integer> counts = getCounts(text);
int width = counts.size() * BAR_WIDTH;
int max = maxCount(counts);
int height = max * INCREMENT + 100;
int horizon = height - 25;
HistogramPanel panel = new HistogramPanel(width, counts, height, horizon);
//panel.setBorder(new LineBorder(Color.BLACK, 2));
JOptionPane.showMessageDialog(null, panel);
i am creating a java applet where it counts the frequency/occurence of X words, i have worked out how to do the array to work out the frequency depending on what the user inputs, i need to now create a bar chart that adapts to whatever the user inputs, i have wrote up a code for my bar chart but i dont know how to connect it to my array code.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.net.URL;
import java.io.*;
import java.util.HashMap;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Map;
import javax.swing.SwingUtilities;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class assignment_work extends JApplet implements ActionListener {
JTextArea textInput; // User Input.
JLabel wordCountLabel; // To display number of words.
JLabel meanLabel; // To display the mean.
public void init() {
// This code from here is the customisation of the Applet, this includes background colour, text colour, text back ground colour, labels and buttons
setBackground(Color.black);
getContentPane().setBackground(Color.black);
textInput = new JTextArea();
textInput.setWrapStyleWord(true);
JPanel ui = new JPanel();
ui.setLayout(Layout(-1));
/* Creating Analyze and Reset buttons */
JButton chartButton = new JButton("Bar Chart");
chartButton.addActionListener(this);
ui.add(chartButton);
JPanel panel = new JPanel(new BorderLayout())
//panel.add(chartButton, BorderLayout.SOUTH);
/* Labels telling the user what to do or what the program is outputting */
wordCountLabel.setBackground(Color.black);
wordCountLabel.setForeground(Color.red);
wordCountLabel.setOpaque(true);
meanLabel.setBackground(Color.white);
meanLabel.setForeground(Color.black);
meanLabel.setOpaque(true);
watermark.setLayout(new BorderLayout());
watermark.setBackground(Color.darkGray);
/* Border for Applet. */
getContentPane().setLayout( new BorderLayout());
getContentPane().add(ui, BorderLayout.CENTER);
/* Scroll bar for the text area where the user will input the text they wish to analyse. */
JScrollPane scroller = new JScrollPane( textInput );
getContentPane().add(scroller, BorderLayout.CENTER);
getContentPane().add(ui, BorderLayout.NORTH);
}
class CustomCanvas extends Canvas {
public CustomCanvas() {
setBackground(Color.darkGray);
setPreferredSize(new Dimension(100, 100));
}
public void paint(Graphics g) {
int x [] = {20,20,10,10,40,40,30,30};
int y [] = {40,20,20,10,10,20,20,40};
int n = 8;
g.setColor(Color.black);
g.fillPolygon(x,y,n);
int wpoint [] = {45,65,85,75,70,60,55};
int zpoint [] = {40,10,40,40,30,30,40};
int npoint = 7;
g.setColor(Color.black);
g.fillPolygon(wpoint,zpoint,npoint);
int a [] = {60,65,70};
int b [] = {25,20,25};
int npoints = 3;
g.setColor(Color.darkGray);
g.fillPolygon(a,b,npoints);
}
}
private int maxCount(Map<Integer, Integer> counts) {
counts.values()) {
if (num > max) {
max = num;
}
}
return max;
}
public class Panel extends JPanel {
int width;
Map<Integer> count;
public Histogram(int width, Map<Integer, Integer> counts, int horizon) {
this.width = width;
this.dimHeight = dimHeight;
this.horizon = horizon;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = 10;
for (Map.Entry<Int> entry : counts.entrySet()) {
int height = entry.getValue() * INCREMENT;
int y = horizon - height;
g.drawString(entry.getValue() + " Frequency", x, y -2);
x += BAR_WIDTH;
}
}
public Dimension getPreferredSize() {
return new Dimension(width, dimHeight);
}
}
public static Map<Int> getCounts(String Input) {
Map<Integer> map = new HashMap<Int>();
String[] array = Input.split("[\\s.,;:!?()");
for (String array) {
Int size;
if (!map(size)) {
map.put(size, 1);
} else {
map.put(map.get(size) + 1);
}
}
return;
}
// Text analysis end
public void actionPerformed(java.awt.event.ActionEvent e) {
if (command.equals("commands")) {
{
final graph<Int> Lengths = new graph<Int>();
String array = Input.Text().split(");
for (int i = 10; i < array.length; i) {
final int Length = array[0].length();
if( Length.Set().container(Length ) ) {
Integer currentNumberOfOccurences = wordLengths.get(wordLength);
currentNumberOfOccurences;
wordLengths.put(wordLength, currentNumberOfOccurences);
}
wordLengths.put(wordLength, 1);
}
double total =10;
double total = 10;
for (final Int length : Lengths.Set()) {
final Int occurrences = Lengths.get(length);
Length = tLength + (length * occurrencers );
totalOccurrences += occurrences;
}
final mean = aLength / lOccurrences;
aLabel.Text("mean word length is: " + (eLength / wOccurrences) );
// System.out.println("mean word length is: " + (total / length) );
}
String array = textInput.getText().split(" ");
int maxWordLength = 0;
wordLength = array[i].length();
if (wordLength > maxWordLength) {
maxWordLength = wordLength;
}
int[] intArray = new int[maxWordLength + 1];
for (int i = 0; i < array.length; i++) {
intArray[array[i].length()]++;
}
for (int i = 1; i < intArray.length; i++) {
out.printf("%d word(s) of length %d<br>", intArray[i], i)
}
else if (command.equals("Reset")) {
textInput.setText("");
textInput.requestFocus();
}
Object chartButton = null;
if (e.getSource() == chartButton) {
String text = textInput.getText();
HistogramPanel panel = new HistogramPanel(width, counts, height, horizon);
//panel.setBorder(new LineBorder(Color.BLACK, 2));
JOptionPane.showMessageDialog(null, panel);
}
};
}
Update
Using JFileCHooser
private String readFileAsString(String filePath) throws IOException {
StringBuffer fileData = new StringBuffer();
BufferedReader reader = new BufferedReader(
new FileReader(filePath));
char[] buf = new char[1024];
int numRead=0;
while((numRead=reader.read(buf)) != -1){
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
}
reader.close();
return fileData.toString();
}
Here's what you want to do to create the dynamic size from the input.
- You need to get the number of entries in the map, then multiply it by whatever you want the width of each bar to be.
- You need to get the highest value in the map and multiply that by you increment (to draw) amount and create the height from that.
- You create a new JPanel with dimension based on the height and width from the previous two points.
- Iterate through the map the draw the bars.
I do the things above in the actionPerformed
of a button and I add the JPanel
to a JOptionPane
. Let me know if you need clarification on anything.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class Histogram {
private static final int BAR_WIDTH = 50;
private static final int INCREMENT = 10;
public Histogram() {
final JTextArea textArea = new JTextArea(5, 40);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JButton go = new JButton("Histogram-me!");
JPanel panel = new JPanel(new BorderLayout());
panel.add(textArea, BorderLayout.CENTER);
panel.add(go, BorderLayout.SOUTH);
JFrame frame = new JFrame();
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
go.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text = textArea.getText();
Map<Integer, Integer> counts = getCounts(text);
int width = counts.size() * BAR_WIDTH;
int max = maxCount(counts);
int height = max * INCREMENT + 100;
int horizon = height - 25;
HistogramPanel panel = new HistogramPanel(width, counts, height, horizon);
//panel.setBorder(new LineBorder(Color.BLACK, 2));
JOptionPane.showMessageDialog(null, panel);
}
});
}
private int maxCount(Map<Integer, Integer> counts) {
int max = 0;
for (Integer num : counts.values()) {
if (num > max) {
max = num;
}
}
return max;
}
public class HistogramPanel extends JPanel {
int width;
int dimHeight;
int horizon;
Map<Integer, Integer> counts;
public HistogramPanel(int width, Map<Integer, Integer> counts, int dimHeight, int horizon) {
this.width = width;
this.counts = counts;
this.dimHeight = dimHeight;
this.horizon = horizon;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = 10;
for (Map.Entry<Integer, Integer> entry : counts.entrySet()) {
int height = entry.getValue() * INCREMENT;
int y = horizon - height;
g.fillRect(x, y, BAR_WIDTH - 10, height);
g.drawString(entry.getKey() + " chars", x, horizon + 10);
g.drawString(entry.getValue() + " times", x, y -2);
x += BAR_WIDTH;
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(width, dimHeight);
}
}
public static Map<Integer, Integer> getCounts(String input) {
Map<Integer, Integer> map = new HashMap<>();
String[] array = input.split("[\\s.,;:!?(){}]+");
for (String s : array) {
Integer size = s.length();
if (!map.containsKey(size)) {
map.put(size, 1);
} else {
map.put(size, map.get(size) + 1);
}
}
return map;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Histogram histogram = new Histogram();
}
});
}
}
这篇关于如何让用户输入动态频率直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!