Java For Loop Inside Constructor is Infinitely Repeating - java

So, for some reason when I try to use a for loop to initialize panels in chess board, it actually loops the loop itself. In other words, it doesn't go on forever, but it starts and completes again and again.
package chessgame;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ChessGame extends JFrame implements ActionListener{
public static final int WIDTH=800;
public static final int HEIGHT=800;
public static void main(String[] args) {
ChessGame gui = new ChessGame();
gui.setVisible(true);
}
public ChessGame(){
super("Chess Game Demo");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(8,8));
JPanel[] chessSquares = new JPanel[64];
for (int a=0;a<64;a++){
System.out.println(a);
}
}
}
I have included all potentially relevant code because I plan to use indices of chessSquares to color squares black and white. When I do this I also get a NullPointerException. I can understand why I'm getting that given the following error, but I cannot at all understand why a would be printed 0, 1....62, 63 over and over again. I am relatively new to Swing and have absolutely no idea why it does this. If anyone could explain that would be tremendously helpful. Thanks.

Don't put meaningful initialization in ChessGame's constructor, but instead override frameInit. When you do, also be sure to call super.frameInit(). See the javadoc or this tutorial.

Related

Embed PApplet intp JApplet

How can I embed a PApplet into a JApplet ?
I wanted to add it to a JPanel inside the applet, but I couldn't.
If any of you know how I can do this. ??
As of Processing 3, you can no longer do this. PApplet no longer extends Applet, so it can't be treated as a component.
For 95% of users, this is okay. Applets are dead anyway, so you really shouldn't be using them. If at all possible, you should try deploying with Processing.js.
If you need to execute a Processing sketch from Java code, then you should use the PApplet.main("YourSketchNameHere"); function to launch it. Processing will take care of the window for you.
If you really need to treat a PApplet as a component, then you're going to have to go through its PSurface. The PSurface class contains a getNative() function that returns an object that can be treated as a component. But that's overkill for most Processing users.
Prior to Processing 3, this code should have worked for you as #Kevin has explained. So, if your question is directed towards understanding a legacy code here is what you will need to know:
import javax.swing.JFrame;
import javax.swing.JPanel;
class MyPApplet extends PApplet implements ActionListener{
#Override
public void setup() {
super.setup();
// setup
}
#Override
public void draw() {
// my draw code
}
}
public class PAppletDemo {
public static void main(String[] args) {
final JFrame frame = new JFrame("PApplet in Java Application");
JPanel panel = new JPanel();
//create an instance of your processing applet
final MyPApplet applet = new MyPApplet();
applet.init();
panel.add(applet); // From processing 3, this will give you error that applet is not a Component
frame.add(panel);
frame.setSize(applet.getSize().width, applet.getSize().height +200);
frame.setVisible(true);
}
}
To circumvent this, you will need to use PSurface getNative() function. Please refer to the example and discussion given on this link.

Need Help Updating JTextArea - Java

I'm on week three of a Java class. I am working on a class assignment that is due next week. I can complete the assignment without any problem using the console as output, which is acceptable. However, the Professor also suggested we research JTextArea and consider using it for our program output.
I found some code from a tutorial and was able to at least get a text block to appear with my first line of text to appear. But as I write the actual program, I need to continue to add additional lines to the text block as the program progresses.
When I attempt to use the following line of code in the main method to display text line 2, I get an error saying, "non-static variable textarea cannot be referenced from a static context".
textarea.append("Product1\t3\t$3.01\t$9.03");
Here is the code I have so far. Thanks in advance for any help!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ta extends JFrame{
JTextArea textarea;
public ta(){
setLayout(new FlowLayout ());
textarea = new JTextArea ("Product\tQuantity\tLine Cost\tOrder Cost\n", 5,30);
add(textarea);
}
public static void main(String[] args) {
ta gui = new ta();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(500,200);
gui.setVisible(true);
textarea.append("Product1\t3\t$3.01\t$9.03");
}
}
You can not reference textarea (which is a instance field) from a static context (ie from within main).
Instead, move textarea.append("Product1\t3\t$3.01\t$9.03"); to be within your constructor
public ta(){
setLayout(new FlowLayout ());
textarea = new JTextArea ("Product\tQuantity\tLine Cost\tOrder Cost\n", 5,30);
add(textarea);
textarea.append("Product1\t3\t$3.01\t$9.03");
}
Or provide some other "update" method for your ta class which you can call
You might like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others

nothing paints on JFrame

