JFrame window not popping up? - java

I'm pretty new to java, and I'm trying to make a simple JFrame application, although when I click run, nothing displays. I have followed some youtube tutorials, and i've pretty much copied and pasted this code, although i'm not sure why it works for the youtube demonstration, and not mine. Some help would be greatly appreciated.
Thanks!
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Game extends JFrame{
private JButton clicker;
private int clicks = 0;
public Game(){
createView();
setTitle("Game");
setSize(400, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setResizable(true);
}
private void createView(){
JPanel panel = new JPanel();
getContentPane().add(panel);
clicker = new JButton("Here's a jbutton");
clicker.addActionListener(new Button());
panel.add(clicker);
}
public static void main(String[] args) {
new Game().setVisible(true);
}
private class Button implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
clicks += 1;
}
}
}

Related

Java Button not appearing on (GUI)

I've been figuring out a nice way to lay nice foundations when working on a somewhat bigger project than I have before. If i write everything in main it works fine. When doing classes like this the Frame works but the Button i've added doesn't wanna appear:
//main
package taxsystem;
import java.awt.*;
import javax.swing.*;
public class Taxmain
{
public mainFrame mf;
public Interface gui;
public void startApplication()
{
mf = new mainFrame();
mf.startApp();
gui = new Interface();
gui.makeLayout();
}
public static void main(String[] args)
{
Taxmain tm = new Taxmain();
tm.startApplication();
}
}
//The actual Frame
package taxsystem;
import java.awt.*;
import javax.swing.*;
public class mainFrame extends JFrame
{
public void startApp()
{
setResizable(false);
setVisible(true);
setSize(720,340);
setLocation(0,0);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBackground(Color.WHITE);
setTitle("Tax Handler");
}
}
//the layout (where i create the button that doesn't appear)
package taxsystem;
import java.awt.*;
import javax.swing.*;
public class Interface extends JPanel
{
Taxmain mc;
public JButton testButton;
public void makeLayout()
{
testButton = new JButton();
testButton.setText("Printer");
testButton.setFont(new Font("verdana", Font.ITALIC, 16));
testButton.setForeground(Color.BLACK);
testButton.setFocusable(false);
testButton.setSize(new Dimension(150, 40));
testButton.setLocation(10, 10);
this.setLayout(null);
this.add(testButton);
}
}
Currently it looks like this: https://gyazo.com/fad5dbca6c59905faea0a8ac1fbd424a
Thanks in advance, also are there anyway i can improve the code i have so far?
You need to add the JPanel to your JFrame
public void startApplication()
{
mf = new mainFrame();
mf.startApp();
gui = new Interface();
gui.makeLayout();
mf.add(gui); // here is get's added
}

Stack overflow error GUI programming

I have a big problem i tried to solve it for days. I programmed a little program but it doesn't work.The error is Stackoverflow I already searched this website on and on again .I broke it down to the part wich doesn't works so here is the code.
This is the frame:
package snippet;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MyFrame extends JFrame {
JButton button;
JLabel label;
TextEdit textEdit = new TextEdit();
public void LetsGo() {
setBounds(0, 0, 800, 510);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Game");
setResizable(false);
setLocationRelativeTo(null);
//Labels
label = new JLabel();
label.setText("Change Me");
label.setBounds(30, 25, 200, 50);
label.setVisible(true);
add(label);
button = new JButton();
button.setText("I Will Change A Text");
button.setBounds(30, 130, 200, 400);
button.addActionListener(new Listener());;
add(button);
}
public class Listener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
textEdit.editTheText();
}
}
And this object should edit the Text :
package snippet;
public class TextEdit {
MyFrame frame = new MyFrame();
public void editTheText(){
frame.label.setText("Text was edited");
}
}
So the real code is much more complex so i won't put all in one Object
Would be great if i receive some help would be very very thankful for that
You are creating a new MyFrame in TextEdit, which I don't think is what you want to do because frame.label will be null.
What you really should be doing is assigning the JFrame inside of Listener.
public class Listener implements ActionListener {
private JFrame frame;
public Listener(JFrame frame) {
this.frame = frame;
}
#Override
public void actionPerformed(ActionEvent e) {
if (this.frame.label != null) {
this.frame.label.setText("Text was edited");
}
}
}
Then for the the other code, you don't have a constructor or your actual class is called LetsGo?
Assuming it is not called LetsGo and it actually is MyFrame, you need an actual constructor.
public MyFrame() {
LetsGo();
}
Then in the LetsGo method, add the frame to the Listener
button.addActionListener(new Listener(this));

