Previous class gets called when calling the next class - java

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);
}

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

Code works, but getting strange error from file I'm not allowed to change

The error is coming from when I try to run the AnagramMainGUI.java. I can change Word.java and AnagramManager.java but CANNOT CHANGE AnagramMainGUI.java.
This is the Word class:
import java.util.*;
public class Word implements Comparable<Word>
{
private String word;
private String canonical;
public Word(String word)
{
String lowerCase = word.toLowerCase();
this.word = lowerCase;
canonical = CanonicalForm(word);
}
public String getWord()
{
return word;
}
public String getForm()
{
return canonical;
}
public String toString()
{
return "[" + word + "=" + canonical + "]";
}
public int compareTo(Word someWord)
{
return getForm().compareTo(someWord.getForm());
}
private static String CanonicalForm(String word)
{
if(word == null || word.length() < 1)
{
throw new IllegalArgumentException();
}
char arr[] = word.toCharArray();
Arrays.sort(arr);
return new String(arr);
}
}
This is the AnagramManager class:
import java.util.*;
public class AnagramManager
{
private Word[] words;
private Random rand;
private Map<String,Set<String>> theMap;
public AnagramManager(List<String> list)
{
if (list == null || list.size() < 1)
{
throw new IllegalArgumentException();
}
rand = new Random();
words = new Word[list.size()];
theMap = new TreeMap<String,Set<String>>();
makeWords(list);
makeAnagrams();
}
public void sortByWord()
{
for (Word i : words)
{
i.getWord();
}
Arrays.sort(words);
}
public void sortByForm()
{
for(Word c : words)
{
c.getForm();
}
Arrays.sort(words);
}
public String getAnagram(String word)
{
String canonWord = CanonicalForm(word);
if(theMap.containsKey(canonWord))
{
Set<String> anagramSet = theMap.get(canonWord);
String[] match = anagramSet.toArray(new String[anagramSet.size()]);
return match[rand.nextInt(match.length)];
}
else
{
return "";
}
}
public Set<String> getAnagrams(String word)
{
String canonWord = CanonicalForm(word);
boolean hasAnagram = theMap.containsKey(canonWord);
Set<String> anagrams = (hasAnagram) ? theMap.get(canonWord) : new TreeSet<String>();
return anagrams;
}
public String toString()
{
String printWords = "";
int length = words.length;
if (length < 1)
{
printWords += "[]";
}
else
{
for (int i=0; i < length; i++)
{
printWords += words[i];
}
printWords += "[...]";
for(int i = length - 5; i < length; i++)
{
printWords += words[i];
}
}
return printWords;
}
private static String CanonicalForm(String word)
{
if(word == null || word.length() < 1)
{
throw new IllegalArgumentException();
}
char arr[] = word.toCharArray();
Arrays.sort(arr);
return new String(arr);
}
private void makeWords(List<String> list)
{
int ind = 0;
for (String orgWord : list)
{
words[ind] = new Word(orgWord);
ind++;
}
}
private void makeAnagrams()
{
for(Word i : words)
{
String canon = i.getForm();
String org = i.getWord();
if(!theMap.containsKey(canon))
{
Set<String> set = new TreeSet<String>();
set.add(org);
theMap.put(canon,set);
}
else
{
theMap.get(canon).add(org);
}
}
}
}
and here is the AnagramMainGUI class:
// CS 145 ASSIGNMENT 5
// GUI INTERFACE
import java.awt.*; // for Dimension
import java.awt.event.*;
import javax.swing.*; // for GUI components
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
/** CS145
* Class AnagramMainGUI is the driver program for the Anagram program. It reads a
* dictionary of words to be used during the game and then asks the user to create a
* data structure to sort through them.
*
* <p>This version uses a GUI to force students to not have access to the console.
*
* <p><B>
* STUDENTS SHOULD NOT MODIFY THIS PROGRAM IN ANY WAY.
* </B>
* #author Michael A. Wood
* #version 1.0
*/
public class AnagramMainGUI implements ActionListener
{
// Dictionary File name.
public static final String DICTIONARY_FILE = "dictionary.txt";
// GUI ELEMENTS
private JFrame frame;
private JButton button1;
private JTextField edit1;
private JLabel text1;
private JLabel text2;
private JTextArea text3;
private JTextArea text4;
private JLabel sortW;
private JLabel sortF;
private JScrollPane scrollPane3;
private JScrollPane scrollPane4;
private JCheckBox debugMode;
private List<String> dictionary;
private List<String> dictionary2;
private AnagramManager catalog;
/** Main Program.
*
* #param args The OS parameters
*/
public static void main(String[] args) {
AnagramMainGUI gui = new AnagramMainGUI();
}
/** The constructor that preps the GUI and all its components
*
*/
public AnagramMainGUI()
{
// Call private method to set up the form.
formSetup();
// Open the file and read the words into the dictionary.
// Lower case as going.
try{
Scanner input = new Scanner(new File(DICTIONARY_FILE));
dictionary = new ArrayList<String>();
while (input.hasNext()) {
dictionary.add(input.next().toLowerCase());
}
}
catch (FileNotFoundException e)
{
// Exit the program after outputing error to both console and Dialog box.
System.out.println("File not found error : " + e);
JOptionPane.showMessageDialog(null,"File not found error : " + e);
System.exit(0);
}
// set up the AnagramManager
// Create an unmodifiable dictionary list to pass to the manager
// the manager is called catalog.
dictionary2 = Collections.unmodifiableList(dictionary);
catalog = new AnagramManager(dictionary2);
// Show the debugging data.
// This is where the sorting is needed.
catalog.sortByWord();
text3.setText(catalog.toString());
catalog.sortByForm();
text4.setText(catalog.toString());
// Open the frame.
frame.setVisible(true);
}
/**
* This method responds to all events thrown by the various elements
* of the GUI
* #param event The action event thrown by the GUI
*/
#Override
public void actionPerformed(ActionEvent event)
{
// If button is pressed or enter is pressed while the edit box has focus.
if (event.getActionCommand().equals("FindAnagram"))
{
// Get the text from the edit box.
String x = edit1.getText();
String y;
// Use the AnagramManager HERE
String result = catalog.getAnagram(x);
// if the result is blank
if (!result.equals("") )
y = "One possible anagram of the word " + x + " is :: " + result;
else
y = "Your word was not found in the list";
// Display the output.
text1.setText(y);
// Show the list of anagrams.
String z = "In fact the list of anagrams for the word are :: ";
z+= catalog.getAnagrams(x);
text2.setText(z);
}
if (event.getActionCommand().equals("debugMode"))
{
// Display the neccessary debuging tools
scrollPane3.setVisible(debugMode.isSelected());
scrollPane4.setVisible(debugMode.isSelected());
sortW.setVisible(debugMode.isSelected());
sortF.setVisible(debugMode.isSelected());
// Resize the window.
if (debugMode.isSelected())
frame.setSize(new Dimension(800, 300));
else
frame.setSize(new Dimension(800, 150));
}
}
// Commands to set up the form.
// Note that the form must still be set to visible.
// This does everything but that.
private void formSetup()
{
// GUI SETUP
// Window setup.
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(new Point(100, 500));
frame.setSize(new Dimension(800, 150));
frame.setTitle("Anagrams");
frame.setLayout(new FlowLayout());
// Find Anagram button
button1 = new JButton();
button1.setText("Find Anagram");
button1.addActionListener(this );
button1.setActionCommand("FindAnagram");
// User input Edit Field
edit1 = new JTextField();
edit1.setPreferredSize( new Dimension( 200, 24 ) );
edit1.setActionCommand("FindAnagram");
edit1.addActionListener(this );
// Output Text Fields
text1 = new JLabel();
text1.setText("NOTHING");
text2 = new JLabel();
text2.setText("NOTHING");
text3 = new JTextArea();
text3.setText("NOTHING");
text4 = new JTextArea();
text4.setText("NOTHING");
// Debugging Tools
scrollPane3 = new JScrollPane(text3);
scrollPane4 = new JScrollPane(text4);
scrollPane3.setVisible(false);
scrollPane4.setVisible(false);
sortW = new JLabel();
sortW.setText("Sorted by Word");
sortF = new JLabel();
sortF.setText("Sorted by Form");
sortW.setVisible(false);
sortF.setVisible(false);
// Debugging Radio Button
debugMode = new JCheckBox();
debugMode.setText("Debug Mode");
debugMode.addActionListener(this );
debugMode.setActionCommand("debugMode");
// Add components to frame.
frame.add(button1);
frame.add(edit1);
frame.add(text1);
frame.add(text2);
frame.add(scrollPane3);
frame.add(scrollPane4);
frame.add(debugMode);
frame.add(sortW);
frame.add(sortF);
// Layout the frame.
// null layout to demonstrate the idea.
// not using the default layouts to show the idea.
frame.setLayout(null);
edit1.setBounds (185, 10, 200, 25);
button1.setBounds(10,10,150,25);
text1.setBounds(10, 50, 750,25);
text2.setBounds(10, 80, 750,25);
sortW.setBounds(10, 110, 100,40);
sortF.setBounds(10, 180, 1000,40);
scrollPane3.setBounds(115, 110, 650,40);
scrollPane4.setBounds(115, 180, 650,40);
debugMode.setBounds(400, 10, 100,25);
// Inline function to set focus on the edit box.
frame.addWindowFocusListener(new WindowAdapter()
{ public void windowGainedFocus(WindowEvent e)
{edit1.requestFocusInWindow();}
});
}
}
Here is the error:
AnagramMainGUI.java:158: error: constructor Point in class Point cannot be applied to given types;
frame.setLocation(new Point(100, 500));
^
required: no arguments
found: int,int
reason: actual and formal argument lists differ in length
1 error
/* CS145
* Class AnagramMain is the driver program for the Anagram program. It reads a
* dictionary of words to be used during the game and then asks the user to create a
* data structure to sort through them.
*/
import java.util.*;
import java.io.*;
public class AnagramMain {
public static final String DICTIONARY_FILE = "dictionary.txt";
public static void main(String[] args) throws FileNotFoundException {
System.out.println("Welcome to the CS145 Anagram Practice");
System.out.println();
// open the dictionary file and read dictionary into an ArrayList
Scanner input = new Scanner(new File(DICTIONARY_FILE));
Scanner keyboard = new Scanner(System.in);
List<String> dictionary = new ArrayList<String>();
while (input.hasNext()) {
dictionary.add(input.next().toLowerCase());
}
// set up the AnagramManager
List<String> dictionary2 = Collections.unmodifiableList(dictionary);
AnagramManager catalog = new AnagramManager(dictionary2);
// Start the program asking for run style
System.out.println("Press enter to start, or any other input for debug mode");
String DEBUG = keyboard.nextLine();
// If in DEBUG mode
if (!DEBUG.equals("") )
{
System.out.println("** The first and last five sorted by word elements are **");
catalog.sortByWord();
System.out.println(catalog);
System.out.println("** The first and last five sorted by form elements are **");
catalog.sortByForm();
System.out.println(catalog);
System.out.println("\n\n\n");
}
// Start the Loop
getAnagram(keyboard, catalog);
}
// Executes the primary anagram loop
public static void getAnagram(Scanner console, AnagramManager theCatalog)
{
String input;
System.out.println("Please type in a word to anagram or QUIT to quit :");
input = console.nextLine();
while (!input.toUpperCase().equals("QUIT") && !input.equals("") )
{
String result = theCatalog.getAnagram(input);
if (!result.equals("") )
{
System.out.print("One possible anagram of your word " + input );
System.out.println(" is " +result);
}
else
{
System.out.println("Your word was not found in the list");
}
System.out.print("In fact the list of anagrams for your word are : ");
System.out.println(theCatalog.getAnagrams(input));
System.out.println("Please type in a word to anagram or QUIT to quit :");
input = console.nextLine();
}
}
}

