I'm sorry if you've been annoyed by the recent posts. I usually can figure things if I Google them or use the API, but this project may have been over my head. I am using Swing to create a simple calculator that displays in a LED format in the IDE BlueJ (which offers no macros).
I'm sorry that the code is long but here is the JFrame I am displaying it with.
//Swing classes
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;
import javax.swing.Box;
import javax.swing.JTextField;
import javax.swing.JButton;
//Graphics classes
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.geom.AffineTransform;
import java.awt.Dimension;
import java.awt.event.*;
import java.awt.FlowLayout;
//Array, and math classes
import java.util.Arrays;
import java.util.ArrayList;
import java.lang.Math;
public class MCVE
{
public static void main(String[] args)
{
SwingUtilities.invokeLater( new Runnable() {
public void run() {
//frame width and height
final int FRAME_WIDTH = 317;
final int FRAME_HEIGHT = 415;
final JFrame myFrame = new JFrame();
myFrame.setSize(FRAME_WIDTH,FRAME_HEIGHT);
final JPanel myPanel = new JPanel();
myPanel.setLayout(null);
final JFrame ledFrame = new JFrame();
ledFrame.setLayout(new FlowLayout());
final MLED[] ledDisplay = new MLED[8];
for(int i = 0; i < ledDisplay.length; i++)
{
ledDisplay[i] = new MLED();
}
for(int i = 0; i < ledDisplay.length; i++)
{
ledFrame.add(ledDisplay[i]);
}
//Buttons on Simple Calculator
final JButton zeroButton = new JButton("0");
zeroButton.setSize(50,50);
zeroButton.setLocation(62,206);
final JButton endButton = new JButton("End");
endButton.setSize(102,50);
endButton.setLocation(186,275);
ledFrame.pack();
ledFrame.setSize(480,170);
ledFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
ledFrame.setLocationRelativeTo( null );
ledFrame.setVisible( true );
myFrame.add(myPanel);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
myPanel.add(zeroButton);
myPanel.add(endButton);
ledFrame.pack();
ledFrame.setSize(480,170);
ledFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
ledFrame.setLocationRelativeTo( null );
ledFrame.setVisible( true );
class CalculatorListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//The entry
int x=0;
//final answer
int finalAnswer = 0;
//the variable count has two uses: to give an index to store into the array storage and to signal to the program that the operation has been completed and that it is time to move into a new operation.
int count = 0;
int count2 = 6;
String tempString;
ArrayList<Character> toLedArray = new ArrayList<Character>();
if(e.getSource() == zeroButton)
{
if(count>1)
{
x = 0;
count = 0;
}
else
{
if(x!=0)
{
x*=10;
x+=0;
}
else
{
x = 0;
}
}
tempString = String.valueOf(x);
for (char c : tempString.toCharArray()) {
toLedArray.add(c);
}
count = toLedArray.size();
if(count <= 8)
{
for(int i = 0; i < count ; i++)
{
tempString += toLedArray.get(i);
System.out.println("Calculator: 0 Button: Count = " + count2);
ledDisplay[count2].display(toLedArray.get(i));
count2--;
}
}
}
else if(e.getSource() == endButton)
{
myFrame.dispose();
}
}
}
//buttons are given life
CalculatorListener myListener = new CalculatorListener();
zeroButton.addActionListener(myListener);
endButton.addActionListener(myListener);
}
});
}
}
This class creates a JFrame that holds 2 buttons, one with the number zero on it and one that says "end". The zero button when pressed is supposed to light up the right most 7 segment display into the shape of a zero. Unfortunately, this is not the case. I suspect that there may be some threading issues in coming from the Swing operations.
I was hoping that you could take a look at it and point out my logic errors in the code.
Here are the two classes for the custom JPanel and JButton
public class MLED extends JPanel
{
// instance variables - replace the example below with your own
private static Bar[] bars = new Bar[7];
private GridBagConstraints c = new GridBagConstraints();
private final Dimension SIZE = new Dimension(60, 140);
/**
* Constructor for objects of class LED
*/
public MLED()
{
bars[0] = new MBar(30, 10);
bars[1] = new MBar(10, 30);
bars[2] = new MBar(10, 30);
bars[3] = new MBar(30, 10);
bars[4] = new MBar(10, 30);
bars[5] = new MBar(10, 30);
bars[6] = new Bar(30, 10);
this.setLayout(new GridBagLayout());
System.out.println("The LED class is being accessed");
}
public void display(char str)
{
if(str == '0')
{
System.out.println("LED: The zero has been pressed");
bars[0].lightUp();
bars[1].lightUp();
bars[2].lightUp();
bars[4].lightUp();
bars[5].lightUp();
bars[6].lightUp();
}
repaint();
}
public void clear()
{
bars[0].dim();
bars[1].dim();
bars[2].dim();
bars[3].dim();
bars[4].dim();
bars[5].dim();
bars[6].dim();
bars[7].dim();
repaint();
}
#Override public void paintComponent(Graphics g)
{
super.paintComponent(g);
for(int i = 0; i < bars.length; i++)
{
switch(i)
{
case 0:
c.gridx = 1;
c.gridy = 0;
break;
case 1:
c.gridx = 0;
c.gridy = 1;
break;
case 2:
c.gridx = 2;
c.gridy = 1;
break;
case 3:
c.gridx = 1;
c.gridy = 2;
break;
case 4:
c.gridx = 0;
c.gridy = 3;
break;
case 5:
c.gridx = 2;
c.gridy = 3;
break;
case 6:
c.gridx = 1;
c.gridy = 4;
break;
}
this.add(bars[i], c);
}
}
#Override public Dimension getPreferredSize()
{
return SIZE;
}
}
And the custom JComponent:
public class MBar extends JComponent
{
// instance variables - replace the example below with your own
private boolean litUp = false;
private boolean vertical = false;
private boolean rotated = false;
private boolean rotClockwise = false;
private int positionX;
private int positionY;
private final Dimension SIZE;
public MBar(int sizeX, int sizeY)
{
litUp = false;
//vertical = vert;
SIZE = new Dimension(sizeX, sizeY);
//positionX = posX;
//positionY = posY;
repaint();
}
public void lightUp()
{
litUp = true;
repaint();
}
public void dim()
{
litUp = false;
repaint();
}
public void setDirection(boolean vert)
{
vertical = vert;
repaint();
}
public void rotate(boolean rot, boolean dir)
{
rotated = rot;
rotClockwise = dir;
repaint();
}
public void moveRight()
{
positionX = positionX + 11;
repaint();
}
public void moveLeft()
{
positionX = positionX - 11;
repaint();
}
#Override public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2D = (Graphics2D)g;
System.out.println("BAR: Paint Component");
Color color;
int sizeX;
int sizeY;
// if(vertical == true)
// {
// sizeX = 10;
// sizeY = 30;
if(rotated == true)
{
if(rotClockwise == true)
{
g2D.rotate(0.3398);
}
else
{
g2D.rotate(-0.3398);
}
}
if(litUp == true)
{
color = Color.red;
}
else
{
color = Color.black;
}
// else{
// sizeX = 30;
// sizeY = 10;
// if(litUp == true)
// {
// color = Color.red;
// }
// else
// {
// color = Color.black;
// }
// }
g2D.setColor(color);
g2D.fillRect(0 , 0, SIZE.width, SIZE.height);
}
#Override public Dimension getPreferredSize(){
return SIZE;
}
}
The problem is private static Bar[] bars = new Bar[7];.
Every instance of MLED you create re-initialises this with their own values, meaning that each instance of MLED actually gets the SAME reference, instead of there own, which they should have.
When I make it private Bar[] bars = new Bar[7]; it produces...
Related
Currently I'm working on an assignment about creating a version of "Game of Life". However my cells won't appear.
This is my Cell Class:
class Cell{
boolean alive; //true if cell is alive, false if cell is dead
int numNeighbors; //number of alive neightboring cells
//change alive/dead state of the cell
void setAlive(boolean state){
alive = state;
}
//return alive/dead state of the cell
boolean isAlive(){
return alive;
}
//set numNeightbors of the cell to n
void setNumNeighbors(int n){
numNeighbors = n;
}
//take the cell to the next generation
void update(){
if(numNeighbors <2 || numNeighbors >3){
alive = false;
} else if((numNeighbors == 2 || numNeighbors == 3) && alive == true){
alive = true;
} else if(numNeighbors == 3 && alive == false){
alive = true;
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor( Color.blue );
g.setOpaque(true);
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
if(grid[i][j].isAlive()){
g.setColor( Color.BLACK);
} else {
g.setColor ( Color.WHITE);
g.fillRect(50, 50, 50*i, 50*j);
}
}
}
}
And this is my GameOfLife Class
<pre>import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import java.io.*;
public class GameOfLife implements MouseListener{
Cell[][] grid; //contain grid of cells
String birthFilename = "birth.txt"; //text file where initial generation is stored
int row; //number of rows
int col; //number of columns
ActionListener actionListener = new ActionListener(){
javax.swing.Timer timer = new javax.swing.Timer(500, this); //new timer
#Override
public void actionPerformed(ActionEvent event){
}
};
public void buildIt() {
int width = 600;
int height = 600;
JFrame frame = new JFrame("Game of Life");
readInitial();
//adds button interface
JPanel buttonbar = new JPanel();
frame.add(buttonbar, BorderLayout.SOUTH);
JButton start = new JButton("Start");
JButton stop = new JButton("Stop");
JButton nextg = new JButton("Next Generation");
buttonbar.add(nextg);
buttonbar.add(start);
buttonbar.add(stop);
JPanel panel = new JPanel();
frame.add(panel);
panel.setPreferredSize(new Dimension(width, height));
panel.setLayout(new GridLayout(row, col, 4, 4));
frame.pack();
frame.setBackground(Color.WHITE);
frame.setVisible(true);
}
public void mousePressed( MouseEvent e) {
//add code to update x and y
}
public void mouseReleased( MouseEvent e) { }
public void mouseClicked( MouseEvent e) { }
public void mouseEntered( MouseEvent e) { }
public void mouseExited( MouseEvent e) { }
//calculate number of living neightbors of each cell and sets numNeighbors
//Does not update dead/live state of cells
void calculateNumNeighbors(){
int numNeighbors = 0;
for(int i = 1; i < row + 1; i++){
for(int j = 1; j < col + 1; j++){
for(int k = -1; k < 2; k++){
for(int m = -1; m < 2; m++){
if(grid[i+k][j+m].isAlive() && !(k == 0 && m == 0)){
numNeighbors++;
}
}
}
grid[i][j].setNumNeighbors(numNeighbors);
}
}
}
//create grid and read initial generation from file
void readInitial(){
try{
grid = new Cell[row + 2][col + 2]; //empty neighbors at corners, so + 2
File file = new File(birthFilename);
Scanner scanner = new Scanner( file );
row = scanner.nextInt();
col = scanner.nextInt();
for(int i = 0; i < row + 2; i++){
for (int j = 0; j < col + 2; j++){
grid[i][j] = new Cell();
}
}
for(int i = 1; i < row + 1; i++){
for (int j = 1; j < col + 1; j++){
if(scanner.next().equals(".")){
grid[i][j].setAlive(false);
} else if(scanner.next().equals("*")){
grid[i][j].setAlive(true);
}
}
}
for(int i = 0; i < row + 2; i++){
grid[0][i].setAlive(false);
grid[row+2][i].setAlive(false);
}
for(int j = 0; j < col + 2; j++){
grid[j][0].setAlive(false);
grid[j][col+2].setAlive(false);
}
} catch(FileNotFoundException e) {
grid = new Cell[12][12];
row = 10;
col = 10;
for(int i = 0; i < 12; i++){
for (int j = 0; j < 12; j++){
grid[i][j] = new Cell();
grid[i][j].setAlive(false);
}
}
}
}
//update grid to the next generation, using the values of numNeightbors in the cells
void nextGeneration(){
for(int i = 1; i < row + 1; i++){
for (int j = 1; j < col + 1; j++){
grid[i][j].update();
}
}
}
public static void main(String[] arg) {
(new GameOfLife()).buildIt();
}
I hope anyone can help me out to make this program work.
I don't see why anything should draw. You've got a Cell class that yes has a paintComponent method, but this method is meaningless since it's not part of a Swing component. Your JPanel, where you should do drawing -- does nothing. You've other problems with the Cell class too in that it appears to be trying to draw the whole grid and not just a single cell.
Get rid of Cell's paintComponent method
Instead give it a public void draw(Graphics g) method that allows it to draw itself.
Create a JPanel that holds a grid of cells
Have this JPanel do the drawing in its paintComponent override. It will call the draw(g) method of all the Cells that it holds within a for loop.
Always place an #Override annotation above any overridden method. If you had done this, above your paintComponent, the compiler would have warned you that something was wrong.
For example: here's a small program that does not do the Game of Life, but shows an example of a JPanel holding and displaying a grid of non-component cells. By "non-component" the SimpleCell class does not extend from a Swing component, does not have any Swing methods, but as suggested above, does have a draw(...) method and can use this to draw itself. It also has a public boolean contains(Point p) method that the main program can use in its MouseListener to decide if it's been clicked:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class SimpleCellGrid extends JPanel {
private static final int ROWS = 40;
private static final int COLS = 40;
private static final int CELL_WIDTH = 10;
private static final int PREF_W = CELL_WIDTH * COLS;
private static final int PREF_H = CELL_WIDTH * ROWS;
private SimpleCell[][] cellGrid = new SimpleCell[ROWS][COLS];
public SimpleCellGrid() {
MyMouse myMouse = new MyMouse();
addMouseListener(myMouse);
for (int row = 0; row < cellGrid.length; row++) {
for (int col = 0; col < cellGrid[row].length; col++) {
int x = col * CELL_WIDTH;
int y = row * CELL_WIDTH;
cellGrid[row][col] = new SimpleCell(x, y, CELL_WIDTH);
}
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
for (SimpleCell[] cellRow : cellGrid) {
for (SimpleCell simpleCell : cellRow) {
simpleCell.draw(g2);
}
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class MyMouse extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
for (SimpleCell[] cellRow : cellGrid) {
for (SimpleCell simpleCell : cellRow) {
if (simpleCell.contains(e.getPoint())) {
simpleCell.setAlive(!simpleCell.isAlive());
}
}
}
repaint();
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("SimpleCellGrid");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new SimpleCellGrid());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
public class SimpleCell {
private static final Color CELL_COLOR = Color.RED;
private boolean alive = false;
private int x;
private int y;
private int width;
private Rectangle rectangle;
public SimpleCell(int x, int y, int width) {
this.x = x;
this.y = y;
this.width = width;
rectangle = new Rectangle(x, y, width, width);
}
public boolean isAlive() {
return alive;
}
public void setAlive(boolean alive) {
this.alive = alive;
}
public void draw(Graphics2D g2) {
if (alive) {
g2.setColor(CELL_COLOR);
g2.fill(rectangle);
}
}
public boolean contains(Point p) {
return rectangle.contains(p);
}
#Override
public String toString() {
return "SimpleCell [alive=" + alive + ", x=" + x + ", y=" + y + ", width=" + width + ", rectangle=" + rectangle
+ "]";
}
}
I have a class called BoardSquare that is an inherited class of JButton. Each of the BoardSquare objects is stored in an array BoardSquare[][] boardsquares. I have used the following code
BoardSquare.boardSquares[j][i].add(new JLabel((j+1)+":"+(i+1)));
to add labels to each of the squares in the array according to their coordinates. I need them to have these labels(I think) so that I can identify them and addActionListeners, etc. How do I make the JLabels invisible so they don't show up in my JFrame?
Alternatively, how can I make the JLabel of each button an instance variable so that I can call JLabel.setVisible(false) but still use them when I add action listeners?
EDIT: If anyone's interested, it's for a Checkers Game.
Here are my classes:
GameWindow
BoardSquare
Checker
MyListener
Thank you for the edit. If this were my application, I'd probably do things very differently including,
Use a grid of JLabels not JButtons. I see no need to use JButtons, and a problem in that the button would not be as visually appealing as other possible solutions.
Either give the JLabel cells or the containing JPanel a MouseListener,
Have the JPanel cells have no Icon and thus be empty if no checker is on them,
Or have them hold an ImageIcon of an appropriately colored checker if they are not empty.
You could even animate the GUI by using the glass pane to hold a JPanel with an appropriate checker ImageIcon that the user can drag.
Note that if you absolutely have to use JButtons, then don't add JLabels to them. Instead simply set the JButton's Icon to null or to an appropriate Checker ImageIcon.
Edit
For example, a bad code example as a proof of concept. Try compiling and running this.
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.EnumMap;
import java.util.Map;
import javax.swing.*;
#SuppressWarnings("serial")
public class Checkers extends JPanel {
public static final int SIDE_LENGTH = 60;
public static final int ROW_COUNT = 8;
private static final String ROW = "row";
private static final String COLUMN = "column";
private static final Color LIGHT_COLOR = new Color(210, 180, 140);
private static final Color DARK_COLOR = new Color(107, 68, 35);
private Map<Checker, Icon> checkerIconMap = new EnumMap<Checker, Icon>(
Checker.class);
private JLabel[][] labelGrid = new JLabel[ROW_COUNT][ROW_COUNT];
private Checker[][] checkerGrid = new Checker[ROW_COUNT][ROW_COUNT];
public Checkers() {
for (Checker checker : Checker.values()) {
checkerIconMap.put(checker, createCheckerIcon(checker));
}
setLayout(new GridLayout(ROW_COUNT, ROW_COUNT));
for (int row = 0; row < labelGrid.length; row++) {
for (int col = 0; col < labelGrid[row].length; col++) {
checkerGrid[row][col] = Checker.EMPTY;
JLabel gridCell = new JLabel(checkerIconMap.get(Checker.EMPTY));
gridCell.setOpaque(true);
gridCell.putClientProperty(ROW, row);
gridCell.putClientProperty(COLUMN, col);
Color c = row % 2 == col % 2 ? LIGHT_COLOR : DARK_COLOR;
gridCell.setBackground(c);
add(gridCell);
labelGrid[row][col] = gridCell;
}
}
for (int i = 0; i < labelGrid.length / 2 - 1; i++) {
for (int j = 0; j < labelGrid.length / 2; j++) {
int row = i;
int col = j * 2;
col += row % 2 == 0 ? 1 : 0;
labelGrid[row][col].setIcon(checkerIconMap.get(Checker.BLACK));
checkerGrid[row][col] = Checker.BLACK;
row = ROW_COUNT - row - 1;
col = ROW_COUNT - col - 1;
labelGrid[row][col].setIcon(checkerIconMap.get(Checker.RED));
checkerGrid[row][col] = Checker.RED;
}
}
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
addMouseListener(myMouseAdapter);
addMouseMotionListener(myMouseAdapter);
}
private Icon createCheckerIcon(Checker checker) {
BufferedImage img = new BufferedImage(SIDE_LENGTH, SIDE_LENGTH,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
g2.setColor(checker.getColor());
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int x = 3;
int y = x;
int width = SIDE_LENGTH - 2 * x;
int height = width;
g2.fillOval(x, y, width, height);
g2.dispose();
return new ImageIcon(img);
}
private class MyMouseAdapter extends MouseAdapter {
private int selectedRow = -1;
private int selectedCol = -1;
private Checker selectedChecker = null;
private JPanel glassPane = null;
private Point p = null;
private JLabel movingLabel = new JLabel(checkerIconMap.get(Checker.EMPTY));
public MyMouseAdapter() {
movingLabel.setSize(movingLabel.getPreferredSize());
movingLabel.setVisible(false);
}
#Override
public void mousePressed(MouseEvent e) {
p = e.getPoint();
for (int row = 0; row < labelGrid.length; row++) {
for (int col = 0; col < labelGrid[row].length; col++) {
JLabel gridCell = labelGrid[row][col];
if (gridCell == getComponentAt(p)) {
if (checkerGrid[row][col] != Checker.EMPTY) {
selectedRow = row;
selectedCol = col;
selectedChecker = checkerGrid[row][col];
checkerGrid[row][col] = Checker.EMPTY;
labelGrid[row][col].setIcon(checkerIconMap.get(Checker.EMPTY));
JRootPane rootPane = SwingUtilities.getRootPane(Checkers.this);
glassPane = (JPanel) rootPane.getGlassPane();
glassPane.setVisible(true);
glassPane.setLayout(null);
movingLabel.setIcon(checkerIconMap.get(selectedChecker));
movingLabel.setVisible(true);
glassPane.add(movingLabel);
int x = p.x - SIDE_LENGTH / 2;
int y = p.y - SIDE_LENGTH / 2;
movingLabel.setLocation(x, y);
}
}
}
}
}
#Override
public void mouseReleased(MouseEvent e) {
if (selectedChecker == null) {
return;
}
p = e.getPoint();
if (!Checkers.this.contains(p)) {
// if mouse releases and is totally off of the grid
returnCheckerToOriginalCell();
clearGlassPane();
return;
}
for (int row = 0; row < labelGrid.length; row++) {
for (int col = 0; col < labelGrid[row].length; col++) {
JLabel gridCell = labelGrid[row][col];
if (gridCell == getComponentAt(p)) {
if (isMoveLegal(row, col)) {
checkerGrid[row][col] = selectedChecker;
labelGrid[row][col].setIcon(checkerIconMap.get(selectedChecker));
// todo: check for jumped pieces...
} else {
// illegal move
returnCheckerToOriginalCell();
}
}
}
}
clearGlassPane();
}
// this code would go in the model class
private boolean isMoveLegal(int row, int col) {
if (checkerGrid[row][col] != Checker.EMPTY) {
// trying to put a checker on another checker
returnCheckerToOriginalCell();
} else if (row == selectedRow && col == selectedCol) {
// trying to put checker back in same position
returnCheckerToOriginalCell();
} else if (row % 2 == col % 2) {
// invalid square
returnCheckerToOriginalCell();
} else {
// TODO: more logic needs to go here to test for a legal move
// and to remove jumped pieces
return true;
}
return false;
}
#Override
public void mouseDragged(MouseEvent e) {
if (selectedChecker == null || p == null) {
return;
}
p = e.getPoint();
int x = p.x - SIDE_LENGTH / 2;
int y = p.y - SIDE_LENGTH / 2;
movingLabel.setLocation(x, y);
}
private void clearGlassPane() {
glassPane.setVisible(false);
movingLabel.setVisible(false);
selectedChecker = null;
p = null;
selectedCol = -1;
selectedRow = -1;
}
private void returnCheckerToOriginalCell() {
checkerGrid[selectedRow][selectedCol] = selectedChecker;
labelGrid[selectedRow][selectedCol].setIcon(checkerIconMap.get(selectedChecker));
}
}
private static void createAndShowGui() {
Checkers mainPanel = new Checkers();
JFrame frame = new JFrame("JLabelGrid");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class CheckerModel {
}
enum Checker {
EMPTY(new Color(0, 0, 0, 0)), RED(Color.red), BLACK(Color.black);
private Color color;
private Checker(Color color) {
this.color = color;
}
public Color getColor() {
return color;
}
}
Better Model-View example being worked on...
Instead of adding the new Jlabel() directly to the array , make an instance first then add that ... i guess this is done in a loop so for example :
JLabel lbl;
for(....) {
lbl = new JLabel(new JLabel((j+1)+":"+(i+1));
lbl.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt()){
// TODO here
}
});
BoardSquare.boardSquares[j][i].add(lbl);
I am currently writing code for a program that, when it works, opens an external window that has a building and a scrolling banner on it. If you input a phrase into a textbox above the building, that phrase will scroll across the banner.
DisplayWindow
import javax.swing.*;
import java.awt.*;
public class DisplayWindow extends JFrame {
private Container c;
public DisplayWindow() {
super("Display");
c = this.getContentPane();
}
public void addPanel(JPanel p) {
c.add(p);
}
public void showFrame() {
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
MovingSignPanel
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class MovingSignPanel extends JPanel implements ActionListener{
JMenuBar b;
JButton start = new JButton("Start");
JButton stop = new JButton("Stop");
JButton quit = new JButton("Quit");
JTextField phrase = new JTextField(20);
private int lVar = 200;
private int rVar = 600;
private int hVar = 200;
private int ground = 400;
private Timer scroll = new Timer(40,this);
private int xVel = 2;
private int xVal = lVar;
private int yVal = 150;
private String input = " ";
private int inputWidth = 0;
private Boolean scrolling = false;
public MovingSignPanel(JMenuBar b){
setPreferredSize(new Dimension(1000, 1000));
setBackground(Color.white);
this.add(phrase);
phrase.addActionListener(this);
this.add(start);
start.addActionListener(this);
this.add(stop);
stop.addActionListener(this);
this.add(quit);
quit.addActionListener(this);
}
public void drawBanner(Graphics g){
clearBanner(g);
drawBuilding(g);
int position = xVal;
while(position < rVar){
g.drawString(input,position,yVal);
position += inputWidth;
}
position = xVal - inputWidth;
while(position > lVar - inputWidth){
g.drawString(input,position,yVal);
position -= inputWidth;
}
if(xVal > rVar)
xVal -= inputWidth;
xVal += xVel;
drawBuilding(g);
}
public void drawBuilding(Graphics g){
super.paintComponent(g);
g.setColor(Color.white);
g.fillRect(0,0,1000,1000);
g.setColor(Color.gray);
g.fillRect(lVar,200,rVar-lVar,hVar);
g.fillRect(lVar,100,rVar-lVar,hVar-800);
g.setColor(Color.lightGray);
g.fillRect(0, ground, 700, 400 - ground);
g.setColor(Color.blue);
for(int n = lVar + 20; n < rVar - 10; n += 40){
for(int m = 60; m < 150; m += 30){
g.fillRect(n,m,20,20);
}
}
for(int n = lVar + 20; n < rVar - 10; n += 40){
for(int m = 210; m < 350; m += 30){
g.fillRect(n,m,20,20);
}
}
g.setColor(Color.darkGray);
g.fillRect(0,0,lVar,ground);
g.fillRect(rVar,0,lVar,ground);
}
public void inputMsg(){
input = phrase.getText();
inputWidth = phrase.getText().length();
}
public void resetTimer(){
scroll.stop();
scrolling = false;
}
public void startMsg(){
inputMsg();
if(!scrolling){
scroll.start();
scrolling = true;
}
}
public void clearBanner(Graphics g){
g.clearRect(0,0,1000,1000);
}
public void actionPerformed(ActionEvent e){
if (e.getSource() == quit)
System.exit(0);
if (e.getSource() == start)
repaint();
startMsg();
if (e.getSource() == stop)
resetTimer();
}
}
SignDriver
import javax.swing.*;
public class SignDriver {
public static void main(String[] args) {
DisplayWindow d = new DisplayWindow();
JMenuBar menuBar = new JMenuBar();
d.setJMenuBar(menuBar);
MovingSignPanel p = new MovingSignPanel(menuBar);
d.addPanel(p);
d.showFrame();
}
}
I can organize this better if needed. I know the buttons don't work yet, but right now I'm more concerned with why nothing is being drawn when the program is run. The error occurs whenever I try to run the program and looks like this:
java.lang.NoSuchMethodError: MovingSignPanel.<init>(Ljavax/swing/JMenuBar;)V
at SignDriver.main(SignDriver.java:9)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
Seems your SignDriver class at runtime has an old version of the class MovingSignPanel, a version that does not have this constructor MovingSignPanel(javax.swing.JMenuBar). Just try to clean and rebuild, and this error should disappear.
I want to click on the screen and have the character move to that destination. Not instantly, but rather "walk" to the given coordinate. Currently I'm using JLabels and they're fine if I only use static images, but everytime I click somewhere on the screen the image shows up at that exact point. Could someone give me some tips?
edit: Should I override the paint class and draw some items that way?
Here's some code:
package mod;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.awt.KeyboardFocusManager;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Board2 extends JPanel {
private Thread animator;
int x, y;
double ix, iy;
double dx, dy;
final int frameCount = 8;
BufferedImage flower;
private int[][] fPos = {{232, 15},{400, 200},{335, 335}}; // flower coordinates
private static int bWIDTH = 800; // width of window
private static int bHEIGHT = 600;// height of window
private Font font;
private FontMetrics metrics;
ImageIcon grassI = new ImageIcon(this.getClass().getResource("grass.png"));
ImageIcon riverI = new ImageIcon(this.getClass().getResource("river.png"));
private Image grass = grassI.getImage();
private Image river = riverI.getImage();
private House house = new House();
private River river1 = new River();
//private Flower flower = new Flower();
private TitleScreenLayer ts = new TitleScreenLayer();
private Player girlP = new Player();
private static int px = 250;
private static int py = 250;
private boolean visTl = false;
private boolean plant = false;
ArrayList<Flower> flowers= new ArrayList<Flower>();
private long period;
private volatile boolean running = false;
private volatile boolean gameOver = false;
private volatile boolean isPaused = false;
// New stuff for Board2 below
private JLayeredPane lpane;
private JLabel grassLabel;
private JLabel riverLabel;
private JLabel houseLabel;
private JLabel pear1Label;
private JLabel pear2Label;
private JLabel pear3Label;
private JLabel drivewayLabel;
private JLabel girlLabel;
private JProgressBar progressBar;
private JLabel toolLabel;
private JTextArea textBubble;
ImageIcon girlImage = new ImageIcon(girlP.getImage());
int mouseClicks = 0;
CountdownTimer cTimer;
private static String message;
public static String setMessage(String newMessage){
return message = newMessage;
}
private static ImageIcon playerTool = new ImageIcon("BradfordPear.png");
public ImageIcon getPlayerTool(){
return playerTool;
}
public static void setPlayerTool(String image){
playerTool = new ImageIcon(image);
}
public JTextArea getTextBubble(){
return textBubble;
}
public Player getPlayer(){
return girlP;
}
public static int getPlayerX(){
return px;
}
public static int getPlayerY(){
return py;
}
public JLayeredPane getLayeredPane(){
return lpane;
}
public Board2(){
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
//create the layered pane
lpane = new JLayeredPane();
lpane.setPreferredSize(new Dimension(800, 600));
//create the "background" image
ImageIcon image = new ImageIcon("grass.png");
grassLabel = new JLabel(image);
grassLabel.setBounds(0, 0, image.getIconWidth(), image.getIconHeight());
//create the house image
ImageIcon houseImage = new ImageIcon("house.png");
houseLabel = new JLabel(houseImage);
houseLabel.setBounds(-330, -150, image.getIconWidth(), image.getIconHeight());
//create the driveway image
ImageIcon drivewayImage = new ImageIcon("driveway.png");
drivewayLabel = new JLabel(drivewayImage);
drivewayLabel.setBounds(-335, 105, image.getIconWidth(), image.getIconHeight());
//create the river image
ImageIcon riverImage = new ImageIcon("river.png");
riverLabel = new JLabel(riverImage);
riverLabel.setBounds(360, 0, image.getIconWidth(), image.getIconHeight());
//create pear1 image
ImageIcon pear1Image = new ImageIcon("BradfordPear.png");
pear1Label = new JLabel(pear1Image);
pear1Label.setBounds(100, 100, image.getIconWidth(), image.getIconHeight());
//create pear2 image
ImageIcon pear2Image = new ImageIcon("BradfordPear.png");
pear2Label = new JLabel(pear2Image);
pear2Label.setBounds(50, -100, image.getIconWidth(), image.getIconHeight());
//create pear3 image
ImageIcon pear3Image = new ImageIcon("BradfordPear.png");
pear3Label = new JLabel(pear3Image);
pear3Label.setBounds(-100, -50, image.getIconWidth(), image.getIconHeight());
//create initial Player(girl) image
//ImageIcon girlImage = new ImageIcon(girlP.getImage());
girlLabel = new JLabel(girlImage);
girlLabel.setBounds((int)girlP.getPositionX(), (int)girlP.getPositionY(), image.getIconWidth(), image.getIconHeight());
//create progress bar
progressBar = new JProgressBar(JProgressBar.VERTICAL, 0, 10);
progressBar.setValue(0);
progressBar.setBounds(720, 50, 100, 500);
//create timer
JTextField timerField = new JTextField();
cTimer = new CountdownTimer(timerField);
timerField.setBounds(400, 0, 50, 50);
//create toolbox
Toolbox toolbox = new Toolbox();
toolbox.setBounds(550, 0, 250, 50);
//create the text bubble
textBubble = new JTextArea("IDPC is the best coding group ever");
textBubble.setLineWrap(true);
//textBubble.setBounds(200, 200, 100, 100);
//add the background & various images
lpane.add(grassLabel, new Integer(1));
lpane.add(houseLabel, new Integer(2));
lpane.add(riverLabel, new Integer(2));
lpane.add(drivewayLabel, new Integer(2));
lpane.add(pear1Label, new Integer(2));
lpane.add(pear2Label, new Integer(2));
lpane.add(pear3Label, new Integer(2));
lpane.add(progressBar, new Integer(3));
lpane.add(girlLabel, new Integer(3));
lpane.add(timerField, new Integer(2));
lpane.add(toolbox, new Integer(3));
add(lpane);
cTimer.start();
// listen for action events
new ActionListener() {
public void actionPerformed(ActionEvent e) {
girlP.move();
//girlLabel.setLocation(px, py);
}
};
// listen for mouse presses
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
//lpane.remove(textBubble);
mouseClicks+= 1;
testPress(e.getX(), e.getY());
//textBubble.setBounds(e.getX(), e.getY(), 40, 40);
updateProgressBar();
}
});
//listen for player action
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if(e.getClickCount() == 2){
ImageIcon flowerImage = playerTool;
JLabel flowerPanel = new JLabel(flowerImage);
flowerPanel.setBounds((px -((int)girlP.getPositionX() / 2)),
(py - ((int)girlP.getPositionY() / 2)),
flowerImage.getIconWidth(),
flowerImage.getIconHeight());
lpane.add(flowerPanel, new Integer(3));
textBubble.setBounds(e.getX(), e.getY(), 200, 40);
textBubble.replaceSelection(message);
lpane.add(textBubble, new Integer(3));
//lpane.remove(textBubble);
}
}
});
x = 15;
y = 150;
ix = 0;
iy = 0;
dx = .05;
dy = .05;
girlP.setDestination(px, py);
}
public void testPress(int x, int y){
px = x;
py = y;
if (px < (ix + house.getImage().getWidth(this))
&& (py < (iy + house.getImage().getHeight(this)))) {
px = px + (house.getImage().getWidth(this)/3);
py = py + (house.getImage().getHeight(this)/3);
}
if (px > (bWIDTH - river1.getImage().getWidth(this))) {
px = px - 80 - (river1.getImage().getWidth(this)/2);
}
girlLabel.setBounds((px -((int)(girlP.getPositionX()*2.5))),
(py - ((int)(girlP.getPositionY()*2.5))),
girlImage.getIconWidth(), girlImage.getIconHeight());
girlP.setDestination((px-(girlP.getImage().getWidth(this)/2)),
(py-(girlP.getImage().getHeight(this)/2)));
girlP.pinned(x, y);
}
public void updateProgressBar(){
if(progressBar.getValue() == 3){
//progressBar.setBackground(Color.red);
//UIManager.put("progressBar.foreground", Color.RED);
UIDefaults defaults = new UIDefaults();
defaults.put("progressBar[Enabled].foregroundPainter", Color.RED);
progressBar.putClientProperty("Nimbus.Overrides.InheritDefaults", Boolean.TRUE);
progressBar.putClientProperty("Nimbus.Overrides", defaults);
}
progressBar.setValue(mouseClicks);
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
JComponent newContentPane = new TitleScreenLayer();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Here's the player class:
package mod;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.ImageObserver;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
public class Player {
int tile;
double positionX;
double positionY;
int destinationX;//Used when moving from place to place
int destinationY;
Tool currentTool;
int direction; //Position the image is facing
double dx;
double dy;
int [] pin = new int[10];
private String girl = "girl.png";
ImageIcon ii = new ImageIcon(this.getClass().getResource(girl)); // load girl image
private Image image = ii.getImage();
private boolean visible = true;
public boolean plant = false;
Image playerImage;
public double getPositionX() {
return positionX;
}
public void setPositionX(double positionX) {
this.positionX = positionX;
}
public double getPositionY() {
return positionY;
}
public void setPositionY(double positionY) {
this.positionY = positionY;
}
public Player(){
positionX=30;
positionY=20;
dx = 0.2;
dy = 0.2;
destinationX=(int)positionX;
destinationY=(int)positionY;
//this.playerImage=playerImage;
}
public void doAction() {
//currentTool.getNum();
plant = true;
}
public void pinned(int x, int y) {
if (plant == true) {
pin[0] = x;
pin[1] = y;
}
//plant = false;
}
public void plant(Graphics g, ImageObserver io) {
int x = pin[0];
int y = pin[1];
if (plant == true) {
// g.drawImage(flower.getImage(), x, y, io);
}
}
public void ActionPerformed(ActionEvent e) {
positionX += dx;
positionY += dy;
}
public boolean isVisible() {
return visible;
}
public void setVisible(Boolean visible) {
this.visible = visible;
}
public Image getImage() {
return image;
}
public void move(){
//MOVE LEFT AND RIGHT
if(destinationX<positionX){
positionX-=dx;
}
if(destinationX>positionX){
positionX+=dx;
}
//MOVE UP AND DOWN
if(destinationY<positionY){
positionY-=dy;
}
if(destinationY>positionY){
positionY+=dy;
}
}
public double setDx(double speed) {
dx = speed;
return dx;
}
public double setDy(double speed) {
dy = speed;
return dy;
}
public void TileIn(int px, int py)
{
px=destinationX;
py=destinationY;
int tileX=1;
int tileY = 1;
int bWIDTH=800;
int bHEIGHT=600;
if(px >= 0 && px <= 800*.1)
{
tileX=2;
}
else if(px> bWIDTH*.1 && px <= bWIDTH*.2)
{
tileX=3;
}
else if(px > bWIDTH*.2 && px <= bWIDTH*.3)
{
tileX=4;
}
else if(px > bWIDTH*.3 && px <= bWIDTH*.4)
{
tileX=5;
}
else if(px > bWIDTH*.4 && px <= bWIDTH*.5)
{
tileX=6;
}
else if(px > bWIDTH*.5 && px <= bWIDTH*.6)
{
tileX=7;
}
else if(px > bWIDTH*.6 && px <= bWIDTH*.7)
{
tileX=8;
}
else if(px > bWIDTH*.7 && px <= bWIDTH*.8)
{
tileX=9;
}
else if(px > bWIDTH*.8 && px <= bWIDTH*.9)
{
tileX=10;
}
else if(px > bWIDTH*.9 && px <= bWIDTH)
{
tileX=11;
}
if(py >= 0 && py <= bHEIGHT*.1)
{
tileY=2;
}
else if(py> bHEIGHT*.1 && py <= bHEIGHT*.2)
{
tileY=3;
}
else if(py > bHEIGHT*.2 && py <= bHEIGHT*.3)
{
tileY=4;
}
else if(py > bHEIGHT*.3 && py <= bHEIGHT*.4)
{
tileY=5;
}
else if(py > bHEIGHT*.4 && py <= bHEIGHT*.5)
{
tileY=6;
}
else if(py > bHEIGHT*.5 && py <= bHEIGHT*.6)
{
tileY=7;
}
else if(py > bHEIGHT*.6 && py <= bHEIGHT*.7)
{
tileY=8;
}
else if(py > bHEIGHT*.7 && py <= bHEIGHT*.8)
{
tileY=9;
}
else if(py > bHEIGHT*.8 && py <= bHEIGHT*.9)
{
tileY=10;
}
else if(py > bHEIGHT*.9 && py <= bHEIGHT)
{
tileY=11;
}
System.out.println("Grid X: " + tileX + " Grid Y: " + tileY);
}
public void setDestination(int x, int y){
destinationX=x;
destinationY=y;
System.out.println(x + "," + y);
TileIn(x,y);
}
// public void tileIn(int a)
// {
//
// b=destinationY;
// return TileIn(x,y)
// }
public void draw(Graphics g,ImageObserver io){
g.drawImage(image, (int)positionX,(int) positionY,io);
}
}
Here is the main class:
package mod;
import java.awt.Container;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
public class Skeleton2 extends JFrame /*implements WindowListener*/{
private static int DEFAULT_FPS = 80;
private Board2 bd;
public Skeleton2(long period) {
super("Skeleton");
makeGUI(period);
//addWindowListener(this);
pack();
setResizable(false);
setVisible(true);
}
public void makeGUI(long period) {
Container c = getContentPane();
bd = new Board2();
c.add(bd, "Center");
} // end of makeGUI()
//==================================================================================
// Window Events
//==================================================================================
/*
public void windowActivated(WindowEvent e) {
bd.resumeGame();
}
public void windowDeactivated(WindowEvent e) {
bd.pauseGame();
}
public void windowDeiconified(WindowEvent e) {
bd.resumeGame();
}
public void windowIconified(WindowEvent e) {
bd.pauseGame();
}
public void windowClosing(WindowEvent e) {
bd.stopGame();
}
*/
public void windowClosed(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
//==================================================================================
public static void main(String[] args) {
int fps = DEFAULT_FPS;
long period = (long) 1000.0/fps;
new Skeleton2(period);
System.out.println("Period: " + period);
}
}
Not instantly, but rather "walk" to the given coordinate.
Then you need to use a Swing Timer. The Timer is used to schedule the animation. So you would need to calculate a path between the two points. Every time the Timer fires you would move the label a few pixels until it reaches it's destination.
There is no need to do custom painting for this. A JLabel will work fine. The hard part is calculating the path you want the character to take. Also make sure you use a null layout on the panel you add the JLabel to, which means you will also need to set the size of the label equal to the preferred size of the label.
You should rather use g.drawImage in your component paintComponent method.
Im trying to use SwingWorker to update my gui.
The part of my gui that I'm trying to update is a JPanel (gridPanel) with a GridLayout [50][50].
Each grid in the GridLayout has a custom GridGraphic JComponent.
In the doInBackground() of my SwingWorker, I update each GridGraphic which represents some color. Then, I publish it to a List that the process() uses to update the gui. Though, the gui isn't updating.
Is there a way to do this without calling repaint().
How do I fix my SwingWorker so the gui is responsive. What do I want to return in order for the gridPanel, which is a [50][50] GridLayout of GridGraphic components responsive to changes
The SwingWorker is executed in the stepButton.addActionListener(new ActionListener()...............in SlimeGui
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
public class SlimeGui extends JFrame{
private JPanel buttonPanel, populationPanel, velocityPanel;
private JPanel gridPanel = new JPanel(new GridLayout(50, 50));
private JButton setupButton, stepButton, goButton;
private JLabel populationNameLabel, velocityNameLabel, populationSliderValueLabel, velocitySliderValueLabel;
private JSlider populationSlider, velocitySlider;
private GridGraphic [] [] gridGraphic;
private GridGraphic test;
private int agents = 125;
private int velocity = 500;
private boolean resetGrid;
public SlimeGui() {
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//Set up JButtons
buttonPanel = new JPanel();
setupButton = new JButton("Setup");
stepButton = new JButton("Step");
goButton = new JButton("Go");
buttonPanel.add(setupButton);
buttonPanel.add(stepButton);
buttonPanel.add(goButton);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 3;
add(buttonPanel, c);
//Set up population JSlider
populationPanel = new JPanel();
populationNameLabel = new JLabel(" Population");
populationSliderValueLabel = new JLabel(Integer.toString(agents));
populationSlider = new JSlider(JSlider.HORIZONTAL,0, 1000, 125);
populationSlider.setMajorTickSpacing(125);
populationSlider.setPaintTicks(true);
populationSlider.addChangeListener(new PopulationSliderListener());
populationPanel.add(populationNameLabel);
populationPanel.add(populationSlider);
populationPanel.add(populationSliderValueLabel);
c.gridx = 0;
c.gridy = 2;
add(populationPanel, c);
//Set up veolicty JSlider
velocityPanel = new JPanel();
velocityNameLabel = new JLabel(" Velocity");
velocitySliderValueLabel = new JLabel(Integer.toString(velocity));
velocitySlider = new JSlider(JSlider.HORIZONTAL,0, 1000, 500);
velocitySlider.setMajorTickSpacing(125);
velocitySlider.setPaintTicks(true);
velocitySlider.addChangeListener(new VelocitySliderListener());
velocityPanel.add(velocityNameLabel);
velocityPanel.add(velocitySlider);
velocityPanel.add(velocitySliderValueLabel);
c.gridx = 0;
c.gridy = 3;
add(velocityPanel, c);
//Set up grid with GridGraphic objects
gridGraphic = new GridGraphic[50][50];
for(int i = 0; i < 50; i++){
for(int j = 0; j < 50; j++){
gridGraphic[i][j] = new GridGraphic();
gridPanel.add(gridGraphic[i][j]);
}
}
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 3;
add(gridPanel, c);
//Set up ActionListener for the 'Setup' JButton
setupButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
int n1=0;
int n2=0;
//resets the grid so there are no agents
if(resetGrid){
for(int i = 0; i < 50; i++){
for(int j = 0; j < 50; j++){
gridGraphic[i][j].setDefault();
}
}
}
//sets a random number of positions for GridGraphics
for (int numOfAgenets = 0; numOfAgenets < agents; numOfAgenets++){
int lowerB = 0;
int upperB = 50;
n1 = (lowerB + (int)(Math.random()*(upperB-lowerB))); //random number 1
n2 = (lowerB + (int)(Math.random()*(upperB-lowerB))); //random number 2
System.out.println("Choosing random agent "+(numOfAgenets+1)+": "+n1 +" "+n2);
//sets the GridGraphic to an agent if it's available
if (gridGraphic[n1][n2].getIntensity() == 0)
gridGraphic[n1][n2].setAgent();
//if the GridGraphic is already an agent, it continues to search
else if(gridGraphic[n1][n2].getIntensity() == 5){
while(gridGraphic[n1][n2].getIntensity() == 5){
n1 = (lowerB + (int)(Math.random()*(upperB-lowerB)));
n2 = (lowerB + (int)(Math.random()*(upperB-lowerB)));
}
gridGraphic[n1][n2].setAgent();
}
}
repaint();
resetGrid = true;
}
});
//Set up ActionListener for the 'Step' JButton
stepButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
StepManager step = new StepManager(SlimeGui.this);
step.execute();
//repaint();
}
});
}
class PopulationSliderListener implements ChangeListener{
public void stateChanged(ChangeEvent e){
agents = ((JSlider)e.getSource()).getValue();
populationSliderValueLabel.setText(Integer.toString(agents));
System.out.println("Population of agents: " + agents);
}
}
class VelocitySliderListener implements ChangeListener{
public void stateChanged(ChangeEvent e){
velocity = ((JSlider)e.getSource()).getValue();
velocitySliderValueLabel.setText(Integer.toString(velocity));
System.out.println("Velocity(ms) of agents: " + velocity);
}
}
public Integer getVelocity(){
return velocity;
}
public GridGraphic getGridGraphic(int n1, int n2){
return gridGraphic[n1][n2];
}
public GridGraphic [][] getGridGraphic(){
return gridGraphic;
}
public void setGridGraphicArray(GridGraphic xxx, int n1, int n2 ){
gridGraphic[n1][n2] = xxx;
}
public void setGridPanel(GridGraphic[][] xxx){
for(int i = 0; i < 50; i++){
for(int j = 0; j < 50; j++){
gridPanel.add(xxx[i][j]);
}
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
SlimeGui slime = new SlimeGui();
slime.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Display the window.
slime.pack();
slime.setVisible(true);
slime.setResizable(false);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
My SwingWorker
import java.util.List;
import java.awt.*;
import javax.swing.*;
import java.util.concurrent.ExecutionException;
public class StepManager extends SwingWorker<Void, GridGraphic>{
private SlimeGui gui;
public StepManager(SlimeGui sg){
gui=sg;
}
#Override
protected Void doInBackground() throws Exception{
for(int i = 0; i < 50; i++){
for(int j = 0; j < 50; j++){
if(gui.getGridGraphic(i,j).getIntensity()==5){
if (i==0){
gui.getGridGraphic(i,j).setDefault();
gui.getGridGraphic(49,j).setAgent();
}
else{
gui.getGridGraphic(i,j).setDefault();
gui.getGridGraphic(i-1,j).setAgent();
}
}
publish(gui.getGridGraphic(i,j));
}
}
return null;
}
#Override
protected void process(List <GridGraphic> gg){
int k=0;
for ( int i = 0; i < 50; i++ ){
for(int j = 0; j < 50; j++){
gui.setGridGraphicArray(gg.get(k),i,j);
k++;
}
}
gui.setGridPanel(gui.getGridGraphicArray());
System.out.println("process has completed");
}
#Override
protected void done(){
System.out.println("doInBackground has completed");
}
}
My GridGraphic
import java.awt.*;
import javax.swing.*;
public class GridGraphic extends JComponent {
private int intensity = 0;
public GridGraphic() {
//setBorder(BorderFactory.createLineBorder(Color.BLUE));
}
public void paintComponent(Graphics g) {
//paints the GridGraphic black
if (intensity == 0){
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
}
//paints the GridGraphic black with a yellow dot
else if (intensity == 5){
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.YELLOW);
g.fillOval(3, 3, getWidth()/2, getHeight()/2);
}
//paints the GridGraphic dark yellow (pheromone)
if (intensity == 2){
super.paintComponent(g);
g.setColor(Color.BLACK.brighter());
g.fillRect(0, 0, getWidth(), getHeight());
}
}
public Dimension getPreferredSize() {
return new Dimension(10, 10);
}
public void setAgent(){
intensity = 5;
}
public void setPheromone1(){
intensity = 2;
}
public void setDefault(){
intensity = 0;
}
public int getIntensity(){
return intensity;
}
}
The line number in the stack trace indicates where the exception occurs. Your gui attribute in StepManager is null. It's never initialized.