Add a GUI to class - java

I want to know how to add a GUI to my program. I have started creating a java program in Blue J and the first class of the program is a class which has been extended by other classes.
Now I have to make a GUI too but from my understanding I can only implement an interface as the GUI extends the class Frame. The problem is I want to create a GUI of my class, it has instance variables too so is there a work around? Could I make my first class an interface without altering the extensions too much?
code:
public class Players /* Class name */
{
private int attack; /* Instance variables* */
private int defence;
private int jump;
public Players(int a, int d, int j) /* Constructor being defined */
{
int total = a + d + j;
if((total) == 100)
{
attack = a;
defence = d;
jump = j;
}
else
{
System.out.println("Make stats add to 100");
}
}
public Players()/* Default contructor if not user defined */
{
attack = 34;
defence = 33;
jump = 33;
}
public void addAttack(int a)
{
attack += a;
}
public void addDefence(int a)
{
defence += a;
}
public void addJump(int a)
{
jump += a;
}
public void getBasicStats()
{
System.out.println(attack + " " + defence + " " + jump);
}
}
This is my first class and my superclass for most of the other classes

I suggest learning how to use Swing. You will have several different classes interacting together. In fact, it is considered good practice to keep separate the code which creates and manages the GUI from the code which performs the underlying logic and data manipulation.

Another suggestion:
Learn JavaFX and download SceneBuilder from Oracle: here
At my university they have stopped teaching Swing and started to teach JavaFX, saying JavaFX has taken over the throne from Swing.
SceneBuilder is very easy to use, drag and drop concept. It creates a FXML file which is used to declare your programs GUI.

How will I declare aan instance variable inside the GUI class?
Like as shown bellow, you could start with something like this, note that your application should be able to hand out your data to other classes, for instance I changed getBasicStats() to return a String, this way you can use your application class anywhere you want, I guess this is why you were confused about where to place the GUI code...
public class PlayersGUI extends JFrame {
private static final long serialVersionUID = 1L;
private Players players; // instance variable of your application
private PlayersGUI() {
players = new Players();
initGUI();
}
private void initGUI() {
setTitle("This the GUI for Players application");
setPreferredSize(new Dimension(640, 560));
setLocation(new Point(360, 240));
JPanel jPanel = new JPanel();
JLabel stat = new JLabel(players.getBasicStats());
JButton attack = new JButton("Attack!");
attack.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
players.addAttack(1);
}
});
JButton hugeAttack = new JButton("HUGE Attack!");
hugeAttack.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
players.addAttack(10);
}
});
JButton defend = new JButton("Defend");
defend.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
players.addDefence(1);
}
});
JButton showStats = new JButton("Show stats");
showStats.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
stat.setText(players.getBasicStats());
}
});
jPanel.add(stat);
jPanel.add(attack);
jPanel.add(hugeAttack);
jPanel.add(defend);
jPanel.add(showStats);
add(jPanel);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
PlayersGUI pgui = new PlayersGUI();
pgui.pack();
pgui.setVisible(true);
}
});
}
}

I would recommend using netbeans to start with. From there you can easily select pre created classes such as Jframes. Much easier to learn. You can create a GUI from there by dragging and dropping buttons and whatever you need.
Here is a youtube tut to create GUI's in netbeans.
https://www.youtube.com/watch?v=LFr06ZKIpSM
If you decide not to go with netbeans, you are gonna have to create swing containers withing your class to make the Interface.

Related

JButton call function in other class

