Disable Buttons on JAVA but leave unique button alone - java

According to my previous question here:
Remove a Button with same text when clicked
I need that the only buttons that appearing more then one will disappearing while clicking on them
Problem is when clicking on the "Unique" ones ( see picture ), they will disappear also.
My code:
private String namesArr[] = {"Yakir","Yarden","Igor","Maoz","Moshe","Israel","Tal","Haim","Nati","Mor","Daniel","Idan"};
private Button buttonArr[] = new Button[namesArr.length];
private Font font;
public StudentsGUI(String caption) {
super(caption);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
dispose();
System.exit(0);
}
});
this.setLayout(new GridLayout(3,3));
font = new Font("Ariel",Font.BOLD,35);
for(int i=0;i<namesArr.length;i++) {
buttonArr[i] = new Button(" "+namesArr[(int)(Math.random()*namesArr.length)]);
buttonArr[i].setFont(font);
buttonArr[i].addActionListener(this);
this.add(buttonArr[i]);
}
setLocation(800,500);
setVisible(true);
pack();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof Button) {
String btnText = ((Button)e.getSource()).getLabel();
for(int i=0; i<buttonArr.length; i++) {
if (buttonArr[i].getLabel().equals(btnText)) {
this.remove(buttonArr[i]);
pack();
}
}
}
}
The picture to help you understand:
So if clicking on "Idan", witch is a unique name nothing will happen as it only have one instance, but if clicking on "Maoz" all the buttons with "Maoz" title will disappear ( this already happening )

using collections as per #Freddy's answer should be better. However if you're to stick with arrays, something like below should do it (haven't tested it though)
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof Button) {
String btnText = ((Button)e.getSource()).getLabel();
int counter = 0;
for(int i=0; i<buttonArr.length; i++) {
if (buttonArr[i].getLabel().equals(btnText)) counter++;
if (count > 1) {
for(int j=0; j<buttonArr.length; j++) {
if (buttonArr[j].getLabel().equals(btnText))
this.remove(buttonArr[j]);
}
}
}
pack();
}
}

You mean something like this (code may have syntax errors)?
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof Button) {
String btnText = ((Button)e.getSource()).getLabel();
List<Button> btnList = new ArrayList<Button>();
for(int i=0; i<buttonArr.length; i++) {
if (buttonArr[i].getLabel().equals(btnText)) {
btnList.add(buttonArr[i]);
//this.remove(buttonArr[i]);
//pack();
}
}
if (btnList.size() > 1) {
for (Iterator<Button> it = btnList.iterator(); it.hasNext()) {
this.remove(it.next());
}
pack();
}
}
}

Related

One program, different on multiple computers