Java GUI, why isn't mine showing up?

//leaving out import statements
public class MVCView extends JFrame{
private JButton add = new JButton("Click me");
private JTextArea center = new JTextArea(200,300);
private JTextField bottom = new JTextField(200);
public MVCView() {
setLayout(new BorderLayout());
add(add, BorderLayout.NORTH);
add(center, BorderLayout.CENTER);
add(bottom, BorderLayout.SOUTH);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
public class MVCTester {
public static void main(String[] args) {
MVCView view = new MVCView();
}
}
I'm just trying to get this to show up on my screen. I create a class with main to create the object which is in a different class. When I click run nothing pops up. I've been following a few tutorials and my code doesn't look much different. Already tried putting everything in a JPanel first which didn't work... I don't know what I'm leaving out or doing wrong.
I just modified code you posted and thing works.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MVCView extends JFrame{
private JButton add = new JButton("Click me");
private JTextArea center = new JTextArea(200,300);
private JTextField bottom = new JTextField(200);
public MVCView() {
setLayout(new BorderLayout());
add(add, BorderLayout.NORTH);
add(center, BorderLayout.CENTER);
add(bottom, BorderLayout.SOUTH);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
MVCView view = new MVCView();
}
}

When i change JPanel in JFrame i lose focus

As in subject: When i change JPanel in JFrame i lose focus. I have class Game, Action, Button.
I have also class Stage when drawing the game stage.
At first in Game i have Action panel, which contains buttons, after push button NewGame i change panel in Game to Stage, but i cant control ship, which i am flying.
How to fix it or how to do it different?
Action.java
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.io.FileNotFoundException;
import javax.swing.*;
#SuppressWarnings("serial")
public class Action extends JPanel {
public static final int xxx = 800;
public static final int yyy = 600;
private Button buttonPanel;
public Action(Game game) {
setLayout(new FlowLayout());
setPreferredSize(new Dimension(xxx, yyy));
buttonPanel = new Button(game);
add(buttonPanel);
setVisible(true);
}
}
Button.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class Button extends JPanel implements ActionListener{
public static final int xxx = 100;
public static final int yyy = 300;
private JButton NewGame;
private JButton Scores;
private JButton Exit;
private Game game;
public Button(Game game) {
NewGame = new JButton("NewGame");
Scores = new JButton("Scores");
Exit = new JButton("Wyjście");
this.game=game;
NewGame.addActionListener(this);
setLayout(new FlowLayout());
setPreferredSize(new Dimension(xxx, yyy));
add(NewGame);
add(Scores);
add(Exit);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == NewGame){
game.setPanel("stage");
}
;
}
}
Game.java
#SuppressWarnings("serial")
public class Game extends JFrame {
private Action menu;
private static Stage stage = new Stage();
public Game() {
super("Lunar Lander");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(Stage.WIDTH,Stage.HEIGHT);
setMinimumSize(new Dimension(400,300));
this.setResizable(true);
//stage = new Stage(0);
menu = new Action(this);
add(menu);
pack();
//setPanel("stage");
setVisible(true);
}
public void setPanel(String panel) {
if (panel=="stage") {
remove(menu);
add(stage);
pack();
} else if (panel=="menu") {
remove(stage);
add(menu);
pack();
}
}
public static void main(String[] args) throws FileNotFoundException {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Game();
}
});
Thread a = new Thread(stage);
a.start();
while (a.isAlive()) {}
Scores scores = new Scores();
scores.changeScores(stage.getPlayer().getName(),stage.getPlayer().getPoints());
}
}
but i cant control ship, which i am flying.
KeyEvents are only passed to the component with focus. When you swap panels the panel no longer has focus.
Don't use a KeyListener. Instead you should be using Key Bindings. Then you can handle the event even if the component doesn't have focus.
See Motion Using the Keyboard for more information and working examples.
Edit:
Don't use "==" for String comparisons. Use the String.equals(...) method.
Variable names should NOT start with an upper case character.

Use variables from other class from other file to another in java

