for loop for array only processing one element in java? - java

I can't figure out why whenever I cycle through my array using the for-loop it only produces one element (the first) to console? I'm pretty sure it's a rookie-mistake I'm looking over, so any tips and suggestions would help.
I'm making a program for fun that compares two strings typed in a text field and if they don't exist in the array it produces a JOPtionPane message on the contrary. It's for a battle-hack I may produce in the future for vBulletin forum, but I'm messing around with algorithms before I move to that step. Thanks, guys!
package battleoptionspart1;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.lang.*;
import javax.swing.border.*;
public class BattleOptionsPart1 extends JFrame{
JButton newthread, previewpost;
JRadioButton battle1;
JTextField postcount, oppA, oppB;
JLabel battle2, max;
JPanel panel;
String [] array = {"Bill","Tom","Wendy", "Paula"};
public BattleOptionsPart1 () {
panel = new JPanel();
Toolkit tool = Toolkit.getDefaultToolkit();
Dimension dim = tool.getScreenSize();
this.setSize(500, 500);
this.setTitle("Battle Options");
GridLayout grid = new GridLayout(0,1,2,2);
this.setLayout(grid);
newthread = new JButton("Post New Thread");
previewpost = new JButton("Preview Post");
postcount = new JTextField("", 4);
oppA = new JTextField("",10);
oppB = new JTextField("",10);
battle1 = new JRadioButton();
battle2 = new JLabel("Would you like to start a recorded battle?");
max = new JLabel("Enter max post count user must have to vote");
ListenForButton listen = new ListenForButton();
newthread.addActionListener(listen);
previewpost.addActionListener(listen);
JPanel opponents = new JPanel();
Border oppBorder = BorderFactory.createTitledBorder("Battlers");
opponents.setBorder(oppBorder);
opponents.add(oppA);
opponents.add(oppB);
JPanel battle = new JPanel();
Border battleBorder = BorderFactory.createTitledBorder("Start Battle");
battle.setBorder(battleBorder);
battle.add(battle1);
battle.add(battle2);
JPanel buttons = new JPanel();
Border buttonBorder = BorderFactory.createTitledBorder("Create Thread");
buttons.setBorder(buttonBorder);
buttons.add(newthread);
buttons.add(previewpost);
JPanel restriction = new JPanel();
Border resBorder = BorderFactory.createTitledBorder("Restrictions");
restriction.setBorder(buttonBorder);
restriction.add(postcount);
restriction.add(max);
this.add(opponents);
this.add(battle);
this.add(restriction);
this.add(buttons);
this.add(panel);
int xPos = (dim.width / 2) - (this.getWidth() / 2);
int yPos = (dim.height / 2) - (this.getHeight() / 2);
this.setLocation(xPos,yPos); //places form in the middle
this.setVisible(true); // users can see form
this.setResizable(false); //users can't resize the form
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class ListenForButton implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String compareA = oppA.getText();
String compareB = oppB.getText();
if (e.getSource() == newthread)
{
System.out.println(compareA + "\n" + compareB);
for(int j = 0; j < array.length; j++)
{
System.out.println(array[j]);
if(!compareA.equals(array[j]))
{
JOptionPane.showMessageDialog(null, compareA + " doesn't exist!", "Error Message", JOptionPane.ERROR_MESSAGE);
oppA.requestFocus();
break;
}
if (!compareB.equals(array[j]))
{
JOptionPane.showMessageDialog(null, compareB + " doesn't exist!", "Error Message", JOptionPane.ERROR_MESSAGE);
oppB.requestFocus();
break;
}
else
{
JOptionPane.showMessageDialog(null, "New thread created successfully!", "Success", JOptionPane.INFORMATION_MESSAGE);
break;
}
}
}
else if (e.getSource() == previewpost)
{
System.exit(0);
}
}
}
public static void main(String[] args) {
BattleOptionsPart1 battle = new BattleOptionsPart1();
}
}

In each of the possible options in your loop, you use break, which leaves the loop immediately. If you remove those statements, you'll process each object in the array.
If you want to check if there's a match, you need to go through every element and do your processing after going through the whole array. Here is an example for an array of type int:
boolean contains = false;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == searchKey)
{
contains = true;
break;
}
}

You're breaking out of the loop. with the break; command after the first array element

Related

Centering GUI's

