StringBuilder - Java
Формулировка задачи:
Помогите исправить 2 ошибки.
Должен быть калькулятор, который юзает файл и сохраняет калькуляцию.
Ошибки выдает на методе append и getText.
package webstart;
import java.awt.event.*;
import java.beans.*;
import java.io.*;
import java.net.*;
import javax.jnlp.*;
import javax.swing.*;
/**
* Фрейм с панелью калькулятора и меню для загрузки и сохранения предысторий калькуляций.
* Created by Михаил on 03.08.2016.
*/
public class CalculatorFrame extends JFrame{
private CalculatorPanel panel;
public CalculatorFrame()
{
setTitle();
panel = new CalculatorPanel();
add(panel);
JMenu fileMenu = new JMenu("File");
JMenuBar menuBar = new JMenuBar();
menuBar.add(fileMenu);
setJMenuBar(menuBar);
JMenuItem openItem = fileMenu.add("Open");
openItem.addActionListener(EventHandler.create(ActionListener.class, this, "open"));
JMenuItem saveItem = fileMenu.add("Save");
saveItem.addActionListener(EventHandler.create(ActionListener.class, this, "save"));
pack();
}
/**
* Получает заголовок из постоянного хранилища или запрашивает
* заголовок у пользователя, если он не был прежде сохранен
*/
public void setTitle()
{
try
{
String title = null;
BasicService basic =
(BasicService) ServiceManager.lookup("javax.jnlp.BasicService");
URL codeBase = basic.getCodeBase();
PersistenceService service = (PersistenceService) ServiceManager.lookup("javax.jnlp.BasicService");
URL key = new URL(codeBase, "title");
try
{
FileContents contents = service.get(key);
InputStream in = contents.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
title = reader.readLine();
}
catch (FileNotFoundException e)
{
title =
JOptionPane.showInputDialog("Please supply a frame title:");
if (title == null) return;
service.create(key, 100);
FileContents contents = service.get(key);
OutputStream out = contents.getOutputStream(true);
PrintStream printOut = new PrintStream(out);
printOut.print(title);
}
setTitle(title);
}
catch (UnavailableServiceException e)
{
JOptionPane.showMessageDialog(this, e);
}
catch (MalformedURLException e)
{
JOptionPane.showMessageDialog(this, e);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(this, e);
}
}
/**
* Открывает файл предыстории и обновляет отображаемый данные
*/
public void open()
{
try
{
FileOpenService service = (FileOpenService) ServiceManager.lookup("javax.jnlp.FileOpenService");
FileContents contents = service.openFileDialog(".", new String[] { "txt" });
JOptionPane.showMessageDialog(this, contents.getName());
if (contents != null)
{
InputStream in = contents.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null)
{
panel.append(line);
panel.append("\n");
}
}
}
catch (UnavailableServiceException e)
{
JOptionPane.showMessageDialog(this, e);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(this, e);
}
}
/**
* Сохраняет предысторию калькуляций в файле
*/
public void save()
{
try
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintStream printOut = new PrintStream(out);
printOut.print(panel.getText());
InputStream data = new ByteArrayInputStream(out.toByteArray());
FileSaveService service = (FileSaveService) ServiceManager.lookup("javax.jnlp.FileSaveService");
service.saveFileDialog(".", new String[] { "txt" }, data, "calc.txt");
}
catch (UnavailableServiceException e)
{
JOptionPane.showMessageDialog(this, e);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(this, e);
}
}
}package webstart;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Created by Михаил on 03.08.2016.
*/
public class CalculatorPanel extends JPanel {
public CalculatorPanel() {
setLayout(new BorderLayout());
result = 0;
lastCommand = "=";
start=true;
display = new JButton("Вводи");
display.setEnabled(false);
add(display, BorderLayout.NORTH);
ActionListener insert = new InsertAction();
ActionListener command = new CommandAction();
panel = new JPanel();
panel.setLayout(new GridLayout(4, 4));
addButton("7", insert);
addButton("8", insert);
addButton("9", insert);
addButton("/", command);
addButton("4", insert);
addButton("5", insert);
addButton("6", insert);
addButton("*", command);
addButton("1", insert);
addButton("2", insert);
addButton("3", insert);
addButton("-", command);
addButton("0", insert);
addButton(".", insert);
addButton("=", command);
addButton("+", command);
add(panel, BorderLayout.CENTER);
}
/**
* Вводит кнопку на центральной панели
* @param label Метка кнопки
* @param listener Приемник действий кнопки
*/
private void addButton(String label, ActionListener listener) {
JButton button = new JButton(label);
button.addActionListener(listener);
panel.add(button);
}
/**
* При обработке событий строка действия кнопки вводится
* в конце отображаемого текста
*/
private class InsertAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String input = event.getActionCommand();
if(start) {
display.setText("");
start = false;
}
display.setText(display.getText() + input);
}
}
/**
* При обработке событий выполняется команда,
* указанная в строке действия кнопки
*/
private class CommandAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();
if(start)
{
if(command.equals("-"))
{
display.setText(command);
start = false;
}
else lastCommand = command;
}
else
{
calculate(Double.parseDouble(display.getText()));
lastCommand = command;
start=true;
}
}
}
/**
* Выполняет ожидающую калькуляцию
* @param x Значение, накапливаемое с учетом предыдущего результата
*/
public void calculate(double x)
{
if(lastCommand.equals("+")) result += x;
else if(lastCommand.equals("-")) result -= x;
else if(lastCommand.equals("*")) result *= x;
else if(lastCommand.equals("/")) result /= x;
else if(lastCommand.equals("=")) result = x;
display.setText("" + result);
}
private JButton display;
private JPanel panel;
private double result;
private String lastCommand;
private boolean start;
}Решение задачи: «StringBuilder»
textual
Листинг программы
private CalculatorPanel panel;
panel.append(line);
panel.append("\n");