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

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
....

Related

Previous class gets called when calling the next class

I am not experienced, and only 14 tears old!
I made a little application, that would quiz me. Basically I would put in questions and answers in a notepad like this:
H
Hydrogen
O
Oxygen
K
Potassium
The program would sort the words like so↓, and display them in a TextArea with a ScrollPane
H = Hydrogen
O = Oxygen
K = Potassium
On the bottom theres, a JButton("Start Test"), and it would ask you the questions in order. E.g. ``H means? O Means? K Means? and then it would give you feedback E.g. Wrong! H means Hydrogen, or Correct!
here are the two classes! GUI is just simply the GUI. and the test is the class responsible for the testing
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class GUI extends JFrame
{
//JFrame components
public static JButton btn = new JButton("Start Test");
public static JPanel panelBtn = new JPanel();
public static JPanel panelTxt = new JPanel();
public static JTextArea txt = new JTextArea();
public static JScrollPane scroll = new JScrollPane(txt);
static String[] words;
static String link = "words.txt";
//constructor
public GUI()
{
//title
setTitle("Test");
//size
setSize(400,400);
//layout
setLayout(new BorderLayout());
//on close
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//OTHER
txt.setLineWrap(true);
txt.setWrapStyleWord(true);
txt.setEditable(false);
txt.setBackground(Color.white);
btn.setEnabled(false);
//border for panelTxt
LineBorder b1 = new LineBorder(Color.BLACK);
LineBorder b2 = new LineBorder(panelBtn.getBackground() ,5);
txt.setBorder(BorderFactory.createCompoundBorder(b2,b1));
//actionListnere
btn.addActionListener(new lst());
//add
add(scroll, BorderLayout.CENTER);
panelBtn.add(btn);
add(panelBtn, BorderLayout.SOUTH);
//visible
setVisible(true);
}
//action listener for btn
private class lst implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
new test(words);
GUI g = new GUI() ;
g.setVisible(false);
}
}
//main
public static void main(String[] args) throws IOException
{
new GUI();
final int ARRAY_LEN = getArrayLength();
words = makeArray(ARRAY_LEN);
displayArray(words);
btn.setEnabled(true);
}
//get the length of the array, using hasNext from Scanner class
private static int getArrayLength() throws IOException
{
File file = new File(link);
Scanner scanner = new Scanner(file);
int len = 0;
while(scanner.hasNext())
{
scanner.nextLine();
len++;
}
final int ARRAY_LEN = len +1;
return ARRAY_LEN;
}
//declares and initializes String array, with length of ARRAY_LEN
private static String[] makeArray(final int ARRAY_LEN) throws FileNotFoundException
{
String[] words = new String[ARRAY_LEN];
int value = 0;
int count = ARRAY_LEN;
words[value] = null;
count--;
value++;
File file = new File(link);
Scanner scanner = new Scanner(file);
do
{
words[value] = scanner.nextLine();
count--;
value++;
}while(count != 0);
return words;
}
//displays the array in text area
private static void displayArray(String[] words)
{
int len = words.length - 1;
int i = 0;
i++;
txt.setText(words[i]);
i++;
txt.setText(txt.getText() + "\t=");
txt.setText(txt.getText() + "\t" + words[i]);
do
{
i ++;
txt.setText(txt.getText() + "\n\n" + words[i]);
i++;
txt.setText(txt.getText() + "\t=");
txt.setText(txt.getText() + "\t" + words[i]);
}while(i != len);
}
}
Class 2
import javax.swing.*;
import java.util.Random;
public class test extends GUI
{
public static String[] words;
//constructor
public test(String[] word)
{
words = word;
main(word);
}
public static void main(String[] args)
{
int len = words.length;
boolean first = true;
for(int i = 0; i != len; i++)
{
if(first == true) //to skip null
{
i++;
first = false;
}
String question = words[i];
i++;
String answer = JOptionPane.showInputDialog(question+ " is?");
String rightAnswer = words[i];
if(answer.equals(rightAnswer))
JOptionPane.showMessageDialog(null, "Correct!");
else
{
JOptionPane.showMessageDialog(null, "Wrong! " + question +" means " + rightAnswer);
}
}
}
}
So here is the problem
Whenever I press the Button, it starts the test, but a new window from GUI class is created, and setVisible(false) doesn't actually do anything.
So there are 2 problmes;
1 setVisible(false) doesn't work.
2 a new window gets created at ButtonClikced(), so there are 2 identical windows, and closing one, closes the other too.
Please help because I don't know what to do
Remove the new GUI (); from the main method.
In your code, button was invisibled when action performe. But inthis time GUI object also was created. When the GUI object is created, it main method will be executed. There you are going to visible the button.
So change the
btn.setEnabled(true); to required another method.
Try this following code,
//main
public static void main(String[] args) throws IOException
{
final int ARRAY_LEN = getArrayLength();
words = makeArray(ARRAY_LEN);
displayArray(words);
// btn.setEnabled(true);
}