I am creating a timer application. I created my timer (in millisecond) and my interface (with JFrame). I would like to start my chrono (in class "Chrono") when I click on bouton "Start_button" (in class "WindowChrono") from my main class "Application".
Start_button in WindowChrono
JButton Start_button = new JButton("Start");
Start_button.setForeground(Color.BLUE);
Start_button.setFont(new Font("Tahoma", Font.PLAIN, 20));
Start_button.setBackground(new Color(255, 255, 255));
Start_button.setBounds(474, 456, 142, 27);
Start_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(i==0) {
Start_button.setText("Stop");
i = 1;
}
else {
Start_button.setText("Start");
i = 0;
}
}
});
main in Application
public class Application extends WindowChrono {
public void main(String[] args) {
WindowChrono window = new WindowChrono();
run();
Chrono Timer = new Chrono();
int refreshTime = 10;
Timer.start(); // LORS DE L ACTIVATION DU BOUTON START
Timer.stop(); // LORS DE L ACTIVATION DU BOUTON STOP
while (Timer.getStopTime == 0) {
Thread.sleep(refreshTime);
System.out.println(Timer.actualTime()); // AFFICHE LE TEMPS ACUTEL DANS LA FENETRE D'AFFICHAGE
}
System.out.println(Timer.getTime());
}
}
How can I do that?
First you want to show your window. So in your main method you can put this code to start it:
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
Application window = new Application(); // Application is a WindowChrono because it extends it
window.setVisible(true);
}
});
It will make sure that Swing handles the appearance of the window as soon as possible (invokeLater). So you don't have to worry about that anymore.
Now, once the window is visible it will take over. All algorithms, methods or what ever you execute should be done in the Window instance (and no longer in your main)
So your Application has a constructor somewhere:
public class Application extends WindowChrono{
public Application(){
// your constructor will be executed when you call "new Application()"
}
}
In your constructor you could initialise your timer (without starting it) so that the "timer" instance exists in your Window.
private Chrono timer;
public Application(){
this.timer = new Chrono();
}
Your button is looking good already. Now you only need to start/stop the timer from inside the ActionListener:
public void actionPerformed(ActionEvent arg0) {
if(i==0) {
Start_button.setText("Stop");
i = 1;
Application.this.timer.start();
}
else {
Start_button.setText("Start");
i = 0;
Application.this.timer.stop();
}
}
The mentioning of Application before the this is necessary to tell Java that you mean the current Application instance (not the instance of the ActionListener.
You can also put the "actionListener" method in your Application directly:
public void performButtonAction(int i){
// the code from your action listener
}
and then just call the method like this:
Start_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
performButtonAction(i);
}
});
The only thing that is not clear to me is where your i is coming from (and why it is an int and not a boolean which could be easier don't you think?).
Oh, one more thing: variable names should start with a small letter start_Button instead of Start_Button. Only class names start with a capital letter. It helps you keep your code clear. Imagine you had something like this: Application Application = new Application() .. now what is what? :)

Creating JFrame in an instance object

I'm trying to display a countdown and I'm searching how to do it and trying codes out but that's not what I'm here to ask in this question, although I'd be happy if you helped me in that area too.
This seems a bit elementary but I can't seem to get the JFrame showing.
I predicted that if I create an instance of the testmain and there's a creation of a JFrame in the constructor, it'd show the JFrame.
I even tried getting an input from the keyboard so that it'll stop.
But nothing happens and the program ends right away.
It says build successful.
What am I missing?
public class testmain
{
Timer t;
JLabel label;
public void testmain()
{
JFrame myFrame = new JFrame();
label = new JLabel();
myFrame.setSize(400, 400);
myFrame.setAlwaysOnTop(true);
myFrame.setLocationRelativeTo(null);
label.setText("This works");
myFrame.add(label);
myFrame.setVisible(true);
// Scanner keyboard = new Scanner(System.in);
// keyboard.nextInt();
// start();
}
void start()
{
t = new Timer(1000, new TimeTest());
}
class TimeTest implements ActionListener
{
private int counter = 0;
#Override
public void actionPerformed(ActionEvent e)
{
label.setText("" + counter++);
if(counter == 10)
t.removeActionListener(this);
}
}
public static void main(String[] args)
{
testmain tester = new testmain();
}
}
You've got a pseudo-constructor which is not being called. Constructors have no return type, not void, not anything.
Change
// this never gets called
public void testmain() {
}
to
// but this **will** be called
public testmain() {
}
As an aside, you will want to learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.
So the class should actually be called TestMain:
public class TestMain {
public TestMain() {
// constructor code here
}
}

Java basic GUI program errors