First of all, I want to ask you to ask as much information as possible to me to be able to help me out.
I've been creating an automatic reminder system which is able to create the reminder in PDF then automatically send it to the clients which you've chosen to be reminded.
The program is working perfectly fine, but once I try to start it on another computer, it does not work anymore. The following problems occur:
On one computer in Eclipse it does not even open the frame which handles the user input (telling the program which clients have to be reminded). The code is given below. An interesting point here is that I've tried to print a line if the actionPerformed method is running. It does NOT appear at all. So for some reason it is not listening to that whole method.
if(starter.getAccess().equals("admin") || starter.getAccess().equals("god")){
menu = new JMenu("Aanmaningen");
menu.setMnemonic(KeyEvent.VK_N);
menu.getAccessibleContext().setAccessibleDescription(
"Debiteuren aanmanen");
menuBar.add(menu);
menu.addSeparator();
ButtonGroup group2 = new ButtonGroup();
rbMenuItem = new JRadioButtonMenuItem("Pyxis Distribution B.V.");
rbMenuItem.setSelected(false);
rbMenuItem.setMnemonic(KeyEvent.VK_R);
group2.add(rbMenuItem);
menu.add(rbMenuItem);
rbMenuItem.addActionListener(new ActionListener() {
#SuppressWarnings("static-access")
#Override
public void actionPerformed(ActionEvent arg0) {
chosenComp = true;
f.getContentPane().add(new Main());
f.revalidate();
f.repaint();
Distrscherm obj = new Distrscherm();
obj.plannerJTable();
}
});
On the other computers it was jarred and did open the menu, but did the JComboBox did not automatically complete the searchterms. It neither sent the mail. When clicking on the button save and send it didn't do anything. The codes are shown below.
This is the code which handles automatic completion (pretty basic code)
public AutoComboBox() {
setModel(new DefaultComboBoxModel(myVector));
setSelectedIndex(-1);
setEditable(true);
JTextField text = (JTextField) this.getEditor().getEditorComponent();
text.setFocusable(true);
text.setText("");
text.addKeyListener(new ComboListener(this, myVector));
setMyVector();
}
/**
* set the item list of the AutoComboBox
* #param patternExamples an String array
*/
public static void setKeyWord(Object[] patternExamples) {
AutoComboBox.keyWord = patternExamples;
setMyVectorInitial();
}
private void setMyVector() {
int a;
for (a = 0; a < keyWord.length; a++) {
myVector.add(keyWord[a]);
}
}
private static void setMyVectorInitial() {
myVector.clear();
int a;
for (a = 0; a < keyWord.length; a++) {
myVector.add(keyWord[a]);
}
This is the code which handles the SAVE button
#Override
public void actionPerformed(ActionEvent e) {
#SuppressWarnings("unused")
Writer obj1 = new Writer(getTableData(table), "./planningdagelijks/week.csv");
for(int i =0; i < model.getRowCount(); i++) {
Datareader.Runner(model.getValueAt(i, 0));
internalfile obj2 = new internalfile();
obj2.intern();
try {
maildata.Reader((String)model.getValueAt(i, 0));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Pdfgenerator.Filegenerator((String)model.getValueAt(i, 0));
}
}
});

How to check if any button in JPanel is clicked by a user

I've been making a bus booking project and I've made a booking page.
The JPanel named PanelSeat and it contains buttons (about 36 buttons) inside.
I want to check if any button inside JPanel is clicked, then disable the button and finally if a user clicks util 3 buttons, it will be stopped or a user can't click it anymore.
This is the code I've written so far:
private void CountTicket() {
try {
int count = 3;
Component[] components = PanelSeat.getComponents();
for (int i = 0; i < components.length; i++) {
if (components[i] instanceof JButton) {
if (((JButton) components[i]).isSelected()) { // I wanna check if any button is clicked by a user
if (JOptionPane.showConfirmDialog(this, "Seat Confirmation") == JOptionPane.YES_OPTION) { // confirm message
((JButton) components[i]).setEnabled(false); // disable the button
count--;
System.out.println("Your ramaining seat : " + count);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
How do I check if button has been clicked?
Since you want to count how many times a button was pressed, and then disable it with counts involved I would suggest that you wrap the Jbutton class in order to make performing those tasks easier, this solution is generally better
class JbuttonWrapper extends JButton {
int count=0;
public void increment()
{
count++;
if (count==numberOfclicksToDisable)
{
this.setEnabled(false);
}
}
}
//then you can simply do the following.
JbuttonWrapper [] buttons= new JbuttonWrapper [NumbersOfButtonsYouHave];
for (int i=0; i<=NumbersOfButtonsYouHave;i++)
{
buttons[i].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { buttons[i].increment(); } });
}
and this solution is based on your code
static int count=3;
Component[] components = PanelSeat.getComponents();
for (int i = 0; i < components.length; i++) {
if (components[i] instanceof JButton) {
{
components[i].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
count--;
}
});
}
Add ActionListener to JButton, check example here.

How to capture the amount of clicks over a group of loop generated JToggleButtons?

I have 20 loop-generated JToggleButtons and I need to count how many of them are active.
private void generarBotones(){
JToggleButton b;
this.panelCuerpo.setLayout(new GridLayout(4,5));
for(int i = 1; i<=20; i++){
b = new JToggleButton();
b.setText(String.valueOf(i));
this.panelCuerpo.add(b);
b.addActionListener(new ActionListener() {
int clicks = 0;
#Override
public void actionPerformed(ActionEvent ae2){
clicks = clicks + 1;
System.out.println(clicks);
}
public void setCantidadBoletas(int clicks){
cantidadBoletas = clicks;
}
});
}
}
The problem here is that it counts how many times is EACH ONE of them clicked instead of count how many of them are selected.
PS. I tried to use (b.isSelected()) but b needs to be final to access it so it wasn't the solution.
If you declare the JToggleButton inside the loop, you can make it final:
for (int i = 1; i<=20; i++) {
JToggleButton b = new JToggleButton();
Then you can use b.isSelected:
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (b.isSelected())
clicks++;
else
clicks--;
}
});
}
clicks would have to be a class variable.
Suggestions:
Create a field, JToggleButton[] toggleButtons = new JToggleButton[20]
Or use an ArrayList if you so choose
In your for loop create your JToggleButton and assign it to the proper array item.
In the ActionListener simply iterate through the array, counting how many of its JToggleButton items are selected.
You're done.
Create a class attribute that will count the selected toggles:
private int selectedCount;
Initialize the counter to 0 in your constructor:
this.selectedCount = 0;
Increment or decrement the counter every time the state of a toggle changes:
b.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
if (ev.getStateChange() == ItemEvent.SELECTED){
YourClass.this.selectedCount++;
} else if (ev.getStateChange() == ItemEvent.DESELECTED){
YourClass.this.selectedCount--;
}
System.out.println(YourClass.this.selectedCount);
}
});
There are many ways to get this done and the best way depends on the rest of your code. I tried to keep it as close to yours.
You can just declare the buttons as final inside the loop and keep a global count of the number of buttons selected, which will be modified in the ActionListener:
public class ButtonsCount extends JFrame {
int clicks = 0;
ButtonsCount() {
JLabel label = new JLabel("0");
JPanel buttonsPanel = new JPanel(new GridLayout(4,5));
for(int i = 1; i <= 20; i++) {
final JToggleButton b = new JToggleButton();
b.setText(String.valueOf(i));
buttonsPanel.add(b);
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae2){
if (b.isSelected())
label.setText(String.valueOf(++clicks));
else
label.setText(String.valueOf(--clicks));
}
});
}
add(buttonsPanel);
add(label, BorderLayout.PAGE_END);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new ButtonsCount();
}
}