How to highlight keywords in java while opening a file and while the user is typing

So I am trying to highlight the keywords in java,which I have stored in a text file, as the user opens a .java file or writes to .java file. I think I know how to tell if the file is of the right type. However, I do not know how to change the color of certain keywords. If anyone could help out that would be great because right now it's pretty confusing. I was wondering if I could use my replace function somehow. I have tried to go about trying to do this with the few methods I have, yet it's still not clear. I have taken out he majority of the methods and listeners, just know they are there but kept out to make it easier to read.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.DocumentListener;
import javax.swing.event.DocumentEvent;
import java.util.Scanner;
import java.io.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
import javax.swing.text.Highlighter.HighlightPainter;
import javax.swing.text.JTextComponent;
import java.net.URI;
import java.util.*;
public class MyTextEditor extends JFrame implements ActionListener
{
private JPanel panel = new JPanel(new BorderLayout());
private JTextArea textArea = new JTextArea(0,0);
private static final Color TA_BKGRD_CL = Color.BLACK;
private static final Color TA_FRGRD_CL = Color.GREEN;
private static final Color TA_CARET_CL = Color.WHITE;
private JScrollPane scrollPane;
private MenuBar menuBar = new MenuBar();
public MyTextEditor()
{
this.setSize(750,800);
this.setTitle("Zenith");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textArea.setFont(new Font("Consolas", Font.BOLD, 14));
textArea.setForeground(TA_FRGRD_CL);
textArea.setBackground(TA_BKGRD_CL);
textArea.setCaretColor(TA_CARET_CL);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVisible(true);
textArea.add(scrollPane,BorderLayout.EAST);
final LineNumberingTextArea lineNTA = new LineNumberingTextArea(textArea);
DocumentListener documentListen = new DocumentListener()
{
public void insertUpdate(DocumentEvent documentEvent)
{
lineNTA.updateLineNumbers();
}
public void removeUpdate(DocumentEvent documentEvent)
{
lineNTA.updateLineNumbers();
}
public void changedUpdate(DocumentEvent documentEvent)
{
lineNTA.updateLineNumbers();
}
};
textArea.getDocument().addDocumentListener(documentListen);
// Line numbers
lineNTA.setBackground(Color.BLACK);
lineNTA.setForeground(Color.WHITE);
lineNTA.setFont(new Font("Consolas", Font.BOLD, 13));
lineNTA.setEditable(false);
lineNTA.setVisible(true);
textArea.add(lineNTA);
scrollPane.setVisible(true);
scrollPane.add(textArea);
getContentPane().add(scrollPane);
}
public void findKeyWords(String ext)
{
ArrayList<String> wordsInTA = new ArrayList<String>();
int index = 0;
if(ext == "java")
{
for(String line : textArea.getText().split(" "))
{
wordsInTA.add(line);
index++;
}
try
{
while(index>0)
{
String temp = wordsInTA.get(index);
boolean isKeyWord = binarySearch(temp);
if(isKeyWord)
{
//Code that has not yet been made
}
index--;
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
}
private ArrayList<String> loadJavaWords() throws FileNotFoundException
{
ArrayList<String> javaWords = new ArrayList<String>();
Scanner scan = new Scanner(new File("JavaKeyWords.txt"));
while(scan.hasNext())
{
javaWords.add(scan.next());
}
scan.close();
return javaWords;
}
private boolean binarySearch(String word) throws FileNotFoundException
{
ArrayList<String> javaWords = loadJavaWords();
int min = 0;
int max = javaWords.size()-1;
while(min <= max)
{
int index = (max + min)/2;
String guess = javaWords.get(index);
int result = word.compareTo(guess);
if(result == 0)
{
return true;
}
else if(result > 0)
{
min = index +1;
}
else if(result < 0)
{
max = index -1;
}
}
return false;
}
public void replace()
{
String wordToSearch = JOptionPane.showInputDialog(null, "Word to replace:");
String wordToReplace = JOptionPane.showInputDialog(null, "Replacement word:");
int m;
int total = 0;
int wordLength = wordToSearch.length();
for (String line : textArea.getText().split("\\n"))
{
m = line.indexOf(wordToSearch);
if(m == -1)
{
total += line.length() + 1;
continue;
}
String newLine = line.replaceAll(wordToSearch, wordToReplace);
textArea.replaceRange(newLine, total, total + line.length());
total += newLine.length() + 1;
}
}
public static void main(String args[])
{
MyTextEditor textEditor = new MyTextEditor();
textEditor.setVisible(true);
}
}

How can i stop the program from skipping my check the second time around?

I am creating a program to take in sets of binary digits and convert them into hammingcodes (Effectively take in 8 digits, turn into 12, print out) but i am having trouble. Currently, i am using a JTextField for the user to enter their number, then they press a JButton to enter the data. I then do funky shit with that number to put it into a list and confirm that this is the last of the numbers they wish to enter. If they click a JButton called yes (New text in button, but same button) if goes on to do what i need. But if they click the other JButton called no, it goes back and repeats the same process. My problem is after clicking no once, the program stops allowing you to press no at the step to check if you want to add another list of numbers. IT appears to skip the check all together and assume they pressed yes as it does the rest of the working out thats done after all entry is finished.
My code is a tad messy due to messing with it for a few hours.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
public class MainProgram extends JFrame
{
public MainProgram()
{
}
public static void main(String[] args)
{
MainProgram mp = new MainProgram();
mp.run();
}
private void run()
{
java.util.List<Integer> streamSplit = new ArrayList<>();
java.util.List<Integer> tempEight = new ArrayList<>();
java.util.List<Integer> finalStream = new ArrayList<>();
yes.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
checkYes = true;
}
});
no.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
checkNo = true;
}
});
init();
yesChange("Enter");
boolean confirm = false;
int aCheck = 0;
while (aCheck == 0)
{
confirm = false;
while (!confirm)
{
setTopText("<html>Please enter your next 8 bits. Do not enter more than 8 bits.<br> Press Enter when done</html>");
yesChange("Enter");
confirm = checkYes();
}
confirm = false;
setTopText("Digits Successfully added.");
int stream = checkInput();
do
{
streamSplit.add(stream % 10);
stream /= 10;
} while (stream != 0);
setYesNo();
setTopText("<html>Are you finished entering streams?</html>");
yesChange("YES");
noChange("NO");
aCheck = 2;
checkYes();
checkNo();
while (aCheck == 2)
{
if ( checkNo())
{
aCheck = 0;
System.out.println("CrapNo");
}
else if (checkYes())
{
aCheck = 1;
System.out.println("CrapYes");
}
}
}
int arrayLength = streamSplit.size();
int bufferLength = 8 - arrayLength % 8;
int numberOfStreams = 0;
if (bufferLength != 8)
{
numberOfStreams = arrayLength / 8 + 1;
} else
{
numberOfStreams = arrayLength / 8;
}
int tempStreams = numberOfStreams;
System.out.println(numberOfStreams + "<Streams Buffer>" + bufferLength);
while (bufferLength > 0 && bufferLength != 8)
{
streamSplit.add(0);
bufferLength--;
}
while (tempStreams > 0)
{
for (int i = 0; i < 8; i++)
{
tempEight.add(streamSplit.get(i));
}
if ((tempEight.get(0) + tempEight.get(1) + tempEight.get(3) + tempEight.get(4) + tempEight.get(6)) % 2 == 0)
{
tempEight.add(0, 0);
} else
{
tempEight.add(0, 1);
}
if ((tempEight.get(1) + tempEight.get(3) + tempEight.get(5) + tempEight.get(6) + tempEight.get(7)) % 2 == 0)
{
tempEight.add(1, 0);
} else
{
tempEight.add(1, 1);
}
if ((tempEight.get(3) + tempEight.get(4) + tempEight.get(5) + tempEight.get(8) + tempEight.get(9)) % 2 == 0)
{
tempEight.add(3, 0);
} else
{
tempEight.add(3, 1);
}
if ((tempEight.get(7) + tempEight.get(8) + tempEight.get(9) + tempEight.get(10)) % 2 == 0)
{
tempEight.add(7, 0);
} else
{
tempEight.add(7, 1);
}
tempStreams--;
for (int i = 0; i < 12; i++)
{
finalStream.add(tempEight.get(0));
tempEight.remove(0);
}
}
Collections.reverse(streamSplit);
System.out.print("Your original bit-stream was: ");
for (int i = 0; i < numberOfStreams * 2; i++)
{
for (int j = 0; j < 4; j++)
{
System.out.print(streamSplit.get(j + (i * 4)));
}
System.out.print(" ");
}
System.out.println();
System.out.print("Your new HammingCode bit-stream is: ");
for (int i = 0; i < numberOfStreams * 3; i++)
{
for (int j = 0; j < 4; j++)
{
System.out.print(finalStream.get(j + (i * 4)));
}
System.out.print(" ");
}
System.out.println();
}
public Boolean checkYes = false;
public Boolean checkNo = false;
private JFrame frame = new JFrame("Absolute Layout Example");
private JPanel contentPane = new JPanel();
private JLabel topText = new JLabel("Welcome to my Hamming Code Generator", JLabel.CENTER);
private JTextField inputText = new JTextField();
private JButton yes = new JButton("YES");
private JButton no = new JButton("NO");
public void init()
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane.setOpaque(true);
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(null);
topText.setLocation(0, 0);
topText.setSize(400, 50);
topText.setBorder(BorderFactory.createLineBorder(Color.black));
inputText.setLocation(0,50);
inputText.setSize(400,75);
inputText.setBorder(BorderFactory.createLineBorder(Color.black));
yes.setSize(80, 40);
yes.setLocation(60, 135);
no.setSize(80, 40);
no.setLocation(260, 135);
contentPane.add(topText);
contentPane.add(inputText);
contentPane.add(yes);
contentPane.add(no);
frame.setContentPane(contentPane);
frame.setSize(400, 225);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public void setTopText(String s)
{
topText.setText(s);
}
public void setYesNo()
{
checkYes = false;
checkNo = false;
}
public Boolean checkYes() {return checkYes;}
public Boolean checkNo() {return checkNo;}
public int checkInput()
{
String temp1 = inputText.getText();
int temp = Integer.parseInt(temp1);
return temp;
}
public void yesChange(String s)
{
yes.setText(s);
}
public void noChange(String s)
{
no.setText(s);
}
}
I find it tough to answer this question not fully knowing what your code is doing, especially the part where you "... do funky #### with that number..."
But I do know that you have significant issues with your program structure, especially within your lengthy run() method where you have numerous nested while (...) loops and do-while loops, code constructs that might seem at home within a linear processing console program but which seems out of place within an event-driven Swing GUI.
What I suggest that you do is try to use some state-dependent coding. For instance, you could give your class the boolean variables, enteringData and dataValidYet, to represent two key states: whether the user is now entering data into the JTextField, and whether that data has yet been validated yet. And then within your JButton ActionListeners, use if and if/else blocks to decide what to do on button push depending on the state of these boolean fields, and likely other key fields of the class.
For a code "skeleton" example, one that doesn't yet do anything, but hopefully will show you the structure I'm talking about:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class StateMachine extends JPanel {
private static final String INITIAL_TITLE = "Please enter your next 8 bits. "
+ "Do not enter more than 8 bits.\n"
+ "Press Enter when done";
private static final String ARE_YOU_FINISHED = "Are you finished entering streams?";
private static final String YES = "Yes";
private static final String ENTER = "Enter";
private static final String NO = "No";
private static int GAP = 8;
private static final int COLUMNS = 30;
// this is a JTextArea built to look like a JLabel
private JTextArea topTextArea = new JTextArea(2, COLUMNS);
private JTextField dataEntryField = new JTextField(COLUMNS);
private JButton yesEnterButton = new JButton(ENTER);
private JButton noButton = new JButton(NO);
private boolean enteringData = true;
private boolean dataValidYet = false;
public StateMachine() {
yesEnterButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
yesEnterButtonActionPerfromed(e);
}
});
noButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
noButtonActionPerfromed(e);
}
});
topTextArea.setWrapStyleWord(true);
topTextArea.setLineWrap(true);
topTextArea.setFocusable(false);
topTextArea.setEditable(false);
topTextArea.setOpaque(false);
topTextArea.setText(INITIAL_TITLE);
JPanel innerButtonPanel = new JPanel(new GridLayout(1, 0, GAP, 0));
innerButtonPanel.add(yesEnterButton);
innerButtonPanel.add(noButton);
JPanel outerButtonPanel = new JPanel();
outerButtonPanel.add(innerButtonPanel);
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new BorderLayout(GAP, GAP));
add(topTextArea, BorderLayout.PAGE_START);
add(dataEntryField, BorderLayout.CENTER);
add(outerButtonPanel, BorderLayout.PAGE_END);
}
protected void noButtonActionPerfromed(ActionEvent e) {
// TODO depending on state of enteringData and dataValidYet booleans
// change text in buttons, do things with JTextField data
// set state of enteringData and dataValidYet booleans
if (enteringData) {
// a no press is meaningless if entering data
return;
}
// .... more
}
private void yesEnterButtonActionPerfromed(ActionEvent e) {
// TODO depending on state of enteringData and dataValidYet booleans
// change text in buttons, do things with JTextField data
// set state of enteringData and dataValidYet booleans
if (enteringData) {
topTextArea.setText(ARE_YOU_FINISHED);
yesEnterButton.setText(YES);
yesEnterButton.setActionCommand(YES);
enteringData = false;
return;
}
// .... more
}
private static void createAndShowGui() {
StateMachine mainPanel = new StateMachine();
JFrame frame = new JFrame("State Machine");
frame.setDefaultCloseOperation(JFrame.DISPOSE_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();
}
});
}
}
Also, as a "side" recommendation, one unrelated to your main problem, understand that null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
Note that if this were my program, I would use more indirection including creating separate classes to separate out the GUI portion of the program from the logic portion.

