so I'm a 6th grader who's trying to program a TicTacToe program using netbeans 8.1 and java.
This is my code so far (for the sake of simplicity i've only included the code of one button):
public class TicTacToe extends JFrame{
static Random computerGenerate = new Random();
static int rounds = 0;
static JPanel panel = new JPanel();
static JButton s1 = new JButton();
public static void main(String[] args) {
Gui();
}
public static void Gui() {
JFrame Gui = new JFrame("TicTacToe");
Gui.setVisible(true);
Gui.setResizable(false);
Gui.setSize(320, 340);
Gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setLayout(null);
Gui.add(panel);
s1.setBounds(0, 0, 100, 100);
s1.setFont(new Font("Times New Roman", Font.PLAIN, 50));
s1.addActionListener(new Response());
panel.add(s1);
}
private static class Response extends TicTacToe implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == tictactoe.TicTacToe.s1) {
s1.setText("X");
s1.setEnabled(false);
rounds += 1;
}
}
}
public static void Moves() {
if (rounds == 1) {
int computerStartPos = 1 + computerGenerate.nextInt(8);
switch (computerStartPos) {
case 1:
if (button"s1" is disabled)) {
computer will generate a new starting position for the AI
} else {
button s1 will be disabled and it will show a "O" to show the computer has selected the square
}
break;
}
}
}
}
The section which I have a problem with is the very last method, method Moves().
What I'm trying to do is, after the player has selected their starting square, the computer will generate a number, 1-9 which will determine its own starting position.
The problem I have is if the player has already selected that button before the computer, I need the computer to re-generate a new number as its starting point.
My idea to solve this is "if s1.setEnabled() is equal to false, then the computer will re-generate a new number which corresponds to its new starting position".
Is this posible to write? This is only a small time project but I would appreciate the help.
Oh, and I have been told I'm incorrectly using static in java, however if I don't include "static" in the code netbeans gives me errors for days until all of my code is like RED ERROR!!!! If anyone knows why or can explain how to properly use it please do as well :D
I sincerely appreciate any help I receive.
There is a method for checking whether a button is enabled or not...
if (button.isEnabled()) {
}else {}
and
if I don't include "static" in the code netbeans gives me errors for
days until all of my code is like RED ERROR!!
you Cannot make a static reference to the non-static field...
try dont using static things and create instances instead...
you can use as start point:
remove the static keyword from the fields, define a construtor and create an instance in the main method..
like this:
// YOU NEED A CONSTRUCTOR
public TicTacToe () {
computerGenerate = new Random();
panel = new JPanel();
s1 = new JButton();
}
public static void main(String[] args) {
TicTacToe demoExample = new TicTacToe ();
demoExample.Gui();
}
Static methods in java belong to the class (not an instance of it).
They use no instance variables and will usually take input from the
parameters, perform actions on it, then return some result
Secondly yes you can check that.
if(! s1.isEnabled())
{
...
}
Remember there is ! at the start of the condition which will check for enabled or not!
Related
I'm going off of what I saw in a textbook to make an action listener for a button. To do it, I made an inner class. When I try to call the inner class, the error comes up: cannot find symbol.
Here's the code:
package GUI;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ATMGUI extends GUI
{
public ATMGUI()
{
this.makePane();
this.makeButton("Withdraw");
button.addActionListener(new WithdrawListener());
pane.add(button);
this.makeText("Enter amount to withdraw: ");
pane.add(text);
this.makeTextField("Enter amount here");
pane.add(field);
this.makeFrame();
frame.add(pane);
class WithdrawListener implements ActionListener
{
public void actionPerformed(ActionEvent click)
{
System.out.println("This is a test.");
}
}
}
//------------------------------------------------------------------
public void makeFrame()
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
public void makePane()
{
pane = new JPanel();
pane.setLayout(new GridLayout(3,3));
pane.setVisible(true);
}
public void makeButton(String buttonName)
{
button = new JButton(buttonName);
}
public void makeText(String addText)
{
text = new JLabel(addText);
}
public void makeTextField(String addText)
{
field = new JTextField(addText);
}
}
This is the particular bit that is giving me trouble
button.addActionListener(new WithdrawListener());
I saw somewhere else that it had to be instantiated in a certain way.
I tried something like:
ATMGUI a = new ATMGUI();
ATMGUI.WithdrawListener w = a.new WithdrawListener();
and then put w in for the argument, but that didn't really work for me either.
Not sure if it is because I'm working in a subclass. Also not really sure if things need to be done differently because I'm working with an interface.
Place the WithdrawListener outside of the constructor context
public class ATMGUI extends GUI {
public ATMGUI() {
//...
button.addActionListener(new WithdrawListener());
//...
}
class WithdrawListener implements ActionListener {
public void actionPerformed(ActionEvent click) {
System.out.println("This is a test.");
}
}
Add listener to button after local class declaration.
public void abc(){
PQR pqr = new PQR(); // incorrect
class PQR {
}
}
Correct way is
public void abc(){
class PQR {
}
PQR pqr = new PQR(); //correct
}
It seems like you must declare the local class before you use it. The follwing code snippets I tested:
This one showed no errors:
public void testFunc() {
class Test {
}
Test test = new Test();
}
But this one does:
public void testFunc() {
Test test = new Test();
class Test {
}
}
Edit: Sorry for posting nearly at the same time, next time I will check three times if someone already posted.
Use of anonymous type is recommended when you are not reusing a class.
Have a look at it (frequently used with listeners) - It's a great answer!!
quoted from above link
Using this method makes coding a little bit quicker, as I don't need
to make an extra class that implements ActionListener -- I can just
instantiate an anonymous inner class without actually making a
separate class.
I only use this technique for "quick and dirty" tasks where making an
entire class feels unnecessary. Having multiple anonymous inner
classes that do exactly the same thing should be refactored to an
actual class, be it an inner class or a separate class.
this.makePane();
this.makeButton("Withdraw");
button.addActionListener(new ActionListener() { //starts here
public void actionPerformed(ActionEvent click)
{
System.out.println("This is a test.");
}
});//ends
pane.add(button);
this.makeText("Enter amount to withdraw: ");
pane.add(text);
this.makeTextField("Enter amount here");
pane.add(field);
this.makeFrame();
frame.add(pane);
I have an error for the code below. Sorry if this is too basic as I am new to java.
Basically, I cannot retrieve the String "44418" from the class CityChange.
I know the reason is because I created a new instance cc in the class MainPanel.
However I do not know any other way of doing it.
public class CityChange extends JPanel {
public CityChange() {
JButton btn1 = new JButton("London")
this.add(btn1);
btn1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
//London Yahoo Weather Code 44418
setCitySelected("44418");
}
});
}
public void setCitySelected(String citySelected) {
this.citySelected = citySelected;
}
public String getCitySelected() {
return citySelected;
}
private String citySelected;
}
public class MainPanel extends JPanel {
public MainPanel() {
CityChange cc = new CityChange();
System.out.println(cc.getCitySelected()); //returns null instead of 44418
}
}
Please give some advice. Thank you.
For timing reasons, the value has no choice but to be null.
What happens here "immediately" (at init time) is that a new CityChange object is created and its citySelected is gotten and printed. As nobody set it otherwise, it is null.
Only after firing the event (clicking the button), it gets a value, and if you print the value then, you'll see the new value.
The code setCitySelected("44418"); is only executed when you call the method public void actionPerformed(ActionEvent evt) which is not happening at the moment. This Method is only called via a Button in a GUI so you first need at least a simple Window with a Button. Here is a good example http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
Hi I'm making an app but, I found a problem. I'm using netbeans gui builder to build my gui.
So, the first gui class has a lot of button(every button does the same function) that have an actionlistener that looks like this:
public class Guipanel extends JPanel {
private void jbtTTActionPerformed(java.awt.event.ActionEvent evt) {
if(mb.getlevel() > 16){
if(ttp != 20 && mb.getpoints() != 0){
point();
ttp++;
jbtTT.setText(""+ttp);
}
}
}
private void point(){
mb.reducepoints();
}
int ttp;
Base mb = new Base();
JButton jbtTT = new JButton();
}
The Base Class has a lot of method but the one that is related to this problem looks like this:
public class Base extends JFrame {
//point decrement method
public void reducepoints(){
points--;
jlbPoints.setText("Points Available: "+points);
}
//return point value
public int getpoints(){
return this.points;
}
//return level value
public int getlevel(){
return this.level;
}
private static int level = 1;
private static int points = 20;
private JLabel jlbPoints = new JLabel("Points Available: "+points);
}
So the problem is this, when I pressed the jbtTT the points variable will decrement so the value will change from 20 to 19. I used System.out.println to verify that. As you can see, the reducepoints() method should update the jlbPoints text which it doesnt. I have tried making the Base mb = new Base() to static Base mb = new Base() but it still doesn't work. Am I doing this wrong? Anyone have a suggestion?
EDIT: I've tried to do System.out.println(jlbPoints.getText()); and the text did changed. The only one that didn't change is the text that the user can see. Even repaint() and revalidate didn't work.
EDIT2: I finally found the answer to this question. I have to pass the 'Base' class object to the 'Guipanel' class since I created the 'Base' class object in a main class(I don't want to use this class as a main class). I passed it with the following method:
public void passObj(Base mb){
this.mb = mb;
}
and changing the constructor of 'Guipanel' class like this:
public Guipanel(Base mb) {
initComponents();
this.mb = mb;
}
also changing this Base mb = new Base(); to Base mb;
I wanted to thank everyone that have tried to answer this question.
Try using SwingUtilities.invokeLater() to ensure you are changing the text on the event dispatch thread, as you are supposed to. All we can do is guess given the current information.
I'm trying to make a 'game' using swing and I'm experiencing a problem which I can't solve. It's probably something easy and obvious but I still can't figure out. Here's a piece of my code:
public class LevelOne {
private static Crate[] crates = new Crate[3];
public LevelOne(){
crates[0].setX(200);
crates[0].setY(200);
crates[1].setX(280);
crates[1].setY(40);
crates[2].setX(440);
crates[2].setY(40);
}
//more code here
}
I try to create object of LevelOne class to make my crates variable living. (is this a way to do so?).
public static void main(String[] args) {
LevelOne l = new LevelOne();
JFrame frame = new JFrame("blabla");
Board board = new Board();
frame.add(board);
frame.setSize(805, 830);
frame.setVisible(true);
frame.setFocusable(false);
frame.setResizable(false);
frame.setDefaultCloseOperation(3);
frame.setLocation(400, 200);
board.requestFocus(true);
}
It gives me NPE at line
LevelOne l = new LevelOne();
As I said, it's a small piece of project but I think this might solve whole issue. I'm using this Crate[] crates to paint components on my board, to check collision and other stuff. Without creating object of LevelOne class, I still get NPE when trying to draw them. Any suggestions, ideas, solutions?
You forgot to initialize elements in crates:
private static Crate[] crates = new Crate[3];
public LevelOne(){
crates[0] = new Crate(); // <= add this
crates[0].setX(200);
crates[0].setY(200);
// same for other elements
You have to propagate Crate object into your crates array. You are getting NullPointerException because crates array doesn't have any reference of Carte in it. Do the following.
private static Crate[] crates = new Crate[3];
public LevelOne(){
for(int i = 0; i < crates.length; i++)
crates[i] = new Crate();
crates[0].setX(200);
crates[0].setY(200);
crates[1].setX(280);
crates[1].setY(40);
crates[2].setX(440);
crates[2].setY(40);
}
I am trying to design a very basic aircraft attitude indicator to put into a JFrame Form using Netbeans 7.3, essentially consisting of a black box with a white line in the middle that rotates proportionally with the degree of roll of the aircraft. This then needs to be put into a JFrame form to create a virtual cockpit user interface. I am a novice programmer with very limited knowledge of the Java library, so any help would be greatly appreciated!
So far, I have created the following class:
public class AttitudeIndicator extends JPanel {
private Graphics attIndBackground;
private Graphics attIndLine;
private int aILStartX;
private int aILStartY;
private int aILEndX;
private int aILEndY;
public AttitudeIndicator(int a,int b,int c,int d){
aILStartX = a;
aILStartY = b;
aILEndX = c;
aILEndY = d;
}
public void createAttitudeIndicator(){
attIndBackground.setColor(Color.BLACK);
attIndBackground.fillRect(0, 0, 200, 150);
attIndBackground.setColor(Color.RED);
attIndBackground.drawLine(0,75,200,75);
attIndLine.setColor(Color.WHITE);
attIndLine.drawLine(aILStartX,aILStartY,aILEndX,aILEndY);
}
}
The idea is that arguments a,b,c and d will change and therefore change the line with the degree of pitch and roll, but I am yet to get to that point. I have then put this into the main class to try and create it:
public static void main(String[] args) {
JFrame f = new JFrame("Title");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
AttitudeIndicator a = new AttitudeIndicator(50,50,150,75);
a.createAttitudeIndicator();
f.add(a);
f.setSize(500,400);
f.setVisible(true);
}
}
When I try to run this, I am getting a null pointer exception. Any ideas?
i think this might help you. NetBeans has a great GUI to help you make GUI's for your programs
https://netbeans.org/kb/70/java/quickstart-gui.html