I've created a simple guessing game with GUI's. The problem is, whenever I maximize my window, the whole GUI is stuck in the top middle. I would like to know how to center it in the middle and how to make it bigger. Here's the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GuessingGameNew implements ActionListener {
private final double VERSION = 2.3;
//Initializing Main Window and Difficulty Window
JFrame window = new JFrame("Guess The Number " + VERSION);
JFrame DiffFrame = new JFrame("Difficulty");
JButton btnNewGame = new JButton("New Game");
JButton btnInstruction = new JButton("Instructions");
JButton btnDifficulty = new JButton("Change Difficulty");
JButton btnAbout = new JButton("About");
JButton btnExit = new JButton("Exit");
JButton btnOK = new JButton("Ok");
JButton btnDiff[] = new JButton[6];
//Making Panel for Main Menu Buttons
JPanel pnlMainMenu = new JPanel();
//Making Panel for Difficulty Buttons
JPanel pnlDifficulty = new JPanel();
int diff = 10;
int tries;
int Secret;
int Guess;
int option = 0;
boolean Cancel = false;
GuessingGameNew() { //constructor
//Setting Main Window properties
window.setSize(400, 300);
window.setLocation(500, 260);
window.setLayout(new FlowLayout(FlowLayout.CENTER));
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DiffFrame.setSize(230, 210);
DiffFrame.setLocation(530, 230);
DiffFrame.setLayout(new BorderLayout());
//MainMenu Panel Layout and adding Main Menu Buttons
// GridLayout(int rows, int columns, int Horizontal_Gap, intVertical_Gap)
pnlMainMenu.setLayout(new GridLayout(5, 1, 2, 8));
pnlMainMenu.add(btnNewGame);
pnlMainMenu.add(btnInstruction);
pnlMainMenu.add(btnDifficulty);
pnlMainMenu.add(btnAbout);
pnlMainMenu.add(btnExit);
pnlMainMenu.setBackground(Color.red);
//Setting Layout for Difficulty Panel
pnlDifficulty.setLayout(new GridLayout(6, 1, 2, 2));
btnDiff[0] = new JButton("Very Easy (0 - 3)");
btnDiff[1] = new JButton("Easy (0 - 50)");
btnDiff[2] = new JButton("Medium (0 - 100)");
btnDiff[3] = new JButton("Hard (0 - 500)");
btnDiff[4] = new JButton("Very Hard (0 - 1000)");
btnDiff[5] = new JButton("Custom (0 - ?)");
btnNewGame.addActionListener(this);
btnInstruction.addActionListener(this);
btnDifficulty.addActionListener(this);
btnAbout.addActionListener(this);
btnExit.addActionListener(this);
btnOK.addActionListener(this);
for(int i=0; i<6; i++) {
btnDiff[i].addActionListener(this);
pnlDifficulty.add(btnDiff[i]);
}
window.add(pnlMainMenu);
window.setVisible(true);
}
public void actionPerformed(ActionEvent click) {
System.out.println("Action Performed");
if(click.getSource() == btnNewGame) {
NewGame();
}
if(click.getSource() == btnExit) {
option = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?", "Exit Game" ,JOptionPane.YES_NO_OPTION);
if(option == JOptionPane.YES_OPTION)
System.exit(0);
}
if(click.getSource() == btnInstruction) {
JOptionPane.showMessageDialog(null,
"Game:" + "\nClick New Game to start a new game.\nGuess a number between 0 and the selected number. Keep Guessing until you get it correct."
+ "\n\nDifficulty:" + "\nYou can change the difficulty of the game\n in the Main Menu to a Custom range or a \npreset range."
, "Instructions", JOptionPane.INFORMATION_MESSAGE);
}
if(click.getSource() == btnAbout) {
JOptionPane.showMessageDialog(null,JOptionPane.INFORMATION_MESSAGE);
}
if(click.getSource() == btnDifficulty) {
Change_Difficulty();
}
for(int i=0; i<6; i++) {
if(click.getSource() == btnDiff[i]) {
if(click.getSource() == btnDiff[0])
diff = 3;
if(click.getSource() == btnDiff[1])
diff = 50;
if(click.getSource() == btnDiff[2])
diff = 100;
if(click.getSource() == btnDiff[3])
diff = 500;
if(click.getSource() == btnDiff[4])
diff = 1000;
if(click.getSource() == btnDiff[5])
diff = Custom();
DiffFrame.setVisible(false);
}
}
}
public void NewGame() {
tries = 1;
Guess = 101;
Secret = (int)((Math.random()) * (diff + 1));
Cancel = false;
while(Guess != Secret) {
try {
if(tries == 1) {
Guess = Integer.parseInt(JOptionPane.showInputDialog(null, "Try: 1" + "\nGuess a number between 0 and " + diff, "Guess?", JOptionPane.PLAIN_MESSAGE));
tries++;
} else {
if(Guess > Secret)
Guess = Integer.parseInt(JOptionPane.showInputDialog(null, "Try: " + tries + "\n" + Guess + "\nGuess Lower..."));
else if(Guess < Secret)
Guess = Integer.parseInt(JOptionPane.showInputDialog(null, "Try: " + tries + "\n" + Guess + "\nGuess Higher..."));
tries++;
}
} catch(NumberFormatException e) {
if(e.getMessage() == "null") {
option = JOptionPane.showConfirmDialog(null, "Are you sure you want to go back to the Main Menu?", "Cancel?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if(option == JOptionPane.YES_OPTION) {
Cancel = true;
break;
}
}
JOptionPane.showMessageDialog(null, "Error: " + e.getMessage() + "\nEnter whole numbers only!");
}
}
if(!Cancel) {
tries--;
JOptionPane.showMessageDialog(null, Guess + " is Correct!!\nYou WON in " + tries + " tries.", "Winner", JOptionPane.INFORMATION_MESSAGE);
option = JOptionPane.showConfirmDialog(null, "Do you want to try again?", "Try Again?", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);
if(option == JOptionPane.YES_OPTION)
NewGame();
}
}
public void Change_Difficulty() {
DiffFrame.add(pnlDifficulty, BorderLayout.CENTER);
DiffFrame.setVisible(true);
}
public int Custom() {
try {
diff = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter a number that you want to be the range (0 to ?)", diff));
} catch(NumberFormatException e) {
}
return diff;
}
public static void main(String[] args) {
new GuessingGameNew();
}
}
You are setting a FlowLayout:
window.setLayout(new FlowLayout(FlowLayout.CENTER));
This layout has no notion of vertical alignment, it will only wrap its contents when out of horizontal space. Setting the alignment applies only to horizontal behavior.
I would like to know how to center it in the middle and how to make it bigger.
If you delete that line then the default CENTER position of BorderLayout will be used, which centers and stretches the component both horizontally and vertically:
The default Layout Manager for a JFrame is the BorderLayout. Calling window.getContentPane().add(component); or if you feel like typing more, then window.getContentPane().add(component, BorderLayout.CENTER); adds your component to the center of the window. Also, as a tip, do study Layout Managers deeply. You can build really cool stuff with the proper understanding of how they work, what they do, and which one is more appropriate for which scenario.