The method ... is undefined for type JFrame

I'm trying to make a gui with two menu lists, with 3 items in each. What my problem is, is that when I click on an item, I get an error "The method displayList(int, AirplaneList) is undefined for the type JFrame"
Code for AirplaneController.java:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.util.StringTokenizer;
public class AirplaneController implements ActionListener{
public static StringTokenizer myTokens; //Declares a string tokenizer.
public static String[] animals;
public static int i;//Total including error.
public static int a; //Total strings
final static String[] DATA =
{...
};
final int Cargo = 0;
final int Passenger = 1;
final int Business = 2;
final int All= 4;
int count=0;
AirplaneList close= new AirplaneList();
AirplaneList end=new AirplaneList();
CargoJet Cairplanes[]= new CargoJet[5];
BusinessJet Bairplanes[]= new BusinessJet[5];
PassengerJet Pairplanes[]= new PassengerJet[5];
JFrame gui;
/**
* One-argument constructor that sets the default JFrame and sets
* to listen on buttons of that frame.
* #param frame
*/
public AirplaneController(JFrame frame) {
gui = frame;
//gui.setButtonListener;
}
public void runList(){
Airplane parts2 []= new Airplane[8];
String hate[]= new String [80];
//AirplaneList close= new AirplaneList();
i=0;
animals = new String[80];
for(int i=0; i<8; i++){
myTokens = new StringTokenizer(DATA[i],",");
while (myTokens.hasMoreTokens()) {
animals[a]=myTokens.nextToken();
hate[a]=animals[a];
a++;
}
}
a=0;
int k=0;
int z=0;
int d=0;
for(i=0; i<80; i+=10){
if(hate[i].equals("B")){
Bairplanes[k]= new BusinessJet(hate[i],hate[i+1],hate[i+2],hate[i+3],hate[i+4],hate[i+5],hate[i+6],hate[i+7],hate[i+8],hate[i+9]);
parts2[d]=Bairplanes[k];
d++;
k++;
count++;
}
if(hate[i].equals("C")){
Cairplanes[a]= new CargoJet(hate[i],hate[i+1],hate[i+2],hate[i+3],hate[i+4],hate[i+5],hate[i+6],hate[i+7],hate[i+8],hate[i+9]);// hate[i]="Catastrophy";
parts2[d]=Cairplanes[k];
d++;
a++;
count++;
}
if(hate[i].equals("P")){
Pairplanes[z]= new PassengerJet(hate[i],hate[i+1],hate[i+2],hate[i+3],hate[i+4],hate[i+5],hate[i+6],hate[i+7],hate[i+8],hate[i+9]);// hate[i]="Catastrophy";
parts2[d]=Pairplanes[k];
d++;
z++;
count++;
}
}
for(i=0; i<8; i++){
System.out.println(parts2[i]+" Parts");
close.append(parts2[i]);
}
System.out.println(close);
}
public void createList(int selection) {
int numPlanes = DATA.length;
AirplaneList list = new AirplaneList();
Airplane parts2 []= new Airplane[8];
String hate[]= new String [80];
//AirplaneList close= new AirplaneList();
i=0;
animals = new String[80];
for(int i=0; i<8; i++){
myTokens = new StringTokenizer(DATA[i],",");
while (myTokens.hasMoreTokens()) {
animals[a]=myTokens.nextToken();
hate[a]=animals[a];
a++;
}
}
a=0;
int k=0;
int z=0;
int d=0;
for(i=0; i<80; i+=10){
if(hate[i].equals("B")){
Bairplanes[k]= new BusinessJet(hate[i],hate[i+1],hate[i+2],hate[i+3],hate[i+4],hate[i+5],hate[i+6],hate[i+7],hate[i+8],hate[i+9]);
parts2[d]=Bairplanes[k];
d++;
k++;
count++;
}
if(hate[i].equals("C")){
Cairplanes[a]= new CargoJet(hate[i],hate[i+1],hate[i+2],hate[i+3],hate[i+4],hate[i+5],hate[i+6],hate[i+7],hate[i+8],hate[i+9]);// hate[i]="Catastrophy";
parts2[d]=Cairplanes[k];
d++;
a++;
count++;
}
if(hate[i].equals("P")){
Pairplanes[z]= new PassengerJet(hate[i],hate[i+1],hate[i+2],hate[i+3],hate[i+4],hate[i+5],hate[i+6],hate[i+7],hate[i+8],hate[i+9]);// hate[i]="Catastrophy";
parts2[d]=Pairplanes[k];
d++;
z++;
count++;
}
}
for (int i = 0; i < numPlanes; i++) {
switch (selection)
{
case Business:
list.append(Bairplanes[i]);
break;
case Passenger:
list.append(Pairplanes[i]);
break;
case Cargo:
list.append(Cairplanes[i]);
default:
list.insert(parts2[i]);
}
gui.displayList(selection, list); // PROBLEM HERE!!
}
}
//#Override
/**
* Create a LinkedList of airplane objects either by append, prepend or insert.
* And display the LinkedList on the GUI.
*
* #param selection given order of the LinkedList
* 0 for APPEND, 1 for PREPEND, 2 for INSERT
*/
/*public AirplaneList createList(int selection) {
gui.displayList();
if(selection==All) return close;
return close;
}*/
//gui.displayList(selection, close.toString());
#Override
public void actionPerformed(ActionEvent arg0) {
String item = arg0.getActionCommand();
if (item.equals("Start")){
createList(All);
}
else if(item.equals("Clear")){
}
else if (item.equals("Passenger")){
createList(Passenger);
}
else if( item.equals("Business")){
createList(Business);
}
else if( item.equals("Cargo")){
createList(Cargo);
}
else
System.exit(0);
}
}
The problem is here: gui.displayList(selection, list); and creates this error:
Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problem:
The method displayList(int, AirplaneList) is undefined for the type JFrame
Here's the current code for AirplaneGUI.java:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.Border;
public class AirplaneGUI {
public static void main(String[] args) {
initialize();
}
//JButton[] buttons;
private JMenuBar menuBar;
private JMenuItem item;
JFrame frame;
final Color[] colors = {Color.blue, Color.yellow, Color.green};
JTextArea[] textAreas;
final int NUM_LISTS = 3;
final String[] LIST = {"passenger", "cargo", "bussiness"};
JTextArea spite;
public static void initialize() {
JFrame frame = new JFrame();
frame.setTitle("flight schedule");
frame.setSize(250, 250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
AirplaneController listener = new AirplaneController(frame);
listener.runList();
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
JMenuItem startItem = new JMenuItem("Start");
startItem.addActionListener(listener);
menu.add(startItem);
JMenuItem clearItem = new JMenuItem("Clear");
clearItem.addActionListener(listener);
menu.add(clearItem);
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(listener);
menu.add(exitItem);
JMenu menu1 = new JMenu("Filter");
JMenuItem passengerItem = new JMenuItem("Passenger");
passengerItem.addActionListener(listener);
menu1.add(passengerItem);
//frame.setBackground(Color.blue);
JMenuItem bussinessItem = new JMenuItem("Business");
bussinessItem .addActionListener(listener);
menu1.add( bussinessItem );
//frame.setBackground(Color.yellow);
JMenuItem cargoItem = new JMenuItem("Cargo");
cargoItem.addActionListener(listener);
menu1.add(cargoItem);
//frame.setBackground(Color.green);
menuBar.add(menu);
menuBar.add(menu1);
Container pane = frame.getContentPane();
frame.setJMenuBar(menuBar);
frame.setVisible(true);
}
public void setupDisplayPanel() {
Border squareBorder = BorderFactory.createLineBorder(Color.BLACK, 0);
textAreas = new JTextArea[NUM_LISTS];
for (int i = 0; i < NUM_LISTS; ++i) {
textAreas[i] = new JTextArea(LIST[i] + "\n");
textAreas[i].setBorder(squareBorder);
textAreas[i].setBackground(colors[i]);
}
}
public void displayList(int selection, AirplaneList result) {
spite.append(result.toString());
}
public void deleteList(){
spite=null;
}
}
I've tried changing the JFrame gui; in AirplaneController to AirplaneGUI gui;, which then created errors in AirplaneGUI.java:
javax.swing.JFrame cannot be cast to AirplaneGUI
How can I fix this?
displayList is a method you have written in AirplaneGUI why do you expect it to be in JFrame? Change JFrame gui; to AirplaneGUI gui; and public AirplaneController(JFrame frame) to public AirplaneController(AirplaneGUI frame).
Having said that there are too many compilation errors and missing classes for me to be able to run it.
May be you need extend JFrame like public class AirplaneGUI extends JFrame{ . I said "may be" because do not get what you are trying to do .

Categories