I'm using the Swing library to ask a user for their zipcode, but all that is appearing is a box, without the text box, or any of the other elements that I've added in (see code). Also, you likely need to know that I'm trying to get the int AskZip() in my public static void main(String[] args) method.
private static int zip;
public static int AskZip() {
JFrame zaWindow = new JFrame("What Zipcode");
zaWindow.setSize(200, 300);
JPanel jp = new JPanel();
final JTextField tf = new JTextField("Enter Zip Here");
JLabel label = new JLabel();
JButton button = new JButton("Get Weather");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String sZip = tf.getText();
int rZip = 0;
try {
if (sZip.length() != 5) {
JOptionPane.showMessageDialog(null, "Invalid zipcode!", "Error", JOptionPane.ERROR_MESSAGE);
} else {
rZip = Integer.parseInt(sZip);
}
} catch (NumberFormatException arg) {
JOptionPane.showMessageDialog(null, "Invalid zipcode!", "Error", JOptionPane.ERROR_MESSAGE);
}
zip = rZip;
}
});
label.setText("What is your zipcode?");
jp.add(label);
jp.add(tf);
jp.add(button);
zaWindow.add(jp);
return zip;
}
JFrame zaWindow..
This should be a modal dialog or a JOptionPane. E.G. This country has 3 states, each with 10 postcodes.
import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.event.ChangeListener;
class ZipQuery {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
ZipNumberModel znm = new ZipNumberModel();
JSpinner zip = new JSpinner(znm);
JOptionPane.showMessageDialog(null, zip, "Enter Zipcode", JOptionPane.QUESTION_MESSAGE);
System.out.println("User chose " + znm.getValue());
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
class ZipNumberModel extends SpinnerNumberModel {
private ArrayList<Integer> zipCodes;
private int index = 0;
ZipNumberModel() {
zipCodes = new ArrayList<Integer>();
int zip = 10000;
for (int jj = 1; jj < 4; jj++) {
for (int ii = jj * zip; ii < jj * zip + 10; ii++) {
zipCodes.add(new Integer(ii));
}
}
}
#Override
public Object getValue() {
return zipCodes.get(index);
}
#Override
public Object getNextValue() {
if (index < zipCodes.size()-1) {
index++;
} else {
index = 0;
}
return zipCodes.get(index);
}
#Override
public Object getPreviousValue() {
if (index > 0) {
index--;
} else {
index = zipCodes.size()-1;
}
return zipCodes.get(index);
}
}
Related
I'm trying to finish my project about searching graphs, where one of the functions is input (vertex and edges) from user.
I already have a method for this in another class, but now I need to put it into GUI.
I've already tried many of tutorials, but nothing worked. Can somebody help me, how to put the method getInputFromCommand to gui?
I've already tried to copy the method into the GUI, but there was problem with the "return g" because of the void result type, I've tried just to call the method, (I know.. stupid) but it didn't work either.
package Process;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
public class FindIslands {
String message = "";
int V;
LinkedList<Integer>[] adjListArray;
static LinkedList<String> nodeList = new LinkedList<String>();
// constructor
FindIslands(int V) {
this.V = V;
adjListArray = new LinkedList[V];
for (int i = 0; i < V; i++) {
adjListArray[i] = new LinkedList<Integer>();
}
}
void addEdge(int src, int dest) {
adjListArray[src].add(dest);
adjListArray[dest].add(src);
}
void DFSUtil(int v, boolean[] visited) {
visited[v] = true;
message += getValue(v) + " ";
// System.out.print(getValue(v) + " ");
for (int x : adjListArray[v]) {
if (!visited[x]) {
DFSUtil(x, visited);
}
}
}
void connectedComponents() {
boolean[] visited = new boolean[V];
int count = 0;
message = "";
for (int v = 0; v < V; ++v) {
if (!visited[v]) {
DFSUtil(v, visited);
message += "\n";
// System.out.println();
count++;
}
}
System.out.println("" + count);
System.out.println("");
System.out.println("Vypis ostrovu: ");
String W[] = message.split("\n");
Arrays.sort(W, new java.util.Comparator<String>() {
#Override
public int compare(String s1, String s2) {
// TODO: Argument validation (nullity, length)
return s1.length() - s2.length();// comparison
}
});
for (String string : W) {
System.out.println(string);
}
}
public static void main(String[] args) {
FindIslands g = null; //
String csvFile = "nodefile.txt";
BufferedReader br = null;
String line = "";
int emptyLine = 0;
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
if (line.equals("")) {
emptyLine = 1;
// System.out.println("found blank line");
}
if (emptyLine == 0) {
// System.out.println(line);
nodeList.add(line);
} else if (line.isEmpty()) {
g = new FindIslands(nodeList.size());
} else {
String[] temp = line.split(",");
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
}
} catch (FileNotFoundException e) {
System.out.println("Soubor nenalezen, zadejte data v danem formatu");
g = getInputFromCommand();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Pocet ostrovu");
if (g != null) {
g.connectedComponents();
}
}
public static int getIndex(String str) {
return nodeList.indexOf(str);
}
public static String getValue(int index) {
return nodeList.get(index);
}
public static FindIslands getInputFromCommand() {
FindIslands g = null;
BufferedReader br = null;
String line = "";
int emptyLine = 0;
Scanner scanner = new Scanner(System.in);
line = scanner.nextLine();
while (!line.equals("")) {
if (line.equals("--gui")) {
Guicko gui = new Guicko();
gui.setVisible(true);
} else
nodeList.add(line);
line = scanner.nextLine();
}
g = new FindIslands(nodeList.size());
line = scanner.nextLine();
while (!line.equals("")) {
String[] temp = line.split(",");
if (temp.length != 2) {
System.out.println("spatny format zadanych dat, prosim zkuste znovu");
} else {
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
line = scanner.nextLine();
}
return g;
}
}
Where important is the last method "getInputFromCommand()"
and... gui
package Process;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.util.Scanner;
public class Guicko extends JFrame {
private JButton štartButton;
private JPanel panel;
private JTextField textField2;
private JTextArea textArea1;
public Guicko() {
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setTitle("Zadej hodnoty");
setSize(500, 400);
textField2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
FindIslands.getInputFromCommand();
}
});
štartButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String str = "asd";
FindIslands g = null;
g.connectedComponents();
textArea1.setText(str);
}
});
}
public static void main (String args[]){
Guicko gui = new Guicko();
gui.setVisible(true);
}
}
I'm sure there are many correct ways this code can be fixed, but in IMHO, your Guicko class needs to have a FindIslands class member, and I think you need to move some stuff from FindIslands.main() into Guicko.main() or some other method.
Then your "Action Listener" inner classes' actionPerformed methods just delegate to the methods in the FindIslands member instance, like this
....
private FindIslands fi;
public Guicko() {
....
textField2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
fi = FindIslands.getInputFromCommand();
}
});
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String comps = fi.connectedComponents();// method needs to return a string
textArea1.setText(comps);
}
});
}
The whole idea of seperating GUI from domain is to make changes easily. GUI has knowledge of the domain but domain has no knowledge about the GUI. We can use an interface to seperate them, in that case, Domain says , i don't care who implements this interface but whoever implements this interface will get response and can work with me.
So , If we create a new GUI, we can let it implements that interface and the same domain will work with that GUI.
There are many mistakes but in order to make it work and to show you an example i did few changes.
public class Guicko extends JFrame implements PropertyChangeListener{
private JButton štartButton;
private JPanel panel;
private JTextField textField2;
private JTextArea textArea1;
private FindIslands land;
private JTextField textField;
private JButton button;
public Guicko() {
JPanel panel = new JPanel();
super.getContentPane().setLayout(new GridLayout());
//For each gui, there should be one land.
this.setLand(new FindIslands(100));
//Subscribe to the domain so that you can get update if something change in domain.
this.getLand().subscribe(this);
//Dummy buttons are fields(need too initiate first)
textField2 = new JTextField("",30);
štartButton = new JButton();
textField = new JTextField("",30);
button = new JButton();
button.setPreferredSize(new Dimension(100, 40));
button.setText("Get input from Domain");
štartButton.setPreferredSize(new Dimension(100, 40));
textField.setEditable(false);
štartButton.setText("Start");
panel.add(textField2);
panel.add(štartButton);
panel.add(textField);
panel.add(button);
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setTitle("Zadej hodnoty");
setSize(500, 400);
//When you type something in , then this function will send it to domain(i mean to function : getInputFromCommand();).
this.addListerToField(štartButton,this.getLand(),textField2);
//Now the second case, suppose you press a button and want something to show up in textfield. In that case , this function will do work.
this.addListerToSecondField(button,this.getLand(),textField);
}
//Here i can catch the events from the domain.
#Override
public void propertyChange(PropertyChangeEvent e) {
if(e.getPropertyName().equals("String changed")) {
this.getTextField().setText((String) e.getNewValue());
}
}
private void addListerToSecondField(JButton button, FindIslands land, JTextField field) {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
land.requireArgumentsForField();
}
});
}
private void addListerToField(JButton štartButton, FindIslands land, JTextField field) {
štartButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
land.getInputFromCommand(field.getText());
}
});
}
public static void main (String args[]){
Guicko gui = new Guicko();
gui.setVisible(true);
}
public FindIslands getLand() {
return land;
}
public void setLand(FindIslands land) {
this.land = land;
}
public JTextField getTextField() {
return textField;
}
public void setTextField(JTextField textField) {
this.textField = textField;
}
public JButton getButton() {
return button;
}
public void setButton(JButton button) {
this.button = button;
}
Here is the second class. Run it and try to get feeling for it how it works.
public class FindIslands {
String message = "";
int V;
LinkedList<Integer>[] adjListArray;
static LinkedList<String> nodeList = new LinkedList<String>();
// constructor
FindIslands(int V) {
this.V = V;
//initialize the list
this.setListeners(new ArrayList<>());
adjListArray = new LinkedList[V];
for (int i = 0; i < V; i++) {
adjListArray[i] = new LinkedList<Integer>();
}
}
void addEdge(int src, int dest) {
adjListArray[src].add(dest);
adjListArray[dest].add(src);
}
void DFSUtil(int v, boolean[] visited) {
visited[v] = true;
message += getValue(v) + " ";
// System.out.print(getValue(v) + " ");
for (int x : adjListArray[v]) {
if (!visited[x]) {
DFSUtil(x, visited);
}
}
}
void connectedComponents() {
boolean[] visited = new boolean[V];
int count = 0;
message = "";
for (int v = 0; v < V; ++v) {
if (!visited[v]) {
DFSUtil(v, visited);
message += "\n";
// System.out.println();
count++;
}
}
System.out.println("" + count);
System.out.println("");
System.out.println("Vypis ostrovu: ");
String W[] = message.split("\n");
Arrays.sort(W, new java.util.Comparator<String>() {
#Override
public int compare(String s1, String s2) {
// TODO: Argument validation (nullity, length)
return s1.length() - s2.length();// comparison
}
});
for (String string : W) {
System.out.println(string);
}
}
//You need only one main class, not two.----------------------------
/**
public static void main(String[] args) {
FindIslands g = null; //
String csvFile = "nodefile.txt";
BufferedReader br = null;
String line = "";
int emptyLine = 0;
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
if (line.equals("")) {
emptyLine = 1;
// System.out.println("found blank line");
}
if (emptyLine == 0) {
// System.out.println(line);
nodeList.add(line);
} else if (line.isEmpty()) {
g = new FindIslands(nodeList.size());
} else {
String[] temp = line.split(",");
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
}
} catch (FileNotFoundException e) {
System.out.println("Soubor nenalezen, zadejte data v danem formatu");
g = getInputFromCommand();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Pocet ostrovu");
if (g != null) {
g.connectedComponents();
}
}
**/
public static int getIndex(String str) {
return nodeList.indexOf(str);
}
public static String getValue(int index) {
return nodeList.get(index);
}
//Static cases are to be avoided.This is the property of object not class.
public void getInputFromCommand(String string) {
//Here you will recieve a string from the GUI and will be printed in command prompt.You can do whatever you want to do with it.
System.out.println("Recieve string is " + string);
//No idea what you are trying to do.
/** FindIslands g = null;
BufferedReader br = null;
String line = "";
int emptyLine = 0;
Scanner scanner = new Scanner(System.in);
line = scanner.nextLine();
while (!line.equals("")) {
if (line.equals("--gui")) {
Guicko gui = new Guicko();
gui.setVisible(true);
} else
nodeList.add(line);
line = scanner.nextLine();
}
g = new FindIslands(nodeList.size());
line = scanner.nextLine();
while (!line.equals("")) {
String[] temp = line.split(",");
if (temp.length != 2) {
System.out.println("spatny format zadanych dat, prosim zkuste znovu");
} else {
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
line = scanner.nextLine();
}
return line;**/
}
//This function is triggered with second button and you can send data to gui as shown below.
public void requireArgumentsForField() {
//Suppose i want to send following string.
String name = "I don't know";
this.getListeners().stream().forEach(e -> {
// I will catch this in view.
e.propertyChange(new PropertyChangeEvent(this, "String changed", null, name));
});
}
private ArrayList<PropertyChangeListener> listeners;
//Let the objects subscibe. You need this to publish the changes in domain.
public void subscribe(PropertyChangeListener listener) {
this.getListeners().add(listener);
}
public ArrayList<PropertyChangeListener> getListeners() {
return listeners;
}
public void setListeners(ArrayList<PropertyChangeListener> listeners) {
this.listeners = listeners;
}
I want the user to select options from a combo box and based on what they select the output field will calculate the price in it.
For example if they select Intel Core i5 it will add $50 to the calculated price
They error I have is that my output box is adding only the highest/last values together.
My three combo boxes are name Processor, Memory, Disk
the box I want the price to calculate in is named Output
i mainly just need help with how to select the options in my combo boxes in the if statements
private void calculateButtonActionPerformed(java.awt.event.ActionEvent evt) {
double price; //initilize variable
double windowsUpgrade; //Initilize variable
double processorPrice;
double memoryPrice;
double diskPrice;
if(Processor.getSelectedItem().equals("Intel Core i3"));
{
processorPrice = 0;
}
if(Processor.getSelectedItem().equals("Intel Core i5"));
{
processorPrice = 50;
}
if(Processor.getSelectedItem().equals("Intel Core i7"));
{
processorPrice = 150;
}
if(Memory.getSelectedItem().equals("4GB"));
{
memoryPrice = 0;
}
if(Memory.getSelectedItem().equals("8GB"));
{
memoryPrice = 50;
}
if(Memory.getSelectedItem().equals("16GB"));
{
memoryPrice = 100;
}
if(Memory.getSelectedItem().equals("32GB"));
{
memoryPrice = 150;
}
if(Disk.getSelectedItem().equals("1TB"));
{
diskPrice = 0;
}
if(Disk.getSelectedItem().equals("2TB"));
{
diskPrice = 50;
}
if(Disk.getSelectedItem().equals("512GB SSD"));
{
diskPrice = 150;
}
double calculation;
calculation = processorPrice + memoryPrice + diskPrice;
NumberFormat currency = NumberFormat.getCurrencyInstance();
String message =
currency.format(calculation);
Output.setText(message);
}
Here is the code.
You could use listener which react on your selection.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
class ComboBoxTest
{
//A reference to the UI class where you initialize the buttons,
//combo box etc
private ComboBoxUI _ui;
private double _processorPrice;
private double _memoryPrice;
private double _diskPrice;
public ComboBoxTest()
{
_processorPrice = 0;
_memoryPrice = 0;
_diskPrice = 0;
_ui = new ComboBoxUI();
registerListener();
}
//Register three different comboBoxes and a button for
//the calculation to listener
private void registerListener()
{
_ui.getProcessorBox().addItemListener(new ItemListener()
{
#Override
public void itemStateChanged(ItemEvent e)
{
if (e.getItem().equals("Intel Core i3"))
{
_processorPrice = 0;
}
else if (e.getItem().equals("Intel Core i5"))
{
_processorPrice = 50;
}
else if (e.getItem().equals("Intel Core i7"))
{
_processorPrice = 150;
}
}
});
_ui.getMemoryBox().addItemListener(new ItemListener()
{
#Override
public void itemStateChanged(ItemEvent e)
{
if (e.getItem().equals("4GB"))
{
_memoryPrice = 0;
}
else if (e.getItem().equals("8GB"))
{
_memoryPrice = 50;
}
else if (e.getItem().equals("16GB"))
{
_memoryPrice = 100;
}
else if (e.getItem().equals("32GB"))
{
_memoryPrice = 150;
}
}
});
_ui.getDiscBox().addItemListener(new ItemListener()
{
#Override
public void itemStateChanged(ItemEvent e)
{
if (e.getItem().equals("1TB"))
{
_diskPrice = 0;
}
else if (e.getItem().equals("2TB"))
{
_diskPrice = 50;
}
else if (e.getItem().equals("512GB SSD"))
{
_diskPrice = 150;
}
}
});
//getCalcButton() is a new Button that calcualtes the price
_ui.getCalcButton().addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println(_processorPrice + _memoryPrice + _diskPrice);
}
});
}
}
With my example you need a UI class of your components. Something like this :)
import java.awt.BorderLayout;
import javax.swing.*;
public class ComboBoxUI
{
JFrame _frame;
JPanel _componentPanel;
JButton _calcButton;
JComboBox _procBox;
JComboBox _memBox;
JComboBox _discBox;
ComboBoxUI()
{
initFrame();
initComponenentPanel();
showGui();
}
//initialize a new JFrame with BorderLayout in this example
private void initFrame()
{
_frame = new JFrame("Title");
_frame.setLayout(new BorderLayout());
}
//initialize a new JPanel with your components like comboBox, buttons...
private void initComponenentPanel()
{
_componentPanel = new JPanel();
String[] proc = { "Intel Core i3", "Intel Core i5", "Intel Core i7"};
_procBox = new JComboBox(proc);
String[] memory = { "4GB", "8GB", "16GB", "32GB"};
_memBox = new JComboBox(memory);
String[] disc = { "1TB", "2TB", "512GB SSD"};
_discBox = new JComboBox(disc);
_calcButton = new JButton("Calculate");
_componentPanel.add(_procBox);
_componentPanel.add(_memBox);
_componentPanel.add(_discBox);
_componentPanel.add(_calcButton);
_frame.add(_componentPanel, BorderLayout.NORTH);
}
//Set the size of your JFrame and make it visible
private void showGui()
{
_frame.setSize(500, 200);
_frame.setVisible(true);
_frame.setDefaultCloseOperation(_frame.EXIT_ON_CLOSE);
}
public JComboBox getProcessorBox()
{
return _procBox;
}
public JComboBox getMemoryBox()
{
return _memBox;
}
public JComboBox getDiscBox()
{
return _discBox;
}
public JButton getCalcButton()
{
return _calcButton;
}
}
Im making a simon game and i have no idea what to do. I got sound and all that good stuff working but as for everything else I have no idea what im doing. I need some help making the buttons work and flash in the right order. (comments are failed attempts) Any help is very much appreciated.
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.border.*;
import java.util.Random;
import java.applet.*;
import java.util.ArrayList;
public class Game extends JFrame
{
JButton button1, button2, button3, button4, button5;
JLabel label1, label2, label3;
JPanel panel1, panel2;
File wavFile1 = new File("NewRing1.wav");
File wavFile2 = new File("NewRing2.wav");
File wavFile3 = new File("NewRing3.wav");
File wavFile4 = new File("NewRing4.wav");
AudioClip sound1;
AudioClip sound2;
AudioClip sound3;
AudioClip sound4;
int sequence1;
int[] anArray;
public Game()
{
anArray = new int[1000];
GridLayout grid = new GridLayout(3, 2);
this.getContentPane().setLayout(grid);
Container theContainer = this.getContentPane();
EtchedBorder edge = new EtchedBorder(EtchedBorder.RAISED);
button1 = new JButton();
button1.setForeground(Color.BLACK);
button1.setBackground(Color.RED);
button2 = new JButton();
button2.setForeground(Color.BLACK);
button2.setBackground(Color.BLUE);
button3 = new JButton();
button3.setForeground(Color.BLACK);
button3.setBackground(Color.GREEN);
button4 = new JButton();
button4.setForeground(Color.BLACK);
button4.setBackground(Color.YELLOW);
button5 = new JButton("Begin");
label1 = new JLabel("Score");
label2 = new JLabel("High Score");
label3 = new JLabel("Follow The Pattern");
panel1 = new JPanel();
panel1.add(label1);
panel1.add(label2);
panel2 = new JPanel();
panel2.add(label3);
panel2.add(button5);
button1.setBorder(edge);
button2.setBorder(edge);
button3.setBorder(edge);
button4.setBorder(edge);
label1.setBorder(edge);
label2.setBorder(edge);
panel1.setBorder(edge);
panel2.setBorder(edge);
label3.setBorder(edge);
theContainer.add(panel1);
theContainer.add(panel2);
theContainer.add(button1);
theContainer.add(button2);
theContainer.add(button3);
theContainer.add(button4);
Button1Handler handleButton1 = new Button1Handler();
button1.addActionListener(handleButton1);
Button2Handler handleButton2 = new Button2Handler();
button2.addActionListener(handleButton2);
Button3Handler handleButton3 = new Button3Handler();
button3.addActionListener(handleButton3);
Button4Handler handleButton4 = new Button4Handler();
button4.addActionListener(handleButton4);
Button5Handler handleButton5 = new Button5Handler();
button5.addActionListener(handleButton5);
try{sound1 = Applet.newAudioClip(wavFile1.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound2 = Applet.newAudioClip(wavFile2.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound3 = Applet.newAudioClip(wavFile3.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound4 = Applet.newAudioClip(wavFile4.toURL());}
catch(Exception e){e.printStackTrace();}
setVisible(true);
}
public class Button1Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound1.play();
}
}
public class Button2Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound2.play();
}
}
public class Button3Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound3.play();
}
}
public class Button4Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound4.play();
}
}
/*
public static int[] buttonClicks(int[] anArray)
{
return anArray;
}
*/
public class Button5Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
for (int i = 1; i <= 159; i++)
{
Random rand = new Random();
int randomNum = rand.nextInt(40) % 4 + 1;
anArray[i] = randomNum;
System.out.println("Element at index: "+ i + " Is: " + anArray[i]);
}
buttonClicks(anArra[3]);
/*
for (int i = 1; i <= 100; i++)
{
Random rand = new Random();
int randomNum = rand.nextInt((4 - 1) + 1) + 1;
if(randomNum == 1)
{
button1.doClick();
sequence1 = 1;
System.out.println(sequence1);
}
else if(randomNum == 2)
{
button2.doClick();
sequence1 = 2;
System.out.println(sequence1);
}
else if(randomNum == 3)
{
button3.doClick();
sequence1 = 3;
System.out.println(sequence1);
}
else
{
button4.doClick();
sequence1 = 4;
System.out.println(sequence1);
}
}
*/
}
}
}
Below is some code to get you started. The playback of the sequences is executed in a separate thread, as you need to use delays in between. This code is by no means ideal. You should use better names for the variables and refactor to try to create a better and more encapsulated game model. Maybe you could use this opportunity to learn about the MVC design pattern?
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.border.*;
import java.util.Random;
import java.applet.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Game extends JFrame {
JButton button1, button2, button3, button4, button5;
JLabel label1, label2, label3;
JPanel panel1, panel2;
File wavFile1 = new File("NewRing1.wav");
File wavFile2 = new File("NewRing2.wav");
File wavFile3 = new File("NewRing3.wav");
File wavFile4 = new File("NewRing4.wav");
AudioClip sound1;
AudioClip sound2;
AudioClip sound3;
AudioClip sound4;
int level;
int score;
int[] anArray;
int currentArrayPosition;
public Game() {
GridLayout grid = new GridLayout(3, 2);
this.getContentPane().setLayout(grid);
Container theContainer = this.getContentPane();
EtchedBorder edge = new EtchedBorder(EtchedBorder.RAISED);
level = 0;
score = 0;
button1 = new JButton();
button1.setForeground(Color.BLACK);
button1.setBackground(Color.RED);
button2 = new JButton();
button2.setForeground(Color.BLACK);
button2.setBackground(Color.BLUE);
button3 = new JButton();
button3.setForeground(Color.BLACK);
button3.setBackground(Color.GREEN);
button4 = new JButton();
button4.setForeground(Color.BLACK);
button4.setBackground(Color.YELLOW);
button5 = new JButton("Begin");
label1 = new JLabel("Score: " + String.valueOf(score));
label2 = new JLabel("High Score");
label3 = new JLabel("Follow The Pattern");
panel1 = new JPanel();
panel1.add(label1);
panel1.add(label2);
panel2 = new JPanel();
panel2.add(label3);
panel2.add(button5);
button1.setBorder(edge);
button2.setBorder(edge);
button3.setBorder(edge);
button4.setBorder(edge);
label1.setBorder(edge);
label2.setBorder(edge);
panel1.setBorder(edge);
panel2.setBorder(edge);
label3.setBorder(edge);
theContainer.add(panel1);
theContainer.add(panel2);
theContainer.add(button1);
theContainer.add(button2);
theContainer.add(button3);
theContainer.add(button4);
Button1Handler handleButton1 = new Button1Handler();
button1.addActionListener(handleButton1);
Button2Handler handleButton2 = new Button2Handler();
button2.addActionListener(handleButton2);
Button3Handler handleButton3 = new Button3Handler();
button3.addActionListener(handleButton3);
Button4Handler handleButton4 = new Button4Handler();
button4.addActionListener(handleButton4);
Button5Handler handleButton5 = new Button5Handler();
button5.addActionListener(handleButton5);
try {
sound1 = Applet.newAudioClip(wavFile1.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound2 = Applet.newAudioClip(wavFile2.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound3 = Applet.newAudioClip(wavFile3.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound4 = Applet.newAudioClip(wavFile4.toURL());
} catch (Exception e) {
e.printStackTrace();
}
setVisible(true);
}
public class Button1Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound1.play();
buttonClicked(button1);
}
}
public class Button2Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound2.play();
buttonClicked(button2);
}
}
public class Button3Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound3.play();
buttonClicked(button3);
}
}
public class Button4Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound4.play();
buttonClicked(button4);
}
}
private void buttonClicked(JButton clickedButton) {
if (isCorrectButtonClicked(clickedButton)) {
currentArrayPosition++;
addToScore(1);
if (currentArrayPosition == anArray.length) {
playNextSequence();
} else {
}
} else {
JOptionPane.showMessageDialog(this, String.format("Your scored %s points", score));
score = 0;
level = 0;
label1.setText("Score: " + String.valueOf(score));
}
}
private boolean isCorrectButtonClicked(JButton clickedButton) {
int correctValue = anArray[currentArrayPosition];
if (clickedButton.equals(button1)) {
return correctValue == 1;
} else if (clickedButton.equals(button2)) {
return correctValue == 2;
} else if (clickedButton.equals(button3)) {
return correctValue == 3;
} else if (clickedButton.equals(button4)) {
return correctValue == 4;
} else {
return false;
}
}
public class Button5Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
playNextSequence();
}
}
private void playNextSequence() {
level++;
currentArrayPosition = 0;
anArray = createSequence(level);
(new Thread(new SequenceButtonClicker())).start();
}
private int[] createSequence(int sequenceLength) {
int[] sequence = new int[sequenceLength];
for (int i = 0; i < sequenceLength; i++) {
Random rand = new Random();
int randomNum = rand.nextInt(40) % 4 + 1;
sequence[i] = randomNum;
}
return sequence;
}
private JButton getButtonFromInt(int sequenceNumber) {
switch (sequenceNumber) {
case 1:
return button1;
case 2:
return button2;
case 3:
return button3;
case 4:
return button4;
default:
return button1;
}
}
private void flashButton(JButton button) throws InterruptedException {
Color originalColor = button.getBackground();
button.setBackground(new Color(255, 255, 255, 200));
Thread.sleep(250);
button.setBackground(originalColor);
}
private void soundButton(JButton button) {
if (button.equals(button1)) {
sound1.play();
} else if (button.equals(button2)) {
sound2.play();
} else if (button.equals(button3)) {
sound3.play();
} else if (button.equals(button4)) {
sound4.play();
}
}
private void addToScore(int newPoints) {
score += newPoints;
label1.setText("Score: " + String.valueOf(score));
}
private class SequenceButtonClicker implements Runnable {
public void run() {
for (int i = 0; i < anArray.length; i++) {
try {
JButton nextButton = getButtonFromInt(anArray[i]);
soundButton(nextButton);
flashButton(nextButton);
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Game.class.getName()).log(Level.SEVERE, "Interrupted", ex);
}
}
}
}
}
Another problem, same program:
The following is MainGUI.java
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class MainGUI extends JFrame implements ActionListener
{
private static final long serialVersionUID = 4149825008429377286L;
private final double version = 8;
public static int rows;
public static int columns;
private int totalCells;
private MainCell[] cell;
public static Color userColor;
JTextField speed = new JTextField("250");
Timer timer = new Timer(250,this);
String generationText = "Generation: 0";
JLabel generationLabel = new JLabel(generationText);
int generation = 0;
public MainGUI(String title, int r, int c)
{
rows = r;
columns = c;
totalCells = r*c;
System.out.println(totalCells);
cell = new MainCell[totalCells];
setTitle(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Timer set up
timer.setInitialDelay(Integer.parseInt(speed.getText()));
timer.setActionCommand("timer");
//set up menu bar
JMenuBar menuBar = new JMenuBar();
JMenu optionsMenu = new JMenu("Options");
JMenu aboutMenu = new JMenu("About");
menuBar.add(optionsMenu);
menuBar.add(aboutMenu);
JMenuItem helpButton = new JMenuItem("Help!");
helpButton.addActionListener(this);
helpButton.setActionCommand("help");
aboutMenu.add(helpButton);
JMenuItem aboutButton = new JMenuItem("About");
aboutButton.addActionListener(this);
aboutButton.setActionCommand("about");
aboutMenu.add(aboutButton);
JMenuItem colorSelect = new JMenuItem("Select a Custom Color");
colorSelect.addActionListener(this);
colorSelect.setActionCommand("colorSelect");
optionsMenu.add(colorSelect);
JMenuItem sizeChooser = new JMenuItem("Define a Custom Size");
sizeChooser.addActionListener(this);
sizeChooser.setActionCommand("sizeChooser");
optionsMenu.add(sizeChooser);
//Create text field to adjust speed and its label
JPanel speedContainer = new JPanel();
JLabel speedLabel = new JLabel("Enter the speed of a life cycle (in ms):");
speedContainer.add(speedLabel);
speedContainer.add(speed);
speedContainer.add(generationLabel);
Dimension speedDim = new Dimension(100,25);
speed.setPreferredSize(speedDim);
//Create various buttons
JPanel buttonContainer = new JPanel();
JButton randomizerButton = new JButton("Randomize");
randomizerButton.addActionListener(this);
randomizerButton.setActionCommand("randomize");
buttonContainer.add(randomizerButton);
JButton nextButton = new JButton("Next"); //forces a cycle to occur
nextButton.addActionListener(this);
nextButton.setActionCommand("check");
buttonContainer.add(nextButton);
JButton startButton = new JButton("Start");
startButton.addActionListener(this);
startButton.setActionCommand("start");
buttonContainer.add(startButton);
JButton stopButton = new JButton("Stop");
stopButton.addActionListener(this);
stopButton.setActionCommand("stop");
buttonContainer.add(stopButton);
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(this);
clearButton.setActionCommand("clear");
buttonContainer.add(clearButton);
//holds the speed container and button container, keeps it neat
JPanel functionContainer = new JPanel();
BoxLayout functionLayout = new BoxLayout(functionContainer, BoxLayout.PAGE_AXIS);
functionContainer.setLayout(functionLayout);
functionContainer.add(speedContainer);
speedContainer.setAlignmentX(CENTER_ALIGNMENT);
functionContainer.add(buttonContainer);
buttonContainer.setAlignmentX(CENTER_ALIGNMENT);
//finish up with the cell container
GridLayout cellLayout = new GridLayout(rows,columns);
JPanel cellContainer = new JPanel(cellLayout);
cellContainer.setBackground(Color.black);
int posX = 0;
int posY = 0;
for(int i=0;i<totalCells;i++)
{
MainCell childCell = new MainCell();
cell[i] = childCell;
childCell.setName(String.valueOf(i));
childCell.setPosX(posX);
posX++;
childCell.setPosY(posY);
if(posX==columns)
{
posX = 0;
posY++;
}
cellContainer.add(childCell);
childCell.deactivate();
Graphics g = childCell.getGraphics();
childCell.paint(g);
}
//make a default color
userColor = Color.yellow;
//change icon
URL imgURL = getClass().getResource("images/gol.gif");
ImageIcon icon = new ImageIcon(imgURL);
System.out.println(icon);
setIconImage(icon.getImage());
//add it all up and pack
JPanel container = new JPanel();
BoxLayout containerLayout = new BoxLayout(container, BoxLayout.PAGE_AXIS);
container.setLayout(containerLayout);
container.add(cellContainer);
container.add(functionContainer);
add(menuBar);
setJMenuBar(menuBar);
add(container);
pack();
}
private void checkCells()
{
//perform check for every cell
for(int i=0;i<totalCells;i++)
{
cell[i].setNeighbors(checkNeighbors(i));
}
//use value from check to determine life
for(int i=0;i<totalCells;i++)
{
int neighbors = cell[i].getNeighbors();
if(cell[i].isActivated())
{
System.out.println(cell[i].getName()+" "+neighbors);
if(neighbors==0||neighbors==1||neighbors>3)
{
cell[i].deactivate();
}
}
if(cell[i].isActivated()==false)
{
if(neighbors==3)
{
cell[i].activate();
}
}
}
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("randomize"))
{
Random rn = new Random();
for(int i=0;i<totalCells;i++)
{
cell[i].deactivate();
if(rn.nextInt(6)==0)
{
cell[i].activate();
}
}
}
//help button, self-explanatory
if(e.getActionCommand().equals("help"))
{
JOptionPane.showMessageDialog(this, "The game is governed by four rules:\nFor a space that is 'populated':"
+ "\n Each cell with one or no neighbors dies, as if by loneliness."
+ "\n Each cell with four or more neighbors dies, as if by overpopulation."
+ "\n Each cell with two or three neighbors survives."
+ "\nFor a space that is 'empty' or 'unpopulated':"
+ "\n Each cell with three neighbors becomes populated."
+ "\nLeft click populates cells. Right click depopulates cells.","Rules:",JOptionPane.PLAIN_MESSAGE);
}
//shameless self promotion
if(e.getActionCommand().equals("about"))
{
JOptionPane.showMessageDialog(this, "Game made and owned by *****!"
+ "\nFree usage as see fit, but give credit where credit is due!\nVERSION: "+version,"About:",JOptionPane.PLAIN_MESSAGE);
}
//clears all the cells
if(e.getActionCommand().equals("clear"))
{
timer.stop();
generation = 0;
generationText = "Generation: "+generation;
generationLabel.setText(generationText);
for(int i=0;i<totalCells;i++)
{
cell[i].deactivate();
}
}
//starts timer
if(e.getActionCommand().equals("start"))
{
if(Integer.parseInt(speed.getText())>0)
{
timer.setDelay(Integer.parseInt(speed.getText()));
timer.restart();
}
else
{
JOptionPane.showMessageDialog(this, "Please use a value greater than 0!","Rules:",JOptionPane.ERROR_MESSAGE);
}
}
//stops timer
if(e.getActionCommand().equals("stop"))
{
timer.stop();
}
//run when timer
if(e.getActionCommand().equals("timer"))
{
generation++;
generationText = "Generation: "+generation;
generationLabel.setText(generationText);
timer.stop();
checkCells();
timer.setInitialDelay(Integer.parseInt(speed.getText()));
timer.restart();
}
//see checkCells()
if(e.getActionCommand().equals("check"))
{
generation++;
generationText = "Generation: "+generation;
generationLabel.setText(generationText);
checkCells();
}
//color select gui
if(e.getActionCommand().equals("colorSelect"))
{
userColor = JColorChooser.showDialog(this, "Choose a color:", userColor);
if(userColor==null)
{
userColor = Color.yellow;
}
}
//size chooser!
if(e.getActionCommand().equals("sizeChooser"))
{
SizeChooser size = new SizeChooser();
size.setLocationRelativeTo(null);
size.setVisible(true);
}
}
private int checkNeighbors(int c)
{
//if a LIVE neighbor is found, add one
int neighbors = 0;
if(cell[c].getPosX()!=0&&cell[c].getPosY()!=0)
{
if(c-columns-1>=0)
{
if(cell[c-columns-1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-columns-1].getName());
neighbors++;
}
}
}
if(cell[c].getPosY()!=0)
{
if(c-columns>=0)
{
if(cell[c-columns].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-columns].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=columns-1&&cell[c].getPosY()!=0)
{
if(c-columns+1>=0)
{
if(cell[c-columns+1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-columns+1].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=0)
{
if(c-1>=0)
{
if(cell[c-1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c-1].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=columns-1)
{
if(c+1<totalCells)
{
if(cell[c+1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+1].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=0&&cell[c].getPosY()!=rows-1)
{
if(c+columns-1<totalCells)
{
if(cell[c+columns-1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+columns-1].getName());
neighbors++;
}
}
}
if(cell[c].getPosY()!=rows-1&&cell[c].getPosY()!=rows-1)
{
if(c+columns<totalCells)
{
if(cell[c+columns].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+columns].getName());
neighbors++;
}
}
}
if(cell[c].getPosX()!=columns-1&&cell[c].getPosY()!=rows-1)
{
if(c+columns+1<totalCells)
{
if(cell[c+columns+1].isActivated())
{
System.out.println(cell[c].getName()+" found "+cell[c+columns+1].getName());
neighbors++;
}
}
}
return neighbors;
}
}
The following is MainCell.java:
public class MainCell extends JPanel implements MouseListener
{
//everything here should be self-explanatory
private static final long serialVersionUID = 1761933778208900172L;
private boolean activated = false;
public static boolean leftMousePressed;
public static boolean rightMousePressed;
private int posX = 0;
private int posY = 0;
private int neighbors = 0;
private URL cellImgURL_1 = getClass().getResource("images/cellImage_1.gif");
private ImageIcon cellImageIcon_1 = new ImageIcon(cellImgURL_1);
private Image cellImage_1 = cellImageIcon_1.getImage();
private URL cellImgURL_2 = getClass().getResource("images/cellImage_2.gif");
private ImageIcon cellImageIcon_2 = new ImageIcon(cellImgURL_2);
private Image cellImage_2 = cellImageIcon_2.getImage();
private URL cellImgURL_3 = getClass().getResource("images/cellImage_3.gif");
private ImageIcon cellImageIcon_3 = new ImageIcon(cellImgURL_3);
private Image cellImage_3 = cellImageIcon_3.getImage();
public MainCell()
{
Dimension dim = new Dimension(17, 17);
setPreferredSize(dim);
addMouseListener(this);
}
public void activate()
{
setBackground(MainGUI.userColor);
System.out.println(getName()+" "+posX+","+posY+" activated");
setActivated(true);
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if(getPosX()==MainGUI.columns-1&&getPosY()==0)
{
//do nothing
}
else if(getPosY()!=0&&getPosX()!=MainGUI.columns-1)
{
g.drawImage(cellImage_1,0,0,null);
}
else if(getPosY()==0)
{
g.drawImage(cellImage_2,0,0,null);
}
else if(getPosX()==MainGUI.columns-1)
{
g.drawImage(cellImage_3,0,0,null);
}
}
public void setActivated(boolean b)
{
activated = b;
}
public void deactivate()
{
setBackground(Color.gray);
System.out.println(getName()+" "+posX+","+posY+" deactivated");
setActivated(false);
}
public boolean isActivated()
{
return activated;
}
public void setNeighbors(int i)
{
neighbors = i;
}
public int getNeighbors()
{
return neighbors;
}
public int getPosX()
{
return posX;
}
public void setPosX(int x)
{
posX = x;
}
public int getPosY()
{
return posY;
}
public void setPosY(int y)
{
posY = y;
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
if(leftMousePressed&&SwingUtilities.isLeftMouseButton(e))
{
activate();
}
if(rightMousePressed&&SwingUtilities.isRightMouseButton(e))
{
deactivate();
}
}
public void mouseExited(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
if(SwingUtilities.isRightMouseButton(e)&&!leftMousePressed)
{
deactivate();
rightMousePressed = true;
}
if(SwingUtilities.isLeftMouseButton(e)&&!rightMousePressed)
{
activate();
leftMousePressed = true;
}
}
public void mouseReleased(MouseEvent e)
{
if(SwingUtilities.isRightMouseButton(e))
{
rightMousePressed = false;
}
if(SwingUtilities.isLeftMouseButton(e))
{
leftMousePressed = false;
}
}
}
The following is SizeChooser.java:
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import javax.swing.*;
public class SizeChooser extends JFrame
{
private static final long serialVersionUID = -6431709376438241788L;
public static MainGUI GUI;
private static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
JTextField rowsTextField = new JTextField(String.valueOf((screenSize.height/17)-15));
JTextField columnsTextField = new JTextField(String.valueOf((screenSize.width/17)-10));
private static int rows = screenSize.height/17-15;
private static int columns = screenSize.width/17-10;
public SizeChooser()
{
setResizable(false);
setTitle("Select a size!");
JPanel container = new JPanel();
BoxLayout containerLayout = new BoxLayout(container, BoxLayout.PAGE_AXIS);
container.setLayout(containerLayout);
add(container);
JLabel rowsLabel = new JLabel("Rows:");
container.add(rowsLabel);
container.add(rowsTextField);
JLabel columnsLabel = new JLabel("Columns:");
container.add(columnsLabel);
container.add(columnsTextField);
JButton confirmSize = new JButton("Confirm");
confirmSize.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
GUI.setVisible(false);
GUI = null;
if(Integer.parseInt(rowsTextField.getText())>0)
{
rows = Integer.parseInt(rowsTextField.getText());
}
else
{
JOptionPane.showMessageDialog(rootPane, "Please use a value greater than 0!","Rules:",JOptionPane.ERROR_MESSAGE);
}
if(Integer.parseInt(columnsTextField.getText())>0)
{
columns = Integer.parseInt(columnsTextField.getText());
}
else
{
JOptionPane.showMessageDialog(rootPane, "Please use a value greater than 0!","Rules:",JOptionPane.ERROR_MESSAGE);
}
GUI = new MainGUI("The Game of Life!", rows, columns);
GUI.setLocationRelativeTo(null);
GUI.setVisible(true);
setVisible(false);
}
});
container.add(confirmSize);
URL imgURL = getClass().getResource("images/gol.gif");
ImageIcon icon = new ImageIcon(imgURL);
System.out.println(icon);
setIconImage(icon.getImage());
pack();
}
public static void main(String[]args)
{
GUI = new MainGUI("The Game of Life!", rows, columns);
GUI.setLocationRelativeTo(null);
GUI.setVisible(true);
}
}
So the problem now is, when the randomize button is pressed, or a large number of cells exist and then the timer is started, the cells aren't as snappy as they would be with less active cells. For example, with 100 columns and 50 rows, when the randomize button is pressed, one cell activates, then the next, then another, and so forth. Can I have them all activate at exactly the same time? Is this just a problem with too many things calculated at once? Would concurrency help?
QUICK EDIT: Is the swing timer the best idea for this project?
I havent read through your code completely but I am guessing that your listener methods are fairly computationally intensive and hence the lag in updating the display.
This simple test reveals that your randomize operation should be fairly quick:
public static void main(String args[]) {
Random rn = new Random();
boolean b[] = new boolean[1000000];
long timer = System.nanoTime();
for (int i = 0; i < b.length; i++) {
b[i] = rn.nextInt(6) == 0;
}
timer = System.nanoTime() - timer;
System.out.println(timer + "ns / " + (timer / 1000000) + "ms");
}
The output for me is:
17580267ns / 17ms
So this leads me into thinking activate() or deactivate() is causing your UI to be redrawn.
I am unable to run this because I don't have your graphical assets, but I would try those changes to see if it works:
In MainGUI#actionPerformed, change:
if(e.getActionCommand().equals("randomize"))
{
Random rn = new Random();
for(int i=0;i<totalCells;i++)
{
cell[i].deactivate();
if(rn.nextInt(6)==0)
{
cell[i].activate();
}
}
}
to:
if(e.getActionCommand().equals("randomize"))
{
Random rn = new Random();
for(int i=0;i<totalCells;i++)
{
// This will not cause the object to be redrawn and should
// be a fairly cheap operation
cell[i].setActivated(rn.nextInt(6)==0);
}
// Cause the UI to repaint
repaint();
}
Add this to MainCell
// You can specify those colors however you like
public static final Color COLOR_ACTIVATED = Color.RED;
public static final Color COLOR_DEACTIVATED = Color.GRAY;
And change:
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if(getPosX()==MainGUI.columns-1&&getPosY()==0)
{
//do nothing
}
to:
protected void paintComponent(Graphics g)
{
// We now make UI changes only when the component is painted
setBackground(activated ? COLOR_ACTIVATED : COLOR_DEACTIVATED);
super.paintComponent(g);
if(getPosX()==MainGUI.columns-1&&getPosY()==0)
{
//do nothing
}
My aim is to select all the files named with MANI.txt which is present in their respective folders and then load path of the MANI.txt files different location in table. After I load the path in the table,I used to select needed path and modifiying those.
To load the MANI.txt files taking more time,because it may present more than 30 times in my workspace or etc. until load the files I want to give alarm to the user with help of ProgessBar.Once the list size has been populated I need to disable ProgressBar.
i came up with this ProgressBar, but progress bar operation gets complete or not, if the background process(finding files and putting their path in the table) got completed means, the result getting displayed and hiding the progress bar? i want the presence of progress bar opertion gets complete 100% in either case? please give me some ideas?how to implement it?
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class JTableHeaderCheckBox extends JFrame implements ActionListener {
protected int counter = 0;
Object colNames[] = { "", "Path" };
Object[][] data = {};
DefaultTableModel dtm;
JTable table;
JButton but;
java.util.List list;
File folder;
JProgressBar current;
JFrame fr1, frame;
int num = 0;
JProgressBar pbar;
JTableHeaderCheckBox it;
public void buildGUI() throws InterruptedException {
dtm = new DefaultTableModel(data, colNames);
table = new JTable(dtm);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
int vColIndex = 0;
TableColumn col = table.getColumnModel().getColumn(vColIndex);
int width = 10;
col.setPreferredWidth(width);
int vColIndex1 = 1;
TableColumn col1 = table.getColumnModel().getColumn(vColIndex1);
int width1 = 500;
col1.setPreferredWidth(width1);
JFileChooser chooser = new JFileChooser();
// chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("Choose workSpace Path");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
{
}
String path = chooser.getSelectedFile().getAbsolutePath();
folder = new File(path);
but = new JButton("REMOVE");
SwingWorker worker = new SwingWorker() {
#Override
public Object doInBackground() {
GatheringFiles ob = new GatheringFiles();
list = ob.returnlist(folder);
return list;
}
#Override
protected void done() {
// java.util.List list = (java.util.List)get();
for (int x = 0; x < list.size(); x++) {
dtm.addRow(new Object[] { new Boolean(false),
list.get(x).toString() });
}
try {
JPanel pan = new JPanel();
JScrollPane sp = new JScrollPane(table);
TableColumn tc = table.getColumnModel().getColumn(0);
tc.setCellEditor(table.getDefaultEditor(Boolean.class));
tc.setCellRenderer(table.getDefaultRenderer(Boolean.class));
tc.setHeaderRenderer(new CheckBoxHeader(
new MyItemListener()));
JFrame f = new JFrame();
pan.add(sp);
pan.add(but);
f.add(pan);
f.setSize(700, 100);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
if (list.size() >= 0) {
// hide the progress bar
frame.hide();
}
} catch (Exception ex) {
}
}
};
worker.execute();
but.addActionListener(this);
//calling progressbar
if(!path.isEmpty())
{
SwingProgressBar();
}
}
public void SwingProgressBar() {
UIManager.put("ProgressBar.selectionBackground", Color.black);
UIManager.put("ProgressBar.selectionForeground", Color.white);
UIManager.put("ProgressBar.foreground", new Color(8, 32, 128));
pbar = new JProgressBar();
pbar.setMinimum(0);
pbar.setMaximum(100);
pbar.setForeground(Color.RED);
pbar.setStringPainted(true);
it = new JTableHeaderCheckBox();
frame = new JFrame("Loading");
final JLabel lb = new JLabel("0");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// frame.setContentPane(it);
frame.add(pbar);
frame.pack();
frame.setVisible(true);
counter = 0;
Thread runner = new Thread() {
public void run() {
counter = 0;
while (counter <= 99) {
Runnable runme = new Runnable() {
public void run() {
pbar.setValue(counter);
}
};
SwingUtilities.invokeLater(runme);
counter++;
try {
Thread.sleep(1000);
} catch (Exception ex) {
}
}
}
};
runner.start();
}
public void updateBar(int newValue) {
pbar.setValue(newValue);
}
class MyItemListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
Object source = e.getSource();
if (source instanceof AbstractButton == false)
return;
boolean checked = e.getStateChange() == ItemEvent.SELECTED;
for (int x = 0, y = table.getRowCount(); x < y; x++) {
table.setValueAt(new Boolean(checked), x, 0);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
new JTableHeaderCheckBox().buildGUI();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
} catch (Exception ex) {
}
}
});
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource() == but) {
System.err.println("table.getRowCount()" + table.getRowCount());
for (int x = 0, y = table.getRowCount(); x < y; x++) {
if ("true".equals(table.getValueAt(x, 0).toString())) {
System.err.println(table.getValueAt(x, 0));
System.err.println(list.get(x).toString());
delete(list.get(x).toString());
}
}
}
}
public void delete(String a) {
String delete = "C:";
System.err.println(a);
try {
File inFile = new File(a);
if (!inFile.isFile()) {
return;
}
// Construct the new file that will later be renamed to the // filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(inFile));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
// Read from the original file and write to the new
// unless content matches data to be removed.
while ((line = br.readLine()) != null) {
System.err.println(line);
line = line.replace(delete, " ");
pw.println(line);
pw.flush();
}
pw.close();
br.close();
// Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
// Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
class CheckBoxHeader extends JCheckBox implements TableCellRenderer,
MouseListener {
protected CheckBoxHeader rendererComponent;
protected int column;
protected boolean mousePressed = false;
public CheckBoxHeader(ItemListener itemListener) {
rendererComponent = this;
rendererComponent.addItemListener(itemListener);
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (table != null) {
JTableHeader header = table.getTableHeader();
if (header != null) {
rendererComponent.setForeground(header.getForeground());
rendererComponent.setBackground(header.getBackground());
rendererComponent.setFont(header.getFont());
header.addMouseListener(rendererComponent);
}
}
setColumn(column);
rendererComponent.setText("Check All");
setBorder(UIManager.getBorder("TableHeader.cellBorder"));
return rendererComponent;
}
protected void setColumn(int column) {
this.column = column;
}
public int getColumn() {
return column;
}
protected void handleClickEvent(MouseEvent e) {
if (mousePressed) {
mousePressed = false;
JTableHeader header = (JTableHeader) (e.getSource());
JTable tableView = header.getTable();
TableColumnModel columnModel = tableView.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
int column = tableView.convertColumnIndexToModel(viewColumn);
if (viewColumn == this.column && e.getClickCount() == 1
&& column != -1) {
doClick();
}
}
}
public void mouseClicked(MouseEvent e) {
handleClickEvent(e);
((JTableHeader) e.getSource()).repaint();
}
public void mousePressed(MouseEvent e) {
mousePressed = true;
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
}
//
import java.io.File;
import java.util.*;
public class GatheringFiles {
public static List returnlist(File folder)
{
List<File> list = new ArrayList<File>();
List<File> list1 = new ArrayList<File>();
getFiles(folder, list);
return list;
}
private static void getFiles(File folder, List<File> list) {
folder.setReadOnly();
File[] files = folder.listFiles();
for(int j = 0; j < files.length; j++) {
if( "MANI.txt".equals(files[j].getName()))
{
list.add(files[j]);
}
if(files[j].isDirectory())
getFiles(files[j], list);
}
}
}