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.
Related
Please Help. When I run this GUI the numbers run off the frame. I know I have to use JTextArea and append but where do I put that in my code. can someone explain to me in simple terms and show me? I want to make it scroll vertically and horizontally?
import java.io.*;
import java.util.*;
import java.lang.*;
import java.text.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class prime extends JFrame
{
public static void main(String[] args)
{
prime frame = new prime();
}
private TextPanel panel;
private JPanel inPanel;
private JTextField inField;
public prime()
{
final int width = 500;
final int height = 500;
setSize(width, height);
setTitle("Find Prime Numbers");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new TextPanel();
add(panel, "Center");
inPanel = new JPanel();
inPanel.add(new JLabel("Enter Your Number", SwingConstants.RIGHT));
inField = new JTextField(20);
ActionListener inListener = new TextListener();
inField.addActionListener(inListener);
inPanel.add(inField);
add(inPanel, "South");
setVisible(true);
}
private class TextListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String message = inField.getText();
inField.setText("");
panel.setMessage(message); }
}
class TextPanel extends JPanel
{
private String message;
private Color backGroundColor;
public TextPanel()
{
message = "";
backGroundColor = Color.white;
}
public TextPanel(String x, Color background)
{
message = x;
backGroundColor = background;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
int width = getWidth();
int height = getHeight();
setBackground(backGroundColor);
g2.setColor(Color.black);
Font x = new Font("TimesNewRoman", Font.BOLD,20);
g2.setFont(x);
FontMetrics fm = g2.getFontMetrics(x);
g2.drawString(message,50, 50);
if(!(message.equals("")))
g2.drawString(previousPrime(message),50,78);
}
public void setMessage(String message) {
if (isPrime(Integer.parseInt(message))){
this.message = message + " is a prime number.";
}
else
this.message = message + " is not a prime number.";
repaint();
}
public boolean isPrime(int num){
for(int i = 2; i < num; i++){
if (num % i == 0)
return false;
}
if(num < 2)
return false;
return true;
}
public String previousPrime(String message){
String totalPrimeNum = "";
int finalNum = Integer.parseInt(message.substring(0,message.indexOf(" ")));
int count = 0;
for(int i = 2; i < finalNum; i++){
if(isPrime(i)) {
totalPrimeNum += " " + i;
count++;
}
if(count == 10) {
totalPrimeNum += "\n";
count = 0;
}
}
if (isPrime(Integer.parseInt(message.substring(0,message.indexOf(" ")))))
totalPrimeNum += " " + finalNum;
System.out.println(totalPrimeNum);
return totalPrimeNum;
}}}
Replace your TextPanel with JTextArea, wrap the JTextArea in a JScrollPane
private JTextArea panel;
//...
panel = new JTextArea(20, 10);
add(new JScrollPane(panel), "Center");
Use either setText or append to update the JTextArea. You will need to extract your calculation code from your existing TextPanel and re-use it
See How to Use Text Areas and How to Use Scroll Panes for more details
I have this program below. I want the program to rotate the shape on the same spot and also rotate the rectangle more than once. However, the program only rotates the rectangle once and puts the rotated shape on another spot on the frame. I really need help. Thanks!!!!*
import javax.swing.JPanel;
import java.awt.*;
import java.util.Random;
import java.awt.event.*;
import javax.swing.*;
import java.awt.geom.AffineTransform;
public class BoxesPanel extends JPanel
{
private boolean drawRect = false, drawCircle = false, Repaint = false;
private JButton enter;
int count = 0;
//------------------------------------------------------------------
// Sets up the drawing panel
//------------------------------------------------------------------
public BoxesPanel(int num)
{
if(num == 1)
drawRect = true;
else if(num == 2)
drawCircle = true;
enter = new JButton("click");
enter.addActionListener(new ButtonListener());
add(enter);
setBackground(Color.gray);
setPreferredSize(new Dimension(400, 400));
}
private class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
System.out.println("Rotate has been clicked: " + Repaint+ " " + count);
Repaint = true;
repaint();
}
}
public void paintComponent(Graphics page)
{
super.paintComponent(page);
Graphics2D g2d = (Graphics2D)page;
int x, y, width, height;
x = 100;
y = 100;
width = 100;
height = 100;
if(Repaint)
g2d.rotate(Math.toRadians(45), (x+width)/2, (y+height)/2);
g2d.setColor(Color.yellow);
AffineTransform old = g2d.getTransform();
if(drawRect)
g2d.fillRect(x,y,width,height);
else if(drawCircle)
g2d.fillOval(x,y,width,height);
g2d.setTransform(old);
System.out.println("Painted: " + Repaint+ " " + count);
Repaint = false;
}
}
import javax.swing.JFrame;
public class Boxes
{
//---------------------------------------------------------
// Creates the main frame of the program.
//---------------------------------------------------------
public static void main(String[] args)
{
JFrame frame = new JFrame ("Boxes");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BoxesPanel panel = new BoxesPanel(1);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
I made a few changes. It seems to work now.
public class BoxesPanel extends JPanel
{
private boolean drawRect = false, drawCircle = false;
private int angle = 0;
private JButton enter;
int count = 0;
//------------------------------------------------------------------
// Sets up the drawing panel
//------------------------------------------------------------------
public BoxesPanel(int num)
{
if(num == 1)
drawRect = true;
else if(num == 2)
drawCircle = true;
enter = new JButton("click");
enter.addActionListener(new ButtonListener());
add(enter);
setBackground(Color.gray);
setPreferredSize(new Dimension(400, 400));
}
private class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
System.out.println("Rotate has been clicked: " + count);
count++;
angle = (angle + 45)%360;
repaint();
}
}
public void paintComponent(Graphics page)
{
super.paintComponent(page);
Graphics2D g2d = (Graphics2D)page;
int x, y, width, height;
x = 100;
y = 100;
width = 100;
height = 100;
AffineTransform old = g2d.getTransform();
g2d.rotate(Math.toRadians(angle), x+width/2, y+height/2);
g2d.setColor(Color.yellow);
if(drawRect)
g2d.fillRect(x,y,width,height);
else if(drawCircle)
g2d.fillOval(x,y,width,height);
g2d.setTransform(old);
System.out.println("Painted: " + count);
}
}
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...
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I created a GUI named Menu class for my Start, Help and Exit button. my problem is my game won't start, it hangs everytime I press the Start button. Can someone check my error and explain it to me because its my case study at school.
package spaceSip;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
public class Menu extends JFrame implements ActionListener
{
private JLabel titleL;
private JButton startB, helpB, exitB;
static JFrame frame1 = new JFrame();
public Menu()
{
frame1.setSize(500,250);
Container mainP = frame1.getContentPane();
mainP.setLayout(null);
titleL = new JLabel("WELCOME");
startB = new JButton("Start");
helpB = new JButton("Help");
exitB = new JButton("Exit");
mainP.add(titleL);
titleL.setFont(new Font("Chiller",Font.BOLD,50));
titleL.setBounds(100, 30, 200, 50);
mainP.add(startB);
startB.setMnemonic(KeyEvent.VK_S);
startB.setBounds(200, 80, 100, 20);
mainP.add(helpB);
helpB.setMnemonic(KeyEvent.VK_H);
helpB.setBounds(200, 100, 100, 20);
mainP.add(exitB);
exitB.setMnemonic(KeyEvent.VK_E);
exitB.setBounds(200, 120, 100, 20);
startB.addActionListener(this);
helpB.addActionListener(this);
exitB.addActionListener(this);
frame1.setVisible(true);
frame1.setResizable(false);
}
public void actionPerformed(ActionEvent e)
{
String key = e.getActionCommand();
if(key == "Start")
{
frame1.dispose();
new SpaceShipMain();
}
else if(key == "Help")
{
}
else
System.exit(0);
}
public static void main(String[]args)
{
new Menu();
}
}
package spaceSip;
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class SpaceShipMain implements MouseListener
{
private JFrame background;
private SpaceShipPanel back;
public static boolean paused;
public static boolean crashed;
public static boolean started;
public static boolean playedOnce;
public boolean goingUp;
private double upCount;
public static int distance;
public static int maxDistance;
public final int XPOS;
public final int NUMRECS;
public final int RECHEIGHT;
public final int RECWIDTH;
private int moveIncrement;
private int numSmoke;
private ArrayList<SpaceShipImage> toprecs;
private ArrayList<SpaceShipImage> bottomrecs;
private ArrayList<SpaceShipImage> middlerecs;
private ArrayList<SpaceShipImage> smoke;
private SpaceShipImage helicopter;
public SpaceShipMain()
{
NUMRECS = 100;
RECHEIGHT = 70;
RECWIDTH = 30;
XPOS = 200;
playedOnce = false;
maxDistance = 0;
load(new File("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/Best.txt"));
initiate();
}
public void load(File file)
{
try
{
Scanner reader = new Scanner(file);
while(reader.hasNext())
{
int value = reader.nextInt();
if(value > maxDistance)
maxDistance = value;
}
}
catch(IOException i )
{
System.out.println("Error. "+i);
}
}
public void save()
{
FileWriter out;
try
{
out = new FileWriter("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/Best.txt");
out.write("" + maxDistance);
out.close();
}
catch(IOException i)
{
System.out.println("Error: "+i.getMessage());
}
}
public void initiate()
{
if(!playedOnce)
{
background = new JFrame("Space Ship Game");
background.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //closes the program when the window is closed
background.setResizable(false); //don't allow the user to resize the window
background.setSize(new Dimension(800,500));
background.setVisible(true);
back = new SpaceShipPanel("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/starfield.jpg");
background.add(back);
back.addMouseListener(this);
}
playedOnce = true;
goingUp = false;
paused = false;
crashed = false;
started = false;
distance = 0;
upCount = 0;
moveIncrement = 2;
numSmoke = 15;
toprecs = new ArrayList<SpaceShipImage>();
middlerecs = new ArrayList<SpaceShipImage>();
bottomrecs = new ArrayList<SpaceShipImage>();
smoke = new ArrayList<SpaceShipImage>();
helicopter = new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/rocketship.GIF",XPOS,200);
for(int x = 0; x < NUMRECS; x++)
toprecs.add(new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/rec2.JPG",RECWIDTH*x,5));
for(int x = 0; x < NUMRECS; x++)
bottomrecs.add(new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/rec2.JPG",RECWIDTH*x,410));
middlerecs.add(new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/asteroid2.jpg",1392,randomMidHeight()));
middlerecs.add(new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/asteroid2.jpg",1972,randomMidHeight()));
drawRectangles();
}
public void drawRectangles()
{
long last = System.currentTimeMillis();
long lastCopter = System.currentTimeMillis();
long lastSmoke = System.currentTimeMillis();
long lastSound = System.currentTimeMillis();
int firstUpdates = 0;
double lastDistance = (double)System.currentTimeMillis();
while(true)
{
if(!paused && !crashed && started && (double)System.currentTimeMillis() - (double)(2900/40) > lastDistance)
{
lastDistance = System.currentTimeMillis();
distance++;
}
if(!paused && !crashed && started && System.currentTimeMillis() - 10 > lastCopter)
{
lastCopter = System.currentTimeMillis();
updateCopter();
updateMiddle();
}
if(!paused && !crashed && started && System.currentTimeMillis() - 100 > last)
{
last = System.currentTimeMillis();
updateRecs();
}
if(!paused && !crashed && started && System.currentTimeMillis() - 75 > lastSmoke)
{
lastSmoke = System.currentTimeMillis();
if (firstUpdates < numSmoke)
{
firstUpdates++;
smoke.add(new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/smoke.GIF",187,helicopter.getY()));
for(int x = 0; x < firstUpdates; x++)
smoke.set(x,new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/smoke.GIF",smoke.get(x).getX() - 12, smoke.get(x).getY()));
}
else
{
for(int x = 0; x < numSmoke - 1; x++)
smoke.get(x).setY(smoke.get(x+1).getY());
smoke.set(numSmoke - 1,new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/smoke.GIF",187,helicopter.getY()));
}
}
back.updateImages(middlerecs,helicopter,smoke);
}
}
public void updateRecs()
{
for(int x = 0; x < (NUMRECS - 1); x++) //move all but the last rectangle 1 spot to the left
{
toprecs.set(x,new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/rec2.JPG",RECWIDTH*x,toprecs.get(x+1).getY()));
bottomrecs.set(x,new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/rec2.JPG",RECWIDTH*x,bottomrecs.get(x+1).getY()));
}
}
public void randomDrop()
{
toprecs.get(26).setY(toprecs.get(26).getY() + (463 - bottomrecs.get(26).getY()));
bottomrecs.get(26).setY(463);
}
public int randomMidHeight()
{
int max = 10000;
int min = 0;
for(int x = 0; x < NUMRECS; x++)
{
if(toprecs.get(x).getY() > min)
min = (int)toprecs.get(x).getY();
if(bottomrecs.get(x).getY() < max)
max = (int)bottomrecs.get(x).getY();
}
min += RECHEIGHT;
max -= (RECHEIGHT + min);
return min + (int)(Math.random() * max);
}
//moves the randomly generated middle rectangles
public void updateMiddle()
{
if(middlerecs.get(0).getX() > -1 * RECWIDTH)
{
middlerecs.set(0,new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/asteroid.gif",middlerecs.get(0).getX() - (RECWIDTH/5), middlerecs.get(0).getY()));
middlerecs.set(1,new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/asteroid.gif",middlerecs.get(1).getX() - (RECWIDTH/5), middlerecs.get(1).getY()));
}
else
{
middlerecs.set(0,new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/asteroid.gif",middlerecs.get(1).getX() - (RECWIDTH/5), middlerecs.get(1).getY()));
middlerecs.set(1,new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/asteroid.gif",middlerecs.get(0).getX() + 580,randomMidHeight()));
}
}
public boolean shoot()
{
for(int x = 3; x <= 7; x++)
if(helicopter.getY() >= bottomrecs.get(x).getY())
return true;
for(int y = 3; y <= 7; y++)
if(helicopter.getY() <= toprecs.get(y).getY())
return true;
for(int z = 0; z <= 1; z++)
if(isInMidRange(z))
return true;
return false;
}
public boolean isInMidRange(int num)
{
Rectangle middlecheck = new Rectangle((int)middlerecs.get(num).getX(),(int)middlerecs.get(num).getY(),RECWIDTH,RECHEIGHT);
Rectangle coptercheck = new Rectangle((int)helicopter.getX(),(int)helicopter.getY(),70,48); //asteroid X and y bump
return middlecheck.intersects(coptercheck);
}
public void crash()
{
crashed = true;
if(distance > maxDistance)
{
maxDistance = distance;
save();
}
int reply = JOptionPane.showConfirmDialog(null, " RESTART ?", "GAME OVER", JOptionPane.YES_NO_OPTION);
if(reply == JOptionPane.YES_OPTION)
initiate();
else
System.exit(0);
initiate();
}
//moves the spaceship
public void updateCopter()
{
upCount += .10;
if(goingUp)
{
if(upCount < 3.5)
helicopter.setPosition(XPOS,(double)(helicopter.getY() - (.3 + upCount)));
else
helicopter.setPosition(XPOS,(double)(helicopter.getY() - (1.2 + upCount)));
helicopter.setImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/rocketship.GIF");
}
else
{
if(upCount < 1)
helicopter.setPosition(XPOS,(double)(helicopter.getY() + upCount));
else
helicopter.setPosition(XPOS,(double)(helicopter.getY() + (1.2 + upCount)));
helicopter.setImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/rocketship.GIF");
}
if(shoot())
crash();
}
//Called when the mouse exits the game window
public void mouseExited(MouseEvent e)
{
paused = true;
}
//Called when the mouse enters the game window
public void mouseEntered(MouseEvent e)
{
}
//Called when the mouse is released
public void mouseReleased(MouseEvent e)
{
goingUp = false;
upCount = -1;
if(paused)
paused = false;
}
//Called when the mouse is pressed
public void mousePressed(MouseEvent e)
{
if (!started)
started = true;
goingUp = true;
upCount = 0;
}
//Called when the mouse is released
public void mouseClicked(MouseEvent e)
{
}
}
package spaceSip;
import java.awt.Image;
import javax.swing.ImageIcon;
public class SpaceShipImage
{
private Image image; //The picture
private double x; //X position
private double y; //Y position
//Construct a new Moving Image with image, x position, and y position given
public SpaceShipImage(Image img, double xPos, double yPos)
{
image = img;
x = xPos;
y = yPos;
}
//Construct a new Moving Image with image (from file path), x position, and y position given
public SpaceShipImage(String path, double xPos, double yPos)
{
this(new ImageIcon(path).getImage(), xPos, yPos);
//easiest way to make an image from a file path in Swing
}
//They are set methods. I don't feel like commenting them.
public void setPosition(double xPos, double yPos)
{
x = xPos;
y = yPos;
}
public void setImage(String path)
{
image = new ImageIcon(path).getImage();
}
public void setY(double newY)
{
y = newY;
}
public void setX(double newX)
{
x = newX;
}
//Get methods which I'm also not commenting
public double getX()
{
return x;
}
public double getY()
{
return y;
}
public Image getImage()
{
return image;
}
}
package spaceSip;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
class SpaceShipPanel extends JPanel
{
private Image background;
private ArrayList<SpaceShipImage> middle;
private SpaceShipImage copter;
private ArrayList<SpaceShipImage> smoke;
//Constructs a new ImagePanel with the background image specified by the file path given
public SpaceShipPanel(String img)
{
this(new ImageIcon(img).getImage());
//The easiest way to make images from file paths in Swing
}
//Constructs a new ImagePanel with the background image given
public SpaceShipPanel(Image img)
{
background = img;
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
//Get the size of the image
//Thoroughly make the size of the panel equal to the size of the image
//(Various layout managers will try to mess with the size of things to fit everything)
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
middle = new ArrayList<SpaceShipImage>();
smoke = new ArrayList<SpaceShipImage>();
}
//This is called whenever the computer decides to repaint the window
//It's a method in JPanel that I've overwritten to paint the background and foreground images
public void paintComponent(Graphics g)
{
//Paint the background with its upper left corner at the upper left corner of the panel
g.drawImage(background, 0, 0, null);
//Paint each image in the foreground where it should go
for(SpaceShipImage img : middle)
g.drawImage(img.getImage(), (int)(img.getX()), (int)(img.getY()), null);
for(SpaceShipImage img : smoke)
g.drawImage(img.getImage(), (int)(img.getX()), (int)(img.getY()), null);
if(copter != null)
g.drawImage(copter.getImage(), (int)(copter.getX()), (int)(copter.getY()), null);
drawStrings(g);
}
public void drawStrings(Graphics g)
{
g.setColor(Color.WHITE);
g.setFont(new Font("Arial",Font.BOLD,20));
g.drawString("Distance: " + SpaceShipMain.distance,30,440);
g.setFont(new Font("Arial",Font.BOLD,20));
if (SpaceShipMain.distance > SpaceShipMain.maxDistance)
g.drawString("Best: " + SpaceShipMain.distance,650,440);
else
g.drawString("Best: " + SpaceShipMain.maxDistance,650,440);
if(SpaceShipMain.paused)
{
g.setFont(new Font("Chiller",Font.BOLD,72));
g.drawString("Paused",325,290);
g.setFont(new Font("Chiller",Font.BOLD,30));
g.drawString("Click to unpause.",320,340);
}
}
//Replaces the list of foreground images with the one given, and repaints the panel
public void updateImages(ArrayList<SpaceShipImage> newMiddle,SpaceShipImage newCopter,ArrayList<SpaceShipImage> newSmoke)
{
copter = newCopter;
middle = newMiddle;
smoke = newSmoke;
repaint(); //This repaints stuff... you don't need to know how it works
}
}
You compare Strings with equals(value equality) not with ==(reference equality). For more information read this previous question How do I compare strings in Java?
As #AndrewThompson always advice don't use NullLayout
Java GUIs might have to work on a number of platforms, on different
screen resolutions & using different PLAFs. As such they are not
conducive to exact placement of components. To organize the
components for a robust GUI, instead use layout managers, or
combinations of
them1, along
with layout padding & borders for white
space2.
As you say that your gui is blocked, that may be cause some of your execution code takes too more time and it's executed in the same thread as gui stuff (The Event Dispatch Thread). As you have a while(true) that's block the gui so use a SwingTimer for execute repeatidly task or if that code that takes long time execute it in a background thread using a Swing Worker. Here you have a complete example. When you perform custom painting you should override paintComponent and in first line you have to call super.paintComponent(..) to follow correct chaining. Read more in Painting in AWT-Swing.
Another error i see is that you are adding components after calling setVisible(true) without calling revalidate() repaint(). So i recommend to first add components to container then call setVisible(true) at final step.
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.