why won't my text print to my JTextArea? - java

I am calling a method that returns a string (edited text from a webpage) and I want to print that string onto my JTextArea. I know that string I am sending to my JTextArea is correct because it will print correctly to the command line, but will not print to the JTextArea. It must be something I am doing wrong in my adding it to the TextArea. Any help would be appreciated.
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
public class BrowserPanel extends JPanel {
private JTextField textField;
private String urlText;
private JTextArea textArea;
private BrowserPageReader myModel;
private String pageContent;
private BrowserFrame myFrame;
private String pageTitle;
private String pageBody;
public BrowserPanel(JTextField myTextField, BrowserPageReader model,
BrowserFrame frame)
{
myFrame = frame;
myModel = model;
textField = myTextField;
textField.addActionListener(new InputHandler());
/*JScrollPane areaScrollPane = new JScrollPane(textArea);
areaScrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
areaScrollPane.setPreferredSize(new Dimension(250,250));*/
textArea = new JTextArea(20,40);
textArea.setEditable(false);
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
JScrollPane scroll = new JScrollPane(textArea);
add(scroll);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
}
private class InputHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
urlText = textField.getText();
//textArea.append(urlText);
myModel.setURL(urlText);
pageTitle = myModel.getTitle();
myFrame.setTitle(pageTitle);
pageBody = myModel.getBody();
textArea.setText(pageBody);
System.out.println(pageBody); //This prints out exactly what Im wanting
// Its just a test
textArea.repaint();
}
}
}
I'm guessing I maybe need to add something to my paintComponent since my TextArea is in a scrollPane that is attached to my Panel. I just really cant figure out what is wrong. If i put textArea.setText("blah"); it does what it should. The variable I am sending in is a very large string, its an entire webpage. Could that be the problem? With the code as is the textArea remains blank and what i'm wanting it to show prints correctly to the command line. HELP!
Edit here is the rest of my code
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class BrowserFrame extends JFrame{
public BrowserFrame()
{
BrowserPageReader myModel = new BrowserPageReader();
setTitle("My Browser");
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize =kit.getScreenSize();
setSize(screenSize.width/2,screenSize.height-500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = getContentPane();
JTextField textField = new JTextField(20);
BrowserPanel myPanel = new BrowserPanel(textField,myModel,this);
contentPane.add(myPanel);
contentPane.add(textField,BorderLayout.PAGE_START);
setVisible(true);
}
}
import javax.swing.*;
import java.io.*;
import java.net.*;
public class BrowserPageReader {
private URL myURL;
//private String webURL;
private String totalWebContent;
private String htmlString;
private String contentToPrint = " ";
private String urlPath;
private String urlHost;
private String pageTitle;
private String pageBody;
private String formattedBody;
public void setURL (String webURL)
{
try{
myURL = new URL(webURL);
urlPath = myURL.getPath();
urlHost = myURL.getHost();
}
catch(MalformedURLException e)
{
JOptionPane.showMessageDialog(null,"URL is incorrectly formatted");
}
}
public void retrieveContent()
{
try{
Socket socket = new Socket(urlHost,80);
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader in = new
BufferedReader(new InputStreamReader(socket.getInputStream()));
out.print("GET " + urlPath + " HTTP/1.1\n");
out.print("Host: "+ urlHost + "\n");
out.print("\n");
out.flush();
while((totalWebContent = in.readLine()) != null)
{
//System.out.println(totalWebContent);
htmlString = htmlString + totalWebContent;
//System.out.println(contentToPrint);
}
//System.out.println("htmlString\n" + htmlString);
}
catch(Exception e){
e.printStackTrace();
}
}
public String getTitle()
{
retrieveContent();
//System.out.println(htmlString);
pageTitle = htmlString.substring(htmlString.indexOf("<title>")+ 7,
htmlString.indexOf("</title>"));
return pageTitle;
}
public String getBody()
{
String toDelete;
String edited;
retrieveContent();
pageBody = htmlString.substring(htmlString.indexOf("<body")+5,
htmlString.indexOf("</body>"));
toDelete = pageBody.substring(0,pageBody.indexOf('<'));
edited = pageBody.replace(toDelete,"");
pageBody = edited
formattedBody = pageBody.replaceAll("<[^>]*>", "");
//System.out.println(formattedBody);
return formattedBody;
}

Since your posted code is not an SSCCE, a small self-contained program that we can compile, run, and test, I don't think that we answer this without guessing. And so my guess: the JTextArea that you're adding text to is not the same one as is being displayed in a JFrame.
To be able to answer this with confidence though, we need that SSCCE, especially the code showing where you create the class above and where you add it to the JFrame that is displayed.
For instance, if I create a small SSCCE with mock BrowserFrame JFrame and BrowserPageReader model classes, everything seems to work fine:
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
public class BrowserPanel extends JPanel {
private JTextField textField;
private String urlText;
private JTextArea textArea;
private BrowserPageReader myModel;
private String pageContent;
private BrowserFrame myFrame;
private String pageTitle;
private String pageBody;
public BrowserPanel(JTextField myTextField, BrowserPageReader model,
BrowserFrame frame) {
myFrame = frame;
myModel = model;
textField = myTextField;
textField.addActionListener(new InputHandler());
/*
* JScrollPane areaScrollPane = new JScrollPane(textArea);
* areaScrollPane.setVerticalScrollBarPolicy(
* JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
*
* areaScrollPane.setPreferredSize(new Dimension(250,250));
*/
textArea = new JTextArea(20, 40);
textArea.setEditable(false);
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
JScrollPane scroll = new JScrollPane(textArea);
add(scroll);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
}
private class InputHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
urlText = textField.getText();
// textArea.append(urlText);
myModel.setURL(urlText);
pageTitle = myModel.getTitle();
myFrame.setTitle(pageTitle);
pageBody = myModel.getBody();
textArea.setText(pageBody);
System.out.println(pageBody); // This prints out exactly what Im
// wanting
// Its just a test
textArea.repaint();
}
}
private static void createAndShowGui() {
BrowserFrame frame = new BrowserFrame();
JTextField textField = new JTextField(10);
BrowserPageReader myModel = new BrowserPageReader();
BrowserPanel mainPanel = new BrowserPanel(textField, myModel, frame);
frame.add(textField, BorderLayout.NORTH);
frame.add(mainPanel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class BrowserFrame extends JFrame {
}
class BrowserPageReader {
public void setURL(String urlText) {
// does nothing for now. for testing purposes.
}
public String getBody() {
return "body"; // for testing purposes
}
public String getTitle() {
return "title"; // for testing purposes
}
}
Since my code "works" it proves that the error is not in the code you've posted above.
Your job is to post similar code that doesn't work fine, that instead demonstrates your problem. I'm guessing that if you put in the effort to create such a program, you'll isolate the error, you'll see where you've likely got two BrowserPanels, one displayed and one that is not displayed but is getting its text changed in the handler, and you'll be able to solve your error without our direct help.
Edit
SwingWorker e.g.
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
public class BrowserPanel extends JPanel {
private JTextField textField;
private String urlText;
private JTextArea textArea;
private BrowserPageReader myModel;
private String pageContent;
private BrowserFrame myFrame;
private String pageTitle;
private String pageBody;
public BrowserPanel(JTextField myTextField, BrowserPageReader model,
BrowserFrame frame) {
myFrame = frame;
myModel = model;
textField = myTextField;
textField.addActionListener(new InputHandler());
/*
* JScrollPane areaScrollPane = new JScrollPane(textArea);
* areaScrollPane.setVerticalScrollBarPolicy(
* JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
*
* areaScrollPane.setPreferredSize(new Dimension(250,250));
*/
textArea = new JTextArea(20, 40);
textArea.setEditable(false);
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
JScrollPane scroll = new JScrollPane(textArea);
add(scroll);
}
private class InputHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
urlText = textField.getText();
// textArea.append(urlText);
System.out.println(urlText);
myModel.setURL(urlText);
myModel.getContent(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (SwingWorker.StateValue.DONE == evt.getNewValue()) {
pageTitle = myModel.getTitle();
myFrame.setTitle(pageTitle);
pageBody = myModel.getBody();
textArea.setText(pageBody);
System.out.println(pageBody);
}
}
});
// textArea.repaint();
}
}
private static void createAndShowGui() {
BrowserFrame frame = new BrowserFrame();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class BrowserFrame extends JFrame {
public BrowserFrame() {
BrowserPageReader myModel = new BrowserPageReader();
setTitle("My Browser");
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();
setSize(screenSize.width / 2, screenSize.height - 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = getContentPane();
JTextField textField = new JTextField(20);
BrowserPanel myPanel = new BrowserPanel(textField, myModel, this);
contentPane.add(myPanel);
contentPane.add(textField, BorderLayout.PAGE_START);
setVisible(true);
}
}
class BrowserPageReader {
private URL myURL;
// private String webURL;
private String totalWebContent;
private String htmlString;
private String contentToPrint = " ";
private String urlPath;
private String urlHost;
private String pageTitle;
private String pageBody;
private String formattedBody;
public void setURL(String webURL) {
try {
myURL = new URL(webURL);
urlPath = myURL.getPath();
urlHost = myURL.getHost();
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(null, "URL is incorrectly formatted");
}
}
public void getContent(PropertyChangeListener listener) {
RetrieveWorker worker = new RetrieveWorker();
worker.addPropertyChangeListener(listener);
worker.execute();
}
private void retrieveContent() {
try {
Socket socket = new Socket(urlHost, 80);
PrintWriter out = new PrintWriter(socket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out.print("GET " + urlPath + " HTTP/1.1\n");
out.print("Host: " + urlHost + "\n");
out.print("\n");
out.flush();
while ((totalWebContent = in.readLine()) != null) {
// System.out.println(totalWebContent);
htmlString = htmlString + totalWebContent;
// System.out.println(contentToPrint);
}
// System.out.println("htmlString\n" + htmlString);
} catch (Exception e) {
e.printStackTrace();
}
}
public String getTitle() {
// !! retrieveContent();
System.out.println(htmlString);
pageTitle = htmlString.substring(htmlString.indexOf("<title>") + 7,
htmlString.indexOf("</title>"));
return pageTitle;
}
public String getBody() {
String toDelete;
String edited;
// !! retrieveContent();
pageBody = htmlString.substring(htmlString.indexOf("<body") + 5,
htmlString.indexOf("</body>"));
toDelete = pageBody.substring(0, pageBody.indexOf('<'));
edited = pageBody.replace(toDelete, "");
pageBody = edited;
formattedBody = pageBody.replaceAll("<[^>]*>", "");
// System.out.println(formattedBody);
return formattedBody;
}
private class RetrieveWorker extends SwingWorker<Void, Void> {
#Override
protected Void doInBackground() throws Exception {
retrieveContent();
return null;
}
}
}

I bet your input handler is getting called multiple times. The text could be set to the body text, then print, then be set back to empty for some reason. Test this in your system.out.println statment by adding
System.out.println("outputStart: " + pagebody + " :END");
Then you'll be able to tell how many times your input handler ran.

Related

Using data of one class in another class (Java/FileMenuHandler)

I have two different FileMenuHandler's for a GUI, I need a way to use the data stored in the TreeMap from FileMenuHadler in EditMenuHandler. EditMenuHandler is supposed to ask the user to enter a word and search in the TreeMap if the word exists.
I tried to create an instance of FMH in EMH but the Tree was always empty, how can I save the values of the tree once the file is opened and then use it for EditMenuHandler?
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class FileMenuHandler implements ActionListener{
JFrame jframe;//creating a local JFrame
public FileMenuHandler (JFrame jf){//passing WordGUI Jframe
jframe = jf;
}
private Container myContentPane;
private TextArea myTextArea1;
private TextArea myTextArea2;
protected ArrayList<Word> uwl = new ArrayList<Word>();
protected TreeMap<Word, String> tree;
private void readSource(File choosenFile){
String choosenFileName = choosenFile.getName();
TextFileInput inFile = new TextFileInput(choosenFileName);
myContentPane = jframe.getContentPane();
myTextArea1 = new TextArea();
myTextArea2 = new TextArea();
myTextArea1.setForeground(Color.blue);
myTextArea2.setForeground(Color.blue);
Font font = new Font("Times", Font.BOLD, 20);
myTextArea1.setFont(font);
myTextArea2.setFont(font);
myTextArea1.setBackground(Color.yellow);
myTextArea2.setBackground(Color.yellow);
String paragraph = "";
String line = inFile.readLine();
while(line != null){
paragraph += line + " ";
line = inFile.readLine();
}
StringTokenizer st = new StringTokenizer(paragraph);
tree = new TreeMap<Word,String>();
while(st.hasMoreTokens()){
String word = st.nextToken();
Word w = new Word(word);
uwl.add(w);
tree.put(w,w.data);
}
for(int i = 0; i < uwl.size(); i++){
myTextArea1.append(uwl.get(i).data + "\n");
}
myTextArea2.append(tree + "\n");
myContentPane.add(myTextArea1);
myContentPane.add(myTextArea2);
jframe.setVisible(true);
}
private void openFile(){
int status;
JFileChooser chooser = new JFileChooser("./");
status = chooser.showOpenDialog(null);
readSource(chooser.getSelectedFile());
}
//instance of edit menu handler
public void actionPerformed(ActionEvent event) {
String menuName = event.getActionCommand();
if (menuName.equals("Open")){
openFile();
}
else if (menuName.equals("Quit")){
System.exit(0);
}
} //actionPerformed
}
//
import java.awt.event.*;
public class EditMenuHandler implements ActionListener {
JFrame jframe;
public EditMenuHandler(JFrame jf) {
jframe = jf;
}
public void actionPerformed(ActionEvent event) {
String menuName = event.getActionCommand();
if (menuName.equals("Search")) {
JOptionPane.showMessageDialog(null, "Search");
}
}
}
there are many ways to do this,
you can declare a static filed (not recommended)
use RXJava or LiveData
use EventBus
use interface as a listener
....

How can I solve a string version of a calculation for a simple calculator? [duplicate]

This question already has answers here:
How to evaluate a math expression given in string form?
(26 answers)
Closed 6 years ago.
This is a simple calculator where the user can type out the calculation and hit enter, and the calculator would determine if it is a valid calculation or not. If it is a valid calculation, the calculation is carried out. If not, an error message is written to the screen.
The calculation is carried out part isn't finished.
Can someone suggest a solutions to the getAnswer() method.
It would be very much appreciated.
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
#SuppressWarnings("serial")
public class Calculator extends JFrame{
private interface CalculatorInterface {
public void writeToScreen(String text);
public void clearScreen();
public String getScreenText();
}
private class CalculatorPanel extends JPanel implements CalculatorInterface {
private class NumberPanel extends JPanel implements CalculatorInterface {
private static final int NUMTOTAL = 10;
private CalculatorPanel calcPanel;
private JButton[] numButtons;
public NumberPanel(CalculatorPanel calcPanel) {
this.calcPanel = calcPanel;
buildLayout();
addButtons();
}
private void buildLayout() {
this.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
GridLayout layout = new GridLayout(4,3);
layout.setHgap(1);
layout.setVgap(1);
this.setLayout(new GridLayout(4,3));
}
private void addButtons() {
numButtons = new JButton[NUMTOTAL];
for(int i = numButtons.length -1; i >= 0 ; i--) {
numButtons[i] = new JButton("" + i);
numButtons[i].setPreferredSize(new Dimension(60,40));
numButtons[i].setFont(new Font("Sans serif", Font.PLAIN, 18));
numButtons[i].addActionListener(
new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = ((JButton)e.getSource()).getText().trim();
if(getScreenText().equals("Invalid Calc")) {
clearScreen();
writeToScreen(text);
}else {
writeToScreen(text);
}
}
});
this.add(numButtons[i]);
}
}
#Override
public void writeToScreen(String text) {
calcPanel.writeToScreen(text);
}
#Override
public void clearScreen() {
calcPanel.clearScreen();
}
#Override
public String getScreenText() {
return calcPanel.getScreenText();
}
}
private class OperPanel extends JPanel implements CalculatorInterface {
private static final int ADD = 0;
private static final int SUB = 1;
private static final int MULT = 2;
private static final int DIV = 3;
private static final int OPENB = 4;
private static final int CLOSEB = 5;
private static final int CLEAR = 6;
private static final int EQL = 7;
private static final int OPERTOTAL = 8;
private CalculatorPanel calcPanel;
private JButton[] operButtons;
public OperPanel(CalculatorPanel calcPanel) {
this.calcPanel = calcPanel;
buildLayout();
addButtons();
}
private void buildLayout() {
GridLayout layout = new GridLayout(4,1);
layout.setHgap(1);
layout.setVgap(1);
this.setLayout(new GridLayout(4,1));
}
private void addButtons() {
operButtons = new JButton[OPERTOTAL];
operButtons[ADD] = makeButton(ADD, "+");
operButtons[SUB] = makeButton(SUB, "-");
operButtons[MULT] = makeButton(MULT, "*");
operButtons[DIV] = makeButton(DIV, "/");
operButtons[CLEAR] = makeButton(CLEAR, "CL");
operButtons[EQL] = makeButton(EQL, "=");
operButtons[OPENB] = makeButton(OPENB, "(");
operButtons[CLOSEB] = makeButton(CLOSEB, ")");
for(JButton button: operButtons) {
this.add(button);
}
}
private JButton makeButton(int index, String label) {
operButtons[index] = new JButton(label);
operButtons[index].addActionListener(
new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = ((JButton)e.getSource()).getText();
if(text.equals("=")) {
String screenText = getScreenText();
clearScreen();
try {
writeToScreen(getAnswer(screenText));
}catch(Exception excep) {
writeToScreen("Invalid Calc");
}
}else if(text.equals("CL")) {
clearScreen();
}else {
writeToScreen(text);
}
}
});
return operButtons[index];
}
private String getAnswer(String text) throws Exception {
/*I'm trying to solve for any input by the user e.g
*(the stuff in square brackets represents what is displayed
* on the screen:.
*[1+1] (hits equals) [2]
*[1+2-3] (hits equals) [0]
*[1+2*3] (hits equals) [7]
*[10*(14+1/2)] (hits equals) [145]
*/
throw new Exception();
}
#Override
public String getScreenText() {
return calcPanel.getScreenText();
}
#Override
public void clearScreen() {
calcPanel.clearScreen();
}
#Override
public void writeToScreen(String text) {
calcPanel.writeToScreen(text);
}
}
private NumberPanel numPanel;
private OperPanel operPanel;
private JTextField calcScreen;
public CalculatorPanel(JTextField calcScreen) {
this.calcScreen = calcScreen;
buildNumPanel();
buildOperPanel();
buildCalcPanel();
}
private void buildNumPanel() {
this.numPanel = new NumberPanel(this);
}
private void buildOperPanel() {
this.operPanel = new OperPanel(this);
}
private void buildCalcPanel() {
this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
this.add(numPanel);
this.add(operPanel);
}
#Override
public void writeToScreen(String text) {
calcScreen.setText(getScreenText() + text);
}
#Override
public String getScreenText() {
return calcScreen.getText();
}
#Override
public void clearScreen() {
calcScreen.setText("");
}
}
private JPanel mainPanel;
private JTextField calcScreen;
private CalculatorPanel calcPanel;
public Calculator() {
buildScreen();
buildCalcPanel();
buildMainPanel();
buildCalculator();
}
private void buildScreen() {
this.calcScreen = new JTextField();
this.calcScreen.setPreferredSize(new Dimension(150,50));
this.calcScreen.setHorizontalAlignment(JTextField.CENTER);
this.calcScreen.setFont(new Font("Sans serif", Font.PLAIN, 30));
}
private void buildCalcPanel() {
this.calcPanel = new CalculatorPanel(this.calcScreen);
}
private void buildMainPanel() {
this.mainPanel = new JPanel();
this.mainPanel.setBorder(new EmptyBorder(10,10,10,10));
this.mainPanel.setLayout(new BoxLayout(this.mainPanel, BoxLayout.Y_AXIS));
this.mainPanel.add(calcScreen);
this.mainPanel.add(calcPanel);
}
private void buildCalculator() {
this.add(mainPanel);
this.setTitle("Calculator");
this.pack();
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public static void main(String[] args) {
#SuppressWarnings("unused")
Calculator calc = new Calculator();
}
}
How can I check to see if a string is a valid calculation for a simple calculator?
Edit 1: Fixed a silly bug in the makeButton() method were I passed in the text of the button to be verified instead of the text on screen. (I'm an idiot.)
Edit 2: Removed the isValid(String text) from the code and make it so the getAnswer() method just threw an exception if input is not a valid calculation.
As well mentioned in a previous StackOverflow answer (Evaluating a math expression given in string form), you could use Javascript's ScriptEngine to calculate expressions based on strings that you would retrieve from the Text Field. Place it in a try-catch block first to see if there's an error in the expression. In the catch block, set the variable storing whether its a valid expression or not to false.
boolean validExpression = true;
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String input = textField.getText() // Modify this to whatever variable you have assigned to your text field
try {
System.out.println(engine.eval(foo));
}
catch (ScriptException e) {
validExpression = false;
System.out.println("Invalid Expression");
}
Make sure you include the following imports:
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
Although you could try to implement Shunting-Yard Algorithm or another arithmetic parser, this is simply a way more pragmatic solution.

Java: Copying data from dialog box text field to JTable

This project requires that a user inputs data into text fields on a dialog box accessed from a menu bar and places the data from the text fields into a JTable. The problem is that once the user clicks okay on the dialog box after putting the information into the text field, the dialog box is no longer visible, but nothing appears in the JTable. The JTable headers are there, but the info just submitted is not.
It is a camping registration program, and all of the classes compile okay. I am only working on taking information from an RV reservation first, but will eventually do the same for a tent reservation. Here are the classes that correspond to an RV check in. There is an RV constructor that has parameters (String (name), String (check in day), int (days staying), String (leave day), int (site number), int (power needed)).
First the dialog box class:
package campingPrj;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DialogCheckInRv extends javax.swing.JDialog implements ActionListener {
private static final long serialVersionUID = 1L;
private javax.swing.JTextField nameTxt;
private javax.swing.JTextField dateIn;
private javax.swing.JTextField stayingTxt;
private javax.swing.JTextField siteNumberTxt;
private javax.swing.JTextField checkOutDate;
private javax.swing.JTextField powerTxt;
private javax.swing.JButton okButton;
private javax.swing.JButton cancelButton;
private boolean cancel;
private boolean okay;
public DialogCheckInRv(java.awt.Frame parent) {
super(parent, true);
setupDialog();
setTitle("RV Check In");
}
private void setupDialog() {
setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
nameTxt = new javax.swing.JTextField(27);
dateIn = new javax.swing.JTextField(25);
stayingTxt = new javax.swing.JTextField(25);
siteNumberTxt = new javax.swing.JTextField(27);
powerTxt = new javax.swing.JTextField(27);
okButton = new javax.swing.JButton("Ok");
okButton.addActionListener(this);
cancelButton = new javax.swing.JButton("Cancel");
cancelButton.addActionListener(this);
setLayout(new GridLayout(6, 1));
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("Name Reserving:"));
panel.add(nameTxt);
add(panel);
panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("Start Date (mm/dd/yy) :"));
panel.add(dateIn);
add(panel);
panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("Days Planning on Staying:"));
panel.add(stayingTxt);
add(panel);
panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("Requested Site Number:"));
panel.add(siteNumberTxt);
add(panel);
panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel.add(new JLabel("Power Needed (in AMPs):"));
panel.add(powerTxt);
add(panel);
panel = new JPanel();
panel.add(okButton);
panel.add(cancelButton);
add(panel);
pack();
setLocationRelativeTo(null);
}
public void actionPerformed(java.awt.event.ActionEvent event) {
if (event.getSource() == okButton) {
okay = true;
cancel = false;
setVisible(false);
}
if (event.getSource() == cancelButton) {
okay = false;
cancel = true;
setVisible(false);
}
}
public boolean isOk() {
return okay;
}
public boolean isCancel() {
return cancel;
}
public String getName() {
return nameTxt.getText();
}
public String getDateIn() {
return dateIn.getText();
}
public String getDaysStaying() {
return stayingTxt.getText();
}
public String getCheckOutDate() {
return checkOutDate.getText();
}
public String getPower() {
return powerTxt.getText();
}
public String getSiteNumber() {
return siteNumberTxt.getText();
}
public void clear() {
nameTxt.setText(null);
dateIn.setText(null);
stayingTxt.setText(null);
dateIn.setText(null);
powerTxt.setText(null);
siteNumberTxt.setText(null);
}
}
The GUI with the table (where I'm guessing the problem is in the actionPerformed method):
package campingPrj;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class GUICampingReg extends javax.swing.JFrame implements ActionListener {
private JMenuItem openSerialFileItem = new JMenuItem("Open Serialized File");
private JMenuItem openTextFileItem = new JMenuItem("Open Text File");
private JMenuItem saveSerialFileItem = new JMenuItem("Save Serialized File");
private JMenuItem saveTextFileItem = new JMenuItem("Save Text File");
private JMenuItem exitItem = new JMenuItem("Exit");
private JMenuItem checkInTentItem = new JMenuItem("Check in tent");
private JMenuItem checkInRVItem = new JMenuItem("Check in RV");
private JMenuItem checkOutItem = new JMenuItem("Date Leaving");
private JTextField nameReservingTxt;
private JTextField dateInTxt;
private JTextField daysStayingTxt;
private JTextField checkOutOnTxt;
private JTextField siteNumberTxt;
private JTextField powerTxt;
private JFrame frame;
private JTable table;
private SiteModel model;
private JScrollPane scrollPane;
private DialogCheckInRv newRv;
public GUICampingReg() {
setupFrame();
newRv = new DialogCheckInRv(this);
model = new SiteModel();
table.setModel(model);
}
private void setupFrame() {
frame = new JFrame();
frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
frame.setTitle("Camping Registration Program");
scrollPane = new JScrollPane();
table = new JTable();
JMenuBar menubar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.add(openSerialFileItem);
fileMenu.add(openTextFileItem);
fileMenu.add(saveSerialFileItem);
fileMenu.add(saveTextFileItem);
fileMenu.add(exitItem);
JMenu checkInMenu = new JMenu("Check In");
checkInMenu.add(checkInRVItem);
checkInMenu.add(checkInTentItem);
JMenu checkOutMenu = new JMenu("Check Out");
checkOutMenu.add(checkOutItem);
menubar.add(fileMenu);
menubar.add(checkInMenu);
menubar.add(checkOutMenu);
openSerialFileItem.addActionListener(this);
openTextFileItem.addActionListener(this);
saveSerialFileItem.addActionListener(this);
saveTextFileItem.addActionListener(this);
exitItem.addActionListener(this);
checkInTentItem.addActionListener(this);
checkInRVItem.addActionListener(this);
checkOutItem.addActionListener(this);
frame.setJMenuBar(menubar);
scrollPane
.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
table.setToolTipText("");
table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
table.getTableHeader().setReorderingAllowed(false);
table.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tableMouseClicked();
}
});
scrollPane.setViewportView(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void tableMouseClicked() {
// TODO Auto-generated method stub
}
public void actionPerformed(ActionEvent evt) {
Object pressed = evt.getSource();
if (pressed == exitItem) {
System.exit(0);
}
if (pressed == openSerialFileItem) {
}
if (pressed == openTextFileItem) {
}
if (pressed == saveSerialFileItem) {
}
if (pressed == saveTextFileItem) {
}
if (pressed == checkInTentItem) {
}
if (pressed == checkInRVItem) {
newRv.clear();
newRv.setVisible(true);
if (newRv.isOk()) {
String nameReserving = nameReservingTxt.getText();
String checkIn = dateInTxt.getText();
int daysStaying = Integer.parseInt(daysStayingTxt.getText());
String checkOutOn = checkOutOnTxt.getText();
int siteNumber = Integer.parseInt(siteNumberTxt.getText());
int power = Integer.parseInt(powerTxt.getText());
RV rv = new RV (nameReserving, checkIn, daysStaying, checkOutOn, siteNumber, power);
model.add(rv);
}
}
if (pressed == checkOutItem) {
}
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new GUICampingReg();
}
});
}
}
The site model class:
package campingPrj;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
public class SiteModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private ArrayList<Site> listSites;
private String[] columnNames = { "Name Reserving", "Checked in Date",
"Days Staying", "Site #", "Tenters/RV Power Needed" };
public SiteModel() {
listSites = new ArrayList<Site>();
}
public String getColumnName(int col) {
return columnNames[col];
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return listSites.size();
}
public Object getValueAt(int row, int col) {
Object val = null;
switch (col) {
case 0:
val = listSites.get(row).getNameReserving();
break;
case 1:
val = listSites.get(row).getCheckIn();
break;
case 2:
val = listSites.get(row).getDaysStaying();
break;
case 3:
val = listSites.get(row).getSiteNumber();
break;
case 4:
val = listSites.get(row).getCheckOutOn();
break;
}
return val;
}
public Site get(int index) {
return listSites.get(index);
}
public int indexOf(Site s) {
return listSites.indexOf(s);
}
public void add(Site s) {
if (s != null) {
listSites.add(s);
fireTableRowsInserted(listSites.size() - 1, listSites.size() - 1);
}
}
public void add(int index, Site s) {
if (s != null) {
listSites.add(index, s);
fireTableRowsInserted(index, index);
}
}
public void remove(int index) {
listSites.remove(index);
fireTableRowsDeleted(index, index);
return;
}
public void remove(Site s) {
remove(indexOf(s));
}
public void saveAsSerialized(String filename) throws IOException {
FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(listSites);
os.close();
}
#SuppressWarnings("unchecked")
public void loadFromSerialized(String filename) throws IOException,
ClassNotFoundException {
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream is = new ObjectInputStream(fis);
listSites = (ArrayList<Site>) is.readObject();
is.close();
}
}
So, how do I get the information to show up in JTable?
Maybe I'm misinterpreting your code, but I don't see where you areextracting the information that the user enters into the dialog. For example here:
if (newRv.isOk()) {
String nameReserving = nameReservingTxt.getText();
String checkIn = dateInTxt.getText();
int daysStaying = Integer.parseInt(daysStayingTxt.getText());
String checkOutOn = checkOutOnTxt.getText();
int siteNumber = Integer.parseInt(siteNumberTxt.getText());
int power = Integer.parseInt(powerTxt.getText());
RV rv = new RV (nameReserving, checkIn, daysStaying, checkOutOn, siteNumber, power);
model.add(rv);
}
You appear to be extracting information from the fields held by the GUICampingReg, not by the newRv object. Shouldn't you be calling methods of newRv to extract the data needed to create your RV object?
for example,
if (newRv.isOk()) {
String nameReserving = newRv.getName();
String checkIn = newRv.getDateIn();
// .... etc
RV rv = new RV (nameReserving, checkIn, daysStaying, checkOutOn, siteNumber, power);
model.add(rv);
}

