I have a JLabel array that contains many words. I am trying to get the first character of the words. In fact I am trying to get all the character, but if I see how to get the first, I will get the others.
I tried this
mport java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
public class WordSearchFrame extends JFrame {
private static final long serialVersionUID = 1L;
private static final int COLS_IN_WORDLIST = 1;
private static final int FRAME_WIDTH = 640;
private static final int FRAME_HEIGHT = 480;
private JLabel[][] wordSearch;
private JLabel[] wordListLabels;
private JPanel wordListPanel;
private JPanel wordsearchPanel;
private JPanel rightSidePanel;
private JPanel leftSidePanel;
private JPanel searchButtonPanel;
private JButton searchButton;
private int numRows;
private int numCols;
private ActionListener searchButtonListener;
private ArrayList<String> wordList;
class SearchListener implements ActionListener {
private int x = 0;
public void actionPerformed(ActionEvent event) {
wordListLabels[0].setForeground(Color.BLACK);
if (x == 0) {
findword(x);
x++;
} else {
wordListLabels[x - 1].setForeground(Color.BLACK);
findword(x);
x++;
}
}
private void findword(int x) {
wordListLabels[x].setForeground(Color.RED);
findword2(x);
}
private void findword2(int x) {
for (int i = 0; i < 7; i++)
wordSearch[x + i][x].setForeground(Color.RED);
}
}
private void buildLeftSidePanel() throws WordSearchException, IOException {
leftSidePanel = new JPanel();
leftSidePanel.setLayout(new BorderLayout());
leftSidePanel.setBorder(new TitledBorder(new EtchedBorder(), "Word Search"));
wordsearchPanel = new JPanel();
wordsearchPanel.setLayout(new GridLayout(numRows, numCols));
leftSidePanel.add(wordsearchPanel, BorderLayout.CENTER);
this.getContentPane().add(leftSidePanel, BorderLayout.CENTER);
}
private void initGridFromFile(String wordSearchFilename) throws WordSearchException, IOException {
this.numRows = 0;
this.numCols = 0;
BufferedReader reader = new BufferedReader(new FileReader(wordSearchFilename));
String line = reader.readLine();
while (line != null) {
StringTokenizer tokenizer = new StringTokenizer(line, " ");
if (this.numCols == 0) {
this.numCols = tokenizer.countTokens();
} else {
if (tokenizer.countTokens() != this.numCols) {
throw new WordSearchException("Invalid number of columns in word search");
}
}
line = reader.readLine();
this.numRows++;
}
reader.close();
this.wordSearch = new JLabel[numRows][numCols];
}
protected void loadGridFromFile(String wordSearchFilename) throws IOException {
int row = 0;
BufferedReader reader = new BufferedReader(new FileReader(wordSearchFilename));
String line = reader.readLine();
while (line != null) {
StringTokenizer tokenizer = new StringTokenizer(line, " ");
int col = 0;
while (tokenizer.hasMoreTokens()) {
String tok = tokenizer.nextToken();
wordSearch[row][col] = new JLabel(tok);
wordSearch[row][col].setForeground(Color.BLACK);
wordSearch[row][col].setHorizontalAlignment(SwingConstants.CENTER);
wordsearchPanel.add(wordSearch[row][col]);
col++;
}
line = reader.readLine();
row++;
}
reader.close();
}
private void buildRightSidePanel() {
rightSidePanel = new JPanel();
rightSidePanel.setBorder(new TitledBorder(new EtchedBorder(), "Word List"));
rightSidePanel.setLayout(new BorderLayout());
wordListLabels = new JLabel[wordList.size()];
wordListPanel = new JPanel();
wordListPanel.setLayout(new GridLayout(wordList.size(), 1));
for (int i = 0; i < this.wordList.size(); i++) {
// If the line below won't compile in Java 1.4.2, make it
// String word = (String)this.wordList.get(i);
String word = this.wordList.get(i);
wordListLabels[i] = new JLabel(word);
wordListLabels[i].setForeground(Color.BLUE);
wordListLabels[i].setHorizontalAlignment(SwingConstants.CENTER);
wordListPanel.add(wordListLabels[i]);
}
rightSidePanel.add(wordListPanel, BorderLayout.CENTER);
searchButton = new JButton("Search");
searchButtonListener = new SearchListener();
searchButton.addActionListener(searchButtonListener);
searchButtonPanel = new JPanel();
searchButtonPanel.add(searchButton);
rightSidePanel.add(searchButtonPanel, BorderLayout.SOUTH);
this.getContentPane().add(rightSidePanel, BorderLayout.EAST);
}
private void loadWordList(String wordListFilename) throws WordSearchException, IOException {
int row = 0;
wordList = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(wordListFilename));
String line = reader.readLine();
while (line != null) {
StringTokenizer tokenizer = new StringTokenizer(line, " ");
if (tokenizer.countTokens() != COLS_IN_WORDLIST) {
throw new WordSearchException("Error: only one word per line allowed in the word list");
}
String tok = tokenizer.nextToken();
wordList.add(tok);
line = reader.readLine();
row++;
}
reader.close();
}
public WordSearchFrame(String wordSearchFilename, String wordListFilename) throws IOException, WordSearchException {
this.setSize(FRAME_WIDTH, FRAME_HEIGHT);
this.getContentPane().setLayout(new BorderLayout());
this.initGridFromFile(wordSearchFilename);
buildLeftSidePanel();
this.loadGridFromFile(wordSearchFilename);
loadWordList(wordListFilename);
buildRightSidePanel();
}
public WordSearchFrame(String[][] wordSearch, String[] wordList) throws IOException, WordSearchException {
this.setSize(FRAME_WIDTH, FRAME_HEIGHT);
this.getContentPane().setLayout(new BorderLayout());
this.numRows = wordSearch.length;
this.numCols = wordSearch[0].length;
this.wordSearch = new JLabel[this.numRows][this.numCols];
buildLeftSidePanel();
for (int row = 0; row < this.numRows; row++) {
for (int col = 0; col < this.numCols; col++) {
this.wordSearch[row][col] = new JLabel(wordSearch[row][col]);
this.wordSearch[row][col].setForeground(Color.BLACK);
this.wordSearch[row][col].setHorizontalAlignment(SwingConstants.CENTER);
this.wordsearchPanel.add(this.wordSearch[row][col]);
}
}
this.wordList = new ArrayList<String>();
for (int i = 0; i < wordList.length; i++) {
this.wordList.add(wordList[i]);
}
buildRightSidePanel();
}
public static void main(String[] args) {
try {
if (args.length != 2) {
System.out.println("Command line arguments: <word search file> <word list>");
} else {
WordSearchFrame frame = new WordSearchFrame(args[0], args[1]);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
I have all the next:
the panel on the left hand side, which consists of the word search
the contents of the word search into the JLabels of the word search grid in the GUI
Now I just need the jlabe[index].charAt(0). That does not work.
I tried jlabe[index].getText().charAt(0). That does not work.
What I tried above works fine, but not for what I want it.
Also the other class
public class WordSearchException extends RuntimeException {
private static final long serialVersionUID = 1L;
public WordSearchException() {
}
public WordSearchException(String reason) {
super(reason);
}
}
The best way to do that is to gettext().charat(index)
Related
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);
}
These Threee Classes are what I got so far.
package ex;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.tree.*;
import java.io.*;
import javax.swing.event.*;
import java.util.*;
import java.text.*;
class ATable extends AbstractTableModel {
private String title[] = { "Name", "Size", "Type", "Modified Date" };
private String val[][] = new String[1][4];
public void setValueArr(int i) {
val = new String[i][4];
}
public int getRowCount() {
return val.length;
}
public int getColumnCount() {
return val[0].length;
}
public String getColumnName(int column) {
return title[column];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
if (columnIndex == 0)
return true;
else
return false;
}
public Object getValueAt(int row, int column) {
return val[row][column];
}
public void setValueAt(String aValue, int rowIndex, int columnIndex) {
val[rowIndex][columnIndex] = aValue;
}
}
package ex;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.tree.*;
import java.io.*;
import javax.swing.event.*;
import java.util.*;
import java.text.*;
class FileViewer implements TreeWillExpandListener, TreeSelectionListener {
private JFrame frame = new JFrame("Explorer");
private Container con = null;
private JSplitPane pMain = new JSplitPane();
private JScrollPane pLeft = null;
private JPanel pRight = new JPanel(new BorderLayout());
private DefaultMutableTreeNode root = new DefaultMutableTreeNode("My Computer");
private JTree tree;
private JPanel pNorth = new JPanel();
private JPanel northText = new JPanel();
private JLabel northLabel0 = new JLabel("Path");
private JTextField pathText = new JTextField();
private JLabel northLabel1 = new JLabel("Search");
private JTextField searchText = new JTextField();
private Dimension dim, dim1;
private int xpos, ypos;
FileViewer() {
init();
start();
frame.setSize(800, 600);
dim = Toolkit.getDefaultToolkit().getScreenSize();
dim1 = frame.getSize();
xpos = (int) (dim.getWidth() / 2 - dim1.getWidth() / 2);
ypos = (int) (dim.getHeight() / 2 - dim1.getHeight() / 2);
frame.setLocation(xpos, ypos);
frame.setVisible(true);
}
void init() {
pMain.setResizeWeight(1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
con = frame.getContentPane();
con.setLayout(new BorderLayout());
pathText.setPreferredSize(new Dimension(300, 20));
searchText.setPreferredSize(new Dimension(300, 20));
northText.add(northLabel0);
northText.add(pathText);
northText.add(northLabel1);
northText.add(searchText);
pNorth.add(northText);
con.add(pNorth, "North");
File file = new File("C:/");
File list[] = file.listFiles();
DefaultMutableTreeNode temp;
for (int i = 0; i < list.length; ++i) {
temp = new DefaultMutableTreeNode(list[i].getPath());
temp.add(new DefaultMutableTreeNode("None"));
root.add(temp);
}
tree = new JTree(root);
pLeft = new JScrollPane(tree);
pMain.setDividerLocation(150);
pMain.setLeftComponent(pLeft);
pMain.setRightComponent(pRight);
con.add(pMain);
}
void start() {
tree.addTreeWillExpandListener(this);
tree.addTreeSelectionListener(this);
}
public static void main(String args[]) {
JFrame.setDefaultLookAndFeelDecorated(true);
new FileViewer();
}
String getPath(TreeExpansionEvent e) {
StringBuffer path = new StringBuffer();
TreePath temp = e.getPath();
Object list[] = temp.getPath();
for (int i = 0; i < list.length; ++i) {
if (i > 0) {
path.append(((DefaultMutableTreeNode) list[i]).getUserObject() + "\\");
}
}
return path.toString();
}
String getPath(TreeSelectionEvent e) {
StringBuffer path = new StringBuffer();
TreePath temp = e.getPath();
Object list[] = temp.getPath();
for (int i = 0; i < list.length; ++i) {
if (i > 0) {
path.append(((DefaultMutableTreeNode) list[i]).getUserObject() + "\\");
}
}
return path.toString();
}
public void getSearch(){
}
public void treeWillCollapse(TreeExpansionEvent event) {
}
public void treeWillExpand(TreeExpansionEvent e) {
if (((String) ((DefaultMutableTreeNode) e.getPath().getLastPathComponent()).getUserObject()).equals("My Computer")) {
} else {
try {
DefaultMutableTreeNode parent = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
File tempFile = new File(getPath(e));
File list[] = tempFile.listFiles();
DefaultMutableTreeNode tempChild;
for (File temp : list) {
if (temp.isDirectory() && !temp.isHidden()) {
tempChild = new DefaultMutableTreeNode(temp.getName());
if (true) {
File inFile = new File(getPath(e) + temp.getName() + "\\");
File inFileList[] = inFile.listFiles();
for (File inTemp : inFileList) {
if (inTemp.isDirectory() && !inTemp.isHidden()) {
tempChild.add(new DefaultMutableTreeNode("None"));
break;
}
}
}
parent.add(tempChild);
}
}
parent.remove(0);
} catch (Exception ex) {
JOptionPane.showMessageDialog(frame, "Can't Find a File");
}
}
}
public void valueChanged(TreeSelectionEvent e) {
if (((String) ((DefaultMutableTreeNode) e.getPath().getLastPathComponent()).getUserObject()).equals("My Computer")) {
pathText.setText("My Computer");
} else {
try {
pathText.setText(getPath(e));
pRight = new FView(getPath(e), null).getTablePanel();
pMain.setRightComponent(pRight);
} catch (Exception ex) {
JOptionPane.showMessageDialog(frame, "Can't Find a File");
}
}
}
}
package ex;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.tree.*;
import java.io.*;
import javax.swing.event.*;
import java.util.*;
import java.text.*;
class FView {
private ATable at = new ATable();
private JTable jt = new JTable(at);
private JPanel pMain = new JPanel(new BorderLayout());
private JScrollPane pCenter = new JScrollPane(jt);
private File file;
private File list[];
private long size = 0, time = 0;
FView(String str, String searchKey) {
init();
if (searchKey!=null){
search(str, searchKey);
}
start(str);
}
void init() {
pMain.add(pCenter, "Center");
}
void start(String strPath) {
file = new File(strPath);
list = file.listFiles();
at.setValueArr(list.length);
for (int i = 0; i < list.length; ++i) {
size = list[i].length();
time = list[i].lastModified();
for (int j = 0; j < 4; ++j) {
switch (j) {
case 0:
at.setValueAt(list[i].getName(), i, j);
break;
case 1:
if (list[i].isFile())
at.setValueAt(Long.toString((long) Math.round(size / 1024.0)) + "Kb", i, j);
break;
case 2:
if (list[i].isFile()) {
at.setValueAt(getLastName(list[i].getName()), i, j);
} else
at.setValueAt("파일폴더", i, j);
break;
case 3:
at.setValueAt(getFormatString(time), i, j);
break;
}
}
}
jt.repaint();
pCenter.setVisible(false);
pCenter.setVisible(true);
}
void search(String strPath, String searchKey){
file = new File(strPath);
list = file.listFiles();
at.setValueArr(list.length);
for (int i = 0; i < list.length; ++i) {
size = list[i].length();
time = list[i].lastModified();
for (int j = 0; j < 4; ++j) {
switch (j) {
case 0:
at.setValueAt("zzzzzzzzz", i, j);
break;
case 1:
if (list[i].isFile())
at.setValueAt(Long.toString((long) Math.round(size / 1024.0)) + "Kb", i, j);
break;
case 2:
if (list[i].isFile()) {
at.setValueAt(getLastName(list[i].getName()), i, j);
} else
at.setValueAt("File Folder", i, j);
break;
case 3:
at.setValueAt(getFormatString(time), i, j);
break;
}
}
}
jt.repaint();
pCenter.setVisible(false);
pCenter.setVisible(true);
}
String getLastName(String name) {
int pos = name.lastIndexOf(".");
String result = name.substring(pos + 1, name.length());
return result;
}
String getFormatString(long time) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
Date d = new Date(time);
String temp = sdf.format(d);
return temp;
}
JPanel getTablePanel() {
return pMain;
}
}
What I want is 'searching a file' function on the right side of path textfield.
The location of search textfield is fine now, but i have no clue how to add function on it.
It should show a file that contains a word which the user type on search text field. (The file that is in current directory ONLY. Don't need to show a file in subdirectory)
And when the search textfield is blank, it should show all the files in current directory as usual.
Please help me on this.
con.add(pNorth, "North");
Don't use magic strings. The API will have variables you can use:
con.add(pNorth, BorderLayout.NORTH);
It should show a file that contains a word which the user type on search text field
You need to add a DocumentListener to the Document of the JTextField. An event will be fired whenever text is added or removed and you can then do your search.
Read the section from the Swing tutorial on How to Write a DocumentListener for more information and examples.
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);
}
}
I have 2 classes (IterativeVsRecursive and Sequence) and the Sequence class performs mathematical actions and returns the values to IterativeVsRecursive, or at least that is the intent.
I believe I am missing something easy, but am stumped on how to make this work.
IterativeVsRecursive Class:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.sound.midi.Sequence;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class IterativeVsRecursiveGUI extends JFrame implements ActionListener {
private JLabel radioButton1Label = new JLabel();
private JLabel radioButton2Label = new JLabel();
private JLabel inputLabel = new JLabel();
private JLabel resultLabel = new JLabel();
private JLabel efficiencyLabel = new JLabel();
private JLabel computeButtonLabel = new JLabel();
private ButtonGroup radioButtonGroup = new ButtonGroup();
private JRadioButton radioButtonIterative = new JRadioButton("Iterative");
private JRadioButton radioButtonRecursive = new JRadioButton("Recursive");
private JTextField inputField = new JTextField();
private JTextField resultField = new JTextField();
private JTextField efficiencyField = new JTextField();
private JButton computeButton = new JButton();
private int efficiencyCounter;
public IterativeVsRecursiveGUI()
{
super("Project 3");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new GridLayout(6, 2));
radioButtonGroup.add(radioButtonIterative);
radioButtonIterative.setSelected(true);
// radioButtonIterative.setText("Iterative");
getContentPane().add(radioButtonIterative);
radioButtonGroup.add(radioButtonRecursive);
// radioButtonRecursive.setText("Recursive");
getContentPane().add(radioButtonRecursive);
inputLabel.setText("Enter number: ");
getContentPane().add(inputLabel);
getContentPane().add(inputField);
computeButton.setText("Compute");
computeButton.addActionListener(this);
getContentPane().add(computeButton);
resultLabel.setText("Result: ");
getContentPane().add(resultLabel);
getContentPane().add(resultLabel);
resultField.setEditable(false);
efficiencyLabel.setText("Efficiency: ");
getContentPane().add(efficiencyLabel);
getContentPane().add(efficiencyField);
efficiencyField.setEditable(false);
pack();
}
#Override
public void actionPerformed(ActionEvent button) {
int result;
efficiencyCounter = 0;
if (radioButtonIterative.isSelected()) {
result = Sequence.computeIterative(Integer.parseInt(inputField.getText()));
} else {
result = Sequence.computeRecursive(Integer.parseInt(inputField.getText()));
}
resultField.setText(Integer.toString(result));
efficiencyField.setText(Integer.toString(efficiencyCounter));
}
public static void main(String[] args) {
IterativeVsRecursiveGUI IterativeVsRecursiveGUI = new IterativeVsRecursiveGUI();
IterativeVsRecursiveGUI.setVisible(true);
}
}
Sequence class:
public class Sequence {
private int efficiencyCounter = 0;
public int computeIterative(int input) {
int answer = 0;
if (input == 0) {
efficiencyCounter++;
answer = 0;
} else if (input == 1) {
efficiencyCounter++;
answer = 1;
} else {
efficiencyCounter++;
int firstTerm = 0;
int secondTerm = 1;
for (int i = 2; i <= input; i++) {
answer = (3 * secondTerm) - (2 * firstTerm);
firstTerm = secondTerm;
secondTerm = answer;
}
}
return answer;
}
public int computeRecursive(int input) {
int answer = 0;
efficiencyCounter++;
if (input == 0) {
answer = 0;
} else if (input == 1) {
answer = 1;
} else {
answer = (3 * computeRecursive(input - 1)) - (2 * computeRecursive(input - 2));
}
return answer;
}
}
The intent is to have a GUI that displays the results of the Sequence class.
I should have been clear in that it is not allowing me to call the non-static methods in Sequence, but if I make them static, by adding "void", then the computeRecursive method throws an errror saying that 'void' type not allowed here
Or, since the method is already an instance method, create an instance of Sequence
#Override
public void actionPerformed(ActionEvent button) {
int result;
efficiencyCounter = 0;
Sequence sequence = new Sequence();
if (radioButtonIterative.isSelected()) {
result = sequence.computeIterative(Integer.parseInt(inputField.getText()));
} else {
result = sequence.computeRecursive(Integer.parseInt(inputField.getText()));
}
resultField.setText(Integer.toString(result));
efficiencyField.setText(Integer.toString(efficiencyCounter));
}
package mainpanel;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
import javax.swing.*;
public class MainPanel extends JFrame implements ActionListener {
String[] deck = null;
String[] discard = null;
Player p1;
Player p2;
Player p3;
public String[] playerList = new String[3];
JPanel panes = new JPanel();
JPanel playerStatPane = new JPanel();
public MainPanel() throws FileNotFoundException {
File masterList = new File("H:/mainPanel/masterList.txt");
File deckFile = new File("H:/mainPanel/deck.txt");
File discardFile = new File("H:/mainPanel/discard.txt");
File player1 = new File("H:/mainPanel/Chip.txt");
File player2 = new File("H:/mainPanel/Dale.txt");
File player3 = new File("H:/mainPanel/Caleb.txt");
deck = extractCards(deckFile);
if (deck.length == 0) {
deck = randomCards(extractCards(masterList));
}
discard = extractCards(discardFile);
p1 = new Player(player1);
p2 = new Player(player2);
p3 = new Player(player3);
setTitle("Bang!");
getContentPane().add(panes);
JLabel label1 = new JLabel();
playerList[0] = p1.name;
playerList[1] = p2.name;
playerList[2] = p3.name;
JComboBox comboBox = new JComboBox(playerList);
panes.add(comboBox);
comboBox.setSelectedIndex(2);
comboBox.addActionListener(this);
playerStatPane = createStats(p1);
panes.add(playerStatPane);
}
public static void main(String[] args) throws FileNotFoundException {
MainPanel mainScreen = new MainPanel();
mainScreen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainScreen.pack();
mainScreen.setVisible(true);
}
/**public static String[] randomCards(String[] unshuffledCards) {
int[] tempInts = randomInts(unshuffledCards.length);
String[] shuffledCards = new String[unshuffledCards.length];
for (int i = 0; i < tempInts.length; i++) {
shuffledCards[i] = unshuffledCards[tempInts[i] - 1];
}
return shuffledCards;
}
public static int[] randomInts(int x) {
Random numGen = new Random();
int index = 0;
boolean repeat = false;
int[] numberList = new int[x];
numberList[numberList.length - 1] = 0;
while (numberList[numberList.length - 1] == 0) {
int newInt = numGen.nextInt(x) + 1;
for (int i = 0; i < numberList.length; i++) {
if (newInt == numberList[i]) {
repeat = true;
}
}
if (repeat == false) {
numberList[index] = newInt;
index++;
}
repeat = false;
}
return numberList;
}
public String[] extractCards(File a) throws FileNotFoundException {
ArrayList < String > cardsInHand = new ArrayList < String > ();
Scanner scanner = new Scanner(a);
while (scanner.hasNextLine()) {
cardsInHand.add(scanner.nextLine());
}
return cardsInHand.toArray(new String[cardsInHand.size()]);
}
public void draw(Player a) {
a.addCard(deck[0]);
if (deck.length == 1) {
deck = discard;
discard = new String[0];
} else {
String[] tempDeck = deck;
deck = new String[deck.length - 1];
for (int i = 1; i < deck.length; i++) {
deck[i - 1] = tempDeck[i];
}
}
}*/
public JPanel createStats(Player a) {
JPanel stat = new JPanel(new FlowLayout());
JComboBox comboBox = new JComboBox(a.cardsInHand);
JLabel label1 = new JLabel("Select card:");
JButton discardButton = new JButton("discard");
JButton drawButton = new JButton("draw");
stat.add(label1);
stat.add(comboBox);
stat.add(drawButton);
stat.add(discardButton);
return stat;
}
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
String name = (String) cb.getSelectedItem();
if (name == "Chip") {
playerStatPane = createStats(p1);
} else if (name == "Dale") {
playerStatPane = createStats(p2);
} else {
playerStatPane = createStats(p3);
}
}
}
Errr, I'm trying to use ActionListener for the first time. I read a couple other question and answers, but I don't understand.
Help would be very appreciated. I'm trying to switch information of players by switching player name in the combo box.
Then I'm trying to get the discard and draw button to work. I have the discard and draw method already, I just need to learn the actionListener thing. Thanks!
You are reassiging the playerStatPane variable, but that does not mean the old value is replaced in panes. Try this:
public void actionPerformed(ActionEvent e) {
panes.remove(playerStatPane);
JComboBox cb = (JComboBox) e.getSource();
String name = (String) cb.getSelectedItem();
if (name.equals("Chip")) {
playerStatPane = createStats(p1);
} else if (name.equals("Dale")) {
playerStatPane = createStats(p2);
} else {
playerStatPane = createStats(p3);
}
panes.add(playerStatPane);
}