Weather API display in JFrame

I am trying to create an java/swing based application which shows weather. So far I have created background and textfield + button to get the location but I do not know how to connect it so it shows and changes the background to another image. I am sorry if that's a noob question, but I never did java before (just processing and arduino plus web design) and my uni forced me to use advanced java with knowledge I never did anything like that before.
Here is my code so far:
package AppPackage;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ApplicationWidget extends JFrame implements ActionListener {
ImageIcon basic;
JLabel label1;
JFrame frame;
JLabel label;
JTextField textfield;
JButton button;
public static void main (String[]args){
ApplicationWidget gui = new ApplicationWidget();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
gui.setSize(320, 480);
}
public ApplicationWidget() {
setLayout(new FlowLayout());
WeatherAPI weather = new WeatherAPI("44418");
System.out.println(WeatherAPI.theWeatherRSS);
for(int i = 0; i < WeatherAPI.weatherForecastList.size(); i++)
{
System.out.println(WeatherAPI.weatherForecastList.get(i).lowTemp + " " +
WeatherAPI.weatherForecastList.get(i).highTemp);
}
label = new JLabel("Welcome! Please Enter your location");
add(label);
textfield = new JTextField(15);
add(textfield);
for(int i = 0; i < WeatherAPI.weatherForecastList.size(); i++)
{
System.out.println(WeatherAPI.weatherForecastList.get(i).lowTemp + " " +
WeatherAPI.weatherForecastList.get(i).highTemp);
}
button = new JButton("Check weather");
add(button);
basic = new ImageIcon(getClass().getResource("basicback.jpg"));
label1 = new JLabel(basic);
add(label1);
/*add design here*/
/*add mouse interaction*/
/*add image capture*/
}
#Override
public void actionPerformed(ActionEvent e){
JButton button = (JButton) e.getSource();
if (e.getSource() == button){
String data = textfield.getText();
System.out.println(data);
}
}
}
And the WeatherAPI code:
package AppPackage;
import java.net.*;
import java.util.regex.*;
import java.util.ArrayList;
import java.io.*;
public class WeatherAPI
{
static String theWeatherRSS;
static String theCity;
static ArrayList<Forecast> weatherForecastList;
//WeatherAPI(String string) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
// }
public class Forecast
{
String lowTemp;
String highTemp;
}
/**
*
* #param city
*/
public WeatherAPI(String city)
{
theCity = city;
theWeatherRSS = getWeatherAsRSS(city);
parseWeather(theWeatherRSS);
}
void parseWeather(String weatherHTML)
{
weatherForecastList = new ArrayList<Forecast>();
int startIndex = 0;
while(startIndex != -1)
{
startIndex = weatherHTML.indexOf("<yweather:forecast", startIndex);
if(startIndex != -1)
{ // found a weather forecast
int endIndex = weatherHTML.indexOf(">", startIndex);
String weatherForecast = weatherHTML.substring(startIndex, endIndex+1);
// get temp forecast
String lowString = getValueForKey(weatherForecast, "low");
String highString = getValueForKey(weatherForecast, "high");
Forecast fore = new Forecast();
fore.lowTemp = lowString;
fore.highTemp = highString;
weatherForecastList.add(fore);
// move to end of this forecast
startIndex = endIndex;
}
}
}
String getValueForKey(String theString, String keyString)
{
int startIndex = theString.indexOf(keyString);
startIndex = theString.indexOf("\"", startIndex);
int endIndex = theString.indexOf("\"", startIndex+1);
String resultString = theString.substring(startIndex+1, endIndex);
return resultString;
}
String getWeatherAsRSS(String city)
{
try{
/*
Adapted from: http://stackoverflow.com/questions/1381617/simplest-way-to-correctly-load-html-from-web-page-into-a-string-in-java
Answer provided by: erickson
*/
URL url = new URL("http://weather.yahooapis.com/forecastrss?w="+city+"&u=c");
URLConnection con = url.openConnection();
Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
Matcher m = p.matcher(con.getContentType());
/* If Content-Type doesn't match this pre-conception, choose default and
* hope for the best. */
String charset = m.matches() ? m.group(1) : "ISO-8859-1";
Reader r = new InputStreamReader(con.getInputStream(), charset);
StringBuilder buf = new StringBuilder();
while (true) {
int ch = r.read();
if (ch < 0)
break;
buf.append((char) ch);
}
String str = buf.toString();
return(str);
}
catch(Exception e) {System.err.println("Weather API Exception: "+e);}
return null;
}
}
Thanks for any help, I am truly desperate because I have mixed up the dates of submission and I have not much time left....
Assuming label1 is your background label, just use label1.setIcon(...). What you will pass to it is a new ImageIcon
Also you haven't registered the ActionListener to your button. If you don't register a listener to the button, it won't do anything. Do this
button = new JButton("Check weather");
button.addActionListener(this);
add(button);
You haven't specified where the new image is coming from, so I really can't help you any further than this.

