code inside jButtonActionPerformed(ActionEvent e) method is not working - java

I have a jTextField, jLabel and a jButton. I want to set the jTextField to empty and update the jLabel to some new text after I perform jButton action.
This my code for jButtonActionPerformed(ActionEvent e) method:
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {
BufferedWriter fw;
StringBuilder guessword = new StringBuilder(word);
try {
fw = new BufferedWriter(new FileWriter("C:\\Users\\Arihant\\JavaApplication1\\src\\javaapplication1\\scores.txt", true));
while(guesses != 0) {
jLabel26.setText(Integer.toString(guesses));
guesschar = jTextField2.getText().charAt(0);
flag = 0;
for(int j = 0; j < word.length() / 2; j++) {
if(Character.toLowerCase(guesschar) == temp[j] && (guessword.toString().indexOf(Character.toLowerCase(guesschar)) < 0)) {
flag = 1;
for(int k = 0; k < word.length(); k++) {
if(Character.toLowerCase(guesschar) == word.charAt(k))
guessword.setCharAt(k, Character.toLowerCase(guesschar));
}
if(guessword.toString().equals(word)) {
switch (difficulty) {
case "EASY":
points = guesses * 50;
break;
case "MODERATE":
points = guesses * 100;
break;
case "HARD":
points = guesses * 200;
break;
default:
points = 0;
break;
}
try {
fw.append(name + " " + points);
fw.newLine();
fw.close();
} catch (IOException ex) {
Logger.getLogger(HangMan.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex);
}
jPanel13.removeAll();
jPanel13.add(jPanel4);
jPanel13.repaint();
jPanel13.revalidate();
jLabel29.setText("<html>YOU WIN!<br/> The word was: </html>" + word);
jLabel31.setText("You scored: " + points + " points.");
jLabel28.setText("Play again?");
}
}
}
if(flag == 0) {
guesses--;
}
jPanel13.repaint();
jPanel13.revalidate();
jLabel1.setText(guessword.toString());
jTextField2.setText("");
Document document = jTextField2.getDocument();
document.addDocumentListener(new JButtonStateController(jButton8, 0));
((AbstractDocument) jTextField2.getDocument()).setDocumentFilter(new JTextFieldFilter(0));
}
} catch (IOException ex) {
Logger.getLogger(HangMan.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex);
}
}
When I click jButton8, it just skips the entire code in try-catch block and goes directly to jPanel13.removeAll();.
I want to set the jTextField2 to empty and jButton8 to disabled, each time I click jButton8.
Tell me, where I am wrong and how can I improve my code?

Related

Drag and drop between two Jtables

