I've setup a simple GUI system to use this XOR encryption system. When I decrypt through the GUI the decryption comes out wrong, but when I hard-code the string to decrypt it comes out right. For example:
For example, this prints "this_is_to_test_if_the_program_in_the_gui_is_working_which_it_wont":
System.out.println(Skeleton.xorDecrypt("BX_Dg_CgLVkCVKLfQUfC^SgHFWSFY^oP]iBPShSC]g^KgO[D\\Q]Qg#PQTPk^MiA_VD", "638460047789894"));
But if I do it through the GUI it comes out as "this_is_to_test_if_the_program_in_the_gui_is_workdiia_xdglf\g{Qykns"
Skeleton.java
public class Skeleton {
public static String xorEncrypt(String data, String key) {
data = data.replaceAll(" ", "_");
byte m_cData[] = data.getBytes();
byte m_cKey[] = key.getBytes();
int keyPointer = 0;
for (int i = 0; i < m_cData.length; i++) {
m_cData[i] ^= m_cKey[keyPointer];
keyPointer += m_cData[i];
keyPointer %= m_cKey.length;
}
return new String(m_cData).replaceAll("\\\\", "\\\\\\\\");
}
public static String xorDecrypt(String data, String key) {
byte m_cData[] = data.getBytes();
byte m_cKey[] = key.getBytes();
int keyPointer = 0;
byte keyPointerAdd = 0;
for (int i = 0; i < m_cData.length; i++) {
keyPointerAdd = m_cData[i];
m_cData[i] ^= m_cKey[keyPointer];
keyPointer += keyPointerAdd;
keyPointer %= m_cKey.length;
}
return new String(m_cData);
}
public static long generateRandom(int length) {
Random random = new Random();
char[] digits = new char[length];
digits[0] = (char) (random.nextInt(9) + '1');
for (int i = 1; i < length; i++) {
digits[i] = (char) (random.nextInt(10) + '0');
}
return Long.parseLong(new String(digits));
}
}
Window.java
public class Window extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JTextField textPasscode;
public Window() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException exception) {
exception.printStackTrace();
}
setTitle("Saypar");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 381);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textPasscode = new JTextField();
textPasscode.setBounds(94, 278, 241, 20);
contentPane.add(textPasscode);
textPasscode.setColumns(10);
JLabel lblPasscode = new JLabel("Passcode (#):");
lblPasscode.setBounds(10, 281, 74, 14);
contentPane.add(lblPasscode);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 11, 424, 256);
contentPane.add(scrollPane);
JTextArea textAreaMessage = new JTextArea();
scrollPane.setViewportView(textAreaMessage);
textAreaMessage.setLineWrap(true);
textAreaMessage.setWrapStyleWord(true);
JButton btnEncrypt = new JButton("Encrypt");
btnEncrypt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (textAreaMessage.getText().trim().length() == 0) {
JOptionPane.showMessageDialog(null, "You need to enter in a message before encrypting.", "Saypar Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (textPasscode.getText().trim().length() == 0) {
JOptionPane.showMessageDialog(null, "You need to enter in a passcode before encrypting.", "Saypar Error", JOptionPane.ERROR_MESSAGE);
return;
}
StringSelection stringSelection = new StringSelection(Skeleton.xorEncrypt(textAreaMessage.getText(), textPasscode.getText()));
Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
clpbrd.setContents(stringSelection, null);
JOptionPane.showMessageDialog(null, "Message Encrypted... Copied to clipboard.", "Encrypted Message", JOptionPane.PLAIN_MESSAGE);
}
});
btnEncrypt.setBounds(345, 277, 89, 23);
contentPane.add(btnEncrypt);
JButton btnDecrypt = new JButton("Decrypt");
btnDecrypt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (textAreaMessage.getText().trim().length() == 0) {
JOptionPane.showMessageDialog(null, "You need to enter in a message before decrypting.", "Saypar Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (textPasscode.getText().trim().length() == 0) {
JOptionPane.showMessageDialog(null, "You need to enter in a passcode before decrypting.", "Saypar Error", JOptionPane.ERROR_MESSAGE);
return;
}
StringSelection stringSelection = new StringSelection(Skeleton.xorDecrypt(textAreaMessage.getText(), textPasscode.getText()));
Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
clpbrd.setContents(stringSelection, null);
JOptionPane.showMessageDialog(null, "Message Decrypted... Copied to clipboard.", "Decrypted Message", JOptionPane.PLAIN_MESSAGE);
}
});
btnDecrypt.setBounds(345, 311, 89, 23);
contentPane.add(btnDecrypt);
JButton btnGeneratePasscode = new JButton("Generate Random Passcode");
btnGeneratePasscode.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
textPasscode.setText("" + Skeleton.generateRandom(15));
}
});
btnGeneratePasscode.setBounds(107, 311, 228, 23);
contentPane.add(btnGeneratePasscode);
JLabel lblRecommended = new JLabel("RECOMMENDED:");
lblRecommended.setBounds(10, 315, 99, 14);
contentPane.add(lblRecommended);
}
}
Related
I am trying to use a JButton based keyboard in a GUI based game of Hangman. However when I want to check that the key pressed is in the hidden word, I am not sure where I need to change the type from String to char. I want to use the GUI based keyboard instead of allowing the user to use the keyboard, to try and minimise the validation that needs to be done. These are the classes that I have created thus far. I am struggling to get this working.
package guis;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class MouseClick extends JFrame implements ActionListener, MouseListener
{
private static final long serialVersionUID = 1L;
private static ActionListener letterHandler = null;
private Container cPane;
private JLabel lblTitle, lblTries, lblCountryToGuess, chancesLabel, message;//, usedLettersPanel;
private JButton btnExit, btnStart, btn1, btn3, btn4, btnX;
private JButton [] btn = new JButton[26];
private JPanel pNorth, pSouth, pEast, pWest, pCenter, wordPanel, messagePanel, usedLettersPanel, hangPanel, drawingFrame;//, lblCountryToGuess;
private JMenuItem mIRules, mIDev, mIRestart, mIExit;
private javax.swing.JLabel jLabel1;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JMenuItem jMenuItem4;
private javax.swing.JMenuItem jMenuItem5;
private javax.swing.JPopupMenu.Separator jSeparator1;
private JFrame frame = new JFrame();
private JButton enter;
private JLabel[] wordArray, usedLetters;
//private JFrame drawingFrame;
private HangmanDrawing drawing;
private char[] incorrectGuesses;
private char[] buttonLetters = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
private String word;
private int chances;
char input;
private JFrame endFrame;
private JPanel top, bottom;
private JLabel doNow;
private JButton restart, exit;
MouseClick() throws IOException
{
super("Assignment 2 - Hangman");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
word = new WordHandler().getRandomWord();
chances = 7;
cPane = getContentPane();
cPane.setBackground(new Color (236, 128, 19));
pNorth = new JPanel();
pSouth = new JPanel();
pEast = new JPanel();
pWest = new JPanel();
pCenter = new JPanel();
lblTitle = new JLabel(" Hangman ", SwingConstants.CENTER);
lblTitle.setFont(new Font("Comic Sans MS", Font.BOLD, 24));
lblTitle.setBorder(BorderFactory.createRaisedBevelBorder());
lblTitle.setBackground(new Color (38, 29, 226));
lblTitle.setOpaque(true);
lblTitle.setForeground(Color.white);
pNorth.add(lblTitle);
/*lblCountryToGuess = new JLabel("", SwingConstants.CENTER);
lblCountryToGuess.setFont(new Font("Comic Sans MS", Font.BOLD, 24));
//lblCountryToGuess.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 5));
lblCountryToGuess.setBounds(50, 1, 500, 60);
lblCountryToGuess.setBorder(BorderFactory.createTitledBorder("This is the country to be guessed..."));
//wordArray = new JLabel [hiddenCountry.length()];
//for (int i = 0 ; i < wordArray.length ; i++)
//{
// wordArray[i] = new JLabel("_");
// wordArray[i].setFont(new Font("Comic Sans MS.", Font.BOLD, 23));
// lblTitle4.add(wordArray[i]);
//}
pCenter.add(lblCountryToGuess);*/
hangPanel = new HangmanDrawing();
//drawing = new HangmanDrawing();
drawingFrame = new JPanel();
//drawingFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
//drawingFrame.setFocusableWindowState(false);
//drawingFrame.getContentPane().add(drawing);
//int xPosition = (int) ((scrnsize.width / 2) + (this.getWidth() / 2));
//drawingFrame.setSize(scrnsize.width - xPosition - 10,
//scrnsize.width - xPosition - 10);
// drawingFrame.setLocation(xPosition,
//(int) (scrnsize.height - this.getHeight())/3);
setVisible (true);
drawingFrame.setVisible(true);
pCenter.add(drawingFrame);
wordPanel = new JPanel();
wordPanel.setBounds(100, 100, 100, 60);
wordPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 5));
wordPanel.setBorder(BorderFactory.createTitledBorder("This is the country to guess..."));
wordArray = new JLabel [word.length()];
for (int i = 0 ; i < wordArray.length ; i++)
{
wordArray[i] = new JLabel("_");
wordArray[i].setFont(new Font("Arial", Font.BOLD, 23));
wordPanel.add(wordArray[i]);
}
pCenter.add(wordPanel);
usedLettersPanel = new JPanel();
usedLettersPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 13, 5));
incorrectGuesses = new char [chances];
usedLetters = new JLabel [incorrectGuesses.length];
for (int i = 0 ; i < usedLetters.length ; i++)
{
usedLetters[i] = new JLabel("~");
usedLetters[i].setFont(new Font("Comic Sans MS", Font.BOLD, 18));
usedLettersPanel.add(usedLetters[i]);
}
pCenter.add(usedLettersPanel);
messagePanel = new JPanel();
messagePanel.setLayout (new FlowLayout (FlowLayout.LEFT));
message = new JLabel ("Guess a letter...");
message.setFont (new Font ("Comic Sans MS", Font.BOLD, 17));
messagePanel.add(message);
pCenter.add(messagePanel);
/*usedLettersPanel = new JLabel();
usedLettersPanel.setFont(new Font("Comic Sans MS", Font.BOLD, 24));
usedLettersPanel.setBounds(50, 1, 500, 60);
usedLettersPanel.setBorder(BorderFactory.createTitledBorder("Letters already guessed..."));
//usedLettersPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 13, 5));
//incorrectGuesses = new char [chances];
//usedLetters = new JLabel [incorrectGuesses.length];
//for (int i = 0 ; i < usedLetters.length ; i++)
//{
//usedLetters[i] = new JLabel("~");
//usedLetters[i].setFont(new Font("Comic Sans MS", Font.BOLD, 18));
//usedLettersPanel.add(usedLetters[i]);
//}
pCenter.add(usedLettersPanel);*/
btnStart = new JButton(" Start / New Game ");
btnStart.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
btnStart.setBackground(Color.GREEN);
btnStart.setForeground(Color.white);
btnStart.setOpaque(true);
btnStart.setBorder(BorderFactory.createRaisedBevelBorder());
pWest.add(btnStart);
btnStart.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
dispose();
jMenuItem1.setVisible(true);
MouseClick sample = null;
try
{
sample = new MouseClick();
}
catch (IOException e1)
{
e1.printStackTrace();
}
sample.setTitle("Assignment 2 - Hangman Game");
sample.setSize(1200, 800);
sample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sample.setVisible(true);
}// end actionPerformed method
});
chancesLabel = new JLabel (chances + " chances left...");
chancesLabel.setFont (new Font ("Comic Sans MS", Font.BOLD, 17));
//lblTries = new JLabel(" Tries Remaining ");
//lblTries.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
chancesLabel.setBackground(new Color (38, 29, 226));
chancesLabel.setForeground(Color.white);
chancesLabel.setOpaque(true);
chancesLabel.setBorder(BorderFactory.createRaisedBevelBorder());
pWest.add(chancesLabel);
btnExit = new JButton(" Exit Game");
btnExit.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
btnExit.setBackground(new Color (236, 19, 35));
btnExit.setForeground(Color.white);
btnExit.setBorder(BorderFactory.createRaisedBevelBorder());
pWest.add(btnExit);
for(int i = 0; i < 26; i++)
{
//JButton btnX = new JButton();
btnX = new JButton(new KeyboardListener(buttonLetters[i]));
btnX.setText("" + buttonLetters[i]);
pSouth.add(btnX);
btnX.setVisible(true);
//btn[i] = btnX;
//btn[i].setText("" + (char)('A'+ i));
//btn[i].setText("" + buttonLetters[i]);
//input = buttonLetters[i];
//pSouth.add(btn[i]);
//btn[i].setVisible(true);
}
cPane.add(pNorth, BorderLayout.NORTH);
cPane.add(pSouth, BorderLayout.SOUTH);
pSouth.setLayout(new GridLayout(3,10,1,1));
cPane.add(pWest, BorderLayout.WEST);
pWest.setLayout(new GridLayout(3,1,1,10));
cPane.add(pEast, BorderLayout.EAST);
cPane.add(pCenter, BorderLayout.CENTER);
pCenter.setLayout(new GridLayout(4, 1, 1, 1));
/*Container chancesContainer = new Container();
chancesContainer.setLayout(new FlowLayout (FlowLayout.RIGHT));
chancesContainer.add(chancesLabel);
JPanel wrongGuessesContainer = new JPanel();
wrongGuessesContainer.setLayout(new GridLayout (1, 2));
wrongGuessesContainer.setBorder(BorderFactory.createTitledBorder ("Wrong Guesses"));
wrongGuessesContainer.add(usedLettersPanel);
wrongGuessesContainer.add (chancesContainer);
Container bottomContainer = new Container();
bottomContainer.setLayout(new BorderLayout());
bottomContainer.add(wrongGuessesContainer, BorderLayout.NORTH);
bottomContainer.add(messagePanel, BorderLayout.SOUTH);
getContentPane().setLayout(new BorderLayout());
//getContentPane().add (inputPanel, BorderLayout.NORTH);
getContentPane().add(wordPanel, BorderLayout.CENTER);
getContentPane().add(bottomContainer, BorderLayout.SOUTH);*/
btnExit.addActionListener(this);
pCenter.addMouseListener(this);
pNorth.addMouseListener(this);
pSouth.addMouseListener(this);
pEast.addMouseListener(this);
pWest.addMouseListener(this);
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
jMenuItem3 = new javax.swing.JMenuItem();
jSeparator1 = new javax.swing.JPopupMenu.Separator();
jMenuItem4 = new javax.swing.JMenuItem();
jMenu3 = new javax.swing.JMenu();
jMenuItem5 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
jMenuItem1.setText("New Game");
jMenuItem1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
dispose();
jMenuItem1.setVisible(true);
MouseClick sample = null;
try
{
sample = new MouseClick();
}
catch (IOException e1)
{
e1.printStackTrace();
}
sample.setTitle("Assignment 2 - Hangman Game");
sample.setSize(1200, 800);
sample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sample.setVisible(true);
}// end actionPerformed method
});
jMenu1.add(jMenuItem1);
jMenuBar1.add(jMenu1);
jMenu2.setText("Help");
jMenuItem3.setText("Rules");
jMenuItem3.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(frame, "Hangman is a guessing game where the word"
+"\n to guess is represented by dashes. The player"
+"\n is given the option to enter a letter. If the letter"
+"\n guessed is contained in the word, the letter will"
+"\n replace the dash in its approprate placement."
+"\n You cannot exceed 7 wrong guesses or else you"
+"\n lose. Words are selected randomly.", "Instructions",
JOptionPane.INFORMATION_MESSAGE);
}
});
jMenu2.add(jMenuItem3);
jMenu2.add(jSeparator1);
jMenuItem4.setText("Developer");
jMenuItem4.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(frame, "Developer: Ryan Smith");
}
});
jMenu2.add(jMenuItem4);
jMenuBar1.add(jMenu2);
jMenu3.setText("Exit");
jMenuItem5.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK));
jMenuItem5.setText("Exit Game");
jMenuItem5.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
jMenu3.add(jMenuItem5);
jMenuBar1.add(jMenu3);
setJMenuBar(jMenuBar1);
pack();
/*drawing = new HangmanDrawing();
drawingFrame = new JFrame();
drawingFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
drawingFrame.setFocusableWindowState(false);
drawingFrame.getContentPane().add(drawing);
int xPosition = (int) ((scrnsize.width / 2) + (this.getWidth() / 2));
drawingFrame.setSize(scrnsize.width - xPosition - 10,
scrnsize.width - xPosition - 10);
drawingFrame.setLocation(xPosition,
(int) (scrnsize.height - this.getHeight())/3);
setVisible (true);
drawingFrame.setVisible(true);*/
}
private void endGame()
{
enter.removeActionListener (this);
//inputField.removeActionListener(this);
//inputField.setEditable (false);
endFrame = new JFrame();
top = new JPanel();
bottom = new JPanel();
doNow = new JLabel ("What do you want to do now?");
restart = new JButton ("Start Again");
exit = new JButton ("Exit Hangman");
doNow.setFont (new Font ("Verdana", Font.BOLD, 17));
top.setLayout (new FlowLayout (FlowLayout.CENTER));
top.add (doNow);
restart.setFont (new Font ("Arial", Font.BOLD, 12));
restart.addActionListener(this);
exit.setFont (new Font ("Arial", Font.BOLD, 12));
exit.addActionListener(this);
bottom.setLayout (new FlowLayout (FlowLayout.CENTER, 44, 10));
bottom.add (restart);
bottom.add (exit);
endFrame.getContentPane().setLayout (new BorderLayout());
endFrame.getContentPane().add (top, BorderLayout.NORTH);
endFrame.getContentPane().add (bottom, BorderLayout.SOUTH);
endFrame.pack();
Dimension scrnsize = Toolkit.getDefaultToolkit().getScreenSize();
endFrame.setLocation ((int) (scrnsize.width - endFrame.getWidth())/2,
(int) (scrnsize.height - this.getHeight())/3 + this.getHeight());
endFrame.setResizable (false);
endFrame.setVisible (true);
this.setFocusableWindowState(false);
}
public void actionPerformed (ActionEvent event)
{
if(event.getSource().equals(btnExit))
{
System.exit(0);
}
else if (event.getSource().equals(restart))
{
endFrame.dispose();
MouseClick.this.dispose();
//drawingFrame.dispose();
//new HangmanMenu();
}
else if (event.getSource().equals(exit))
{
endFrame.dispose();
MouseClick.this.dispose();
//drawingFrame.dispose();
System.exit(0);
}
else
{
try
{
//char input = Character.toUpperCase(inputField.getText().charAt(0));
//if(event.getSource().equals(btn))
//{
//System.out.println("\n" + input);
boolean letterInWord = false;
for (int i = 0 ; i < word.length() ; i++)
{
if (word.charAt (i) == input)
{
letterInWord = true;
break;
}
}
if (!letterInWord) {
boolean alreadyGuessed = false;
for (int i = 0 ; i < incorrectGuesses.length ; i++) {
if (incorrectGuesses [i] == input) {
alreadyGuessed = true;
message.setText ("You already guessed that!");
break;
}
}
if (!alreadyGuessed) {
chances--;
drawing.addPart();
if (chances >= 0) {
incorrectGuesses [incorrectGuesses.length - chances - 1] = input;
usedLetters [usedLetters.length - chances - 1].setText ("" + input);
message.setText ("Woops, wrong! Try again!");
chancesLabel.setText (chances + " chances left...");
} else {
chancesLabel.setText ("Sorry, you lose.");
message.setText ("The word was: " + word);
endGame();
}
}
} else {
boolean alreadyGuessed = false;
for (int i = 0 ; i < wordArray.length ; i++) {
if (wordArray [i].getText().charAt (0) == input) {
alreadyGuessed = true;
message.setText ("You already guessed that!");
break;
}
}
if (!alreadyGuessed) {
for (int i = 0 ; i < word.length() ; i++) {
if (word.charAt (i) == input) {
wordArray [i].setText ("" + input);
}
}
boolean wordComplete = true;
for (int i = 0 ; i < wordArray.length ; i++) {
if (!Character.isLetter (wordArray [i].getText().charAt (0))) {
wordComplete = false;
break;
}
}
if (!wordComplete) {
message.setText ("Well done, you guessed right!");
} else {
message.setText ("Congratulations, you win the game!");
drawing.escape();
endGame();
}
}
//}
}
//inputField.setText ("");
}catch (Exception x)
{
}
}
}
#Override
public void mouseClicked(MouseEvent e){}
#Override
public void mouseEntered(MouseEvent e){}
#Override
public void mouseExited(MouseEvent e){}
#Override
public void mousePressed(MouseEvent e){}
#Override
public void mouseReleased(MouseEvent e){}
class KeyboardListener implements ActionListener
{
private final char letter;
public KeyboardListener(char letter)
{
this.letter = letter;
}
public char getLetter()
{
return letter;
}
#Override
public void actionPerformed(ActionEvent e)
{
char tempLetter;
if (e.getSource().equals(btnX))
{
tempLetter = 'A';
}
}
}
}
This is the code for the WordHandler class.
package guis;
import java.io.*;
class WordHandler
{
private BufferedReader fileIn;
private String[] wordArray;
private File wordFile;
public WordHandler() throws IOException
{
wordFile = new File("countriesnospaces.txt");
int arrayCounter = 0;
try {
BufferedReader fileIn = new BufferedReader(new FileReader(wordFile));
while (fileIn.readLine() != null)
{
arrayCounter++;
}
wordArray = new String [arrayCounter];
fileIn.close();
fileIn = new BufferedReader(new FileReader(wordFile));
for (int pos = 0 ; pos < arrayCounter ; pos++)
{
wordArray[pos] = fileIn.readLine();
}
fileIn.close();
} catch (FileNotFoundException e)
{
System.out.println("File not found. Please create it and add words.");
}
catch (Exception e)
{
System.out.println("Error: " + e);
}
}
public String getRandomWord() throws IOException
{
int random = (int) (Math.random() * wordArray.length);
return wordArray[random].toUpperCase();
}
public void sort()
{
String temp;
for (int loop = 0 ; loop < wordArray.length - 1 ; loop++) {
for (int pos = 0 ; pos < wordArray.length - 1 - loop ; pos++) {
if (wordArray[pos].compareTo(wordArray[pos + 1]) >0) {
temp = wordArray[pos];
wordArray[pos] = wordArray[pos + 1];
wordArray[pos + 1] = temp;
}
}
}
}
public String[] getArray()
{
return wordArray;
}
}
This is the test class.
package guis;
import java.io.IOException;
import javax.swing.JFrame;
public class TestMouseClick
{
public static void main(String[] args) throws IOException
{
MouseClick sample = new MouseClick();
sample.setTitle("Assignment 2 - Hangman");
sample.setSize(800, 750);
sample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sample.setVisible(true);
}
}
A simple fix would be getting the first character in the String returned by JButton tooltip text using the charAt(0) method and assign it to input:
char input = jButton26.getToolTipText().charAt(0);
or you could split it up to make it clearer:
String s = jButton26.getToolTipText();
char input = s.charAt(0);
Also just a tip, instead of manually coding each individual JButton for the GUI keyboard, you could create an array containing all 26 letters and then create the buttons and attach listeners using a for loop. This would significantly reduce the amount of code you have to write.
New Edit: creating and setting up lots of similar objects
(Also I noticed you created an array to store the buttons as well as a buttonLettersarray - this isn't necessary unless you have changed your code to utlise an array of buttons)
The important thing to note here is that ActionListener is an object in Java so it can be defined to store data and other method definitions like any other class. Personally I would prefer to write an inner class that extends ActionListener to store the letter that each button represents.
//define this inner class outside of the methods
class KeyboardListener extends ActionListener {
//field type depends on your buttonLetters array (not sure if it is chars or Strings)
private final String letter;
public KeyboardListener(String letter) {
this.letter = letter;
}
public String getLetter() {
return letter;
}
#Override
public void actionPerformed(ActionEvent ae) {
//do something when button is clicked
//you can make use of the getLetter() method to retrieve the letter
}
}
//this goes in the for loop when creating each button
JButton btnX = new JButton(new KeyboardListener(buttonLetters[i]));
//add button to interface and anything else
Note: one of the JButton constructors can take any class that implements the Action interface (or extends ActionListener in this case) to add it upon creation rather than having to call addActionListener().
I have a Swing Form (Java). In this form I have field, for example Name1. I initialize it so:
private JTextField Name1;
In this code i'm adding JTextField Name1 into my Form:
tabbedPane.addTab("T6", null, panel, "T6");
panel.setLayout(null);
Name1.setBounds(73, 11, 674, 20);
panel.add(Name1);
Additionaly I have Button1 on my form. The event in this button is changing the value of Name1. Its work normaly.
Moreover I have a Button 2 that hiding the Tab with Name1:
tabbedPane.remove(1);
tabbedPane.repaint();
tabbedPane.revalidate();
frame.repaint();
frame.revalidate();
(And, of course, I turn on my tabpane again after this)
After all that, by the pressing the Button 4 I want to change the vlue of Name1 to some text.
But it doesn't work!!!!!! SetTex doesnt work. The field is empty.
So, if I change the Name1 declaration from
private JTextField Name1;
to
static JTextField Name1;
Yes, it works. BUT! Then I can't change the value of Name1 by using
Name1.Settext("Example");
What i have to do to make Name1 available after Button 4 pressed and changable ????
The all code is:
public class GUI {
public JTextField Name_textField;
public static void main(String[] args) {
DB_Initialize();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frame.setVisible(true);
window.frame.setResizable(false);
FirstConnect FC = window.new FirstConnect();
ConnectStatus = true;
FC.FirstEntry();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public GUI() {
CurrentEnty_textField = new JTextField();
Name_textField = new JTextField();
EntriesCountlbl = new JLabel("New label");
initialize();
EntriesCountlbl.setText(Integer.toString(EC1));
if (LoginStatus == true) {
System.out.println("LoginStatus == true");
AdminPartOn();
btnNewButton.setEnabled(false);
} else {
btnNewButton_3.setEnabled(false);
tabbedPane.setEnabledAt(1, false);
// UnableForm();
AdminPartOff();
}
}
public static void DB_Initialize() {
conn3 = con3.DoConnect();
int ID;
ArrayList<String> list = new ArrayList<String>();
String l;
String p;
list = con3.LoginFileRead();
if (list.size() == 2) {
l = list.get(0);
p = list.get(1);
System.out.println("Логин из файла = " + l);
System.out.println("Пароль из файла = " + p);
ID = con3.CRMUserRequest(conn3, l, p);
AdminPanelData = con3.CRMUserFullData(conn3, l, p);
if (ID != 0) {
System.out.println("ID Юзера = " + ID);
LoginStatus = true;
}
}
EC1 = con3.CRMQuery_EntriesCount(conn3); // запрашиваем кол-во записей
StatusTableEntriesCount = con3.CRMQueryStatus_EntriesCount(conn3);
StatusTableFromCount = con3.CRMQueryFRom_EntriesCount(conn3);
System.out.println("Entries count(Из модуля GYU): " + EC1);
if (EC1 > 0) {
CurrentEntry = 1;
System.out.println("Все ОК, текущая запись - " + CurrentEntry);
} else {
System.out.println("Выскакивает обработчик ошибок");
}
con3.Ini();
con3.CRMQuery2(conn3, EC1 + 1);
StatusColumn = con3.CRMQueryStatus(conn3, StatusTableEntriesCount);
FromColumn = con3.CRMQueryFrom(conn3, StatusTableFromCount);
}
public class FirstConnect {
public void FirstEntry() {
int CurStatus = F.GetStatus(CurrentEntry - 1);
int CurFrom = F.GetFrom(CurrentEntry - 1);
if (LoginStatus != false) {
Name_textField.setText(F.GetName(CurrentEntry - 1));
} else {
Name_textField.setText("-");
}
}
}
private void initialize() {
frame = new JFrame();
panel = new JPanel();
frame.setBounds(100, 100, 816, 649);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(10, 250, 780, 361);
frame.getContentPane().add(tabbedPane);
JPanel panel_1 = new JPanel();
tabbedPane.addTab("\u0412\u0445\u043E\u0434", null, panel_1, null);
btnNewButton = new JButton("\u0412\u0445\u043E\u0434");
btnNewButton.setBounds(263, 285, 226, 37);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int ID;
ID = con3.CRMUserRequest(conn3, LoginField.getText(), PasswordField.getText());
if (ID == 0) {
} else {
MainTab();
FirstEntry3();
}
}
});
panel_1.setLayout(null);
panel_1.add(btnNewButton);
tabbedPane.addTab("\u041A\u043B\u0438\u0435\u043D\u0442", null, panel,
"\u041A\u043E\u043D\u0442\u0430\u043A\u0442\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435 \u043A\u043B\u0438\u0435\u043D\u0442\u0430");
panel.setLayout(null);
// Name_textField = new JTextField();
Name_textField.setBounds(73, 11, 674, 20);
panel.add(Name_textField);
Name_textField.setHorizontalAlignment(SwingConstants.CENTER);
Name_textField.setColumns(10);
NextEntryButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (NextEntryButton.isEnabled() != false) {
if (CurrentEntry < EC1) {
CurrentEntry = CurrentEntry + 1;
int CurStatus = F.GetStatus(CurrentEntry - 1);
int CurFrom = F.GetFrom(CurrentEntry - 1);
Name_textField.setText(F.GetName(CurrentEntry - 1));
} else {
}
}
}
});
}
public void MainTab() {
tabbedPane.addTab("1", null, panel,
"1");
tabbedPane.setEnabledAt(1, true);
panel.setLayout(null);
}
public void FirstEntry3() {
Name_textField.setText(F.GetName(CurrentEntry - 1));
}
}
I need some help with my program. I'm trying to make a brute force program as a project and I don't know how to make the loop values appear in the JTextField in the print () method. I don't just need the final value of the loop. I know this question has been asked a lot and I've tried everything but it's just not working. Please can anyone help me? I'll appreciate it !
public class BF implements ActionListener {
private JPanel contentPane;
private JTextField password;
private JTextField length;
public JTextField generateField;
JRadioButton numbers;
JButton generate;
JLabel passwordfound;
JLabel timelabel;
int min;
int max;
int stringLength;
private int[] chars;
String n="";
char[] passCom;
JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
BF frame = new BF();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public BF() {
frame = new JFrame ("Brute Force Attack Program");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 754, 665);
frame.setResizable(false);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
frame.setLocationRelativeTo(null);
frame.setContentPane(contentPane);
contentPane.setLayout(null);
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception e) {
}
backgroundPanel panel = new backgroundPanel();
panel.setBounds(0, 0, 749, 633);
contentPane.add(panel);
panel.setLayout(null);
generate = new JButton("Find Password");
generate.setFont(new Font("Tahoma", Font.BOLD, 15));
generate.setBounds(292, 401, 145, 35);
generate.addActionListener(this);
panel.add(generate);
generateField = new JTextField();
generateField.setForeground(Color.WHITE);
generateField.setFont(new Font("Tahoma", Font.BOLD, 24));
generateField.setEditable(false);
generateField.setBounds(315, 449, 186, 54);
generateField.setBackground(new Color(0,0,0,0));
generateField.setBorder(javax.swing.BorderFactory.createEmptyBorder());
panel.add(generateField);
generateField.setColumns(10);
frame.setVisible(true);
}
public void run(char min, char max, int len)
{
this.min = min;
this.max = max;
this.stringLength = len;
chars = new int[stringLength + 1];
Arrays.fill(chars, 1, chars.length, min);
while (chars[0] == 0&&!n.equals(password.getText()))
{
print();
increment();
n=String.valueOf(passCom);
}
}
public void increment()
{
for (int i = chars.length - 1; i >= 0; i--)
{
if (chars[i] < max)
{
chars[i]++; return;
}
chars[i] = min;
}
}
public void print()
{
int x=0;
for (int i = 1; i < chars.length; i++)
{
passCom[x]=(char)chars[i];
x++;
String txt = new String (passCom);
generateField.setText(txt);
}
}
#Override
public void actionPerformed(ActionEvent e) {
if (!password.getText().equals("") && e.getSource() == generate && !length.getText().equals("")&&numbers.isSelected()){
int count = Integer.parseInt(length.getText());
passCom = new char [count];
run('0','9',count);
}
}
}
For example, the string 123 has length 3 so the permutations can be 000,001,002 etc
Then why only display one at t time?
Instead I would use a JTextArea and append each value to the text field so all values are visible at the same time. Nobody is going to remember all the values if you display one at a time.
Otherwise, you would use a Swing Timer to display one at a time.
When I click the button called Enrolled Subjects, a table showing enrolled subjects is invoked. The data is loaded from a text file. But when I go to another page of the application and go back to the Enrolled Subjects or when I click the Enrolled Subjects Button again, a new table loads and adds to the previously loaded table. This makes the table grow longer every time I click Enrolled Subjects. I have added a removeAll() method which clears the content of the pane before loading the table again, but the previously loaded table, for some reason, does not go away.
Here's the code of the panel where the table is attached.
public class EnrolledSubjectsPanel extends JPanel
{
public EnrolledSubjectsPanel(String path)
{
setBackground(Color.LIGHT_GRAY);
setBounds(183, 280, 1129, 401);
setLayout(null);
LoadTable table = new LoadTable(path);
table.setBounds(0,60,1129,600);
add(table);
JLabel lblEnrolledSubjects = new JLabel("Enrolled Subjects");
lblEnrolledSubjects.setFont(new Font("Tahoma", Font.PLAIN, 35));
lblEnrolledSubjects.setBounds(446, 0, 292, 43);
add(lblEnrolledSubjects);
setVisible(true);
}
}
The class that creates the table
public class LoadTable extends JPanel
{
private static String path;
private static String header[] = {"Subject", "Schedule", "Room", "Proferssor", "Units"};
private static DefaultTableModel dtm = new DefaultTableModel(null, header);
boolean isLaunched;
public LoadTable(String path)
{
this.path = "subjects" + path;
setBackground(Color.LIGHT_GRAY);
setBounds(183, 280, 1129, 401);
setLayout(null);
JTable table = new JTable(dtm);
JScrollPane jsp = new JScrollPane(table);
jsp.setBounds(0, 0, 1129, 380);
add(jsp);
try
{
TextReaderBasic file = new TextReaderBasic(path);
String data[] = file.openFile();
int i = 0;
for(i = 0; i <= data.length; i++)
{
addRow(i);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
setVisible(true);
}
public static void addRow(int x)
{
try
{
TextReaderBasic file = new TextReaderBasic(path);
String data[] = file.openFile();
int size = data.length;
int i = 0 + x;
int j = 6 + x;
int k = 12 + x;
int l = 18 + x;
int m = 24 + x;
dtm.addRow(new Object[]{data[i], data[j], data[k], data[l], data[m]});
}
catch(Exception e)
{
System.out.println("Action completed :)");
}
}
}
The main class where the panel is attached to
public class LaunchPage extends JFrame
{ public LaunchPage(String path)
{
getContentPane().setBackground(Color.white);
getContentPane().setLayout(null);
StudentBasicInformationPanel studentBasicInfo = new StudentBasicInformationPanel(path);
getContentPane().add(studentBasicInfo);
JLabel universityTitleL = new JLabel("Evil Genuises University");
universityTitleL.setFont(new Font("Edwardian Script ITC", Font.ITALIC, 42));
universityTitleL.setBounds(514, 11, 343, 65);
getContentPane().add(universityTitleL);
JPanel panelToAttach = new JPanel();
panelToAttach.setBounds(173, 280, 1129, 404);
getContentPane().add(panelToAttach);
setSize(1366, 768);
JButton enrollmentButton = new JButton("Enrollment");
enrollmentButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
EnrollmentPanel ep = new EnrollmentPanel();
ep.setBackground(Color.LIGHT_GRAY);
ep.setBounds(0, 0, 1129, 401);
panelToAttach.add(ep);
repaint();
}
});
enrollmentButton.setBounds(10, 280, 157, 58);
getContentPane().add(enrollmentButton);
JButton viewEnrolledSubjectsButton = new JButton("Enrolled Subjects");
viewEnrolledSubjectsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
EnrolledSubjectsPanel es = new EnrolledSubjectsPanel(path);
es.setBackground(Color.LIGHT_GRAY);
es.setBounds(0, 0, 1129, 401);
panelToAttach.add(es);
repaint();
}
});
viewEnrolledSubjectsButton.setBounds(10, 349, 157, 58);
getContentPane().add(viewEnrolledSubjectsButton);
JButton viewGradesButton = new JButton("View Grades");
viewGradesButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
GradesPanel gp = new GradesPanel();
gp.setBackground(Color.LIGHT_GRAY);
gp.setBounds(0, 0, 1129, 401);
panelToAttach.add(gp);
repaint();
}
});
viewGradesButton.setBounds(10, 418, 157, 58);
getContentPane().add(viewGradesButton);
JButton clearanceButton = new JButton("Clearance");
clearanceButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
ClearancePanel cp = new ClearancePanel();
cp.setBackground(Color.LIGHT_GRAY);
cp.setBounds(0, 0, 1129, 401);
panelToAttach.add(cp);
repaint();
}
});
clearanceButton.setBounds(10, 487, 157, 58);
getContentPane().add(clearanceButton);
JButton viewAccountButton = new JButton("View Account");
viewAccountButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
panelToAttach.removeAll();
AccountPanel ap = new AccountPanel();
ap.setBackground(Color.LIGHT_GRAY);
ap.setBounds(0, 0, 1129, 401);
panelToAttach.add(ap);
repaint();
}
});
viewAccountButton.setBounds(10, 556, 157, 58);
getContentPane().add(viewAccountButton);
JButton closeButton = new JButton("Close");
closeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
closeButton.setBounds(10, 626, 157, 58);
getContentPane().add(closeButton);
setVisible(true);
}
}
Thanks in advance!
Try using below code in your LoadTable class before you adding the rows to the table. It will clear the rows in the table model.
dtm.setRowCount(0);
So your new LoadTable class should look like this:
public class LoadTable extends JPanel
{
private static String path;
private static String header[] = {"Subject", "Schedule", "Room", "Proferssor", "Units"};
private static DefaultTableModel dtm = new DefaultTableModel(null, header);
dtm.setRowCount(0); //THIS WILL CLEAR THE ROWS IN YOUR STATIC TABLEMODEL
boolean isLaunched;
public LoadTable(String path)
{
this.path = "subjects" + path;
setBackground(Color.LIGHT_GRAY);
setBounds(183, 280, 1129, 401);
setLayout(null);
JTable table = new JTable(dtm);
JScrollPane jsp = new JScrollPane(table);
jsp.setBounds(0, 0, 1129, 380);
add(jsp);
try
{
TextReaderBasic file = new TextReaderBasic(path);
String data[] = file.openFile();
int i = 0;
for(i = 0; i <= data.length; i++)
{
addRow(i);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
setVisible(true);
}
public static void addRow(int x)
{
try
{
TextReaderBasic file = new TextReaderBasic(path);
String data[] = file.openFile();
int size = data.length;
int i = 0 + x;
int j = 6 + x;
int k = 12 + x;
int l = 18 + x;
int m = 24 + x;
dtm.addRow(new Object[]{data[i], data[j], data[k], data[l], data[m]});
}
catch(Exception e)
{
System.out.println("Action completed :)");
}
}
}
I'm very surprised of this superior site!
My Goal is to get a .txt-file, read it in, cut it in single strings depending on which "windowsize" is chosen (how many characters, chosen by a jcombobox) and list it by frequency.
With debugging, it stops where the comment is marked.
I can't eliminate those thrown exceptions:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at xxxx.Babbles_GUI.windowSize(Babbles_GUI.java:247) at
xxxx.Babbles_GUI.actionPerformed(Babbles_GUI.java:203) at
javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
at
javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351)
at
javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at
javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at
javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6375) at
javax.swing.JComponent.processMouseEvent(JComponent.java:3267) at
java.awt.Component.processEvent(Component.java:6140) at
java.awt.Container.processEvent(Container.java:2083) at
java.awt.Component.dispatchEventImpl(Component.java:4737) at
java.awt.Container.dispatchEventImpl(Container.java:2141) at
java.awt.Component.dispatchEvent(Component.java:4565) at
java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4619)
at
java.awt.LightweightDispatcher.processMouseEvent(Container.java:4280)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4210)
at java.awt.Container.dispatchEventImpl(Container.java:2127) at
java.awt.Window.dispatchEventImpl(Window.java:2482) at
java.awt.Component.dispatchEvent(Component.java:4565) at
java.awt.EventQueue.dispatchEventImpl(EventQueue.java:684) at
java.awt.EventQueue.access$000(EventQueue.java:85) at
java.awt.EventQueue$1.run(EventQueue.java:643) at
java.awt.EventQueue$1.run(EventQueue.java:641) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at
java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
at java.awt.EventQueue$2.run(EventQueue.java:657) at
java.awt.EventQueue$2.run(EventQueue.java:655) at
java.security.AccessController.doPrivileged(Native Method) at
java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:654) at
java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
at
java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
at
java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
at
java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
at
java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Code
public class Analysis {
/**
* #param file
*/
public static void analyze(File file, int windowSize) {
ArrayList<String> splittedText = new ArrayList<String>();
System.out.println(windowSize);
StringBuffer buf = new StringBuffer();
if (file.exists()) {
try {
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis,
Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(isr);
String line = "";
while ((line = reader.readLine()) != null) {
buf.append(line);
splittedText.add(line);
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
String wholeString = buf.toString();
// for (int i = 0; i < wholeString.length(); i += (Babbles_GUI
// .WindowSize())) {
// splittedText.add(wholeString.substring(
// i,
// Math.min(i + (Babbles_GUI.WindowSize()),
// wholeString.length())));
// }
// for (int i = 0; (i < wholeString.length()-(Babbles_GUI.WindowSize())); i += Babbles_GUI.WindowSize()) {
// splittedText.add(wholeString.substring(i, Math.min(Babbles_GUI.WindowSize()+i, wholeString.length())));
// }
for(int i = 0; i<wholeString.length()-(windowSize); i++){
splittedText.add(wholeString.substring(i, i+windowSize));
}
System.out.println("error");
Set<String> unique = new HashSet<String>(splittedText);
for (String key : unique) {
Babbles_GUI.txtAnalysis.append(Collections.frequency(splittedText,
key) + "x " + key + "\t" + "\t");
}
Babbles_GUI.txtLog.append("Text analyzed with WindowSize "
+ windowSize + "\n");
}
}
Babbles_GUI
public class Babbles_GUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
JFileChooser fc1;
JButton btnFileCh;
JButton btnOutput;
JLabel lblBtnLabel;
static JTextArea txtLog;
static JTextArea txtOrig;
static JTextArea txtAnalysis;
JTextArea txtGenerated;
static JComboBox cbxWindowSize;
BorderLayout borderlayout;
JScrollPane ScrLog;
private JPanel pnWest;
private JPanel pnEast;
private JPanel pnNorth;
private JPanel pnCenter;
private JPanel pnSouth;
static int numberofchars;
public Babbles_GUI(String title) {
this.setTitle(title);
this.setSize(1200, 2400);
this.createUI();
this.setVisible(true);
this.setResizable(false);
this.pack();
this.setLocation(
(Toolkit.getDefaultToolkit().getScreenSize().width - this
.getSize().width) / 2, (Toolkit.getDefaultToolkit()
.getScreenSize().height - this.getSize().height) / 2);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
/**
*
*/
private void createUI() {
btnFileCh = new JButton("Open...");
// btnFileCh.setForeground(Color.BLACK);
btnFileCh.setFont(new Font("Monospaced", Font.PLAIN, 14));
btnFileCh.setPreferredSize(new Dimension(100, 20));
btnFileCh.addActionListener(this);
lblBtnLabel = new JLabel("Number of letters to shuffle: ");
lblBtnLabel.setFont(new Font("Monospaced", Font.BOLD, 14));
lblBtnLabel.setForeground(Color.WHITE);
txtLog = new JTextArea();
txtLog.setBackground(getBackground());
txtLog.setBackground(Color.BLACK);
txtLog.setForeground(Color.WHITE);
txtLog.setWrapStyleWord(true);
txtLog.setLineWrap(true);
txtLog.setFont(new Font("Monospaced", Font.PLAIN, 13));
JScrollPane spTxtlog = new JScrollPane(txtLog);
spTxtlog.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
spTxtlog.setBorder(BorderFactory.createMatteBorder(5, 0, 0, 0,
Color.RED));
txtOrig = new JTextArea();
txtOrig.setEditable(false);
txtOrig.setWrapStyleWord(true);
txtOrig.setLineWrap(true);
txtOrig.setBackground(Color.BLACK);
txtOrig.setForeground(Color.WHITE);
txtOrig.setFont(new Font("Monospaced", Font.PLAIN, 15));
txtOrig.setBorder(BorderFactory.createMatteBorder(10, 0, 0, 0,
Color.BLUE));
txtAnalysis = new JTextArea();
txtAnalysis.setEditable(false);
txtAnalysis.setWrapStyleWord(true);
txtAnalysis.setLineWrap(true);
txtAnalysis.setBackground(Color.BLACK);
txtAnalysis.setForeground(Color.WHITE);
txtAnalysis.setFont(new Font("Monospaced", Font.PLAIN, 15));
txtAnalysis.setBorder(new EmptyBorder(20, 0, 0, 20));
JScrollPane spTxtAn = new JScrollPane(txtAnalysis);
spTxtAn.setBorder(BorderFactory.createMatteBorder(10, 0, 0, 0,
Color.GREEN));
btnOutput = new JButton("Generate");
btnOutput.addActionListener(this);
btnOutput.setForeground(Color.BLACK);
btnOutput.setFont(new Font("Monospaced", Font.PLAIN, 14));
btnOutput.setPreferredSize(new Dimension(100, 20));
String[] item = { "WindowSize 1", "WindowSize 2", "WindowSize 3",
"WindowSize 4", "WindowSize 5", "WindowSize 6", "WindowSize 7" };
JComboBox cbxWindowSize = new JComboBox(item);
cbxWindowSize.setFont(new Font("Monospaced", Font.PLAIN, 14));
cbxWindowSize.setPreferredSize(new Dimension(200, 20));
Box bxLeft = Box.createHorizontalBox();
bxLeft.add(lblBtnLabel);
bxLeft.add(cbxWindowSize);
Box bxCenter = Box.createHorizontalBox();
bxCenter.add(btnFileCh);
Box bxRight = Box.createHorizontalBox();
bxRight.add(btnOutput);
txtGenerated = new JTextArea();
txtGenerated.setEditable(false);
txtGenerated.setBackground(Color.BLACK);
txtGenerated.setForeground(Color.WHITE);
txtGenerated.setBorder(BorderFactory.createMatteBorder(10, 0, 0, 0,
Color.YELLOW));
pnWest = new JPanel();
pnEast = new JPanel();
pnNorth = new JPanel();
pnCenter = new JPanel();
pnSouth = new JPanel();
pnWest.setLayout(new BorderLayout());
pnWest.setBorder(new EmptyBorder(0, 0, 0, 10));
pnWest.setBackground(Color.BLACK);
pnEast.setLayout(new BorderLayout());
pnEast.setBorder(new EmptyBorder(0, 10, 0, 0));
pnEast.setBackground(Color.BLACK);
pnNorth.setLayout(new FlowLayout(FlowLayout.LEFT));
pnNorth.setBackground(Color.BLACK);
pnCenter.setLayout(new BorderLayout());
pnCenter.setBackground(Color.BLACK);
pnSouth.setLayout(new BorderLayout());
try {
this.fc1 = new JFileChooser();
fc1.setFileFilter(new FileNameExtensionFilter(null, "txt"));
} catch (IllegalArgumentException e) {
txtOrig.append("");
txtLog.append("File format must be .txt" + "\n");
}
pnNorth.add(bxLeft);
pnNorth.add(bxCenter);
pnNorth.add(bxRight);
pnSouth.add(spTxtlog, BorderLayout.SOUTH);
pnWest.add(txtOrig, BorderLayout.CENTER);
pnWest.setPreferredSize(new Dimension(400, 700));
pnCenter.add(spTxtAn, BorderLayout.CENTER);
pnCenter.setPreferredSize(new Dimension(400, 700));
pnEast.add(txtGenerated, BorderLayout.CENTER);
pnEast.setPreferredSize(new Dimension(400, 700));
borderlayout = new BorderLayout();
borderlayout.setHgap(30);
borderlayout.setVgap(3);
setBackground(Color.BLACK);
getContentPane().setLayout(borderlayout);
getContentPane().add(pnEast, BorderLayout.EAST);
getContentPane().add(pnWest, BorderLayout.WEST);
getContentPane().add(pnNorth, BorderLayout.NORTH);
getContentPane().add(pnCenter, BorderLayout.CENTER);
getContentPane().add(pnSouth, BorderLayout.SOUTH);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnFileCh) {
int returnVal = fc1.showOpenDialog(Babbles_GUI.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc1.getSelectedFile();
txtLog.append(file.getName() + " opened" + "\n");
printOrigFile(file);
//DEBUG-STOP**********************************
Analysis.analyze(file, windowSize());
} else {
txtLog.append("Open command cancelled by user" + "\n");
}
txtLog.setCaretPosition(txtLog.getDocument().getLength());
}
}
public static void main(String[] args) {
new Babbles_GUI("Babbles Exercise David Huser");
}
/**
* #param file
* #return
*/
public String printOrigFile(File file) {
StringBuffer buf = new StringBuffer();
if (file.exists()) {
try {
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis,
Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(isr);
String line = "";
while ((line = reader.readLine()) != null) {
buf.append(line + "\n");
}
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
txtOrig.setText(buf.toString());
return (buf.toString());
}
public int windowSize() {
if (cbxWindowSize.getSelectedItem().equals("WindowSize 1")) {
numberofchars = 1;
} else if (cbxWindowSize.getSelectedItem().equals("WindowSize 2")) {
numberofchars = 2;
} else if (cbxWindowSize.getSelectedItem().equals("WindowSize 3")) {
numberofchars = 3;
} else if (cbxWindowSize.getSelectedItem().equals("WindowSize 4")) {
numberofchars = 4;
} else if (cbxWindowSize.getSelectedItem().equals("WindowSize 5")) {
numberofchars = 5;
} else if (cbxWindowSize.getSelectedItem().equals("WindowSize 6")) {
numberofchars = 6;
} else if (cbxWindowSize.getSelectedItem().equals("WindowSize 7")) {
numberofchars = 7;
}
return numberofchars;
}
}
You have an object that is null in windowSize(). Are you sure cbxWindowSize is initialized?
The other possibility is that there is no selected item. getSelectedItem() will return null in that case. You need to check this instead of immediately calling equals() on the result.
Edit:
String[] item = { "WindowSize 1", "WindowSize 2", "WindowSize 3",
"WindowSize 4", "WindowSize 5", "WindowSize 6", "WindowSize 7" };
JComboBox cbxWindowSize = new JComboBox(item);
This defines a new local variable and initializes it. The local variable is hiding the class variable with the same name. Remove JComboBox from the beginning of the line.