Player Input JFrame

I got a little problem which occupies me for hours.
I want the player to make an input during the game that I will then further use. But I don't know how to do this...
Tried JOptionPane, JTextField and Scanner. Scanner worked, but I want it without the use of the console :I
So, here's my code:
Window:
package Main;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Window
{
public static JFrame frame = new JFrame("Z-Stories");
public static JLabel Label = new JLabel ("<html></html>", JLabel.CENTER);
public static String LabelText;
public Window()
{
Label.setVerticalAlignment(JLabel.TOP);
frame.setSize(1920, 1080);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(Label, BorderLayout.CENTER);
frame.setIconImage(new ImageIcon(getImage()).getImage());
frame.pack();
frame.setVisible(true);
}
protected static Image getImage()
{
java.net.URL imgURL = Window.class.getResource("Logo32.png");
if (imgURL != null)
{
return new ImageIcon(imgURL).getImage();
} else
{
return null;
}
}
public static void addText(String Text)
{
LabelText = Label.getText();
LabelText = LabelText.replace("</html>", "");
if(Text != null)
{
Label.setText(LabelText + "<br/>" + Text + "</html>");
}else
{
Label.setText(LabelText + "<br/><br/></html>");
}
System.out.println(Label.getText());
Label.validate();
}
public static int InputInt()
{
//User Input here
//Maybe parse into Int
return output;
}
public static String InputText()
{
//User Input here
//Maybe convert to String
return outputText;
}
}
And the Game.java
...
public void StartGame()
{
ErstesSpiel = 1;
Window.addText("Wähle deine Sprache | Select your language");
Window.addText("");
Window.addText("Deutsch (1) | English (2)");
Window.addText("");
int var3 = Window.InputInt();
Window.addText("");
....
You can use a JTextField and get input when the user presses enter by using an actionlistener or by a JButton click
Create this object
JTextField UserInputField = new JTextField("");
Call this method when user presses enter with an Action Listener (more on Action Listeners)
public static int InputInt()
{
String sInput = UserInputField.getText(); //Gets the string from the JTextField
int output = Integer.parseInt(sInput.trim()); //Parse string to int
return output; //Return as int
}
If what you want is for the method to auto-run whenever the user inputs a number, you can use a keyboard listener
http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html

implementing actionListener with multiple classes?

I'm creating a program for my Java class and I'm having a hard time implementing a actionListener in conjunction to my main class.
This is an example of my main class, I am using other classes to create the components for the tabs. Where I'm running into trouble is when I try to implement action listeners in the other class. I keep running into errors regarding abstract classes. This is probably a simple solution, but I'm still fairly new to programming.
'
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.KeyEvent;
import javax.swing.plaf.ColorUIResource;
public class TaikunStudyResource extends JFrame {
private static final int FRAME_WIDTH = 700;
private static final int FRAME_HIEGHT = 500;
private JPanel searchTab,addTab, grammerTab,testTab,homeTab;
public static void main(String[] args)throws UnsupportedOperationException {
TaikunStudyResource tsr = new TaikunStudyResource();
tsr.setVisible(true);
}
public TaikunStudyResource(){
//set basic features
setTitle("Taikun-Japanese Study Resource!");
setSize(FRAME_WIDTH,FRAME_HIEGHT);
setResizable(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBackground(new Color(226,199,255));
addComponents(getContentPane());
}
public void addComponents(Container contentPane){
//add overlaying panel
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
contentPane.add(topPanel);
//create tabs
contentPane.add(createTabs());
}
public JTabbedPane createTabs(){
//UIManager.put("TabbedPane.contentAreaColor",ColorUIResource.getHSBColor(153,153,255));
//create tabs
JTabbedPane tabs = new JTabbedPane();
SearchPanel sp = new SearchPanel();
tabs.addTab("Search", sp);
addPanel ap = new addPanel();
tabs.addTab("Add",ap);
return tabs;
}
}
'
Here is a example of my my addPanel class
'
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.List;
/**
*
* #author tyler.stanley.4937
*/
public abstract class addPanel extends JPanel{
//variables
private JPanel mainPanel, eastPanel,westPanel, checkboxPanel, radioPanel, typePanel, adjectivePanel, verbPanel, kanjiPanel;
private JLabel kanaKanjiLabel, romanjiLabel;
private JTextField kanaKanjiField, romanjiField,exampleInput, defInput, tagInput;
private JButton radicalButton, addDefButton, addExampleButton, addButton, addTagButton
,clearexButton,clearDefButton,clearTagButton;
private ButtonGroup commonGroup;
private JRadioButton[] commonButton;
private String[] commonTypeArray = {"very-common", "common", "Uncommon", "Out-dated"};
private JCheckBox[] typeCheckBox;
private String[] typeofWordArray = {"Noun", "Pronoun", "Verb","Adjective","Idiom"};
private JComboBox adjectiveTypeCombo;
private String[] adjectivetypeArray ={"Na","i"};
private JComboBox verbTypeCombo;
//private String[] verbTypetext = {"Suru","Kuru","da","desu","iku","-masu"};//these may not make it
private String[] verbTypeArray ={"-u","-ku","-gu","-su","-tsu","-nu","-bu","-mu","-ru"};
private JTextArea definitionArea, exampleArea, tagArea;
private List<String>definitionList, exampleList, tagList, radicalList,typeList;
private String kanjiKana,romanji;
private ActionListener a;
public static void main(String[] arg)throws UnsupportedOperationException{
}
public addPanel(){
setLayout(new BorderLayout());
//setBackground(Color.blue);
addComponents();
}
public void addComponents(){
fillSouthPanel();
fillEastPanel();
}
}
public void fillEastPanel(){
eastPanel = new JPanel(new BorderLayout());
//add definition pane
JPanel definitionPanel = new JPanel(new FlowLayout());
definitionPanel.setBorder(BorderFactory.createTitledBorder("Defintion"));
definitionArea = new JTextArea();
definitionArea.setColumns(22);
definitionArea.setRows(8);
definitionArea.setBorder(BorderFactory.createLineBorder(Color.black));
definitionArea.setEditable(false);
//add scroll pane
JScrollPane scrollPane = new JScrollPane(definitionArea);
scrollPane.setSize(200,135);
definitionPanel.add(scrollPane);
//add input and button
defInput = new JTextField(50);
definitionPanel.add(defInput);
addDefButton = new JButton("Add");
definitionPanel.add(addDefButton);
//addDefButton.addActionListener(al);
clearDefButton = new JButton("Clear");
definitionPanel.add(clearDefButton);
//clearDefButton.addActionListener(al);
//add tags
JPanel tagPanel = new JPanel(new FlowLayout());
tagPanel.setBorder(BorderFactory.createTitledBorder("Tags"));
tagArea = new JTextArea();
tagArea.setColumns(22);
tagArea.setRows(1);
tagArea.setBorder(BorderFactory.createLineBorder(Color.black));
tagArea.setEditable(false);
JScrollPane tagScrollPane = new JScrollPane(tagArea);
tagScrollPane.setSize(200,133);
tagPanel.add(tagScrollPane);
tagInput = new JTextField(22);
tagPanel.add(tagInput);
addTagButton = new JButton("Add Tag");
clearTagButton = new JButton("Clear Tag");
tagPanel.add(addTagButton);
tagPanel.add(clearTagButton);
//clearTagButton.addActionListener(al);
//addTagButton.addActionListener(al);
//examples
JPanel examplePanel = new JPanel(new FlowLayout());
examplePanel.setBorder(BorderFactory.createTitledBorder("example"));
exampleArea = new JTextArea();
exampleArea.setColumns(22);
exampleArea.setRows(8);
exampleArea.setBorder(BorderFactory.createLineBorder(Color.black));
exampleArea.setEditable(false);
JScrollPane exampleScrollPane = new JScrollPane(exampleArea);
exampleScrollPane.setSize(200,135);
examplePanel.add(exampleScrollPane);
exampleInput = new JTextField(30);
examplePanel.add(exampleInput);
addExampleButton = new JButton("Add");
examplePanel.add(addExampleButton);
//addExampleButton.addActionListener(this);
JButton clearExampleButton = new JButton("Clear");
examplePanel.add(clearExampleButton);
//clearExampleButton.addActionListener(this);
add(eastPanel, BorderLayout.EAST);
}
public void fillSouthPanel(){
JPanel southPanel = new JPanel(new FlowLayout());
addButton = new JButton("Add");
southPanel.add(addButton);
addButton.addActionListener(new Action() {
#Override
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
});
add(southPanel, BorderLayout.SOUTH);
}
public void addEntry(int buttonNumber){
switch(buttonNumber){
case 1:
tagList.add(tagInput.getText());
tagArea.append("/n"+tagInput.getText());
break;
case 2:
exampleList.add(exampleInput.getText());
exampleArea.append("/n"+exampleInput.getText());
break;
case 3:
definitionList.add(defInput.getText());
definitionArea.append("/n"+defInput.getText());
break;
}
}
public void clearEntry(int buttonNumber){
switch(buttonNumber){
case 0:
case 1:
case 2:
}
}
//public List radicalList(){
//RadicalFrame rf = new RadicalFrame();
//List<String>radicalList = rf.getRadicals();
//return
//}
public boolean getFieldEntries(){
boolean romaji,kanji, passable;
if(kanaKanjiField.getText()!= null){
kanjiKana = kanaKanjiField.getText();
kanji = true;
}else{
JOptionPane.showMessageDialog(null, "Please entry a vaild Japanese word");
kanaKanjiField.setText(null);
kanji = false;
}
//test if it's english
if(romanjiField.getText() !=null){
romanji = romanjiField.getText();
romaji = true;
}else{
JOptionPane.showMessageDialog(null, "please enter a vaild romaji entry");
romanjiField.setText(null);
romaji = false;
}
if(romaji == true && kanji == true){
passable =true;
}else{
passable = false;
}
return passable;
}
public boolean getTextArea(){
boolean defText, exText, tagText,passable;
if(tagList.size()!=0){
tagText = true;
}else{
JOptionPane.showMessageDialog(null, "Please enter tags to indentify the word");
tagText = false;
}
if(definitionList.size()!=0){
defText = true;
}else{
JOptionPane.showMessageDialog(null,"Please Enter defintion of the word");
defText = false;
}
if(exampleList.size()!=0){
exText = true;
}else{
JOptionPane.showMessageDialog(null, "Please Enter an Example of the word usage");
exText = false;
}
if(exText == true&&defText== true&& tagText == true){
passable = true;
}else{
passable = false;
}
return passable;
}
public void addWord() throws FileNotFoundException, IOException{
boolean vaild = getFieldEntries();
boolean vaild2 = getTextArea();
if(vaild == true&& vaild2 == true){
//Word word = new Word(KanjiKanaEntry, RomanjiEntry, CommonIndex, radicalList,typeentry, adjectiveIndex,VerbIndex);
File outFile = new File("dictionary.dat","UTF-8");
//Writer unicodeFileWriter = new OutputStreamWriter( new FileOutputStream("dictionary.dat)."UTF-8");//can't use writer
//fileOutputStream("dictionary.dat"),"UTF-8");
FileOutputStream outFileStream = new FileOutputStream(outFile,true);
ObjectOutputStream oos = new ObjectOutputStream(outFileStream);//append to a file
//oos.WriteObject(word);//store word
}
}
public void actionPermored(ActionEvent event) throws FileNotFoundException, IOException{
System.out.println("action");
//get even source
if(event.getSource() instanceof JButton){
JButton clickedButton = (JButton)event.getSource();
if(clickedButton == radicalButton){
//radicalList = radicalFrame();
}else if(clickedButton ==addButton){
addWord();
}else if(clickedButton == addTagButton){
addEntry(1);
}else if(clickedButton == addExampleButton){
addEntry(2);
}else if(clickedButton == addDefButton){
addEntry(3);
}else if(clickedButton == clearTagButton){
clearEntry(1);
}else if(clickedButton == clearDefButton){
clearEntry(0);
}else if(clickedButton == clearexButton){
clearEntry(2);
}
}
//get combo box entries
if(event.getSource() instanceof JComboBox){
JComboBox selectedComboBox = (JComboBox)event.getSource();
if(selectedComboBox == adjectiveTypeCombo){
int adjectiveform = selectedComboBox.getSelectedIndex();
}else if(selectedComboBox == verbTypeCombo){
int VerbForm = selectedComboBox.getSelectedIndex();
}
if(event.getSource() instanceof JCheckBox){
for(int i = 0;i<typeCheckBox.length;i++){
if(typeCheckBox[i].isSelected()){
typeList.add(typeCheckBox[i].getText()); //some how assign index numbers
}
}
}
}
}
}'
This is just a piece of code, so sorry if it seems a little jumbled, I'm trying to condense it as much as possible.
I've tried to create a internal class to handle the action listener, but I can't seem to get it to work. Also I know I can create actionlisteners for every button, but I would like to condense all the actionevents to one class or method.
The errors are due to unimplemented methods of the Action class anonymous instance.
Any instance of the Action interface requires that all the its methods be implemented. However using Action as an anonymous instance if neither practical or good practice. Rather create a single concrete instance of a class that extends AbstractAction and set the Action for for each component.
button.setAction(mySingleAction);
where
class SingleAction extends AbstractAction {
#Override
public void actionPerformed(ActionEvent e) {
// do stuff
}
}

why won't my text print to my JTextArea?

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.

Categories