Error when trying to create a print function

I have been following the How to Print Text tutorial on the Oracle Java Documentation website. However when I have tried to implement some of the code into my code I get an error.
javac PrintableForms.java
PrintableForms.java:165: error: incompatible types: PrintableForms cannot be converted to Component
JOptionPane.showMessageDialog(this, msg, "Printing", type);
My code is
import javax.swing.*;
import java.awt.*;
import java.io.*;
import javax.swing.*;
import java.awt.print.PrinterException;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.*;
import java.text.MessageFormat;
import javax.xml.transform.Source;
public class PrintableForms
{
JFrame myMainWindow = new JFrame("This is my title");
JPanel firstPanel = new JPanel();
JButton btnDoc1 = new JButton();
JButton btnP1 = new JButton();
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String []fontFamilies = ge.getAvailableFontFamilyNames();
Font FontT5 = new Font("SansSerif", Font.BOLD, 50);
///////////
JCheckBox backgroundCheck = new JCheckBox();
JCheckBox interactiveCheck = new JCheckBox();
JTextArea text = new JTextArea();
JTextField headerField = new JTextField();
JTextField footerField = new JTextField();
public void runGUI()
{
myMainWindow.setBounds(10, 10, 1200, 500);
myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myMainWindow.setLayout(new GridLayout(1,1));
createFirstPanel();
myMainWindow.getContentPane().add(firstPanel);
myMainWindow.setVisible(true);
load(text, "Athlete.txt");
}
public void createFirstPanel()
{
firstPanel.setLayout(null);
btnDoc1.setLocation(10,120);
btnDoc1.setSize(900,50);
btnDoc1.setText("Update Personal Information");
btnDoc1.setFont(FontT5);
firstPanel.add(btnDoc1);
btnP1.setLocation(910,120);
btnP1.setSize(250,50);
btnP1.setText("Print");
btnP1.setFont(FontT5);
btnP1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
print(evt);
}
});
firstPanel.add(btnP1);
footerField.setText("Page {0}");
headerField.setText("Athlete Form");
backgroundCheck.setSelected(true);
interactiveCheck.setSelected(true);
}
private void load(JTextArea comp, String fileName) {
try {
comp.read(
new InputStreamReader(
getClass().getResourceAsStream(fileName)),
null);
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void print(java.awt.event.ActionEvent evt)
{
MessageFormat header = createFormat(headerField);
MessageFormat footer = createFormat(footerField);
boolean interactive = interactiveCheck.isSelected();
boolean background = backgroundCheck.isSelected();
PrintingTask task = new PrintingTask(header, footer, interactive);
if (background)
{
task.execute();
}
else
{
task.run();
}
}
private class PrintingTask extends SwingWorker<Object, Object>
{
private final MessageFormat headerFormat;
private final MessageFormat footerFormat;
private final boolean interactive;
private volatile boolean complete = false;
private volatile String message;
JTextArea text = new JTextArea();
public PrintingTask(MessageFormat header, MessageFormat footer, boolean interactive)
{
this.headerFormat = header;
this.footerFormat = footer;
this.interactive = interactive;
}
#Override
protected Object doInBackground() {
try {
complete = text.print(headerFormat, footerFormat,
true, null, null, interactive);
message = "Printing " + (complete ? "complete" : "canceled");
} catch (PrinterException ex) {
message = "Sorry, a printer error occurred";
} catch (SecurityException ex) {
message =
"Sorry, cannot access the printer due to security reasons";
}
return null;
}
#Override
protected void done() {
message(!complete, message);
}
}
private MessageFormat createFormat(JTextField source) {
//String text = new Scanner( new File("Athlete.txt") ).useDelimiter("\\A").next();
String text = source.getText();
if (text != null && text.length() > 0) {
try {
return new MessageFormat(text);
} catch (IllegalArgumentException e) {
error("Sorry, this format is invalid.");
}
}
return null;
}
private void message(boolean error, String msg)
{
int type = (error ? JOptionPane.ERROR_MESSAGE :
JOptionPane.INFORMATION_MESSAGE);
JOptionPane.showMessageDialog(this, msg, "Printing", type);
}
private void error(String msg)
{
message(true, msg);
}
public static void main(String[] args)
{
PrintableForms pf = new PrintableForms();
pf.runGUI();
}
}
I am trying to get it so when I click a button, btnP1 in this case, it opens a dialog and then allows you to print off a pre-set document. In this code that document is Athlete.txt and all it reads is This is a test
I would any help in fixing this problem, Thanks
You could pass on the frame object which is the main window that you created when you want to show the dialog window.
Like below.
JOptionPane.showMessageDialog(myMainWindow, msg, "Printing", type);
you should extends Component class or create Component type object and pass as argument instead of this because
JOptionPane.showMessageDialog(this, msg, "Printing", type);
first argument is of Component Type and you are passing parameter of type PrintableForms as this .
Try implementing the Printable interface.

JComboBox ActionEvent performs with multiple comboboxes?

I am performing actions for 2 combo boxes which involves in changing the background color of JLabel. Here is my code,
public class JavaApplication8 {
private JFrame mainFrame;
private JLabel signal1;
private JLabel signal2;
private JPanel s1Panel;
private JPanel s2Panel;
public JavaApplication8()
{
try {
prepareGUI();
} catch (ClassNotFoundException ex) {
Logger.getLogger(JavaApplication8.class.getName())
.log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) throws
ClassNotFoundException
{
JavaApplication8 swingControl = new JavaApplication8();
swingControl.showCombobox1();
}
public void prepareGUI() throws ClassNotFoundException
{
mainFrame = new JFrame("Signal");
mainFrame.setSize(300,200);
mainFrame.setLayout(new GridLayout(3, 0));
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
signal1 = new JLabel("Signal 1",JLabel.LEFT);
signal1.setSize(100,100);
signal1.setOpaque(true);
signal2 = new JLabel("Signal 2",JLabel.LEFT);
signal2.setSize(100,100);
signal2.setOpaque(true);
final DefaultComboBoxModel light = new DefaultComboBoxModel();
light.addElement("Red");
light.addElement("Green");
final JComboBox s1Combo = new JComboBox(light);
s1Combo.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae)
{
if(s1Combo.getSelectedIndex() == 0)
{
signal1.setBackground(Color.RED);
}
else
{
signal1.setBackground(Color.GREEN);
}
}
});
final JComboBox s2Combo1 = new JComboBox(light);
s2Combo1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ae)
{
if(s2Combo1.getSelectedIndex() == 0)
{
signal2.setBackground(Color.RED);
}
else
{
signal2.setBackground(Color.GREEN);
}
}
});
s1Panel = new JPanel();
s1Panel.setLayout(new FlowLayout());
JScrollPane ListScrollPane = new JScrollPane(s1Combo);
s1Panel.add(signal1);
s1Panel.add(ListScrollPane);
s2Panel = new JPanel();
s2Panel.setLayout(new FlowLayout());
JScrollPane List1ScrollPane = new JScrollPane(s2Combo1);
s2Panel.add(signal2);
s2Panel.add(List1ScrollPane);
mainFrame.add(s1Panel);
mainFrame.add(s2Panel);
String[] columnNames = {"Signal 1","Signal 2"};
Object[][] data = {{"1","1"}};
final JTable table = new JTable(data,columnNames);
JScrollPane tablepane = new JScrollPane(table);
table.setFillsViewportHeight(true);
mainFrame.add(tablepane);
mainFrame.setVisible(true);
}
}
When Executed, If I change the item from combo box 1, the 2nd combo box also performs the change. Where did I go wrong?
Yours is a simple solution: don't have the JComboBoxes share the same model. If they share the same model, then changes to the selected item of one JComboBox causes a change in the shared model which changes the view of both JComboBoxes.
I wold use a method to create your combo-jlabel duo so as not to duplicate code. For instance:
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class App8 extends JPanel {
private static final int COMBO_COUNT = 2;
private static final String SIGNAL = "Signal";
private List<JComboBox<ComboColor>> comboList = new ArrayList<>();
public App8() {
setLayout(new GridLayout(0, 1));
for (int i = 0; i < COMBO_COUNT; i++) {
DefaultComboBoxModel<ComboColor> cModel = new DefaultComboBoxModel<>(ComboColor.values());
JComboBox<ComboColor> combo = new JComboBox<>(cModel);
add(createComboLabelPanel((i + 1), combo));
comboList.add(combo);
}
}
private JPanel createComboLabelPanel(int index, final JComboBox<ComboColor> combo) {
JPanel panel = new JPanel();
final JLabel label = new JLabel(SIGNAL + " " + index);
label.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
label.setOpaque(true);
combo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
ComboColor cColor = (ComboColor) combo.getSelectedItem();
label.setBackground(cColor.getColor());
}
});
panel.add(label);
panel.add(combo);
return panel;
}
private static void createAndShowGui() {
App8 mainPanel = new App8();
JFrame frame = new JFrame("App8");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
enum ComboColor {
RED("Red", Color.RED),
GREEN("Green", Color.GREEN);
private String text;
private Color color;
public String getText() {
return text;
}
public Color getColor() {
return color;
}
private ComboColor(String text, Color color) {
this.text = text;
this.color = color;
}
#Override
public String toString() {
return text;
}
}

Categories