How to fill JComboBox after user fills necessary text fields?

I want to add a JComboBox to my main panel and fill it with an ArrayList I made in a different method named rectSizeList (which right now prints the ArrayList to the console), this method gets its parameters from another static method named actionPerformed. I cant figure a way to take the filled array after user input to fill my ComboBox. Any help will be appreciated.
All comment is this format are to aid question:
/*
* Like so
*
*/
All other comments are to help whomever my want to compile and run, so that they might understand what is going on.
Main class
import javax.swing.*;
public class ductulatorApp
{
public static void main(String[] args)
{
JFrame frame = new DuctulatorFrame();
frame.setVisible(true);
}
}
Frame class
import javax.swing.*;
import java.awt.*;
public class DuctulatorFrame extends JFrame
{
private static final long serialVersionUID = 1L;
public DuctulatorFrame()
{
setTitle("Test Scores");
setSize(267, 200);
centerWindow(this);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new DuctulatorPanel();
this.add(panel);
}
private void centerWindow(Window w)
{
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
setLocation((d.width-w.getWidth())/2, (d.height-w.getHeight())/2);
}
}
Panel class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.ArrayList;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class DuctulatorPanel extends JPanel implements ActionListener
{
private static final long serialVersionUID = 1L;
private JTextField staticTextField,
cfmTextField,
rductTextField,
sqductTextField;
private JLabel staticLabel,
cfmLabel,
rductLabel,
sqductLabel;
private JButton calculateButton,
exitButton,
clearButton;
private JComboBox ductSizes; //JComboBox instance
private String[] ductList; //Array to fill JComboBox
double staticP; //static pressure entered by user
double cfm; //cfm entered by user
double deSQ;
double de; //round duct diameter
double pi = 3.14;
double ca; //round duct surface area
double radious;
double sqrA; //rectangular duct area
//two sides of rectangular duct
double a = 4;
double b = 4;
String squareduct;
public DuctulatorPanel()
{
// Creates main panel for labels and text fields
JPanel displayPanel = new JPanel();
displayPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
staticLabel = new JLabel("Static pressure:");
displayPanel.add(staticLabel);
staticTextField = new JTextField(10);
displayPanel.add(staticTextField);
cfmLabel = new JLabel(" CFM:");
displayPanel.add(cfmLabel);
cfmTextField = new JTextField(10);
displayPanel.add(cfmTextField);
rductLabel = new JLabel("Round Duct:");
displayPanel.add(rductLabel);
rductTextField = new JTextField(15);
rductTextField.setEditable(false);
rductTextField.setFocusable(false);
displayPanel.add(rductTextField);
sqductLabel = new JLabel("Square Duct:");
displayPanel.add(sqductLabel);
/*
* This is where I want to add my JComboBox problem is I want to populate ductList arr
* with the array inside rectSizeList(int number) BELOW
* right now this method only prints my array to the console
* this method takes its parameters from the value assigned to
* actionperformed(ActionEvent e)
* below is comboBox commented out
*/
//ductList = new String[list.size]; THIS IS ASSUMING I COULD SOME HOW TRANSFER
//ductList = list.toArray(ductList); ARRAYLIST UP HERE AND NAME IT LIST AND USE IT
//ductSizes = new JComboBox(ductList);
//ductSizes.setSelectedIndex(1);
//displayPanel.add(ductSizes);
sqductTextField = new JTextField(10);
sqductTextField.setEditable(false);
sqductTextField.setFocusable(false);
displayPanel.add(sqductTextField);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
calculateButton = new JButton("Calculate");
calculateButton.addActionListener(this);
buttonPanel.add(calculateButton);
clearButton = new JButton("Clear");
clearButton.addActionListener(this);
buttonPanel.add(clearButton);
exitButton = new JButton("Exit");
exitButton.addActionListener(this);
buttonPanel.add(exitButton);
this.setLayout(new BorderLayout());
this.add(displayPanel, BorderLayout.CENTER);
this.add(buttonPanel, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e)
{
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(1);
Object source = e.getSource();
if(source == exitButton)System.exit(0);
else if(source == clearButton)
{
staticTextField.setText("");
cfmTextField.setText("");
rductTextField.setText("");
sqductTextField.setText("");
staticP = 0;
cfm = 0;
deSQ = 0;
}
else if(source == calculateButton)
{
try
{
staticP = Double.parseDouble(staticTextField.getText());
cfm = Double.parseDouble(cfmTextField.getText());
}
catch(NumberFormatException nfe)
{
staticTextField.setText("Invalid input");
staticP = 0;
cfm = 0;
deSQ = 0;
de = 0;
}
deSQ = staticP * (0.109136 * Math.pow(cfm, 1.9)); //Calculate round duct
de = Math.pow(deSQ, 0.199) * 2.5; //diameter
// Calculate round duct surface area
radious = de/2;
ca = (radious * radious) * pi;
ca = (int)ca;
rectSizeList((int)ca);
double i = 0;
for(i=0; i<ca; i++)
{
a = a + 0.5;
b = b + 0.5;
i = a * b; // convert round duct to rectangular duct
}
sqrA = i;
a = (int)a;
b = (int)b;
rductTextField.setText(number.format(de));
squareduct = (a + " x " + b);
sqductTextField.setText(squareduct);
}
}
public ArrayList<String> rectSizeList(int number)
{
if (number <= 0) throw new IllegalArgumentException("The number should be greater than 0.");
int i = 0;
int j = 0;
/*
* This is the array list I am hoping to use in order to fill array for
* comboBox
*/
ArrayList<String> rectangularDucts = new ArrayList<String>(); //Create array for rectangular duct
// Fill array for rectangular duct using nested for loop
/*
* If statement will ensure the result is with in range of surface
* area of duct
*/
for(i=4; i<=50; i++)
{
for(j=4; j<=50; j++)
{
if(number == i*j || (i*j)+1 == number || (i*j)-2 == number)
{
rectangularDucts.add(i + " x " + j);
}
}
if(number == i*j || (i*j)+1 == number || (i*j)-2 == number)
{
rectangularDucts.add(i + " x " + j);
}
}
System.out.println(rectangularDucts);
return rectangularDucts;
}
}
I think that your problem is easily solved with just a DefaultComboBoxModel object, or in your situation (I guess), a DefaultComboBoxModel<String> object. Give your class this field, create your JComboBox with this as its model, by passing it into the constructor, and then fill this model object as the need arises.
For example:
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class ComboModelEg extends JPanel {
private DefaultComboBoxModel<String> comboModel = new DefaultComboBoxModel<>();
private JComboBox<String> comboBox = new JComboBox<>(comboModel);
private JTextField textField = new JTextField(5);
public ComboModelEg() {
// so combo box is wide enough
comboBox.setPrototypeDisplayValue(" ");
add(comboBox);
add(textField);
add(new JButton(new AddToComboAction("Add Text", KeyEvent.VK_A)));
}
// AbstractAction is like a *super* ActionListener
private class AddToComboAction extends AbstractAction {
public AddToComboAction(String name, int mnemonic) {
super(name); // button's text
putValue(MNEMONIC_KEY, mnemonic); // button's mnemonic key
}
#Override
public void actionPerformed(ActionEvent e) {
String text = textField.getText(); //get text from text field
comboModel.addElement(text); // and put it into combo box's model
}
}
private static void createAndShowGui() {
ComboModelEg mainPanel = new ComboModelEg();
JFrame frame = new JFrame("ComboModelEg");
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();
}
});
}
}
Translated to your code, it could look something like:
for (i = 4; i <= 50; i++) {
for (j = 4; j <= 50; j++) {
if (number == i * j || (i * j) + 1 == number
|| (i * j) - 2 == number) {
// rectangularDucts.add(i + " x " + j); //!!
comboModel.addElement(i + " x " + j); //!!
}
}
if (number == i * j || (i * j) + 1 == number || (i * j) - 2 == number) {
// rectangularDucts.add(i + " x " + j);
comboModel.addElement(i + " x " + j); //!!
}
}
this is how i do it
ArrayList<String> myList = new ArrayList<>();
//some code to populate the list
jComboBox.removeAllItems();
for(int i=0;i<myList.size();i++){
jComboBox.addItem(myList.get(i));
}