So I managed to make Jtable working one way, from table1 to table2. but I don't really know how to make it work both ways(from table2 to table1). I was trying putting transferhandler on both Jtables, but I guess that they interfere with each other. So I'm pretty much stuck. Can someone explain how should I do it?
Here is the implementation (when I'm trying to do the same with the second Jtable it is not working):
table1.setDragEnabled(true);
table2.setTransferHandler(new TransferHandler() {
public boolean canImport(TransferSupport support) {
if (!support.isDrop()) {
return false;
}
if (!support.isDataFlavorSupported(DataFlavor.stringFlavor)) {
return false;
}
return true;
}
public boolean importData(TransferSupport support) {
if (!canImport(support)) {
return false;
}
int row2 = table1.getSelectedRow();
int rows[] = table1.getSelectedRows();
if (rows.length > 1){
Object strings2[][] = new String[rows.length][2];
for (int i=0; i<rows.length; i++) {
for (int j = 0; j < 2; j++)
strings2[i][j] = table1.getValueAt(rows[i], j);
}
String pathToCopy, pathToPaste;
for (int k=0; k<strings2.length; k++) {
if (path.equals("C:\\"))
pathToCopy = text1.getText() + trimmer(strings2[k][0].toString());
else
pathToCopy = text1.getText() + "\\" + trimmer(strings2[k][0].toString());
if (path2.equals("C:\\"))
pathToPaste = path2 + trimmer(strings2[k][0].toString());
else
pathToPaste = text2.getText() + "\\" + trimmer(strings2[k][0].toString());
File toCopy = new File(pathToCopy);
File toPaste = new File(pathToPaste);
try {
copyPaste(toCopy, toPaste);
} catch (IOException e) {
System.out.println("Nie można skopiować pliku!");
}
}
return true;
}
else {
if (row2 != -1) {
for (int i = 0; i < 2; i++)
strings[i] = table1.getValueAt(row2, i);
}
String pathToCopy, pathToPaste;
if (path.equals("C:\\"))
pathToCopy = text1.getText() + trimmer(strings[0].toString());
else
pathToCopy = text1.getText() + "\\" + trimmer(strings[0].toString());
if (path2.equals("C:\\"))
pathToPaste = path2 + trimmer(strings[0].toString());
else
pathToPaste = text2.getText() + "\\" + trimmer(strings[0].toString());
File toCopy = new File(pathToCopy);
File toPaste = new File(pathToPaste);
try {
copyPaste(toCopy, toPaste);
} catch (IOException e) {
System.out.println("Nie można skopiować pliku!");
}
return true;
}
}
});

java- using try-catch in the search algorithm error

i've got a problem when i use try-catch in the search method. when i input the wrong data, it just skips the catch block and output the code below it
do {
System.out.print(menu[1]);
jumlah = sc1.nextInt();
System.out.print(menu[0]);
tujuan = sc1.nextInt();
for (int i = 0; i < DataRek.length; i++) {
try {
if (tujuan == DataRek[i]) {
index = i;
nasabah = NamaRek[index];
break;
}
} catch (InputMismatchException e) {
System.out.println("DATA NASABAH TIDAK DITEMUKAN, SILAHKAN COBA LAGI");
System.exit(0);
}
}
} while (loop2 == 1);
System.out.println("Nomor rekening tujuan: " + tujuan);
System.out.println("Nama Nasabah: " + nasabah);
System.out.println("Jumlah yang ditransfer: " + jumlah);
System.out.println("Apakah data diatas sudah benar? (Y/N) ");
loop1 = sc1.next().charAt(0);
when i input the wrong data, i expect the output of DATA NASABAH TIDAK DITEMUKAN, but the actual output is the code below it.
The InputMismatchException is potentially thrown by Scanner's methods. You need to include them in the try block:
do {
try {
System.out.print(menu[1]);
jumlah = sc1.nextInt();
System.out.print(menu[0]);
tujuan = sc1.nextInt();
for (int i = 0; i < DataRek.length; i++) {
if (tujuan == DataRek[i]) {
index = i;
nasabah = NamaRek[index];
break;
}
}
} catch (InputMismatchException e) {
System.out.println("DATA NASABAH TIDAK DITEMUKAN, SILAHKAN COBA LAGI");
System.exit(0);
}
} while (loop2 == 1);

J2ME , Quizz using choiceGroups

I am working on a driving licence project on j2Me wich is including Tests like quizz , well and i am having a problem after parsing the questions and moving them into choiceGroups just like that :
if (questions.length > 0) {
for (int i = 0; i < questions.length; i++) {
ChoiceGroup reponses = new ChoiceGroup("Reponses" + i, Choice.EXCLUSIVE);
reponses.append(questions[i].getReponse1(), null);
reponses.append(questions[i].getReponse2(), null);
reponses.append(questions[i].getReponse3(), null);
pass.append(questions[i].getContenu());
pass.append(reponses);
}
}
} catch (Exception e) {
System.out.println("Exception:" + e.toString());
}
disp.setCurrent(pass);
and the next step is the command who's controlling the choiceGroups to test them if they are like the true answer or not .
so i am blocked here .
if (c == valider) {
int result = 0;
for (int i = 0; i < pass.size(); i++) {
String ch = pass.get(i).getLabel();
System.out.println(ch);
}
}
I don't know how to get the choice from the choicegroup
any help
Actually, I am not sure what totally you want for:
This code will help you get selected items from choicegroup that i did long time before:
//get a selected array in choicegroup
private String[] choiceGroupSelected(ChoiceGroup cg) {
String selectedArray[] = new String[cg.size()];
int k = 0;
for (int i = 0; i < cg.size(); i++) {
if (cg.isSelected(i)) {
selectedArray[k] = cg.getString(i);
k++;
}
}
return selectedArray;
}
That function will help me get all selected items for deleting action below:
private void deleteSpecificItem() {
try {
String temp = null;
int index;
//get ChoiceGroup size
int numbers = cgTrip.size();
String selectedItems[] = choiceGroupSelected(cgTrip);
//
rs = services.RecordStoreManager.openRecordStoreByName("TripRS");
re = rs.enumerateRecords(null, null, true);
String[] tripList = new String[2];
for (int i = 0; i < numbers; i++) {
temp = selectedItems[i];
if (temp != null) {
while (re.hasNextElement()) {
try {
index = re.nextRecordId();
System.out.println("RecordID: " + index);
byte[] byteBuff = rs.getRecord(index);
String source = new String(byteBuff);
tripList = services.StringManager.getItems(source, ";", 2);
String strProcess = tripList[0] + "-" + tripList[1];
//inspect all of items in choicegroup and if they are selecting then compare with record
//If comparison is true then delete this record
if (temp.equals(strProcess)) {
System.out.println("Delete RecordID: " + index);
rs.deleteRecord(index);
re.keepUpdated(true);
break;
}
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
}
}
}
try {
rs.closeRecordStore();
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
rs = null;
re.destroy();
this.LoadTripItem();
} catch (RecordStoreNotOpenException ex) {
ex.printStackTrace();
}
}

Why can my program not find a file after saving it

I am working on an inventory program and keep running into an issue. I have some text files that are named using a combination of numbers. I call them shelves. I open them up and edit them to store items in them. I am having a problem after I remove some objects from one of these.
How that process goes is I will open the file. Load it into a JTable. Select the item and amount I wish to remove. Then re save the file. That all works great until I go to open another shelf. Any other shelf I try to open after that process tells me that the shelf does not exist even if it the same one I just used. I can still go through the path on my computer and find it just fine and I can close the program and reopen it and it works just fine again until I remove and item from the shelf. I will post any relevant code below. Thanks for the help guys.
String[] binCombos = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10"};
JComboBox<String> aisle, column, row;
JButton open = new JButton("Open Shelf");
tableHolder = new JScrollPane(shelfsContents);
aisle = new JComboBox<String>(binCombos);
column = new JComboBox<String>(binCombos);
row = new JComboBox<String>(binCombos);
open.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
shelfCombo = aisle.getSelectedItem().toString() + column.getSelectedItem().toString() + row.getSelectedItem().toString() + ".txt";
File shelfName = new File(sPath + "\\" + shelfCombo);
if(shelfName.exists() == true && Console.console.IsPulling() == false)
{
OpenShelf(shelfName);
}
else
{
System.out.println(shelfName + " does not exist");
}
}
});
private void SaveShelf()
{
try
{
BufferedWriter bfw = new BufferedWriter(new FileWriter("shelfCombo"));
for(int i = 0; i < tableModel.getRowCount(); i++)
{
for(int j = 0; j < tableModel.getColumnCount(); j++)
{
if(j == 1 || j == 3)
{
if(Integer.parseInt(tableModel.getValueAt(i,3).toString()) > 0)
{
bfw.write(tableModel.getValueAt(i, j).toString());
bfw.write(" : ");
}
}
}
bfw.newLine();
}
bfw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
try this code
private void SaveShelf(){
PrintWriter pw ;
try
{
pw = new PrintWriter(new File("shelfCombo"));
for(int i = 0; i < tableModel.getRowCount(); i++)
{
for(int j = 0; j < tableModel.getColumnCount(); j++)
{
if(j == 1 || j == 3)
{
if(Integer.parseInt(tableModel.getValueAt(i,3).toString()) > 0)
{
pw.print(tableModel.getValueAt(i, j).toString());
pw.print(" : ");
}
}
}
pw.println();
pw.flush();
}
pw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
finally{
pw.close();
}
}

JAVA 6x6 grid colouring game

Hi everyone Im on to the last part now which is file reading. i have tried writing a fileReader but seem to not be changing the value of my variable rNum?
any ideas on why it wont change in the following statements? thanks
public void readStartFile(String fileName){
int rowNumber=-1;
int colNumber = -1;
int rN= 0;
int cN = 0;
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("start.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
String[] temp = strLine.split(" ");
rowNumber = Integer.parseInt(temp[0].substring(1, temp[0].length()));
colNumber = Integer.parseInt(temp[1].substring(1, temp[1].length()));
String colour = temp[2];
if(rowNumber == 0)
rN =0;
else if(rowNumber == 1)
rN =1;
else if(rowNumber == 2)
rN =2;
else if(rowNumber == 3)
rN =3;
else if(rowNumber == 4)
rN =4;
else if(rowNumber == 5)
rN =5;
if(colNumber == 0)
cN =0;
else if(colNumber == 1)
cN =1;
else if(colNumber == 2)
cN =2;
else if(colNumber == 3)
cN =3;
else if(colNumber == 4)
cN =4;
else if(colNumber == 5)
cN =5;
if (colour == "Red")
buttons[rN][cN].setBackground(Color.RED);
System.out.println(""+rN);
System.out.println(""+cN);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
this is a method from the ButtonColours class. Now how would i set the buttons to the specified colour as what i am doing at the minute does not seem to work.
Unfortunately, there is no reliable way to change the color of any JButton. Some "look and feel" implementations don't honor the color set by setBackground(). You'd be better off just adding a MouseListener to the panel(s) to listen for mouse-up events, and responding to those, rather than using buttons at all.
In order to change the Colour of your JButton, first of all you must keep one thing in mind, always to use buttonObject.setOpaque(true); as very much adviced to me once by #Robin :-). As taken from Java Docs the call to setOpaque(true/false)
Sets the background color of this component. The background color
is used only if the component is opaque
Here I had modified your code a bit, and added some comments as to what I had added, see is this what you wanted.
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class ButtonColours extends JFrame
{
private static ButtonColours buttonColours;
/*
* Access Specifier is public, so that they can be
* accessed by the ColourDialog class.
*/
public JButton[][] buttons;
private static final int GRID_SIZE = 600;
public static final int ROW = 6;
public static final int COLUMN = 6;
// Gap between each cell.
private static final int GAP = 2;
private static final Color DEFAULT_COLOUR = new Color(100,100,100);
public static final String DEFAULT_COMMAND = "6";
// Instance Variable for the ColourDialog class.
private ColourDialog dialog = null;
private BufferedReader input;
private DataInputStream dataInputStream;
private FileInputStream fileInputStream;
private String line= "";
/*
* Event Handler for each JButton, inside
* the buttons ARRAY.
*/
public ActionListener buttonActions = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
JButton button = (JButton) ae.getSource();
System.out.println(ae.getActionCommand());
if (dialog != null && dialog.isShowing())
dialog.dispose();
dialog = new ColourDialog(buttonColours, "COLOUR CHOOSER", false, button);
dialog.setVisible(true);
button.setBackground(DEFAULT_COLOUR);
button.setName("6");
}
};
public ButtonColours()
{
buttons = new JButton[ROW][COLUMN];
try
{
fileInputStream = new FileInputStream("start.txt");
dataInputStream = new DataInputStream(fileInputStream);
input = new BufferedReader(new InputStreamReader(dataInputStream));
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
/*
* Instead of explicitly calling getPreferredSize() method
* we will override that method instead, for good
* visual appearance fo the Program on different
* Platforms, i.e. Windows, MAC OS, LINUX
*/
public Dimension getPreferredSize()
{
return (new Dimension(GRID_SIZE, GRID_SIZE));
}
private void readFile()
{
int rowNumber = -1;
int columnNumber = -1;
try
{
while((line = input.readLine()) != null)
{
String[] temp = line.split(" ");
rowNumber = Integer.parseInt(temp[0].substring(1, temp[0].length()));
columnNumber = Integer.parseInt(temp[1].substring(1, temp[1].length()));
String colour = temp[2].trim();
System.out.println("Row is : " + rowNumber);
System.out.println("Column is : " + columnNumber);
System.out.println("Colour is : " + colour);
if (colour.equals("RED") && rowNumber < ROW && columnNumber < COLUMN)
{
System.out.println("I am working !");
buttons[rowNumber][columnNumber].setBackground(Color.RED);
buttons[rowNumber][columnNumber].setName("0");
}
else if (colour.equals("YELLOW") && rowNumber < ROW && columnNumber < COLUMN)
{
buttons[rowNumber][columnNumber].setBackground(Color.YELLOW);
buttons[rowNumber][columnNumber].setName("1");
}
else if (colour.equals("BLUE") && rowNumber < ROW && columnNumber < COLUMN)
{
buttons[rowNumber][columnNumber].setBackground(Color.BLUE);
buttons[rowNumber][columnNumber].setName("2");
}
else if (colour.equals("GREEN") && rowNumber < ROW && columnNumber < COLUMN)
{
buttons[rowNumber][columnNumber].setBackground(Color.GREEN);
buttons[rowNumber][columnNumber].setName("3");
}
else if (colour.equals("PURPLE") && rowNumber < ROW && columnNumber < COLUMN)
{
buttons[rowNumber][columnNumber].setBackground(new Color(102,0,102));
buttons[rowNumber][columnNumber].setName("4");
}
else if (colour.equals("BROWN") && rowNumber < ROW && columnNumber < COLUMN)
{
buttons[rowNumber][columnNumber].setBackground(new Color(102,51,0));
buttons[rowNumber][columnNumber].setName("5");
}
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
private void createAndDisplayGUI()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
JComponent contentPane = (JComponent) getContentPane();
contentPane.setLayout(new GridLayout(ROW, COLUMN, GAP, GAP));
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COLUMN; j++)
{
buttons[i][j] = new JButton();
buttons[i][j].setOpaque(true);
buttons[i][j].setBackground(DEFAULT_COLOUR);
buttons[i][j].setActionCommand(i + " " + j);
buttons[i][j].setName("6");
buttons[i][j].addActionListener(buttonActions);
contentPane.add(buttons[i][j]);
}
}
pack();
setVisible(true);
readFile();
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
buttonColours = new ButtonColours();
buttonColours.createAndDisplayGUI();
}
});
}
}
class ColourDialog extends JDialog
{
private Color[] colours = {
Color.RED,
Color.YELLOW,
Color.BLUE,
Color.GREEN,
new Color(102,0,102),
new Color(102,51,0)
};
private int[] colourIndices = new int[6];
private JButton redButton;
private JButton yellowButton;
private JButton blueButton;
private JButton greenButton;
private JButton purpleButton;
private JButton brownButton;
private JButton clickedButton;
private int leftRowButtons;
private int leftColumnButtons;
public ColourDialog(final ButtonColours frame, String title, boolean isModal, JButton button)
{
super(frame, title, isModal);
leftRowButtons = 0;
leftColumnButtons = 0;
clickedButton = button;
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setLocationByPlatform(true);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1, 5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
redButton = new JButton("RED");
redButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String possibleColour = "0";
/*
* Here we will check, if RED is clicked,
* do we have any block with the same colour
* or not, if yes then nothing will happen
* else we will change the background
* to RED.
*/
if (checkBlockColours(frame, possibleColour))
{
clickedButton.setBackground(Color.RED);
clickedButton.setName("0");
dispose();
System.out.println("LEFT in ROW : " + leftRowButtons);
System.out.println("LEFT in COLUMN : " + leftColumnButtons);
System.out.println("Button Name : " + clickedButton.getName());
fillRemaining(frame);
}
}
});
yellowButton = new JButton("YELLOW");
yellowButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String possibleColour = "1";
if (checkBlockColours(frame, possibleColour))
{
clickedButton.setBackground(Color.YELLOW);
clickedButton.setName("1");
dispose();
System.out.println("LEFT in ROW : " + leftRowButtons);
System.out.println("LEFT in COLUMN : " + leftColumnButtons);
System.out.println("Button Name : " + clickedButton.getName());
fillRemaining(frame);
}
}
});
blueButton = new JButton("BLUE");
blueButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String possibleColour = "2";
if (checkBlockColours(frame, possibleColour))
{
clickedButton.setBackground(Color.BLUE);
clickedButton.setName("2");
dispose();
System.out.println("LEFT in ROW : " + leftRowButtons);
System.out.println("LEFT in COLUMN : " + leftColumnButtons);
System.out.println("Button Name : " + clickedButton.getName());
fillRemaining(frame);
}
}
});
greenButton = new JButton("GREEN");
greenButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String possibleColour = "3";
if (checkBlockColours(frame, possibleColour))
{
clickedButton.setBackground(Color.GREEN);
clickedButton.setName("3");
dispose();
System.out.println("LEFT in ROW : " + leftRowButtons);
System.out.println("LEFT in COLUMN : " + leftColumnButtons);
System.out.println("Button Name : " + clickedButton.getName());
fillRemaining(frame);
}
}
});
purpleButton = new JButton("PURPLE");
purpleButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String possibleColour = "4";
if (checkBlockColours(frame, possibleColour))
{
clickedButton.setBackground(new Color(102,0,102));
clickedButton.setName("4");
dispose();
System.out.println("LEFT in ROW : " + leftRowButtons);
System.out.println("LEFT in COLUMN : " + leftColumnButtons);
System.out.println("Button Name : " + clickedButton.getName());
fillRemaining(frame);
}
}
});
brownButton = new JButton("BROWN");
brownButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
String possibleColour = "5";
if (checkBlockColours(frame, possibleColour))
{
clickedButton.setBackground(new Color(102,51,0));
clickedButton.setName("5");
dispose();
System.out.println("LEFT in ROW : " + leftRowButtons);
System.out.println("LEFT in COLUMN : " + leftColumnButtons);
System.out.println("Button Name : " + clickedButton.getName());
fillRemaining(frame);
}
}
});
panel.add(redButton);
panel.add(yellowButton);
panel.add(blueButton);
panel.add(greenButton);
panel.add(purpleButton);
panel.add(brownButton);
add(panel);
pack();
}
private boolean checkBlockColours(ButtonColours frame, String possibleColour)
{
leftRowButtons = 0;
leftColumnButtons = 0;
String command = clickedButton.getActionCommand();
String[] array = command.split(" ");
int row = Integer.parseInt(array[0]);
int column = Integer.parseInt(array[1]);
// First we will check in ROW. for the same colour, that is clicked.
for (int i = 0; i < ButtonColours.COLUMN; i++)
{
if (i != column)
{
JButton button = frame.buttons[row][i];
if (button.getName().equals(possibleColour))
return false;
else if (button.getName().equals(ButtonColours.DEFAULT_COMMAND))
leftRowButtons++;
}
}
// Now we will check in COLUMN, for the same colour, that is clicked.
for (int i = 0; i < ButtonColours.ROW; i++)
{
if (i != row)
{
JButton button = frame.buttons[i][column];
if (button.getName().equals(possibleColour))
return false;
else if (button.getName().equals(ButtonColours.DEFAULT_COMMAND))
leftColumnButtons++;
}
}
return true;
}
private void fillRemaining(ButtonColours frame)
{
String command = clickedButton.getActionCommand();
String[] array = command.split(" ");
int row = Integer.parseInt(array[0]);
int column = Integer.parseInt(array[1]);
int emptyRow = -1;
int emptyColumn = -1;
if (leftRowButtons == 1)
{
for (int i = 0; i < ButtonColours.COLUMN; i++)
{
JButton button = frame.buttons[row][i];
int colourIndex = Integer.parseInt(button.getName());
switch(colourIndex)
{
case 0:
colourIndices[0] = 1;
break;
case 1:
colourIndices[1] = 1;
break;
case 2:
colourIndices[2] = 1;
break;
case 3:
colourIndices[3] = 1;
break;
case 4:
colourIndices[4] = 1;
break;
case 5:
colourIndices[5] = 1;
break;
default:
emptyRow = row;
emptyColumn = i;
}
}
for (int i = 0; i < colourIndices.length; i++)
{
if (colourIndices[i] == 0)
{
frame.buttons[emptyRow][emptyColumn].setBackground(colours[i]);
setButtonName(frame.buttons[emptyRow][emptyColumn], i);
System.out.println("Automatic Button Name : " + frame.buttons[emptyRow][emptyColumn].getName());
System.out.println("Automatic Row : " + emptyRow);
System.out.println("Automatic Column : " + emptyColumn);
disableListenersRow(frame, row);
if (checkBlockColours(frame, ButtonColours.DEFAULT_COMMAND))
{
System.out.println("LEFT in ROW : " + leftRowButtons);
System.out.println("LEFT in COLUMN : " + leftColumnButtons);
System.out.println("Button Name : " + clickedButton.getName());
fillRemaining(frame);
}
break;
}
}
}
if (leftColumnButtons == 1)
{
for (int i = 0; i < ButtonColours.ROW; i++)
{
JButton button = frame.buttons[i][column];
int colourIndex = Integer.parseInt(button.getName());
switch(colourIndex)
{
case 0:
colourIndices[0] = 1;
break;
case 1:
colourIndices[1] = 1;
break;
case 2:
colourIndices[2] = 1;
break;
case 3:
colourIndices[3] = 1;
break;
case 4:
colourIndices[4] = 1;
break;
case 5:
colourIndices[5] = 1;
break;
default:
emptyRow = i;
emptyColumn = column;
}
}
for (int i = 0; i < colourIndices.length; i++)
{
if (colourIndices[i] == 0)
{
frame.buttons[emptyRow][emptyColumn].setBackground(colours[i]);
setButtonName(frame.buttons[emptyRow][emptyColumn], i);
System.out.println("Automatic Button Name : " + frame.buttons[emptyRow][emptyColumn].getName());
System.out.println("Automatic Row : " + emptyRow);
System.out.println("Automatic Column : " + emptyColumn);
disableListenersColumn(frame, column);
if (checkBlockColours(frame, ButtonColours.DEFAULT_COMMAND))
{
System.out.println("LEFT in ROW : " + leftRowButtons);
System.out.println("LEFT in COLUMN : " + leftColumnButtons);
System.out.println("Button Name : " + clickedButton.getName());
fillRemaining(frame);
}
break;
}
}
}
}
private void setButtonName(JButton button, int index)
{
switch(index)
{
case 0:
button.setName("0");
break;
case 1:
button.setName("1");
break;
case 2:
button.setName("2");
break;
case 3:
button.setName("3");
break;
case 4:
button.setName("4");
break;
case 5:
button.setName("5");
break;
}
}
private void disableListenersRow(ButtonColours frame, int row)
{
System.out.println("Disabled ROW : " + row);
for (int i = 0; i < ButtonColours.ROW; i++)
{
frame.buttons[row][i].removeActionListener(frame.buttonActions);
System.out.println("DISABLED BUTTONS : " + row + " " + i);
}
}
private void disableListenersColumn(ButtonColours frame, int column)
{
System.out.println("Disabled COLUMN : " + column);
for (int i = 0; i < ButtonColours.COLUMN; i++)
{
frame.buttons[i][column].removeActionListener(frame.buttonActions);
System.out.println("DISABLED BUTTONS : " + i + " " + column);
}
}
}
Here is the output of this thingy :-)
(maybe use JColorChooser directly)
don't use two JFrames
use putClientProperty
use ButtonModel or MouseListener
use JOptionsPane put there JButtons that returns Color, or create JDialog(parent, true) with JButtons layed by GridLayout
One convenient and reliable way to alter a button's appearance in any L&F is to implement the Icon interface, as shown in this example.

Categories