I have a button. If I click this button, a popup appears. The popup asking me to write a word. if I write a word 6 letter, 6 jlabels appear, but if I enter another word shorter, the JLabels do not disappear
I want my JLabels may decrease according to a shorter word, but i don't know :(
thx for your great help !
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//BUTTON 1 WORD
Controller c = new Controller();
try {
final JFrame popup = new JFrame();
//display popup
word = JOptionPane.showInputDialog(popup, "Enter one word", null);
//control the length of the word
c.controleW(word);
//display jlabel lenght of word
keyNumber.setText(String.valueOf(word.length()));
//JLabels displays depending on the word length
int pixels = 50;
for (int i = 0; i < word.length(); i++) {
label = new JLabel("_");
label.setBounds(pixels, 200, 30, 30);
add(label);
label.repaint();
pixels += 20;
}
} catch (Exception e) {
System.out.println(e);
}
}
And my class to control the length of the word
public String controleW(String word) {
boolean flag = false;
final JFrame popup = new JFrame();
while (flag == false) {
if (word.length() <= 3) {
word = JOptionPane.showInputDialog(popup, "Enter one word", null);
} else {
flag = true;
}
};
return null;
}
You are always adding labels in your method, never removing any, thus running the code twice will indeed add labels twice. To fix it, you can simply add a removeAll(); in jButton1ActionPerformed before you add any labels. This makes sure that any previously added components will be removed.
Related
I have a JTable wrapped into a JScrollPane. When I scroll to the top or bottom and continue to scroll, I want to be able to detect that in order to possibly load more items at the beginning or end since it is too expensive/not practical to load all items at once. The AdjustmentListener is not fired when the JScrollPane does not move (e.g. when it is already at the top or bottom):
scrollPane.getVerticalScrollBar().addAdjustmentListener(adjustmentEvent ->
{
int value = adjustmentEvent.getValue();
System.out.println(value); // Prints 0 e.g. when the top has been reached
});
However, I need to know when the user scrolls even though the end/start has already been reached.
How can this be done?
I suggest using a change listener on the JViewport of the scroll pane. The following example shows how to proceed. Please note that shouldCheck might be used to prevent false notifications (in my sample top is printed three times upon startup. If you run the sample and move the slider to the top and bottom a corresponding text is printed.
package com.thomaskuenneth;
import javax.swing.*;
public class Main {
static boolean shouldCheck = true;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame("Demo");
f.getContentPane().add(createUI());
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setVisible(true);
});
}
static JComponent createUI() {
String[][] rowData = new String[200][10];
String[] columnNames = new String[10];
for (int i = 0; i < 200; i++) {
for (int j = 0; j < 10; j++) {
if (i == 0) {
columnNames[j] = String.format("#%d", j);
}
rowData[i][j] = String.format("%d - %d", i, j);
}
}
JTable t = new JTable(rowData, columnNames);
JScrollPane sp = new JScrollPane(t);
JScrollBar sb = sp.getVerticalScrollBar();
JViewport vp = sp.getViewport();
vp.addChangeListener((l) -> {
if (!shouldCheck) {
return;
}
if (sb.getValue() == sb.getMinimum()) {
System.out.println("top");
} else if (sb.getValue() + sb.getVisibleAmount() == sb.getMaximum()) {
System.out.println("bottom");
}
});
return sp;
}
}
I created a dialog box and have the user enter 5 colors in it from memory. That all completely works, there's just a slight aesthetic problem. Upon entering all 5 colors correctly, or getting one incorrect, it's suppose to wipe the contents within the dialog box and print a message "Sorry! Incorrect color" or "Congratulations". It prints the message, but the JTextField can still be seen somewhat behind the message (A left over portion/clipping).
I've tried using the hide() and remove() methods but they didn't seem to work (Or I'm using them incorrectly), I tried re-making a dialog box upon either but I couldn't seem to solve the issue still. What am I doing wrong/how can I make the JTextField disappear upon completion? Thank you in advance for any help!
Here's the portion where if the user enters a color incorrectly or gets them all correct (txtName is the JTextField):
if(count == 6)//User either finished or entered a color incorrectly
{
//Entered color incorrectly
if(incorrect == true)
{
txtName.setEnabled(false); //Doesn't work
homeScreen.remove(txtName); //Doesn't work
labelName.setText("Incorrect! Sorry - Wrong color.");
//txtName.removeActionListener(new MyButtonListener());
}
else//Correctly finished the game.
{
labelName.setText("Congratulations - your memory skills are perfect!");
//txtName.removeActionListener(new MyButtonListener());
homeScreen.remove(txtName);//Doesn't work
}
}
Here's my entire program (I can't get it format properly in the post):
package memorygame;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.FlowLayout;
public class MemoryGame
{
private JFrame homeScreen;
private JLabel labelName;
private JTextField txtName;
private JLabel correct;
Vector<String> name = new Vector();
private int count = 1;
private MyButtonListener listen1 = new MyButtonListener();
//Constructor - Method to be called when MemoryGame object called
public void MemoryGame ()
{
homeScreen = new JFrame();
homeScreen.setSize(400,200);
homeScreen.setTitle("Memory Game");
homeScreen.setDefaultCloseOperation(homeScreen.EXIT_ON_CLOSE);
homeScreen.setLayout(new FlowLayout());
labelName = new JLabel();
txtName = new JTextField(10);
createContents();
homeScreen.setVisible(true);
}//End Constructor
//Create components and add them to the window/dialog box
private void createContents()
{
labelName.setText("Enter the color " + count + ":");
System.out.println("The current count is: " + count);
homeScreen.add(labelName);
homeScreen.add(txtName);
txtName.addActionListener(new MyButtonListener());//Allows you to press enter to invoke action
}
//Upon user hitting enter
private class MyButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent e)//When event occurs
{
Scanner in = new Scanner (System.in);//For program input
String answer = "";
//Make memColor an array for randomized colors
/*
Random r = new Random();
String[] memColors = new String[5];
String[] colors = {"red", "green", "blue", "yellow", "brown", "purple"};
for(int i =0; i < memColors.length; i++)
{
memColors[i] = colors[r.nextInt(6)];
}
*/
String memColor1 = "red";
String memColor2 = "black";
String memColor3 = "yellow";
String memColor4 = "green";
String memColor5 = "blue";
boolean incorrect = false;
//If answered incorrectly set count to 5(it'll be 6)
//And have a boolean for if count== 6 for congrats and failure
if(e.getSource() == txtName)
{
answer = txtName.getText();
System.out.println(answer);
}
else
{}
//Check if user entered Correct color, 1= Red, 2= Black, etc.
if(count == 1)
{
if(answer.equalsIgnoreCase(memColor1))
{
txtName.setText("");
}
else
{//Needs to be a custom message box
count = 5;
incorrect = true;
}
}
else if(count == 2)
{
if(answer.equalsIgnoreCase(memColor2))
{
txtName.setText("");
}
else
{
count = 5;
incorrect = true;
}
}
else if(count == 3)
{
if(answer.equalsIgnoreCase(memColor3))
{
txtName.setText("");
}
else
{
count = 5;
incorrect = true;
}
}
else if(count == 4)
{
if(answer.equalsIgnoreCase(memColor4))
{
txtName.setText("");
}
else
{
count = 5;
incorrect = true;
}
}
else if(count == 5)
{
if(answer.equalsIgnoreCase(memColor5))
{
txtName.setText("");
}
else
{
count = 5;
incorrect = true;
}
}
else
{
JOptionPane.showMessageDialog(null, "Something went wrong!");
}
count += 1;
//User has completed the game or entered a color incorrectly
if(count == 6)
{
if(incorrect == true) //Incorrect color
{
txtName.setEnabled(false);
homeScreen.remove(txtName);
labelName.setText("Incorrect! Sorry - Wrong color.");
//txtName.removeActionListener(new MyButtonListener());
}
else //Completed the game correctly
{
labelName.setText("Congratulations - your memory skills are perfect!");
//txtName.removeActionListener(new MyButtonListener());
homeScreen.remove(txtName);
}
}
else
{
labelName.setText("Enter the color " + count + ":");
}
}//End Listener
}//End Button class
public static void main(String[] args) {
//Show message box
//Randomize colors
JOptionPane.showMessageDialog(null, "How good is your memory?\nTry to memorize this color sequence:\n\n red black yellow green blue");
MemoryGame mem = new MemoryGame();
mem.MemoryGame();
}//End Main
}// End Class
Use txtName.setVisible(false); instead of homeScreen.remove(txtName);
Basically, if you want to call remove, you will need to revalidate and repaint container...
You'll also want to ensure that your UI is create within the context of the Event Dispatching Thread, see Initial Threads for more details
Change the code
homeScreen.remove(txtName);
to
homeScreen.remove(txtName);
homeScreen.revalidate();
homeScreen.repaint();
The reason why remove() does not imply revalidate() + repaint() is that remove() is not atomic. The caller might want to perform multiple updates, a sequence of several add() and remove() calls. revalidate() basically "completes" your "UI update transaction", repaint() "pushes it to the screen".
As a side note, your code will be easier to understand and maintain, if you perform a small tiny improvements on variable names. What's homeScreen? And why is it called labelName - what name? And what's txtName - the name of what text? count of what, icecreams?
I suggest the following improvements:
incorrect -> isIncorrect (also change if (incorrect == true) to if (isIncorrect)
homeScreen -> mainFrame or just frame (as you only have one frame)
labelName -> infoLabel or just label (as you only have one label - and remove JLabel correct, it's unused)
txtName -> answerTextField
count -> answerCount
Remove variable listen1, it's not used.
Plus, if you look at the code that does if (count == 1) and the following four if clauses, they are all identical except for the number. A perfect situation for an array. You can convert the variables memColor* to an array String[] memColor. Or maybe that's what the Vector was for. You might instead want to use ArrayList, nobody uses Vector these days in such situations.
I have a program that takes an input file, pulls a color word + hexadecimal value from it (for exaple Red 0xFF0000). I had my code working perfectly except I tried to replace my 2 arrayLists with a HashMap... That is where things took a wrong turn. I have my code back to what I believe it was before except now it is NOT changing colors when the radio buttons are pushed. Anyone want to take a peek?
public HashMapTests() {
JPanel p1 = new JPanel();
this.getContentPane().setLayout(new GridLayout(5,4));
ButtonGroup group = new ButtonGroup();
for (int i = 0; i < colorCollection.size(); i++) {
jrbColor[i] = new JRadioButton(colorCollection.get(i));
jrbColor[i].setText(colorCollection.get(i));
group.add(jrbColor[i]);
p1.add(jrbColor[i]);
}
for(int i = 0; i < colorCollection.size(); i++){
jrbColor[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
for (int j = 0; j < colorCollection.size(); j++){
String hexColor = hexCollection.get(j);
if(hexCollection.get(j).equals(((JRadioButton)e.getSource()).getText())){
getContentPane().setBackground(Color.decode(hexColor));
repaint();
}
}
}
});
}
add(p1);
}
First investigation:
while (colorCollection.size() < 10)
shall be replaced with
if (colorCollection.size() < 10)
Second observation:
jrbColor[i] = new JRadioButton(colorCollection.get(i));
jrbColor[i].setText(colorCollection.get(i));
The second line is useless, see constructor's javadoc.
Third:
The second loop where you attach the listener is useless, you can put this code to the first loop where you create a button.
Finally:
if (hexCollection.get(j).equals(((JRadioButton) e.getSource()).getText())) {
You compare here content of hexCollection with radio button text, but the button has label from colorCollection. I cannot look to your file but I think that this will be the problem.
Map Solution:
Initialization
String name = fileInput.next();
String hexValue = fileInput.next();
colors.put(name, hexValue);
Buttons
int i = 0;
for (String s : colors.keySet()) {
jrbColor[i] = new JRadioButton(s);
group.add(jrbColor[i]);
p1.add(jrbColor[i]);
jrbColor[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String hexColor = colors.get(((JRadioButton) e.getSource()).getText());
getContentPane().setBackground(Color.decode(hexColor));
}
});
}
I am creating a hangman game and I was having trouble getting the jlabel that contained each character of the word to update after the right letter button has been clicked. I have been having trouble with this as I am relatively new to working with Java Guis. Below is the action listener for the letter buttons.
private class LetterHandler implements ActionListener{
private char letterVal;
public LetterHandler(char lv){
letterVal = lv;
}
//checks if clicked button has the correct value as word char
public void actionPerformed(ActionEvent e){
for(int x = 1; x <= selectedWord.wordLength; x++){
if(selectedWord.wordValue.charAt(x - 1) == letterVal){
// JLabel letterValLabel = new JLabel(String.valueOf(letterVal));
wordSpacesArray.get(x-1).setName(String.valueOf(letterVal));
wordSpacesArray.get(x-1).revalidate();
continue;
}
else{
continue;
}
}
checkWin();
triesLeft--;
triesLeftLabel.revalidate();
}
//finds if all jlabels are complete or not
public void checkWin(){
for(int x = 1; x <= wordSpacesArray.size(); x++){
String charVal;
charVal = String.valueOf(wordSpacesArray.get(x-1));
if(charVal != "?"){
System.out.println("youWon");
System.exit(0);
}
else{
break;
}
charVal = null;
}
}
}
Any help is appreciated. Let me know if you need for of the programs code Thanks :)
There are some issues with the code. However, I'll first try to focus on your current problem:
I assume that wordSpacesArray is a list that contains the JLabels of individual letters of the word.
When this ActionListener will be notified, you try to update the labels in wordSpacesArray with the letter that corresponds to this button. However, in order to update the text that is shown on a JLabel, you have to call JLabel#setText(String) and not JLabel#setName(String). So the line should be
wordSpacesArray.get(x-1).setText(String.valueOf(letterVal));
// ^ Use setText here!
Now, concerning the other issues:
As pointed out in the comments, you should use 0-based indexing
The calls to revalidate are not necessary
The use of continue in its current for is not necessary
You should not compare strings with ==, but with equals
// if(charVal != "?") { ... } // Don't do this!
if(!charVal.equals("?")){ ... } // Use this instead
But the charVal in this case will be wrong anyhow: It will be the string representation of the label, and not its contents. So you should instead obtain the text from the label like this:
// String charVal = String.valueOf(wordSpacesArray.get(x-1)); // NO!
String charVal = wordSpacesArray.get(x-1).getText(); // Yes!
The triesLeftLabel will not be updated as long as you don't call setText on it
I think the logic of the checkWin method is flawed. You print "You won" when you find the first letter that is not a question mark. I think it should print "You won" when no letter is a question mark.
You should not call System.exit(0). That's a bad practice. Let your application end normally. (In this case, maybe by just disposing the main frame, although that would also be questionable for a game...)
So in summary, the class could probably look like this:
private class LetterHandler implements ActionListener
{
private char letterVal;
public LetterHandler(char lv)
{
letterVal = lv;
}
// checks if clicked button has the correct value as word char
#Override
public void actionPerformed(ActionEvent e)
{
for (int x = 0; x < selectedWord.wordLength; x++)
{
if (selectedWord.wordValue.charAt(x) == letterVal)
{
wordSpacesArray.get(x).setText(String.valueOf(letterVal));
}
}
checkWin();
triesLeft--;
triesLeftLabel.setText(String.valueOf(triesLeft));
}
// finds if all jlabels are complete or not
public void checkWin()
{
for (int x = 0; x < wordSpacesArray.size(); x++)
{
String charVal = wordSpacesArray.get(x).getText();
if (charVal.equals("?"))
{
// There is still an incomplete label
return;
}
}
// When it reaches this line, no incomplete label was found
System.out.println("You won");
}
}
i am developing a project to a class and i came up with a stand-still.
So, what i want to do is to refresh the label when the user presses enter in the textfield to verify the ID.
Here is my code to catch when "enter" key is pressed, it's an event of the textfield "txtNbi":
if (evt.getKeyCode() == 10) {
this.BI = txtNbi.getText();
String BIs[];
BIs = DadosAplicacao.getInstance().getBIs();
for (int i = 0; i < BIs.length; i++) {
System.out.println("BI: " + this.BI + "\nBIlista: " + BIs[i]);
if (this.BI.equals(BIs[i])) {
encontrou.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pt/estg/dint/imagens/Ok.png")));
this.repaint();
} else {
encontrou.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pt/estg/dint/imagens/Cross.png")));
this.repaint();
}
}
}
txtNbi = name of my textfield;
BIs = array of strings that get pre-inserted IDs from the 'DadosAplicacao' class;
encontrou = name of my label that receives the image as an icon
So here is my problem:
I have the following data:
- BIs[0] = 12345678
- BIs[1] = 87654321
- BIs[2] = 54321678
When i type in the first 2 the label doesn't change to the "Ok.png" icon, but when i type the last one the label changes his icon to "Ok.png"!
Can anyone help me fix this?
You need to use the DocumentListener class:
txtNbi.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent documentEvent) {
//add the code handling the different conditions here
}
});
you need a break after you found the typed ID
if(this.BI.equals(BIs[i]))
{
encontrou.setIcon(newjavax.swing.ImageIcon(getClass().getResource("/pt/estg/dint/imagens/Ok.png")));
this.repaint();
break;
}