Making a button write to one JTextField in an Array

I'm working on a TextTwist java implementation and I'm currently working on the GUI. I was wondering if some of you Swing geniuses could help me out. I'm trying to do a GUI where whenever a button is clicked, the text of that button is written into the first empty textField below it. I'm having trouble thinking through how to do it. What I've tried so far makes the first button click fill all the TextFields.
Any help or pointers in the right direction would be great.
private void makeButtonLayout() {
this.charArray = new char[6];
ArrayList<Character> charArrayList = new ArrayList<Character>();
this.charArray = this.randomString.toCharArray();
for(char tempCharacter : this.charArray){
charArrayList.add(tempCharacter);
}
for (int i = 0; i< 6; i++){
JButton letterButton = new JButton();
Character buttonCharacter = charArrayList.get(i);
charArrayList.remove(i);
String letterString = buttonCharacter.toString();
letterButton.setText(letterString);
this.letterButtonsArray.add(letterButton);
}
for (final JButton currentButton : this.letterButtonsArray){
this.buttonPanel.add(currentButton);
currentButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
int i = 0;
currentButton.setVisible(false);
JTextField temporaryTextField = new JTextField();
String temporaryString = currentButton.getText();
temporaryTextField.setText(temporaryString);
if(textFieldArray.get(i).getText().isEmpty()){
textFieldArray.get(i).setText(temporaryString);
return;
}else{
i++;
return;
}
}
});
}
}
I think you method is really strange. You mixed initialization code and execution code. Do it like this:
for (final JButton currentButton : this.letterButtonsArray){
this.buttonPanel.add(currentButton);
currentButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
currentButton.setVisible(false);
String temporaryString = currentButton.getText();
for(int i = 0; i < textFieldArray.size(); i++)
JTextField elem = textFieldArray.get(i);
if(elem.getText().equals("")){ // or if you don't want spaces do: elem.getText().trim().equals("");
elem.setText(temporaryString);
break;
}
}
}
});
}

method works in the constructor but not in the action listener

my problem is that the method "findChampion" works only in the constructor, and I need to work within the action listener for use in the textfield.
I think the problem was the champion object.try changing the method and static variables but did not work
Thanks.
private JTextField textField;
private Champion[] championsList;
private boolean first = true;
int previous = 0;
public Finder(Champion[] champions) {
setBounds(1,1,795,365);
setLayout(null);
championsList = champions;
textField = new JTextField();
textField.setBounds(354, 5, 107, 44);
add(textField);
textField.setColumns(10);
//WORKS HERE
for (int i=0;i<championsList.length;i++)
{
if (textField.getText().equalsIgnoreCase(championsList[i].getName()))
{
if (first == false)
{
championsList[previous].removeChampion(this);
}
championsList[i].position(119,120,100,100,50,50);
championsList[i].addChampion(this);
previous = i;
first = false;
}
}
//
//BUT DOESN'T WORK HERE
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
findChampion();
}
});
//
}
public void findChampion()
{
for (int i=0;i<championsList.length;i++)
{
if (textField.getText().equalsIgnoreCase(championsList[i].getName()))
{
if (first == false)
{
championsList[previous].removeChampion(this);
}
championsList[i].position(119,120,100,100,50,50);
championsList[i].addChampion(this);
previous = i;
first = false;
}
}
}strong text
You should use DocumentListener instead of ActionListener for JTextField. This is best way to look for changes that happend in TextField.
TextField.getDocument().addDocumentListener(new DocumentListener{
//implement necessary methods
});
Look for example here:
http://docs.oracle.com/javase/tutorial/uiswing/events/documentlistener.html

Categories