Checking to see if a JtextField is NOT equal to saved arrays

Hey guys I'm very new to Java and started in July with an intro to Java class.
I am currently working on a project which is a translator with arrays. The main applet shows 10 words in english that when typed into a JTextField outputs the spanish translation of that work. And vice versa. The program also shows a picture associated with that word.
The program is all done in that case, the only portion I am missing currently is that if a user inputs ANY other word than the 20 given words (10 spanish and 10 english) the JTextArea where translations are displayed is supposed to show "That word is not in the dictionary".
I'm having issues creating an ELSE statement that shows this error message. Here is the complete code. I'm not sure what to do to make it so eg
if (textFieldWord.!equals(englishWords[english])){
translate.setText("That word is not in the Dictionary");}
Here is the complete code - - - -
import java.awt.*;
import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class DictionaryArrays extends JApplet implements ActionListener{
String[] spanishWords = {"biblioteca","reloj",
"alarma", "volcan", "ventana",
"autobus", "raton", "lago", "vaca", "encendedor"};
String[] englishWords = {"library", "clock", "alarm",
"volcano", "window", "bus", "rat",
"lake","cow","lighter"};
String textFieldWord;
Image[] photos;
ImageIcon icon;
ImageIcon icontwo;
JButton getTranslation;
JTextField entry;
JLabel imageviewer;
TextArea translate;
static int defaultX = 10;
static int defaultY = 10;
static int defaultW = 780;
static int defaultH = 50;
public void init() {
photos = new Image[10];
photos[0] = getImage(getCodeBase(), "library.jpg");
photos[1] = getImage(getCodeBase(), "clock.jpg");
photos[2] = getImage(getCodeBase(), "alarm.jpg");
photos[3] = getImage(getCodeBase(), "volcano.jpg");
photos[4] = getImage(getCodeBase(), "window.jpg");
photos[5] = getImage(getCodeBase(), "bus.jpg");
photos[6] = getImage(getCodeBase(), "rat.jpg");
photos[7] = getImage(getCodeBase(), "lake.jpg");
photos[8] = getImage(getCodeBase(), "cow.jpg");
photos[9] = getImage(getCodeBase(), "lighter.jpg");
final JPanel outer = new JPanel(new BorderLayout());
JPanel inner = new JPanel(new BorderLayout());
JPanel viewer = new JPanel(new BorderLayout());
JPanel visualviewer = new JPanel(new BorderLayout());
// here is the main component we want to see
// when the outer panel is added to the null layout
//JButton toSpanish = new JButton("English to Spanish");
//JButton toEnglish = new JButton("Spanish to English");
final JLabel list = new JLabel("<HTML><FONT COLOR=RED>English</FONT> - library, clock, alarm, volcano, window, bus, rat, lake, cow, lighter"
+"<BR><FONT COLOR=RED>Spanish</FONT> - biblioteca, reloj, alarma, volcan, ventana, autobus, raton, lago, vaca, encendedor<BR>");
translate = new TextArea("Your translation will show here");
imageviewer = new JLabel(icon);
viewer.add("West",translate);
visualviewer.add("East",imageviewer);
inner.add("Center",list);
//inner.add("West",toSpanish);
//inner.add("East", toEnglish);
outer.add("Center", inner);
JPanel c = (JPanel)getContentPane();
final JPanel nullLayoutPanel = new JPanel();
nullLayoutPanel.setLayout(null);
c.add("Center", nullLayoutPanel);
// set the bounds of the panels manually
nullLayoutPanel.add(outer);
nullLayoutPanel.add(viewer);
nullLayoutPanel.add(visualviewer);
outer.setBounds(defaultX, defaultY, defaultW, defaultH);
viewer.setBounds(20, 75, 300, 300);
visualviewer.setBounds(485, 75, 300, 300);
JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
entry = new JTextField("Enter English or Spanish word to translate here");
entry.addActionListener(this);
entry.addMouseListener(new MouseAdapter(){
#Override
public void mouseClicked(MouseEvent e){
entry.setText("");
}});
getTranslation = new JButton("Translate");
getTranslation.addActionListener(this);
controlPanel.add(entry);
controlPanel.add(getTranslation);
c.add("South", controlPanel);
viewer.setBackground(Color.blue);
controlPanel.setBackground(Color.red);
inner.setBackground(Color.yellow);
visualviewer.setBackground(Color.black);
outer.setBackground(Color.black);
}
public void paint(Graphics g) {
super.paint(g);
}
public void actionPerformed (ActionEvent ae){
if(ae.getSource()==getTranslation){
textFieldWord=(entry.getText().toLowerCase());
for (int english = 0; english < spanishWords.length; english++){
if (textFieldWord.equals(englishWords[english])){
translate.setText(spanishWords[english]);
icon= new ImageIcon(photos[english]);
imageviewer.setIcon(icon);
break;
}
}
for (int spanish = 0; spanish < englishWords.length; spanish++){
if (textFieldWord.equals(spanishWords[spanish])){
translate.setText(englishWords[spanish]);
icontwo= new ImageIcon(photos[spanish]);
imageviewer.setIcon(icontwo);
break;
}
}
}
}
}
Any help would be appreciated guys. If the top paragraph was TLDR. Im trying to make it so typing in ANY other word in the JTextField (entry) other than the 10 english and 10 spanish words will output an error msg of "That word is not in the Dictionary" in the TextArea (translate)
This is (obviously) wrong...
if (textFieldWord.!equals(englishWords[english])){
and should be...
if (!textFieldWord.equals(englishWords[english])){
Try and think of it this way, String#equals returns a boolean, you want to invert the result of this method call, it would be the same as using something like...
boolean doesEqual = textFieldWord.equals(englishWords[english]);
if (!doesEqual) {...
You need to evaluate the result of the method call, but in oder to make that call, the syntax must be [object].[method], therefore, in order to invert the value, you must complete the method call first, then apply the modifier to it ... ! ([object].[method])
Updated...
Now having said all that, let's look at the problem from a different perspective...
You need to find a matching word, in order to do that, you must, at worse case, search the entire array. Until you've search the entire array, you don't know if a match exists.
This means we could use a separate if-else statement to manage the updating of the output, for example...
String translatedWord = null;
int foundIndex = -1;
for (int english = 0; english < spanishWords.length; english++){
if (textFieldWord.equals(englishWords[english])){
translatedWord = englishWords[english];
foundIndex = english;
break;
}
}
if (translatedWord != null) {
translate.setText(translatedWord);
icon= new ImageIcon(photos[foundIndex]);
imageviewer.setIcon(icon);
} else {
translate.setText("That word is not in the Dictionary");
}
translatedWord = null;
for (int spanish = 0; spanish < englishWords.length; spanish++){
if (textFieldWord.equals(spanishWords[spanish])){
translatedWord = englishWords[english];
foundIndex = spanish;
break;
}
}
if (translatedWord != null) {
translate.setText(translatedWord);
icontwo= new ImageIcon(photos[foundIndex]);
imageviewer.setIcon(icontwo);
} else {
translate.setText("That word is not in the Dictionary");
}
Basically, all this does is sets the translatedWord to a non null value when it finds a match in either of the arrays. In this, you want to display the results, else you want to display the error message...
Equally, you could merge your current approach with the above, so when you find a work, you update the output, but also check the state of the translatedWord variable, displaying the error message if it is null...
String translatedWord = null;
for (int english = 0; english < spanishWords.length; english++){
if (textFieldWord.equals(englishWords[english])){
translatedWord = spanishWords[english];
translate.setText(translatedWord);
icon= new ImageIcon(photos[english]);
imageviewer.setIcon(icon);
break;
}
}
if (translatedWord == null) {
translate.setText("That word is not in the Dictionary");
}
translatedWord = null;
for (int spanish = 0; spanish < englishWords.length; spanish++){
if (textFieldWord.equals(spanishWords[spanish])){
translatedWord = englishWords[spanish];
translate.setText(translatedWord);
icontwo= new ImageIcon(photos[spanish]);
imageviewer.setIcon(icontwo);
break;
}
}
if (translatedWord == null) {
translate.setText("That word is not in the Dictionary");
}
Updated
Okay, you have a logic problem. You're never quite sure which direction you are translating to.
The following basically changes the follow by not translating the work from Spanish IF it was translated to English
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == getTranslation) {
textFieldWord = (entry.getText().toLowerCase());
translate.setText(null);
String translatedWord = null;
for (int english = 0; english < spanishWords.length; english++) {
if (textFieldWord.equals(englishWords[english])) {
translatedWord = spanishWords[english];
translate.append(translatedWord + "\n");
icon = new ImageIcon(photos[english]);
imageviewer.setIcon(icon);
break;
}
}
if (translatedWord == null) {
for (int spanish = 0; spanish < englishWords.length; spanish++) {
if (textFieldWord.equals(spanishWords[spanish])) {
translatedWord = englishWords[spanish];
translate.append(translatedWord + "\n");
icontwo = new ImageIcon(photos[spanish]);
imageviewer.setIcon(icontwo);
break;
}
}
}
if (translatedWord == null) {
translate.append("A Spanish-English match is not in the Dictionary\n");
}
}
}
Now, I would suggest that you replace TextArea with a JTextArea, but you will need to wrap it in a JScrollPane
translate = new JTextArea("Your translation will show here");
viewer.add("West", new JScrollPane(translate));
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
Basically, this was really painful to try and use for this very reason...

Program freezing(not responding) after button click no a Java app

Ok so I'm building to show students how a loop goes through an array, I have added 2 images to help explain and the code, the first is the result I get after I click go then it freezes . The Second image is what I'd like it to do after you put in the values of 1 in start, 15 in stop, 3 in step and click the Go Button. And then to be cleared on the click of Clear button. I think they probably related. Can anyone see the problem? Thanks in advanced!
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import javax.swing.JOptionPane;
public class Checkerboard extends Frame implements ActionListener
{
int[] blocksTextField = new int[15];
Panel blocksPanel = new Panel();
TextArea blocksDisplay[] = new TextArea[16];
TextField start = new TextField (3);
TextField stop = new TextField (3);
TextField step = new TextField (3);
//Colors
Color Red = new Color(255, 90, 90);
Color Green = new Color(140, 215, 40);
Color white = new Color(255,255,255);
//textField ints
int inputStart;
int inputStop;
int inputStep;
//Lables
Label custStartLabel = new Label ("Start : ");
Label custStopLabel = new Label ("Stop : ");
Label custStepLabel = new Label ("Step : ");
//Buttons
Button goButton = new Button("Go");
Button clearButton = new Button("Clear");
//panel for input textFields and lables
Panel textInputPanel = new Panel();
//Panel for buttons
Panel buttonPanel = new Panel();
public Checkerboard()
{//constructor method
//set the 3 input textFields to 0
inputStart = 0;
inputStop = 0;
inputStep = 0;
//set Layouts for frame and three panels
this.setLayout(new BorderLayout());
//grid layout (row,col,horgap,vertgap)
blocksPanel.setLayout(new GridLayout(4,4,10,10));
textInputPanel.setLayout(new GridLayout(2,3,20,10));
buttonPanel.setLayout(new FlowLayout());
//setEditable()
//setText()
//add components to blocks panel
for (int i = 0; i<16; i++)
{
blocksDisplay[i] = new TextArea(null,3,5,3);
if(i<6)
blocksDisplay[i].setText(" " +i);
else
blocksDisplay[i].setText(" " +i);
blocksDisplay[i].setEditable(false);
// blocksDisplay[i].setBackground(Red);
blocksPanel.add(blocksDisplay[i]);
}//end for
//add componets to panels
//add text fields
textInputPanel.add(start);
textInputPanel.add(stop);
textInputPanel.add(step);
//add lables
textInputPanel.add(custStartLabel);
textInputPanel.add(custStopLabel);
textInputPanel.add(custStepLabel);
//add button to panel
buttonPanel.add(goButton);
buttonPanel.add(clearButton);
//ADD ACTION LISTENRS TO BUTTONS (!IMPORTANT)
goButton.addActionListener(this);
clearButton.addActionListener(this);
add(blocksPanel, BorderLayout.NORTH);
add(textInputPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
//overridding the windowcClosing() method will allow the user to clisk the Close button
addWindowListener(
new WindowAdapter()
{
public void windowCloseing(WindowEvent e)
{
System.exit(0);
}
}
);
}//end of constructor method
public void actionPerformed(ActionEvent e)
{
//if & else if to see what button clicked and pull user input
if(e.getSource() == goButton) //if go clicked ...
{
System.out.println("go clicked");
try{
String inputStart = start.getText();
int varStart = Integer.parseInt(inputStart);
if (varStart<=0 || varStart>=15 )throw new NumberFormatException();
System.out.println("start = " + varStart);
// roomDisplay[available].setBackground(lightRed);
String inputStop = stop.getText();
int varStop = Integer.parseInt(inputStop);
if (varStop<=0 || varStart>=15 )throw new NumberFormatException();
System.out.println("stop = " + varStop);
String inputStep = step.getText();
int varStep = Integer.parseInt(inputStep);
if (varStep<=0 || varStep>=15 )throw new NumberFormatException();
System.out.println("step = " + varStep);
for (int i = varStart; i<varStop; varStep++)//ADD WHILE LOOP
{
blocksDisplay[i].setBackground(Red);
blocksDisplay[i].setText(" " +i);
}
}
catch (NumberFormatException ex)
{
JOptionPane.showMessageDialog(null, "You must enter a Start, Stop and Step value greater than 0 and less than 15",
"Error",JOptionPane.ERROR_MESSAGE);
}
}
else if(e.getSource() == clearButton ) //else if clear clicked ...
{
System.out.println("clear clicked");
}
//int available = room.bookRoom(smoking.getState());
//if (available > 0)//Rooms is available
}//end action performed method
public static void main(String[]args)
{
Checkerboard frame = new Checkerboard ();
frame.setBounds(50, 100, 300, 410);//changed size to make text feilds full charater size
frame.setTitle("Checkerboarder Array");
frame.setVisible(true);
}//end of main method
}
The problem is your loop: your loop variable name is i but you change the varStep variable instead of i so basically the loop variable never changes and thus the exit condition will never be true.
I believe you want to step i with varStep, so change your loop to:
for (int i = varStart; i<varStop; i += varStep)
// stuff inside loop
Take a look at this loop.
for (int i = varStart; i<varStop; varStep++)//ADD WHILE LOOP
{
blocksDisplay[i].setBackground(Red);
blocksDisplay[i].setText(" " +i);
}
It ends when i >= varStop, but neither i nor varStop change as a consequence of its execution, so it can never stop. You only increment varStep.
I think you want to increment i by varStep on each iteration instead, i.e. i += varStep
You use varStep++ in your for loop. I think you meant to do i+varStep.
The application freezes because you're never increasing i, resulting in an endless loop.

Issue with displaying information on a program using swing, JButtons,etc

I'm making a multiplication table using swing.Its basically made up of JButtons. The table is formed from input from the user. The user selects the size of the table by entering a number. The last thing i need to do with this is create a heading that displays the numbers of the table created. Here is my sample code, if you run it, you'll see that its done for the vertical numbers. How can i get the numbers above and properly formatted to represent each column. Thank you.
package lab7;
import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class GUIMultiplicationTable{
JFrame theFrame;
int number = 0;
JPanel panel, answerPanel, topPanel, leftPanel;
JLabel answerLabel, topLabel, leftLabel;
private void createAndShowGui(){
String x;
do{
x = JOptionPane.showInputDialog(null, "Enter the number");
number = Integer.parseInt(x);
}while (number <= 0);
theFrame = new JFrame("Multiplication Table");
panel = new JPanel(new GridLayout(number, number));
answerPanel = new JPanel();
answerLabel = new JLabel();
topPanel = new JPanel();
topLabel = new JLabel();
leftPanel = new JPanel();
leftLabel = new JLabel();
for (int i = 0; i < number; i++){
JLabel blah = new JLabel(Integer.toString(i + 1));
panel.add(blah);//add center to label
for (int j = 0; j < number; j++){
JButton button = new JButton();
if (i == 0){
button.setText(String.valueOf(j + 1));
}
if (j == 0){
button.setText(String.valueOf(i + 1));
}
for (int k = 1; k < number; k++)
{
if (i == k)
{
button.setText(String.valueOf((j + 1) * (k + 1)));
}
}
button.addActionListener(new ButtonsTableActionListener(i, j));
panel.add(button);
}
}
answerPanel.add(answerLabel);
theFrame.add(answerPanel, BorderLayout.SOUTH);
topPanel.add(topLabel);
theFrame.add(topPanel, BorderLayout.NORTH);
theFrame.add(panel);
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theFrame.pack();
theFrame.setLocationRelativeTo(null);
theFrame.setVisible(true);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
GUIMultiplicationTable h = new GUIMultiplicationTable();
h.createAndShowGui();
}
});
}
private class ButtonsTableActionListener implements ActionListener{
private int theRow, theColumn;
public ButtonsTableActionListener(int row, int column){
theRow = row;
theColumn = column;
}
#Override
public void actionPerformed(ActionEvent e){
int value = (theRow + 1) * (theColumn + 1);
answerLabel.setText("The value is: " + value + ".\nI got that by multiplying \n" + (theRow + 1) + "x" + (theColumn + 1));
}
};
}
An easy way to do this is to store the position of the button in the ActionListener, you can accomplish this by making your own class extending ActionListener, instead of doing an anonymous class. This way the code executed by the button will already have the information it needs to accomplish whatever you want.
Also you don't need the array of buttons, just add a button in the panel at a time, and at the same time add the actionListener.
This is your code cleaned up and working properly. Now, instead of showing a dialog do whatever you want to do.
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class GUIMultiplicationTable
{
JFrame theFrame;
int number = 0;
JPanel panel;
private void createAndShowGui()
{
String x;
do
{
x = JOptionPane.showInputDialog(null, "Enter the number");
number = Integer.parseInt(x);
} while (number <= 0);
theFrame = new JFrame("Multiplication Table");
panel = new JPanel(new GridLayout(number, number));
for (int i = 0; i < number; i++)
{
for (int j = 0; j < number; j++)
{
JButton button = new JButton();
if (i == 0)
{
button.setText(String.valueOf(j + 1));
}
if (j == 0)
{
button.setText(String.valueOf(i + 1));
}
for (int k = 1; k < number; k++)
{
if (i == k)
{
button.setText(String.valueOf((j + 1) * (k + 1)));
}
}
button.addActionListener(new ButtonsTableActionListener(i, j));
panel.add(button);
}
}
theFrame.add(panel);
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theFrame.pack();
theFrame.setLocationRelativeTo(null);
theFrame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
GUIMultiplicationTable h = new GUIMultiplicationTable();
h.createAndShowGui();
}
});
}
private class ButtonsTableActionListener implements ActionListener
{
private int _row, _column;
public ButtonsTableActionListener(int row, int column)
{
_row = row;
_column = column;
}
#Override
public void actionPerformed(ActionEvent e)
{
// /do something
int value = (_row + 1) * (_column + 1);
String message = "I'm the button in the position (" + _row + ", " + _column + ")\nMy value is " + value + " = " + (_row + 1) + "*" + (_column + 1);
JOptionPane.showMessageDialog(theFrame, message);
}
};
}
Everything you need to do is just putting a JLabel somewhere.
final JLabel resultLabel = new JLabel("Select a button!");
Note that it should be final to be able to use it in the ActionListener. In the ActionListener you already had the right way, just look at these few lines to make it happen:
ActionListener first = new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
for(int i = 0; i < number; i++){
for(int j = 0; j < number; j++){
if(buttons[i][j] == e.getSource()){
// write the equation to the label
resultLabel.setText(buttons[i][j].getText()
+ " = " + (i+1) + " * "
+ (j+1));
// since you found the button you can now break
break;
}
}
}
}
};
Note the i+1 and j+1. The buttons are indexed from 0 to number-1, so the button at (0,0) actually shows the result of 1*1.
This is also important for your next two lines of code:
// you used i=1 and j=1, but you have to start with 0 to make it work for all buttons
for(int i = 0; i < number; i++){
for(int j = 0; j < number; j++){
buttons[i][j].addActionListener(first);
}
}
At a last step you also have to show the the label. If you just add it to the frame, as you do with the panel, you will see that you will not see it.
theFrame.add(resultLabel);
theFrame.add(panel);
The problem is that theFrame doesn't have a layoutmanager yet. So use a new Layout here as well:
theFrame.setLayout(new GridLayout(2,1));
Of course there will be better choices or some nice tweeks to make the layout more beautiful.
So as in sum how to change your code from top to bottom:
set a Layout for theFrame
create a new JLabel for the result of the click, make it final
set the label's text in the actionPerformed() method
add the label to theFrame
You can also consider putting the Label into a new JPanel and add that Panel to theFrame.
The loop in your actionListener is not required, the source of the event is the button that triggered it, so you can simply do...
JButton source = (JButton) e.getSource();
JOptionPane.showMessageDialog(theFrame, source.getText());
Instead.
Now having said that, I would, personally, use some kind of Map to link the JButton to the value, removing the need to have to try and cast the text of the button back to a numeric value (which I believe would be your next step), or store other information you might need to work with for the button (such as the values required to produce the answer)...
private Map<JButton, int[]> answers = new HashMap<JButton, int[]>(25);
//...
for(int i = 0; i < number; i++){
for(int j = 0; j < number; j++){
buttons[i][j] = new JButton();
if(i == 0) {
buttons[i][j].setText(String.valueOf(j+1));
}
if(j == 0) {
buttons[i][j].setText(String.valueOf(i+1));
}
for(int k = 1; k < number; k++){
if(i == k){
buttons[i][j].setText(String.valueOf((j+1) * (k+1)));
}
}
panel.add(buttons[i][j]);
// Store the answer here...
answers.put(buttons[i][j], new int[]{i, j});
}
}
//...
public void actionPerformed(ActionEvent evt) {
JButton source = (JButton) e.getSource();
int[] answer = answers.get(source);
JPanel panel = new JPanel();
JTextField[] fields = new JTextField[]{
new JTextField(2),
new JTextField(2)
};
panel.add(fields[0]);
panel.add(new JLabel("x"));
panel.add(fields[1]);
panel.add(new JLabel(" = " + source.getText()));
JOptionPane.showMessageDialog(theFrame, panel);
// check the values of the fields against the
// values of the answer
}

Categories

Resources