I am trying to make an executable JButton (which opens a new window)radiobutton is chosen and the textfiled is filled within a specific range (the textfield should be from 1800 to 2013) . For the radiobuttons I made a default choise for now, but I cannot figure out how can I return a warning that the textfield should be filled (a number between 1800 and 2013) and if it is there then it run the program.
EDIT:
So if my code is:
JFrame ....
JPanel ....
JTextField txt = new JTextField();
JButton button = new JButton("run");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
//Do things here
}
});
txt.addFocusListener(new FocusListener() {
....
}
how can I use the ItemStateListener. Should I define a listener and then what?
public void actionPerformed(ActionEvent e)
{
String s = txt.getText();
char[] cArr = s.toCharAray();
ArrayList<Character> chars = new ArrayList<Character>();
for (char c : cArr)
if (c.isDigit())
chars.add(c);
cArr = new char[chars.size()];
for (int i = 0;i<chars.size();i++)
cArr[i] = char.get(i);
s = new String(cArr);
txtField.setText(s);
if (s.equals(""))
{
// issue warning
return;
}
int input = Integer.parseInt(s);
if (input >= 1800 && input <= 2013)
{
// do stuff
}
}
Basically, read the string in the text field, remove all non-numeric characters from it, and only proceed if it is in the range specified.
Related
I am currently coding a game and part of it consist of having different tiles to be put in a board. I plan on simulating this by having different buttons that will be used to represent the tiles with their corresponding coordinates. For example, one button will say "A1", "A2", etc. What I would like to accomplish, is to have the user click on the "A1" tile and then the button on the board that represents "A1" will change colors, is there any way to go through the buttons on the board and compare its text to the selection of the user? The following is what I used to create the board:
JButton[][] buttons = new JButton[9][12];
JPanel panel = new JPanel(new GridLayout(9,12,5,5));
panel.setBounds(10, 11, 800, 600);
frame.getContentPane().add(panel);
//board
for (int r = 0; r < 9; r++)
{
for (int c = 0; c < 12; c++)
{
buttons[r][c] = new JButton("" + (c + 1) + numberList[r]);
buttons[r][c].setBackground(Color.WHITE);
panel.add(buttons[r][c]);
}
}
This is what I wrote on the code of one of the tiles
JButton tile1 = new JButton ("A1");
tile1.setBounds(60,725,60,60);
frame.getContentPane().add(tile1);
tile1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String buttonText = tile1.getText();
// iterating through all buttons:
for(int i=0;i<buttons.length;i++){
for(int j=0;j<buttons[0].length;j++)
{
JButton b = buttons[i][j];
String bText = b.getText();
if(buttonText.equals(bText))
{
[i][j].setBackground(Color.BLACK);
}
}
}
}
} );
However, it is given me an error saying that there is an action expected after "{"
You may add an action listener to each of the JButton you are creating in the loop like below:
buttons[r][c].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// your code here
}
} );
Placing the listener in your code may look like
JButton[][] buttons = new JButton[9][12];
JPanel panel = new JPanel(new GridLayout(9,12,5,5));
panel.setBounds(10, 11, 800, 600);
frame.getContentPane().add(panel);
//board
for (int r = 0; r < 9; r++)
{
for (int c = 0; c < 12; c++)
{
buttons[r][c] = new JButton("" + (c + 1) + numberList[r]);
buttons[r][c].setBackground(Color.WHITE);
buttons[r][c].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
String buttonText = button.getText();
// now iterate over all the jbuttons you have
for(int i=0;i<buttons.length;i++){
for(int j=0;j<buttons[0].length;j++){
JButton b = buttons[i][j];
String bText = b.getText();
if(buttonText.equals(bText)){
// you found a match here
// and you have the positions i, j
//
}
}
}
}
} );
panel.add(buttons[r][c]);
}
}
And you could store the the colors to be changed to in global static array, and use that array in your action listener.
For information on adding listener to the JButton, you may refer this thread How do you add an ActionListener onto a JButton in Java
Hope this helps!
You need listeners.
Implement ActionListener to your class. This will require you to add public void actionPerformed(ActionEvent e) {} to your class.
Every JButton you use should have an action listener.
Apply one like that:
JButton but = new JButton();
but.addActionListener(this);
Finally, in the actionPerformed method we added, you need to add something like that:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == but)
but.setBackground(Color.BLACK);
}
P.S. you can get a button's text value by the means of:
but.getText();
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...
I have a swing application that involves a Container, a JButton, a JPanel, a JTextArea and an array. The array of String objects and contains 5 elements.
I want to return all elements in the array by a method and compare each of them with the element entered by end user in the text area, after pressing a JButton.
If they are same a JOptionPane message displaying the matched element should appear. If they are different a JoptionPane should show a message saying Number Entered is not found in myArray else, a message saying please Enter something" should appear
The problem I face is that when the end user enters a valid number a JOptionPane message saying: Number Entered is not found in myArray appear many times, e.g. when entering 4, a JoptionPane message saying
Number Entered is not found in myArray appear 3 times.
How do I prevent this message if the entered element is correct?
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Array_Search extends JFrame {
String myString[] = { "1", "2", "3", "4", "5" };
public String[] get_Element() {
String str[] = new String[myString.length];
str = myString;
return str;
}
public Array_Search() {
Container pane = getContentPane();
JPanel panel = new JPanel();
final JTextField txt = new JTextField(
" ");
JButton b = new JButton("Click Me ");
panel.add(b);
panel.add(txt);
pane.add(panel);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String[] str = get_Element();
String s2 = txt.getText().trim();
if (s2 != null && s2.length() > 0)
for (int i = 0; i < str.length; i++) {
if (s2.equals(str[i].trim())) {
JOptionPane option = new JOptionPane();
option.showInputDialog("" + str[i]);
} else {
JOptionPane option = new JOptionPane();
option.showInputDialog("Number Entered is not found in myArray");
}
}
else {
JOptionPane o = new JOptionPane();
o.showInputDialog("please Enter something");
}
}
});
}
public static void main(String[] args) {
Array_Search myArray = new Array_Search();
myArray.setSize(500, 500);
myArray.setVisible(true);
}
}
Your code shows message every time when non-matching element is found.
Instead, you need to look through all of the elements and display Not found message after that.
Something like this should work:
...
if (s2 != null && s2.length() > 0) {
boolean isFound = false;
for (int i = 0; i < str.length; i++) {
if (s2.equals(str[i].trim())) {
JOptionPane option = new JOptionPane();
option.showInputDialog("" + str[i]);
isFound = true;
break;
}
}
if(!isFound) {
JOptionPane option = new JOptionPane();
option.showInputDialog("Number Entered is not found in myArray");
}
} else
...
You return an empty Array in your get_Element method.
Can be fixed like that:
public void actionPerformed(ActionEvent ae) {
String [] str = get_Element(); // replace this
String [] str = myString; // with this
or change get_Element to:
public String[] get_Element() {
return myString;
}
Note: by Java code conventions use camel case for method names. getElement instead of get_Element.
The following part of the code doesn't work, as the won/lost count keeps incrementing by more than 1 for each word, and sometimes I get a nullpointerexception with the string length. Moreover, although the player is supposed to get 7 tries(int no), sometimes he gets more, sometimes less. The Strings are taken from a text file "Hangeng.txt". The whole game is inside a keyboard keytyped listener that is inside a button listener. Any tips on how the layout of the game should generally be arranged so as to avoid errors are welcome, as I am only beginning to work with swing and gui stuff.
public class test{
static int won = 0;
static int lost = 0;
static String key = "";
static String word = null;
static int no = 0;
static StringBuffer toguess;
public static void main(String[] args) throws IOException{
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(3,1));
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JButton button = new JButton();
JLabel label = new JLabel();
JLabel label2 = new JLabel();
panel1.add(label);
panel2.add(button);
panel3.add(label2);
frame.setSize(800,600);
frame.add(panel1);
frame.add(panel2);
frame.add(panel3);
frame.setVisible(true);
//the button that starts the game or gets a new word
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.requestFocus();
no = 0;
label2.setText("won " + won + ", lost " + lost);
button.setText("Next");
//get random word from file
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(
"hangeng.txt"));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
int lineno = (int) (Math.random() * 100);
for (int i = 0; i < lineno; i++) {
try {
reader.readLine();
} catch (IOException e1) {
e1.printStackTrace();
}
}
try {
word = reader.readLine().replace(" ", "");
} catch (IOException e1) {
e1.printStackTrace();
}
String missing = "";
for (int u = 0; u < (word.length() - 2); u++) {
missing = missing + "*";
}
final String guess = word.charAt(0) + missing
+ word.charAt((word.length() - 1));
toguess = new StringBuffer(guess);
label.setText(toguess.toString());
final ArrayList<String> tried = new ArrayList<String>();
//keylistener that listens to key clicks by the user
frame.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent arg0) {
}
public void keyReleased(KeyEvent arg0) {
}
public void keyTyped(KeyEvent arg0) {
key = "" + arg0.getKeyChar();
String guessing = null;
boolean k = false;
if ((no < 6)) {
guessing = key;
System.out.println(guessing);
if (!(tried.contains(guessing))) {
tried.add(guessing);
for (int length = 1; length < (guess
.length() - 1); length++) {
if (guessing.equals(String.valueOf(word.charAt(length)))) {
toguess.replace(length,
(length + 1),
String.valueOf(word.charAt(length)));
k = true;
}
}
if (k == true) {
label.setText(toguess.toString());
} else {
no = no + 1;
}
k = false;
}
label.setText(toguess.toString());
if (toguess.toString().equals(word)) {
label.setText("Correct! The word was " + word);
no = 6;
won = won + 1;
}
}
else if ((no == 6)
&& (!(toguess.toString().equals(word)))) {
label.setText("Sorry, but the word was " + word);
lost = lost + 1;
}
}
});
}
});
}
}
+1 to all comments....
Adding to them:
Do not use KeyListener use a KeyAdapter however as you are using Swing and not AWT you should use KeyBindings for Swing see here for example.
Dont forget to create and manipulate Swing components on Event Dispatch Thread via SwingUtiltities.invokeLater(..) block see here for more.
Check class naming schemes they shuld start with capital letter, i.e test should be Test and every new word after that should be capitalized.
Do not call setSize on JFrame rather use appropriate LayoutManager and/or override getPreferredSize() of JPanel and return a size which fits its content and call pack() on JFrame instance after adding all components.
Also SSCCE should be compilable from copy and paste this is not.... i.e variables needed to be changed to final and I dont have a sample of Hangeng.txt so cant test
Lastly use the #Override annotation to ensure you are overriding the correct methods, i.e
#Override
public void actionPerformed(ActionEvent e) {
}
I'm try to change the text on a JLabel when the Jbutton is clicked but i can't figure it out why it turns the text into empty when i clicked the button. I'm trying to retrieve the data from the database.
heres my label
labelDisplay = new JLabel[7];
for(int z = 0; z<7; z++){
labelDisplay[z] = new JLabel("d");
labelDisplay[z].setForeground(new Color(230,230,230));
if( z%2==0)
labelDisplay[z].setBounds(130,65,160,25);
else
labelDisplay[z].setBounds(130,30,160,25);
}
I'm sure that my class for retrieving date is working i test it out.
heres my actionListener:
public class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == extendB)
{
ExtensionForm extend = new ExtensionForm();
extend.setVisible(true);
}
else if(e.getSource()== searchB)
{
//get text from the textField
String guest = guestIDTF.getText();
//parse the string to integer for retrieving of date
int id = Integer.parseInt(guest);
GuestsInfo guestInfo = new GuestsInfo(id);
Room roomInfo = new Room(id);
searchB.setText(""+id);
System.out.println(""+guestInfo.getFirstName());
labelDisplay[1].setText(""+id);
String labels[] = {guestInfo.getFirstName()+" "+guestInfo.getLastName(),
""+roomInfo.getRoomNo(),roomInfo.getRoomType(),guestInfo.getTime(),"11:00",
""+guestInfo.getDeposit(),"30"};
labels = new String[7];
for(int z = 0; z<labels.length; z++){
labelDisplay[z].setText(labels[z]);
}
}
}
}
I did put an initial value for the label text, as you can see from my code it's letter "d" but when i clicked the button it turns to empty.The accessor methods there are really working that why i suspect that the error is from my actionListener. Please help me guys
I edit the constructor it should be id not 1.
Heres the code for the actionListener for the button
ButtonHandler bh = new ButtonHandler();
searchB = new JButton("search");
searchB.setBounds(190,30,75,25);
searchB.addActionListener(bh);
labelDisplay[1].setText(""+id);
String labels[] = {guestInfo.getFirstName()+" "+guestInfo.getLastName(),
""+roomInfo.getRoomNo(),roomInfo.getRoomType(), guestInfo.getTime(),
"11:00", ""+guestInfo.getDeposit(),"30"};
labels = new String[7];
for(int z = 0; z<labels.length; z++){
labelDisplay[z].setText(labels[z]);
}
You never set your labels to something valid. Remove labels = new String[7];
Should have checked the code well sorry!