In my online Java class, I need to write a program that counts the number of mouse clicks on a button within a frame. Here is my code:
import java.awt.*;
import java.awt.event.*;
public class option1 extends Frame {
option1() {
setTitle("Final Project Option 1");
setSize(300,300);
show();
}
public static void main(String[] args) {
option1 test = new option1();
int a = 0;
String s1 = "" + a;
Frame objFrame;
Button objButton1;
Label objLabel1;
objFrame = new option1();
objButton1 = new Button("Button");
objLabel1 = new Label();
objLabel1.setBounds(150,220,50,30);
objButton1.setBounds(40,35,50,50);
objLabel1.setText(s1);
objButton1.addMouseListener(new MyMouseListener()); //line 29
objFrame.add(objLabel1);
objFrame.add(objButton1);
}
public class MyMouseListener extends MouseAdapter {
public void mouseClicked(MouseEvent me) {
a++; //line 36
}
}
}
When compiling, I get two errors. One error is on line 29, which is "non-static variable this cannot be referenced from a static context", and the other is on line 36, which is "cannot find symbol".
So, what exactly am I doing wrong? I would appreciate responders telling exactly what I need to do to fix the problem, and avoiding using technical terms since I'm rather new to programming.
I see two issues, namely your inner class should be static (to use it without an instance of option1 which should probably be Option1 to fit with Java naming conventions) and you need to define and initialize a. Something like
public static class MyMouseListener extends MouseAdapter {
int a = 0; //<-- add this.
public void mouseClicked(MouseEvent me) {
a++;
}
}
Also, I suggest you consider using the more modern JFrame instead of the older Frame.
Edit
You'll need to save a reference to your MouseListener like
MyMouseListener mml = new MyMouseListener();
objButton1.addMouseListener(mml);
Then you can get it the a like
System.out.println(mml.a);
Finally, your original approach of "" + a would be "0".
Generally, as soon as you possibly can, get out of the main method into a non-static context...
public class option1 extends Frame {
private int a = 0;
private Label objLabel1;
option1() {
setTitle("Final Project Option 1");
setSize(300,300);
Button objButton1;
objButton1 = new Button("Button");
objLabel1 = new Label();
objLabel1.setBounds(150,220,50,30);
objButton1.setBounds(40,35,50,50);
objLabel1.setText(Integer.toString(a));
objButton1.addMouseListener(new MyMouseListener()); //line 29
add(objLabel1);
add(objButton1);
show();
}
public static void main(String[] args) {
option1 test = new option1();
}
public class MyMouseListener extends MouseAdapter {
public void mouseClicked(MouseEvent me) {
a++; //line 36
objLabel1.setText(Integer.toString(a));
}
}
}
Generally speaking, AWT is out-of-date (by some 15 years) and you really should be trying to use Swing or JavaFX instead.
Buttons should use ActionListener, as a mouse is not the only way a button might be triggered
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
I just tried to make your code working. But there is some issues regarding the standard Java coding. But you should consider previous answers concerning the coding style.
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
public class Main {
public static void main(String[] args) {
final Frame mainFrame = new OptionOne();
Button button = new Button("Button");
final Label label = new Label();
label.setBounds(150, 220, 50, 30);
label.setText("0");
button.setBounds(40, 35, 50, 50);
label.addPropertyChangeListener(label.getText(), new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
mainFrame.addNotify();
}
});
button.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
int value = Integer.parseInt(label.getText());
label.setText(String.valueOf(value + 1));
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
mainFrame.add(label);
mainFrame.add(button);
}
}
class OptionOne extends Frame {
OptionOne() {
setTitle("Final Project Option 1");
setSize(300, 300);
show();
}
}

How to set all of the values back to the original start values

I have a game that is similar to the game of life. the game deals with creating a house and rearranging the neighbors and such. I WANT to restart the game, simply need to set all of these values back to the original start values. How do I do that with a code. I understand the English of it but cant seem to convert it to a code.
This is some of my main program (If anyone want me to post the whole main program I can) but to make it simple and I dont want to confuse you guys.
So what I WANT: to restart the game, simply I want to set all of these values back to the original start values.
Some Of Main Program:
public class Ghetto extends JFrame implements ActionListener, MouseListener,MouseMotionListener
{
protected Grids theGrid;
JButton resetButton;
javax.swing.Timer timer; // generates ticks that drive the animation
public final static int SIZE = 5;
public final static int BLUE = 10;
public final static int RED = 8;
public final static int DIVERSITY_PERCENTAGE = 70;
public static void main(String[] args)
{
new Ghetto();
}
public Ghetto() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
addMouseListener(this);
addMouseMotionListener(this);
setLayout(new FlowLayout());
theGrid = new Grids(SIZE, BLUE, RED, DIVERSITY_PERCENTAGE);
add(theGrid);
resetButton = new JButton("Reset");
add(resetButton);
resetButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
resetWithCurrent();
}
});
setSize(new Dimension(550, 600));
setVisible(true);
}
//public void resetWithCurrent()
//{
//}
#Override
public void actionPerformed(ActionEvent e)
{
timer.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
performStep();
}
});
}
}
Typically, the eaiest way to "reset" is not to. Just throw away the object and make a brand new one! The constructor will take care of everything for you, and you won't have to worry about missing something. If you really need to, you can make a reset method that performs all the necessary setting, and have the constructor call it. You have to be sure to catch everything, so in particular you can't use any field initializations that look like Foo x = bar and you can't use any initializer blocks.
The approach I suggest:
Ghetto ghetto = new Ghetto();
//Do stuff with the ghetto.
ghetto = new Ghetto();
//BLAM! The old ghetto is *gone*, and we have a new one to play with.
If these "values" are stored in a separate class, say class "GameProperties" then you just need to invoke the constructor by creating a new instance of the GameProperties.
The constructor should take care of assigning default values.
So, assuming you have an instance of GameProperties within Ghetto class named props:
Add new instance of GameProperties class and change resetWithCurrent in Ghetto class:
GameProperties props = new GameProperties();
public void resetWithCurrent(){
//This will reset the values to their defaults as defined in the constructor
props = new GameProperties();
}
Remove the values constants as you are using your GameProperties. Use the getters methods
to obtain the properties values.
Create new class:
public class GameProperties {
//assign initial default values
private int size= 5;
private int blue= 10;
private int red= 8;
private int diversity_percentage= 70;
//calling default constructor will set the properties default values
public GameProperties(){
}
public int getSize(){
return size;
}
public int getBlueValue(){
return size;
}
public int getRedValue(){
return size;
}
public int getDiversityPercentage(){
return diversity_percentage;
}
}
Hope it helps.

