Creating JFrame in an instance object - java

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
}
}

Related

Java while loop too fast? [duplicate]

This question already has an answer here:
Loop doesn't see value changed by other thread without a print statement
(1 answer)
Closed 11 months ago.
I have some problem with my code. I want to implement a keylistener. I have a keyHandler class which takes care about keyinput and a while loop in the main class to check if a certain key is pressed or not. I dont understand the behavior of my code. the strange thing is that every thing works when I put the System.out.println("hello") command in front of my if statement. but when i comment it out my programm doesnt realize that i press the key Im checkin in my if statement. I think i could find a workaround. but i would be very glad to understand this strange behavior. why is this happening. Sorry for my bad english. I hope you guys can help me.
public static void main(String[] args) {
boolean running = true;
JFrame window;
KeyHandler k = new KeyHandler();
window = new JFrame();
window.setVisible(true);
window.addKeyListener(k);
while (running) {
//System.out.println("hello");
if (k.isKeyPressed(KeyEvent.VK_W)) {
System.out.println("--------------------------------------------------------------------------");
}
}
}
//here is the KeyHandler class
public class KeyHandler implements KeyListener {
private boolean[] keysPressed = new boolean[128];
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
keysPressed[e.getKeyCode()] = true;
System.out.println(e.getKeyChar());
System.out.println(keysPressed[e.getKeyCode()]);
}
#Override
public void keyReleased(KeyEvent e) {
keysPressed[e.getKeyCode()] = false;
System.out.println(e.getKeyChar());
System.out.println(keysPressed[e.getKeyCode()]);
}
public boolean isKeyPressed(int keyCode) {
return keysPressed[keyCode];
}
}
The whole purpose of events and event handling is you don't need a loop to listen for events. Simply start your UI, add the listeners to a list, and allow the listeners to handle the processing.
Create a listener
public interface MyListener extends EventListener {
public void doSomething();
}
Now use it. With this code it just spits out some text when W is pressed, but the listeners could be another component or anything that uses the interface. No need for extra loops.
public class Main {
private EventListenerList listenerList = new EventListenerList();
public Main() {
JFrame frame = new JFrame();
addListener(new MyListener() {
#Override
public void doSomething() {
System.out.println("Hello 1");
}
});
addListener(new MyListener() {
#Override
public void doSomething() {
System.out.println("Hello 2");
}
});
frame.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_W) {
fireMyEvent();
}
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void addListener(MyListener listener) {
listenerList.add(MyListener.class, listener);
}
private void fireMyEvent() {
MyListener[] listeners = listenerList.getListeners(MyListener.class);
if (listeners == null) {
return;
}
for (MyListener listener : listeners) {
listener.doSomething();
}
}
public static void main(String [] args) {
new Main();
}
}
Here's a link that might help. I would not check for a key being pressed by that method. You are creating a resource hog, first off: by having
boolean running = true;
you then enter a while loop,
while (running) {
do x;
}
this can create a spin lock on some systems, this is a very bad practice. As user Lei Yang stated it is really not needed especially with the classes we have today and modern GUI's, your creating an endless loop. One this most certainly is a way to slow down a system, two you really can't continue coding past that point as you have no way to exit the loop. Some IDE's also have a check that won't allow your application to start if you have a loop that is infinite, almost all will at least give you a warning. you should at least if you are looking for a certain key and have to implement it that way do:
while (running) {
//System.out.println("hello");
if (k.isKeyPressed(KeyEvent.VK_W) = "e") {
running = false;
}
}
at least that won't be an endless loop.

Add a GUI to class

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.

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.

java temperature conversion in GUI

im struggling again, with doing a program in java that converts the temperature from celsius to fahrenhiet, but it must be done in a GUI so that the user may enter in a number for celsius and click a botton to convert it. ive been modeling it off of a example in my book however in the book it shows it working with out having a static main(), but my IDE gave me an error saying that it was needed, so ive added a static main() and ive tried calling the tempwindow() to see if that would work but still nothing and even if i comment out the call it doesnt give me a error but nothing happens.
im hopping someone can help show me what im doing wrong and how i should go about this.
import javax.swing.JOptionPane;
import javax.swing.*;
import java.awt.event.*;
public class tempcon extends JFrame
{
private JPanel panel;
private JLabel messageLabel;
private JTextField tempC;
// private JRadioButton tempF;
// private ButtonGroup radioButtonGroup;
private JButton calcButton;
private final int WINDOW_WIDTH = 400;
private final int WINDOW_HEIGHT = 100;
public tempwindow()
{
setTitle("Temurture convertion");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
setVisible(true);
}
private void buildPanel()
{
messageLabel = new JLabel("enter tempurture in celsius");
tempC = new JTextField(10);
calcButton = new JButton("convert");
calcButton.addActionListener(new CalcButtonListener());
panel = new JPanel();
panel.add(messageLabel);
panel.add(tempC);
panel.add(calcButton);
}
private class CalcButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String input;
double temp;
input = tempC.getText();
temp = Double.parseDouble(input) * 1.8 + 32;
JOptionPane.showMessageDialog(null, "that is " + temp + "degrees fehrenhiet");
}
}
public static void main(String[] args)
{
tempwindow();
}
}
You are doing a few things wrong:
Your constructor can't have a different name from your class name
You need to instantiate the object to call the constructor, rather instantiating an object does call the constructor but you can't just access it like a method.
You should use the Java naming conventions for class names.
The class:
public class TempCon extends JFrame
{
// Variable declarations
public TempCon() // Constructor should match the Class name
{
}
}
The main class:
public static void main(String[] args)
{
TempCon converter = new TempCon();
}
public static void main(String[] args)
{
tempcon myTempWindowInstance = new tempcon();
myTempWindowInstance.tempwindow();
}
You never initialize a tempcon. Your constructor must have the same name as the class, so I recommend the following changes instead:
Replace public tempwindow() with public tempcon() to correct the constructor.
public tempcon()
{
setTitle("Temurture convertion");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
setVisible(true);
}
create an instance of tempcon using new, which calls the constructor:
public static void main(String[] args)
{
tempcon myTempWindowInstance = new tempcon();
}
please write return type your function like.
public void tempwindow()
create object of class and call method.
public static void main(String[] args)
{
tempcon t=new tempcon();
t.tempwindow();
}
and learn java object java object oriented programming.

Categories

Resources