There are two players who will input their name in the JTextFields. What I want to do is that the data I entered from the Welcome frame in Enter.java will be transferred to the JLabels in ActualGame.java.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
public class Enter extends JFrame implements ActionListener {
private String one = "";
private String two = "";
private JTextField txtOne = new JTextField();
private JTextField txtTwo = new JTextField();
public Enter() {
this.setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Welcome");
setSize(200, 130);
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
add(txtOne);
add(txtTwo);
enter.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
Main main = new Main();
this.setVisible(false);
one = txtOne.getText();
two = txtTwo.getText();
}
}
Main is the main class that holds the JFrame of ActualGame() and also the main class of Enter().
import javax.swing.*;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
public class Main extends JFrame {
public Main() {
add(new ActualGame());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Main");
setSize(400, 557);
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
}
public static void main(String[] args) {
Enter enter=new Enter();
}
}
the ActualGame:
import java.awt.*;
import javax.swing.*;
public class ActualGame extends JPanel{
private JLabel lblOne = new JLabel(one);//how i wish it would be that easy
private JLabel lblTwo = new JLabel(two);
public ActualGame() {
setLayout(new FlowLayout());
add(lblOne);
add(lblTwo);
}
}
What should I do to be able to use the String variable one and two from Enter.java to ActualGame.java?
I'm new and noob in programming especially java swing. Open to criticisms and suggestions. Thank you.
Suggestions:
Passing information from one object to another is no different with Swing as with other Java programs. You can call methods or constructors and pass information in via parameters.
A key difference though is when to pass information. With event driven programs, this is often triggered by an event, a listener, and so use of the observer design pattern is comment.
For your purposes, the first window could be a modal dialog such as a JOptionPane or a modal JDialog which will make it easier to figure out when to pass information. When using a modal dialog, all code flow in the calling program is paused while the dialog is visible, and then resumes once the dialog is no longer visible. It's easy then to have the calling program query the dialog once this occurs, because you'll know precisely where in your code this will occur.
You'll want to avoid excessive showing of different windows in your application as it can quickly get annoying to the user. A few dialogs here and there are OK, especially if you need the information to be given in a modal fashion, but in general it's better to swap GUI "views" when needed, and a CardLayout is good for this.
But having said this, separate views are often created by separate classes, so the problem of passing information back and forth remains a problem with similar solutions as described above.
Specifically, give your Enter class a getText method that will allow other objects to query it for the state of its JTextField:
public String getTxtOneText() {
return txtOne.getText();
}
Also, change your ActualGame class so that it can accept String information when needed:
class ActualGame extends JPanel {
private JLabel lblOne = new JLabel();
public ActualGame(String text) {
lblOne.setText(text);
setLayout(new FlowLayout());
add(lblOne);
}
public void setLblOneText(String text) {
lblOne.setText(text);
}
}
e.g.,
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Foo {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ActualGame actualGame = new ActualGame("");
Main main = new Main(actualGame);
main.pack();
Enter enter = new Enter(main);
enter.setVisible(true);
actualGame.setLblOneText(enter.getTxtOneText());
main.pack();
main.setLocationRelativeTo(null);
main.setVisible(true);
}
});
}
}
class Enter extends JDialog implements ActionListener {
private String one = "";
private JTextField txtOne = new JTextField(10);
private JButton enter = new JButton("Enter");
public Enter(JFrame frame) {
super(frame, "Welcome", true);
this.setLayout(new FlowLayout());
enter.addActionListener(this);
txtOne.addActionListener(this);
add(txtOne);
add(enter);
pack();
setLocationRelativeTo(null);
// this has to be done last
// setVisible(true);
}
public String getTxtOneText() {
return txtOne.getText();
}
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
}
class Main extends JFrame {
ActualGame actualGame;
public Main(ActualGame actualGame) {
super("Main");
this.actualGame = actualGame;
add(actualGame);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class ActualGame extends JPanel {
private JLabel lblOne = new JLabel();
public ActualGame(String text) {
lblOne.setText(text);
setLayout(new FlowLayout());
add(lblOne);
}
public void setLblOneText(String text) {
lblOne.setText(text);
}
}
Try to make ActualGam as a underclass of Enter
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
public class Enter extends JFrame implements ActionListener {
private String one = "";
private JTextField txtOne = new JTextField();
public Enter() {
this.setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Welcome");
setSize(200, 130);
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
add(txtOne);
enter.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
Main main = new Main();
this.setVisible(false);
one = txtOne.getText();
}
class ActualGame extends JPanel{
private JLabel lblOne = new JLabel(one);
public ActualGame() {
setLayout(new FlowLayout());
Enter.this.add(lblOne);
}
}
}

Categories