I am having some trouble with my code which is written in java. The first time after I start eclipse it launches and runs perfectly, but if I try to run it again - without making any changes - the only thing I see is an empty JFrame. Why might this happen? I have gotten quite a bit of files so to launch them all up here would be a lot to look through. Maybe you've tried something like this before? Where the program can launch sometimes? If not tell me so I can add the code.
I know that all of my classes are called since I have printed them all in my search to get the game to work.
The entire code worked until I started to put most of it in different objects in order to make it easier to look through.
package Pacman;
import java.util.Scanner;
import javax.swing.JFrame;
public class Frame extends JFrame{
public static int Width, Height;
public static void main(String[] args){
Scanner console = new Scanner(System.in);
Width = console.nextInt();
Height = console.nextInt();
new Frame();
}
public Frame(){
new JFrame();
this.setTitle("PacMan");
this.setLocation(400,300);
this.setResizable(false);
this.setVisible(true);
Screen screen = new Screen(this, Width, Height);
this.add(screen);
}
}
This is the JFrame, but I am pretty sure the problem isn't here.
If you want to see the entire codesystem it's at github: https://github.com/Lampeskaerm/SoftTek_Projekt.git
I hope you can help me
Anne-Katrine
After adding the component you should use this.setVisible(true) in the last.

What's Wrong WIth My Code involving JFrames

It's Giving me an error saying that "The method setContentPane(Container) in the type JFrame is not applicable for the arguments (GamePanel)"
Here is my Code:
package main;
import javax.swing.JFrame;
public class Game {
public static void main(String[] args){
JFrame window = new JFrame("Dragon Tales");
window.setContentPane(new GamePanel());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
}
}
I am following a tutorial exactly and his screen shows no errors at all.
Your GamePanel class does not extend any Swing GUI component such as Container or one of its children. Probably it should extend JPanel.
i.e.,
import javax.swing.JPanel;
public class GamePanel extends JPanel {
// .... etc
}
Please don't add the urgent or "help as soon as possible" bit. Yes your question is very important, but it is no more important than anyone else's.
Edit: Mad's link is worth putting in the answer: The Oracle Swing Tutorial.

How do I use an object reference as an argument if it is instantiated after the class taking the argument?

So I have this code:
package com.erikbalen.game.rpg;
import com.erikbalen.platform.*;
import javax.swing.JFrame;
public class World extends Engine {
public static void main(String[] args) {
Gui display = new Gui(/*takes a Player argument so i can get certain variables*/);
display.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
display.setSize(300,220);
display.setVisible(true);
Player player1 = new Dps("ebalen", display);
Player player2 = new Healer("frankypanky", display);
}
}
package com.erikbalen.game.rpg;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Gui extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = -384241835772507459L;
private JLabel playerInfo;
private JTextField textField;
private final static String newline = "\n";
private JTextArea feed;
private JScrollPane scrollPane;
private Player player;
public Gui(Player currentPlayer) {
super("Erik's RPG");
this.player = currentPlayer;
setLayout(new FlowLayout());
playerInfo = new JLabel("<html>Health = " + currentPlayer.getHealth() + " | " + "Mana = " + currentPlayer.getMana() + "</html>");
playerInfo.setBorder(BorderFactory.createTitledBorder(currentPlayer.getName()));
textField = new JTextField(20);
textField.addActionListener(this);
feed = new JTextArea(5, 20);
scrollPane = new JScrollPane(feed);
feed.setEditable(false);
add(playerInfo);
add(feed);
add(textField);
add(scrollPane);
}
public void actionPerformed(ActionEvent textBox) {
String text = textField.getText();
this.player.chat(text);
}
public void printText(String text) {
feed.append(text + "\n");
feed.setCaretPosition(feed.getDocument().getLength());
}
}
My problem is that class Gui takes a Player as an argument and Player takes Gui as an argument. How do I let both objects take each other as arguments? Feel free to tell me if my code is inefficient.
Well, ideally you should try to break the circular dependency, but otherwise, you could:
Create the GUI, create the players by passing in the GUI, then add the players to the GUI
Create the players, create the GUI by passing in the players, then set the GUI for the players
Create the GUI within the player constructor:
Player(String name)
{
GUI gui = new GUi(this);
...
}
All of these are non-ideal:
You may well want your classes to be immutable, which makes the first two options nasty
Publishing the this reference before your constructor has finished executing has various issues, both in terms of thread safety and the memory model, as well as potentially allowing the GUI constructor to call back to the Player object before it's fully initialized.
This goes back to "try to break the dependency" - but if that's really impossible, I would probably favour the first option, without knowing anything else. It makes sense to be able to add players to a game - it makes less sense to set the GUI for a player after the fact, IMO.
Your stuck in what we call a circular dependency. This is almost everytime the result of a bad design.
There are still solutions, but there are not really pretty. For an elegant way, you should rethink your design.
Does the GUI really need the player ? Maybe you could create a method to set the player later on. If it's not possible, you could also create a setter in the player. You won't be able to set both at construction time.
Try giving the Gui class methods for updating what is displayed to the user/users. Make the directing code (main() for example) responsible for updating the Gui with the right information as events happen.
Neither Gui nor Player should have to take each other as constructor arguments - Gui should only be responsible for displaying information it is told to, and Player should only be a logical representation of a game piece. Event-driven functionality should be reserved for the directing code.

Categories