In my code, I'm trying to use a JScrollPane and add it into a JOptionPane.showMessageDialog. I don't know if this is possible to start with but I don't know how to do it if it is, and how to add the whole array into the one message and not multiple. Here is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Iterator;
public class CulminatingPro implements ActionListener
{
//Create an array of buttons
static JButton[][] buttons = new JButton[10][4];
static JButton jbtList = new JButton("List");
ArrayList<Culminating> flyers = new ArrayList<Culminating>();
String fn;
String ln;
String pn;
String adress;
int column;
int row;
int reply;
int v;
Object[] options = {"First Name",
"Last Name",
"Phone Number",
"Adress"};
public static void main(String[] args)
{
JFrame frame = new JFrame("Fly By Buddies");
frame.setSize(900, 900);
JPanel mainPanel = new JPanel();
mainPanel.setLayout( new GridLayout(1,2));
JPanel paneSeats = new JPanel();
JPanel paneInfo = new JPanel();
paneSeats.setLayout( new GridLayout(11, 4, 5,5));
mainPanel.add(paneSeats);
mainPanel.add(paneInfo);
frame.setContentPane(mainPanel);
for (int i = 0; i < buttons.length; i++)
{
for(int j = 0; j < buttons[0].length; j++)
{
if (j + 1 == 1)
{
buttons[i][j] = new JButton("Seat " + (i + 1) + "A");
buttons[i][j].setBackground(Color.GREEN);
paneSeats.add(buttons[i][j]);
buttons[i][j].addActionListener(new CulminatingPro());
}
else if (j + 1 == 2)
{
buttons[i][j] = new JButton("Seat " + (i + 1) + "B");
buttons[i][j].setBackground(Color.GREEN);
paneSeats.add(buttons[i][j]);
buttons[i][j].addActionListener(new CulminatingPro());
}
else if (j + 1== 3)
{
buttons[i][j] = new JButton("Seat " + (i + 1) + "C");
buttons[i][j].setBackground(Color.GREEN);
paneSeats.add(buttons[i][j]);
buttons[i][j].addActionListener(new CulminatingPro());
}
else if (j + 1== 4)
{
buttons[i][j] = new JButton("Seat " + (i + 1) + "D");
buttons[i][j].setBackground(Color.GREEN);
paneSeats.add(buttons[i][j]);
buttons[i][j].addActionListener(new CulminatingPro());
}
}
}
jbtList.setPreferredSize(new Dimension(400, 40));
jbtList.addActionListener(new CulminatingPro());
paneInfo.add(jbtList, BorderLayout.SOUTH);
frame.setVisible(true);
frame.toFront();
}
public void actionPerformed(ActionEvent event)
{
for (int i = 0; i < buttons.length; i++)
{
for(int j = 0; j < buttons[0].length; j++)
{
if (event.getSource() == buttons[i][j])
{
v = 0;
for (int k = 0; k < flyers.size();k++)
{
if((flyers.get(k).getColumn() == (j) && (flyers.get(k).getColumn() == (j))))
{
if (!flyers.get(k).getFirstName().equals(""))
{
reply = JOptionPane.showConfirmDialog(null,
"Would you like to delete the info on the passenger?", "Deletion", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION)
{
flyers.remove(k);
buttons[i][j].setBackground(Color.GREEN);
}
else if (reply == JOptionPane.NO_OPTION)
{
reply = JOptionPane.showConfirmDialog(null,
"Would you like to modify the info on the passenger?", "Modification", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION)
{
int n = JOptionPane.showOptionDialog(null, "Message", "Title",
JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
n = n + 1;
if(n == 0)
{
fn = JOptionPane.showInputDialog(null,"Re-enter passenger's first name: ");
flyers.get(k).setFirstName(fn);
}
if(n == 2)
{
ln = JOptionPane.showInputDialog(null,"Re-enter passenger's last name: ");
flyers.get(k).setLastName(ln);
}
if(n == 3)
{
pn = JOptionPane.showInputDialog(null,"Re-enter passenger's phone number: ");
flyers.get(k).setPhoneNumber(pn);
}
if(n == 4)
{
adress = JOptionPane.showInputDialog(null,"Re-enter passenger's adress: ");
flyers.get(k).setAdress(adress);
}
}
}
v = 1;
}
}
}
if(v == 0)
{
fn = JOptionPane.showInputDialog(null,"Passenger's first name (Necessary): ");
ln = JOptionPane.showInputDialog(null,"Passenger's last name (Necessary): ");
pn = JOptionPane.showInputDialog(null,"Passenger's phone number: ");
adress = JOptionPane.showInputDialog(null,"Passenger's adress: ");
column = j;
row = i;
flyers.add(new Culminating(fn,ln,pn,adress,column,row));
buttons[i][j].setBackground(Color.RED);
}
}
}
}
if (event.getSource().equals("List"))
{
JScrollPane[] scroll = new JScrollPane[flyers.size()];
for(int p = 0; p < flyers.size(); p++)
{
JTextArea text = new JTextArea(flyers.get(p).toString(), 10, 40);
scroll[p] = new JScrollPane(text);
}
for(int p = 0; p < flyers.size(); p++)
{
JOptionPane.showMessageDialog(null,scroll[p]);
}
}
}
}
Related
I am trying to make a JFrame program that interfaces a binary-decimal-hexadecimal converter with buttons. A part of this, I would like to draw circles to represent binary numbers in a row of circles with a filled circle representing a one and an empty circle representing a zero. However, when I try to call repaint to draw anything, it does not execute the paintComponent() method, which I know because it does not perform the print statement inside of it. Full code below:
package e2;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.FlowLayout;
public class DecBin extends JPanel {
String theText = "IT WORKS";
int style = Font.BOLD; // bold only
Font font = new Font("Arial", style, 40);
DecBin() {
JFrame f = new JFrame("Decimal to binary and binary to decimal converter");
f.setSize(1000, 1000);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout());
Font font = new Font("Arial", style, 40);
JLabel textLabel = new JLabel(theText);
textLabel.setFont(font);
JButton b = new JButton("DectoBin");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = JOptionPane.showInputDialog("input a decimal number");
int num = Integer.parseInt(msg);
theText = num + " is " + decToBin(num) + " in binary";
textLabel.setText(theText);
}
});
f.add(b);
JButton d = new JButton("BintoDec");
d.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = JOptionPane.showInputDialog("input a binary number");
System.out.print("The decimal form of " + msg + " is " + binToDec(msg));
theText = msg + " is " + binToDec(msg) + " in decimal";
textLabel.setText(theText);
}
});
f.add(d);
JButton hd = new JButton("hexToDec");
hd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = JOptionPane.showInputDialog("input a hexadecimal number");
theText = msg + " is " + hexToDec(msg) + " in decimal";
textLabel.setText(theText);
}
});
f.add(hd);
JButton dh = new JButton("DectoHex");
dh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = JOptionPane.showInputDialog("input a decimal number");
int num = Integer.parseInt(msg);
theText = num + " is " + decToHex(num) + " in hexadecimal";
textLabel.setText(theText);
}
});
f.add(dh);
JButton bh = new JButton("BinToHex");
bh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = JOptionPane.showInputDialog("input a binary number");
theText = msg + " is " + decToHex(binToDec(msg)) + " in hexadecimal";
textLabel.setText(theText);
}
});
f.add(bh);
JButton hb = new JButton("HexToBin");
hb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = JOptionPane.showInputDialog("input a Hexadecimal number");
theText = msg + " is " + decToBin(hexToDec(msg)) + " in hexadecimal";
textLabel.setText(theText);
}
});
f.add(hb);
JButton c = new JButton("Draw");
c.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.print("test1");
validate();
repaint();
}
});
f.add(c);
f.add(textLabel, BorderLayout.SOUTH);
f.setVisible(true);
}
public static void main(String[] args) {
new DecBin();
}
static String decToBin(int d) {
StringBuilder binary = new StringBuilder("");
while (d != 0) {
binary.insert(0, d % 2);
d = d / 2;
}
return binary.toString();
}
static int binToDec(String b) {
int total = 0;
int x;
for (int i = b.length(); i > 0; i--) {
x = Integer.parseInt(Character.toString(b.charAt(i - 1)));
if (x == 1) {
total += Math.pow(2, b.length() - i);
}
}
return total;
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.red);
g2.fillOval(100, 100, 20, 20);
System.out.print("painted components");
}
static String decToHex(int d) {
StringBuilder Hex = new StringBuilder("");
while (d != 0) {
int remainder = d % 16;
if (remainder < 10) {
Hex.insert(0, d % 16);
} else if (remainder == 10) {
Hex.insert(0, 'A');
} else if (remainder == 11) {
Hex.insert(0, 'B');
} else if (remainder == 12) {
Hex.insert(0, 'C');
} else if (remainder == 13) {
Hex.insert(0, 'D');
} else if (remainder == 14) {
Hex.insert(0, 'E');
} else if (remainder == 15) {
Hex.insert(0, 'F');
}
d = d / 16;
}
return Hex.toString();
}
static int hexToDec(String b) {
int total = 0;
int len = b.length();
for (int i = len - 1; i >= 0; i--) {
if (b.charAt(i) == 'A') {
total += 10 * Math.pow(16, len - i - 1);
} else if (b.charAt(i) == 'B') {
total += 11 * Math.pow(16, len - i - 1);
} else if (b.charAt(i) == 'C') {
total += 12 * Math.pow(16, len - i - 1);
} else if (b.charAt(i) == 'D') {
total += 13 * Math.pow(16, len - i - 1);
} else if (b.charAt(i) == 'E') {
total += 14 * Math.pow(16, len - i - 1);
} else if (b.charAt(i) == 'F') {
total += 15 * Math.pow(16, len - i - 1);
} else {
total += Character.getNumericValue(b.charAt(i)) * Math.pow(16, len - i - 1);
}
}
return total;
}
}
Pertinent code in my opinion is:
DecBin() {
JFrame f=new JFrame("Decimal to binary and binary to decimal converter");
f.setSize(1000,1000);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new FlowLayout());
JButton c =new JButton("Draw");
c.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.print("test1");
validate();
repaint();
}
});
f.add(c);
f.setVisible(true);
}
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.red);
g2.fillOval(100, 100, 20, 20);
System.out.print("painted components");
}
public static void main(String[] args) {
new DecBin();
}
I have spent hours researching this and have yet to find a solution that will get "painted components" to print.
You do not appear to be adding your DecBin panel to any other UI element. It therefore has no reason to be painted.
You should avoid initializing JFrames inside the constructor of your JPanel child class - it should really be the other way around. That will make things easier to understand (and to debug).
The calculator I am working on will solve the first problem perfectly, but when add is hit a second time, the answer moves closer to the addends and both the addends and the sum remain the same. Can anyone shine some light on what is making my program act this way? Thanks!
public class GUI extends JFrame implements ActionListener{
private JTextField field1;
private JTextField field2;
private JButton add, subtract, multiply, divide;
private JLabel lanswer, label1, label2;
private String input1, input2, sanswer;
private int answer = 0;
JPanel contentPanel, answerPanel;
public GUI(){
super("Calculator");
field1 = new JTextField(null, 15);
field2 = new JTextField(null, 15);
add = new JButton("add");
subtract = new JButton("subtract");
multiply = new JButton("multiply");
divide = new JButton("divide");
lanswer = new JLabel("", SwingConstants.CENTER);
label1 = new JLabel("Value 1:");
label2 = new JLabel("Value 2:");
add.addActionListener(this);
Dimension opSize = new Dimension(110, 20);
Dimension inSize = new Dimension(200, 20);
lanswer.setPreferredSize(new Dimension(200,255));
field1.setPreferredSize(inSize);
field2.setPreferredSize(inSize);
add.setPreferredSize(opSize);
subtract.setPreferredSize(opSize);
multiply.setPreferredSize(opSize);
divide.setPreferredSize(opSize);
contentPanel = new JPanel();
contentPanel.setBackground(Color.PINK);
contentPanel.setLayout(new FlowLayout());
answerPanel = new JPanel();
answerPanel.setPreferredSize(new Dimension(230, 260));
answerPanel.setBackground(Color.WHITE);
answerPanel.setLayout(new BoxLayout(answerPanel, BoxLayout.Y_AXIS));
contentPanel.add(answerPanel);
contentPanel.add(label1); contentPanel.add(field1);
contentPanel.add(label2); contentPanel.add(field2);
contentPanel.add(add); contentPanel.add(subtract); contentPanel.add(multiply); contentPanel.add(divide);
this.setContentPane(contentPanel);
}
public void actionPerformed(ActionEvent e) {
JButton src = (JButton)e.getSource();
if(src.equals(add)){
add();
}
}
private void add(){
input1 = field1.getText();
input2 = field2.getText();
MathEquation problem = new MathEquation(input1, input2);
Dimension lineSize = new Dimension(200, 10);
JPanel line1 = new JPanel(); line1.setBackground(Color.WHITE);
line1.setPreferredSize(lineSize);
JPanel line2 = new JPanel(); line2.setBackground(Color.WHITE);
line2.setPreferredSize(lineSize);
JPanel line3 = new JPanel(); line3.setBackground(Color.WHITE);
line3.setPreferredSize(lineSize);
JPanel line4 = new JPanel(); line4.setBackground(Color.WHITE);
line4.setPreferredSize(lineSize);
JPanel line5 = new JPanel(); line5.setBackground(Color.WHITE);
JLabel[] sumLabels = problem.getSumLabels();
JLabel[] addend1Labels = problem.getAddend1Labels();
JLabel[] addend2Labels = problem.getAddend2Labels();
JLabel[] carriedLabels = problem.getCarriedLabels();
for(int i = 0; i < carriedLabels.length; i++){
line1.add(carriedLabels[i]);
}
for(int i = 0; i < addend1Labels.length; i++){
line2.add(addend1Labels[i]);
}
for(int i = 0; i < addend2Labels.length; i++){
line3.add(addend2Labels[i]);
}
String answerLine = "__";
for(int i = 0; i < sumLabels.length; i++){
answerLine += "__";
}
line4.add(new JLabel(answerLine));
for(int i = 0; i < sumLabels.length; i++){
line5.add(sumLabels[i]);
}
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
answerPanel.add(line1);
answerPanel.add(line1);
answerPanel.add(line2);
answerPanel.add(line3);
answerPanel.add(line4);
answerPanel.add(line5);
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
answerPanel.add(new JLabel(" "));
this.setContentPane(contentPanel);
this.revalidate();
}
private String subtract(){
input1 = field1.getText();
input2 = field2.getText();
answer = Integer.parseInt(input1) - Integer.parseInt(input2);
sanswer = "<html><p align='right'>" + input1 + "<br>-+";
if(input1.length() >= input2.length()){
for(int i = 0; i < input1.length() - input2.length() + 1; i++){
sanswer+=" ";
}
}
sanswer += input2 + "<br>";
if(input1.length() >= input2.length()){
for(int i = 0; i < input1.length(); i++){
sanswer+="--";
}
}
else
{
for(int i = 0; i < input2.length(); i++){
sanswer+="--";
}
}
sanswer += "<br>" + answer + "</p></html>";
return sanswer;
}
private String multiply(){
input1 = field1.getText();
input2 = field2.getText();
answer = Integer.parseInt(input1) * Integer.parseInt(input2);
sanswer = "<html><p align='right'>" + input1 + "<br>x";
if(input1.length() >= input2.length()){
for(int i = 0; i < input1.length() - input2.length() + 1; i++){
sanswer+=" ";
}
}
sanswer += input2 + "<br>";
if(input1.length() >= input2.length()){
for(int i = 0; i < input1.length(); i++){
sanswer+="--";
}
}
else
{
for(int i = 0; i < input2.length(); i++){
sanswer+="--";
}
}
sanswer += "<br>" + answer + "</p></html>";
return sanswer;
}
}
MathEquation:
public class MathEquation {
private ArrayList<Character> addend1, addend2, sum, carried;
public MathEquation(String a, String b){
setAddends(a, b);
findSum();
System.out.println(carried.toString());
System.out.println(" "+addend1.toString());
System.out.println(" "+addend2.toString());
System.out.println(" "+sum.toString());
}
public JLabel[] getAddend1Labels(){
Dimension addendSize = new Dimension(10,10);
JLabel[] getAddend1 = new JLabel[addend1.size()];
for(int i = 0; i < addend1.size(); i++){
getAddend1[i] = new JLabel(addend1.get(i).toString());
getAddend1[i].setPreferredSize(addendSize);
}
return getAddend1;
}
public JLabel[] getAddend2Labels(){
Dimension addendSize = new Dimension(10,10);
JLabel[] getAddend2 = new JLabel[addend2.size()];
for(int i = 0; i < addend2.size(); i++){
getAddend2[i] = new JLabel(addend2.get(i).toString());
getAddend2[i].setPreferredSize(addendSize);
}
return getAddend2;
}
public JLabel[] getSumLabels(){
Dimension sumSize = new Dimension(10,10);
JLabel[] getSum = new JLabel[sum.size()];
for(int i = 0; i < sum.size(); i++){
getSum[i] = new JLabel(sum.get(i).toString());
getSum[i].setPreferredSize(sumSize);
}
return getSum;
}
public JLabel[] getCarriedLabels(){
Dimension carriedSize = new Dimension(10,10);
JLabel[] getCarried = new JLabel[carried.size()];
for(int i = 0; i < carried.size(); i++){
getCarried[i] = new JLabel(carried.get(i).toString());
getCarried[i].setPreferredSize(carriedSize);
}
return getCarried;
}
public void setAddends(String a, String b){
char[] arrayA = a.toCharArray();
char[] arrayB = b.toCharArray();
addend1 = new ArrayList<Character>();
addend2 = new ArrayList<Character>();
ArrayList wholeA = new ArrayList();
ArrayList wholeB = new ArrayList();
boolean wholeNumber = true;
ArrayList decimalA = new ArrayList();
ArrayList decimalB = new ArrayList();
int decALength = 0, decBLength = 0;
for(int i = 0; i < arrayA.length; i++){
if(arrayA[i] != '.'){
addend1.add(arrayA[i]);
if(wholeNumber){
wholeA.add(arrayA[i]);
} else {
decimalA.add(arrayA[i]);
}
} else {
addend1.add(arrayA[i]);
wholeNumber = false;
decALength = Arrays.copyOfRange(arrayA, i+1, arrayA.length).length;
System.out.println(decALength);
}
}
wholeNumber = true;
for(int i = 0; i < arrayB.length; i++){
if(arrayB[i] != '.'){
addend2.add(arrayB[i]);
if(wholeNumber){
wholeB.add(arrayB[i]);
} else {
decimalB.add(arrayB[i]);
}
} else {
addend2.add(arrayB[i]);
wholeNumber = false;
decBLength = Arrays.copyOfRange(arrayB, i+1, arrayB.length).length;
System.out.println(decBLength);
}
}
if(decALength>decBLength){
if(decBLength==0){
addend2.add('.');
}
for(int i = 0; i < decALength-decBLength; i++){
addend2.add('0');
}
} else if(decBLength>decALength){
if(decALength==0){
addend1.add('.');
}
for(int i = 0; i < decBLength-decALength; i++){
addend1.add('0');
}
}
if(wholeA.size() < wholeB.size())
for(int i = 0; i < wholeB.size()-wholeA.size(); i++)
addend1.add(0, '0');
else if(wholeA.size() > wholeB.size())
for(int i = 0; i < wholeA.size()-wholeB.size(); i++)
addend2.add(0, '0');
addend1.add(0, '0');
addend2.add(0, '0');
}
private void findSum(){
sum = new ArrayList<Character>();
carried = new ArrayList<Character>();
int dec = 0;
carried.add('0');
for(int i = addend1.size()-1; i >= 0; i--){
if(addend1.get(i) != '.'){
int a = Character.getNumericValue(addend1.get(i));
int b = Character.getNumericValue(addend2.get(i));
int c = Character.getNumericValue(carried.get(carried.size()-1));
int d = a + b + c;
if(d >= 10){
carried.add('1');
d-=10;
sum.add((char) ('0' + d));
} else {
carried.add('0');
sum.add((char) ('0' + d));
}
} else {
sum.add('.');
carried.add(carried.size()-1, ' ');
}
}
Collections.reverse(sum);
Collections.reverse(carried);
carried.remove(0);
for(int i = 0; i < carried.size(); i++){
if(carried.get(i) == '0'){
carried.set(i, ' ');
}
}
for(int i = 0; i < addend1.size(); i++){
if(addend1.get(i) == '0'){
addend1.set(i, ' ');
}
else break;
}
for(int i = 0; i < addend2.size(); i++){
if(addend2.get(i) == '0'){
addend2.set(i, ' ');
}
else break;
}
for(int i = 0; i < sum.size(); i++){
if(sum.get(i) == '0'){
sum.set(i, ' ');
}
else break;
}
}
}
Am getting a java.lang.NullPointerException on an array I have initialized and I can't quite figure it out what am doing wrong. The error is occuring at line 371.
Below is the code of the parent class followed by the class initializng the letterArray ArrayList:
package wordsearch;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Line2D;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
/**
* Main class of Puzzle Program
* #author mungaialex
*
*/
public class WordSearchPuzzle extends JFrame {
private static final long serialVersionUID = 1L;
/** No. Of Columns in Wordlist*/
private static final int WORDLISTCOLS = 1;
static JButton[][] grid; //names the grid of buttons
GridLayout myGridLayout = new GridLayout(1,2,3,3);
/**Array to hold wordList*/
ArrayList<String> wordList;
JButton btnCheck, btnClear;
/** Panel to hold Components to the left*/
JPanel leftSidePanel;
/** Panel to hold components to the right*/
JPanel rightSidePanel;
/**Panel to hold word List*/
JPanel wordListPanel;
/**Panel to hold grid buttons*/
JPanel gridPanel;
/**Panel to hold clear button and check button*/
JPanel buttonsPanel;
/**Panel to hold output textarea*/
JPanel bottomPanel;
private JLabel[] wordListComponents;
#SuppressWarnings("rawtypes")
List puzzleLines;
//Grid Size
private final int ROWS = 20;
private final int COLS = 20;
/** Output Area of system*/
private JTextArea txtOutput;
/**Scrollpane for Output area*/
private JScrollPane scptxtOutput;
private Object[] theWords;
public String wordFromChars = new String();
/** the matrix of the letters */
private char[][] letterArray = null;
/**
* Constructor for WordSearchPuzzle
* #param wordListFile File Containing words to Search for
* #param wordSearhPuzzleFile File Containing the puzzle
*/
public WordSearchPuzzle(String wordSearchFile,String wordsListFile) throws IOException {
FileIO io = new FileIO(wordSearchFile,wordsListFile,grid);
wordList = io.loadWordList();
theWords = wordList.toArray();
addComponentsToPane();
buildWordListPanel();
buildBottomPanel();
io.loadPuzleFromFile();
//Override System.out
PrintStream stream = new PrintStream(System.out) {
#Override
public void print(String s) {
txtOutput.append(s + "\n");
txtOutput.setCaretPosition(txtOutput.getText().length());
}
};
System.setOut(stream);
System.out.print("MESSAGES");
}
/**
* Constructor two
*/
public WordSearchPuzzle() {
}
/**
* Gets the whole word of buttons clicked
* #return
* Returns whole Word
*/
public String getSelectedWord() {
return wordFromChars;
}
/**
* Adds word lists to Panel on the left
*/
private void buildWordListPanel() {
leftSidePanel.setBackground(Color.WHITE);
// Build the word list
wordListComponents = new JLabel[wordList.size()];
wordListPanel = new JPanel(new GridLayout(25, 1));
wordListPanel.setBackground(Color.white);
//Loop through list of words
for (int i = 0; i < this.wordList.size(); i++) {
String word = this.wordList.get(i).toUpperCase();
wordListComponents[i] = new JLabel(word);
wordListComponents[i].setForeground(Color.BLUE);
wordListComponents[i].setHorizontalAlignment(SwingConstants.LEFT);
wordListPanel.add(wordListComponents[i]);
}
leftSidePanel.add(wordListPanel,BorderLayout.WEST);
}
/**
* Adds an output area to the bottom of
*/
private void buildBottomPanel() {
bottomPanel = new JPanel();
bottomPanel.setLayout(new BorderLayout());
txtOutput = new JTextArea();
txtOutput.setEditable(false);
txtOutput.setRows(5);
scptxtOutput = new JScrollPane(txtOutput);
bottomPanel.add(txtOutput,BorderLayout.CENTER);
bottomPanel.add(scptxtOutput,BorderLayout.SOUTH);
rightSidePanel.add(bottomPanel,BorderLayout.CENTER);
}
/**
* Initialize Components
*/
public void addComponentsToPane() {
// buttonsPanel = new JPanel(new BorderLayout(3,5)); //Panel to hold Buttons
buttonsPanel = new JPanel(new GridLayout(3,1));
leftSidePanel = new JPanel(new BorderLayout());
rightSidePanel = new JPanel(new BorderLayout());
btnCheck = new JButton("Check Word");
btnCheck.setActionCommand("Check");
btnCheck.addActionListener(new ButtonClickListener());
btnClear = new JButton("Clear Selection");
btnClear.setActionCommand("Clear");
btnClear.addActionListener(new ButtonClickListener());
buttonsPanel.add(btnClear);//,BorderLayout.PAGE_START);
buttonsPanel.add(btnCheck);//,BorderLayout.PAGE_END);
leftSidePanel.add(buttonsPanel,BorderLayout.SOUTH);
this.getContentPane().add(leftSidePanel,BorderLayout.LINE_START);
gridPanel = new JPanel();
gridPanel.setLayout(myGridLayout);
myGridLayout.setRows(20);
myGridLayout.setColumns(20);
grid = new JButton[ROWS][COLS]; //allocate the size of grid
//theBoard = new char[ROWS][COLS];
for(int Row = 0; Row < grid.length; Row++){
for(int Column = 0; Column < grid[Row].length; Column++){
grid[Row][Column] = new JButton();//Row + 1 +", " + (Column + 1));
grid[Row][Column].setActionCommand(Row + "," + Column);
grid[Row][Column].setActionCommand("gridButton");
grid[Row][Column].addActionListener(new ButtonClickListener());
gridPanel.add(grid[Row][Column]);
}
}
rightSidePanel.add(gridPanel,BorderLayout.NORTH);
this.getContentPane().add(rightSidePanel, BorderLayout.CENTER);
}
public static void main(String[] args) {
try {
if (args.length !=2) { //Make sure we have both the puzzle file and word list file
JOptionPane.showMessageDialog(null, "One or All Files are Missing");
} else { //Files Found
WordSearchPuzzle puzzle = new WordSearchPuzzle(args[0],args[1]);
puzzle.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
puzzle.setSize(new Dimension(1215,740));
//Display the window.
puzzle.setLocationRelativeTo(null); // Center frame on screen
puzzle.setResizable(false); //Set the form as not resizable
puzzle.setVisible(true);
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public int solvePuzzle( ){
int matches = 0;
for( int r = 0; r < ROWS; r++ )
for( int c = 0; c < COLS; c++ )
for( int rd = -1; rd <= 1; rd++ )
for( int cd = -1; cd <= 1; cd++ )
if( rd != 0 || cd != 0 )
matches += solveDirection( r, c, rd, cd );
return matches;
}
private int solveDirection( int baseRow, int baseCol, int rowDelta, int colDelta ){
String charSequence = "";
int numMatches = 0;
int searchResult;
FileIO io = new FileIO();
charSequence += io.theBoard[ baseRow ][ baseCol ];
for( int i = baseRow + rowDelta, j = baseCol + colDelta;
i >= 0 && j >= 0 && i < ROWS && j < COLS;
i += rowDelta, j += colDelta )
{
charSequence += io.theBoard[ i ][ j ];
searchResult = prefixSearch( theWords, charSequence );
if( searchResult == theWords.length )
break;
if( !((String)theWords[ searchResult ]).startsWith( charSequence ) )
break;
if( theWords[ searchResult ].equals( charSequence ) )
{
numMatches++;
System.out.println( "Found " + charSequence + " at " +
baseRow + " " + baseCol + " to " +
i + " " + j );
}
}
return numMatches;
}
private static int prefixSearch( Object [ ] a, String x ) {
int idx = Arrays.binarySearch( a, x );
if( idx < 0 )
return -idx - 1;
else
return idx;
}
class ButtonClickListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String command = ((JButton)e.getSource()).getActionCommand();
if (command == "Clear") {
//Enable the buttons that have been disabled and not form a whole word
//JOptionPane.showMessageDialog(null, "Cooming Soon");
for (String word : wordList) {
System.out.print(word);
}
} else if (command == "Check") {
String selectedWord = getSelectedWord();
if (!selectedWord.equals("")){
System.out.print("Selected word is " + getSelectedWord());
//First check if selected word exits in wordList
if (ifExists(selectedWord)) {
if(searchWord(selectedWord)){
JOptionPane.showMessageDialog(null, "Success");
wordFromChars = ""; //Reset the selected Word
}
} else {
JOptionPane.showMessageDialog(null, "[" + selectedWord + "] " +
"Does Not Belong to Word list");
wordFromChars = ""; //Reset the selected Word
}
} else {
JOptionPane.showMessageDialog(null, "No Buttons on Grid have been clicked");
}
} else if (command == "gridButton") {
getSelectedCharacter(e);
((JButton)e.getSource()).setEnabled(false);
}
}
/**
* Gets the character of each button and concatenates each character to form a whole word
* #param e The button that received the Click Event
* #return Whole word
*/
private String getSelectedCharacter (ActionEvent e) {
String character;
character = ((JButton) e.getSource()).getText();
wordFromChars = wordFromChars + character;
return wordFromChars;
}
}
/**
* Checks if selected word is among in wordlist
* #param selectedWord
* #return The word to search for
*/
private boolean ifExists(String selectedWord) {
if (wordList.contains(selectedWord)) {
return true;
}
return false;
}
public boolean searchWord(String word) {
if (!wordList.contains(word)) {
return false;
}
//int index = wordList.indexOf(word);
Line2D.Double line = new Line2D.Double();
//System.out.print("LetterArray is " + letterArray.length);
for (int x = 0; x < letterArray.length; x++) {
for (int y = 0; y < letterArray[x].length; y++) {
// save start point
line.x1 = y; // (y + 1) * SCALE_INDEX_TO_XY;
line.y1 = x; // (x + 1) * SCALE_INDEX_TO_XY;
int pos = 0; // current letter position
if (letterArray[x][y] == word.charAt(pos)) {
// first letter correct -> check next
pos++;
if (pos >= word.length()) {
// word is only one letter long
// double abit = SCALE_INDEX_TO_XY / 3;
line.x2 = y; // (y + 1) * SCALE_INDEX_TO_XY + abit;
line.y2 = x; // (x + 1) * SCALE_INDEX_TO_XY + abit;
return true;
}
// prove surrounding letters:
int[] dirX = { 1, 1, 0, -1, -1, -1, 0, 1 };
int[] dirY = { 0, -1, -1, -1, 0, 1, 1, 1 };
for (int d = 0; d < dirX.length; d++) {
int dx = dirX[d];
int dy = dirY[d];
int cx = x + dx;
int cy = y + dy;
pos = 1; // may be greater if already search in another
// direction from this point
if (insideArray(cx, cy)) {
if (letterArray[cx][cy] == word.charAt(pos)) {
// 2 letters correct
// -> we've got the direction
pos++;
cx += dx;
cy += dy;
while (pos < word.length() && insideArray(cx, cy)
&& letterArray[cx][cy] == word.charAt(pos)) {
pos++;
cx += dx;
cy += dy;
}
if (pos == word.length()) {
// correct end if found
cx -= dx;
cy -= dy;
pos--;
}
if (insideArray(cx, cy) && letterArray[cx][cy] == word.charAt(pos)) {
// we've got the end point
line.x2 = cy; // (cy + 1) *
// SCALE_INDEX_TO_XY;
line.y2 = cx; // (cx + 1) *
// SCALE_INDEX_TO_XY;
/*
* System.out.println(letterArray[x][y] +
* " == " + word.charAt(0) + " (" + line.x1
* + "," + line.y1 + ") ->" + " (" + line.x2
* + "," + line.y2 + "); " + " [" + (line.x1
* / SCALE_INDEX_TO_XY) + "," + (line.y1 /
* SCALE_INDEX_TO_XY) + "] ->" + " [" +
* (line.x2 / SCALE_INDEX_TO_XY) + "." +
* (line.y2 / SCALE_INDEX_TO_XY) + "]; ");
*/
//result[index] = line;
// found
return true;
}
// else: try next occurence
}
}
}
}
}
}
return false;
}
private boolean insideArray(int x, int y) {
boolean insideX = (x >= 0 && x < letterArray.length);
boolean insideY = (y >= 0 && y < letterArray[0].length);
return (insideX && insideY);
}
public void init(char[][] letterArray) {
try {
for (int i = 0; i < letterArray.length; i++) {
for (int j = 0; j < letterArray[i].length; j++) {
char ch = letterArray[i][j];
if (ch >= 'a' && ch <= 'z') {
letterArray[i][j] = Character.toUpperCase(ch);
}
}
}
} catch (Exception e){
System.out.println(e.toString());
}
//System.out.println("It is " + letterArray.length);
this.letterArray = letterArray;
}
}
Here is class initializing the letterArray array:
package wordsearch;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
/**
* Reads wordlist file and puzzle file
* #author mungaialex
*
*/
public class FileIO {
String _puzzleFile, _wordListFile;
/**ArrayList to hold words*/
ArrayList<String> wordList;
/** No. Of Columns in Wordlist*/
private static final int WORDLISTCOLS = 1;
List puzzleLines;
JButton[][] _grid;
char theBoard[][];
private final int _rows = 20;
private final int _columns = 20;
WordSearchPuzzle pz = new WordSearchPuzzle();
/**
* Default Constructor
* #param puzzleFile
* #param wordListFile
*/
public FileIO(String puzzleFile, String wordListFile,JButton grid[][]){
_puzzleFile = new String(puzzleFile);
_wordListFile = new String(wordListFile);
_grid = pz.grid;
}
public FileIO() {
}
/**
* Reads word in the wordlist file and adds them to an array
* #param wordListFilename
* File Containing Words to Search For
* #throws IOException
*/
protected ArrayList<String> loadWordList()throws IOException {
int row = 0;
wordList = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(_wordListFile));
String line = reader.readLine();
while (line != null) {
StringTokenizer tokenizer = new StringTokenizer(line, " ");
if (tokenizer.countTokens() != WORDLISTCOLS) {
JOptionPane.showMessageDialog(null, "Error: only one word per line allowed in the word list",
"WordSearch Puzzle: Invalid Format", row);//, JOptionPane.OK_CANCEL_OPTION);
//"Error: only one word per line allowed in the word list");
}
String tok = tokenizer.nextToken();
wordList.add(tok.toUpperCase());
line = reader.readLine();
row++;
}
reader.close();
return wordList;
}
/**
* Reads the puzzle file line by by line
* #param wordSearchFilename
* The file containing the puzzle
* #throws IOException
*/
protected void loadPuzleFromFile() throws IOException {
int row = 0;
BufferedReader reader = new BufferedReader(new FileReader(_puzzleFile));
StringBuffer sb = new StringBuffer();
String line = reader.readLine();
puzzleLines = new ArrayList<String>();
while (line != null) {
StringTokenizer tokenizer = new StringTokenizer(line, " ");
int col = 0;
sb.append(line);
sb.append('\n');
while (tokenizer.hasMoreTokens()) {
String tok = tokenizer.nextToken();
WordSearchPuzzle.grid[row][col].setText(tok);
pz.grid[row][col].setForeground(Color.BLACK);
pz.grid[row][col].setHorizontalAlignment(SwingConstants.CENTER);
puzzleLines.add(tok);
col++;
}
line = reader.readLine();
row++;
theBoard = new char[_rows][_columns];
Iterator itr = puzzleLines.iterator();
for( int r = 0; r < _rows; r++ )
{
String theLine = (String) itr.next( );
theBoard[ r ] = theLine.toUpperCase().toCharArray( );
}
}
String[] search = sb.toString().split("\n");
initLetterArray(search);
reader.close();
}
protected void initLetterArray(String[] letterLines) {
char[][] array = new char[letterLines.length][];
System.out.print("Letter Lines are " +letterLines.length );
for (int i = 0; i < letterLines.length; i++) {
letterLines[i] = letterLines[i].replace(" ", "").toUpperCase();
array[i] = letterLines[i].toCharArray();
}
System.out.print("Array inatoshana ivi " + array.length);
pz.init(array);
}
}
Thanks in advance.
Here it is!
char[][] array = new char[letterLines.length][];
You are only initializing one axis.
When you pass this array to init() and set this.letterArray = letterArray;, the letterArray is also not fully initialized.
Try adding a length to both axes:
char[][] array = new char[letterLines.length][LENGTH];
first you will handle the NullPoinetrException , the code is
if( letterArray != null){
for (int x = 0; x < letterArray.length; x++)
{
..........
............
}
}
I want to select JTable zeroth row be selected by default
I am using following code but it gets the zeroth to be focused, not selected
jtblProduct.setCellSelectionEnabled(true);
jtblProduct.changeSelection(0, 0, false, false);
jtblProduct.requestFocus();
jtblProduct.scrollRectToVisible(new Rectangle(jtblProduct.getCellRect(0, 0, true)));
When I get the selected row by using the following code it returns -1, which means none selected.
jtblProduct.getSelectedRow()
Please provide me the way to select the zeroth row by default.
I haven't any issue with that, meaning
a) table.changeSelection(row, col, false, false);
or
b) table.getSelectedRow()
maybe everything depends of how is set value for ListSelectionModel
for better help sooner edit your question with a SSCCE
code
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.DefaultTableModel;
public class TableSelectionGood implements ListSelectionListener {
private JTable[] tables;
private boolean ignore = false;
public TableSelectionGood() {
Object[][] data1 = new Object[100][5];
Object[][] data2 = new Object[50][5];
//Object[][] data3 = new Object[50][5];
for (int i = 0; i < data1.length; i++) {
data1[i][0] = "Company # " + (i + 1);
for (int j = 1; j < data1[i].length; j++) {
data1[i][j] = "" + (i + 1) + ", " + j;
}
}
for (int i = 0; i < data2.length; i++) {
data2[i][0] = "Company # " + ((i * 2) + 1);
for (int j = 1; j < data2[i].length; j++) {
data2[i][j] = "" + ((i * 2) + 1) + ", " + j;
}
}
/*for (int i = 0; i < data3.length; i++) {
data3[i][0] = "Company # " + (i * 2);
for (int j = 1; j < data3[i].length; j++) {
data3[i][j] = "" + (i * 2) + ", " + j;
}
}*/
String[] headers = {"Col 1", "Col 2", "Col 3", "Col 4", "Col 5"};
DefaultTableModel model1 = new DefaultTableModel(data1, headers);
DefaultTableModel model2 = new DefaultTableModel(data2, headers);
//DefaultTableModel model3 = new DefaultTableModel(data3, headers);
final JTable jTable1 = new JTable(model1);
jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JScrollPane sp1 = new JScrollPane();
sp1.setPreferredSize(new Dimension(600, 100));
sp1.setViewportView(jTable1);
final JTable jTable2 = new JTable(model2);
jTable2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JScrollPane sp2 = new JScrollPane();
sp2.setPreferredSize(new Dimension(600, 100));
sp2.setViewportView(jTable2);
/*final JTable jTable3 = new JTable(model3);
jTable3.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JScrollPane sp3 = new JScrollPane();
sp3.setPreferredSize(new Dimension(600, 100));
sp3.setViewportView(jTable3);
TableSelectionGood tableSelection = new TableSelectionGood(jTable1, jTable2, jTable3);*/
TableSelectionGood tableSelection = new TableSelectionGood(jTable1, jTable2);
JPanel panel1 = new JPanel();
//panel1.setLayout(new GridLayout(3, 0, 10, 10));
panel1.setLayout(new GridLayout(2, 0, 10, 10));
panel1.add(sp1);
panel1.add(sp2);
//panel1.add(sp3);
JFrame frame = new JFrame("tableSelection");
frame.add(panel1);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public TableSelectionGood(JTable... tables) {
for (JTable table : tables) {
table.getSelectionModel().addListSelectionListener(this);
}
this.tables = tables;
}
private JTable getTable(Object model) {
for (JTable table : tables) {
if (table.getSelectionModel() == model) {
return table;
}
}
return null;
}
private void changeSelection(JTable table, String rowKey) {
int col = table.convertColumnIndexToView(0);
for (int row = table.getRowCount(); --row >= 0;) {
if (rowKey.equals(table.getValueAt(row, col))) {
table.changeSelection(row, col, false, false);
return;
}
}
table.clearSelection();
}
#Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() || ignore) {
return;
}
ignore = true;
try {
JTable table = getTable(e.getSource());
int row = table.getSelectedRow();
String rowKey = table.getValueAt(row, table.convertColumnIndexToView(0)).toString();
for (JTable t : tables) {
if (t == table) {
continue;
}
changeSelection(t, rowKey);
JViewport viewport = (JViewport) t.getParent();
Rectangle rect = t.getCellRect(t.getSelectedRow(), 0, true);
Rectangle r2 = viewport.getVisibleRect();
t.scrollRectToVisible(new Rectangle(rect.x, rect.y, (int) r2.getWidth(), (int) r2.getHeight()));
System.out.println(new Rectangle(viewport.getExtentSize()).contains(rect));
System.out.println(table.getSelectedRow());
}
} finally {
ignore = false;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TableSelectionGood tableSelection = new TableSelectionGood();
}
});
}
}
Have you tried jtable.setRowSelectionInterval(..) ?
Addition from comment: also try jtable.addRowSelectionInterval(..).
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.