Simple memory game with replay button

I want to build a simple memory game. I want to put a replay button, which is play again the memory game.
I have built a class named MemoryGame and a main class.
Here is the part of the ButtonListener code.
public void actionPerformed(ActionEvent e) {
if (exitButton == e.getSource()) {
System.exit(0);
}
else if (replayButton == e.getSource()) {
//How can I declare it?
}
}
If I declare the replay button as :
new MemoryGame();
It's work fine, but it pops up another windows.
I want to clear the current display and return to the beginning, without a new windows. How can I do that?
EDIT :
I think I need to rewrite the code of my program, because my program does not have the init() method as suggested which is the initial state of the program.
My Java knowledge is very limited and usually I create less method and dump most into a method.
I will try to redo my program.
Thanks for the suggestions.
Show us what is inside the MemoryGame how you create its initial state. Effectively what folks are suggesting here is for you is to have an initial method which will set-up the game state which the MemeoryGame constructor will call. Then on replay-button of the game you call this method.
Something along these lines:
void init(){
this.x = 10;
this.y = 10;
}
public MemoryGame(){
init();
}
public void actionPerformed(ActionEvent e) {
if (exitButton == e.getSource()) {
System.exit(0);
}
else if (replayButton == e.getSource()) {
init();
}
}
one way you can do it although it might be dirty, is to grab your MemoryGame constructor, and put the stuff inside it inside another method, and call that method in your constructor and inside the button event.
as an example i have made the following class and it resets itself with the use of the previous technique:
public class App extends JFrame{
public static void main(String[] args){
new App();
}
public App(){
init();
}
private JButton changeColorButton;
private JButton resetAppButton;
private JPanel panel;
private void init() {
changeColorButton=null;
resetAppButton=null;
panel=null;
this.setSize(200,400);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setBackground(Color.white);
panel.setPreferredSize(new Dimension(200,400));
changeColorButton = new JButton("Change");
changeColorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panel.setBackground(Color.black);
panel.repaint();
}
});
changeColorButton.setPreferredSize(new Dimension(100,100));
resetAppButton = new JButton("Reset");
resetAppButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
init();
}
});
resetAppButton.setPreferredSize(new Dimension(100,100));
panel.add(changeColorButton);
panel.add(resetAppButton);
this.add(panel);
this.validate();
}
}
what this app does is it has two buttons. one changes the color and the other resets the app itself.
You should think about re-factoring your code so that the MemoryGame class does not create the GUI, then you wont be recreating it whenever you initialise a new Game.
It's a good idea to keep program logic separate to UI code.
What you could do is you could call dispose() on your JFrame. This will get rid of it and go to your title screen like this:
Here's the button code
public void actionPerformed(ActionEvent event)
{
if (closeButton = event.getSource())
{
System.exit(0);
}
if (playAgainButton = event.getSource())
{
Game.frame.dispose(); // Your class name, then the JFrame variable and call dispose
}
}
This will work but you may have a few problems reseting your program. If so then create a reset method where you can reset all your variables and call when playAgainButton is clicked. For example:
public void reset()
{
// Right here you'd reset all your variables
// Perhaps you have a gameOver variable to see if it's game over or not reset it
gameOver = false;
}

Categories

Resources