A Small Guessing Game GUI opens in two windows - java

Alright so here's the problem:
I created this small guessing game and wanted to make it gui based...
but it appears in two different windows -
first window is the menu(button and label)
second window is activated by the button and has the game in it.
Is there a way for me to have both windows in one- AS IN the first window gets overwritten by the second window?
public class Skeleton extends JFrame implements ActionListener
{
JPanel glass = new JPanel();
JButton btn = new JButton("Start");
TextField tf = new TextField();
JLabel label = new JLabel("Enter Guess Here: ");
JLabel answerLabel = new JLabel("Answer:...");
Board bob =new Board();
public Skeleton()
{
setIconImage(new ImageIcon("icon.png").getImage());
getContentPane().setBackground(Color.darkGray);
getContentPane().setForeground(Color.black);
setLayout(new FlowLayout(FlowLayout.CENTER,10,10));
add(label);
label.setForeground(Color.black);
add(tf);
tf.setText("");
add(btn);
btn.setBackground(Color.green);
btn.addActionListener(this);
add(answerLabel);
answerLabel.setForeground(Color.black);
setTitle("Guessing Game");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300,200);
setLocationRelativeTo(null);
setVisible(true);
setResizable(true);
}
public void actionPerformed(ActionEvent e)
{//GAME FRAME
JFrame frame = new JFrame();
int userGuess= Integer.parseInt(tf.getText());
frame.add(bob);
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(300,285);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setIconImage(new ImageIcon("icon.png").getImage());
...........
This is obviously not the full code, just the part that uses the GUI.
NOTE: I do have some other within this actionevent which occur after the button is clicked.
Also this is my first game ever :D (if i can call it one)

You create new JFrame into "actionPerformed" method, so it's normal to have two frames (the Skeleton instance and the new one).
Just use "this" instead of a new JFrame instance to keep only one JFrame instance.

Each JFrame will create a new window. If you want to display everything into the same window, create only one JFrame and change its content.
You can change the whole content of a JFrame by setting its contentPane (frame.setContentPane(...)) or by adding/removing Panel to it.
I suggest to take a look at JPanel since you will use it a lot.

Related

Program with JFrame won't start

I was trying to write a program, where you put some numbers in a JTextField an then it does something with it. I tried figuring out how to even make an input possible. But the way I'm trying it doesn't work despite Eclipse showing no errors. And yes, I know there is no way to stop this program but this is just a test.
import javax.swing.*;
public class NotenEingabe extends JFrame {
public static void main(String[]args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JLabel label = new JLabel("text");
JTextField field = new JTextField("text");
panel.add(label);
panel.add(field);
frame.setTitle("Grade input");
frame.pack();
frame.add(panel);
frame.setVisible(true);
}
}
I hope it is a real problem and not simply my tiredness.
frame.setVisible(true);
frame.add(panel);
Components should be added to the frame BEFORE the frame is made visible.
The layout manager is not invoked so the components have a size of (0, 0) which means there is nothing to paint.
frame.setTitle("Grade input");
frame.add(panel);
//frame.setSize(700, 700);
frame.pack();
frame.setVisible(true);
First of all when you extend your class from jframe you dont need to instantiate new jFrame just make a new instance of your class then access jframe with that or just delete extend Jframe and use functional approach.
The you didn't set de layout of pane
Test this one then you can choose from veriety of layouts
panel.setLayout(newFlowLayout());

How do I create a new JFrame?

I'm a complete beginner to Java, and I'm finding some answers a bit too technical for me (even the most basic tutorials seem to give me syntax errors when I run the code). How, in really simple terms do I add a JButton to a JFrame? I've got as far as:
import javax.swing.JButton;
import javax.swing.JFrame;
public class JF {
public static void main(String[] args) {
JFrame myFrame = new JFrame();
/*some pretty basic code to initialize the JFrame i.e.
myFrame.setSize(300, 200);
This is as far as I got
*/
}
}
I would seriously appreciate some help!
Creating a new JFrame
The way to create a new instance of a JFrame is pretty simple.
All you have to do is:
JFrame myFrame = new JFrame("Frame Title");
But now the Window is hidden, to see the Window you must use the setVisible(boolean flag) method. Like this:
myFrame.setVisible(true);
Adding Components
There are many ways to add a Component to a JFrame.
The simplest way is:
myFrame.getContentPane().add(new JButton());//in this case we are adding a Button
This will just add a new Component that will fill the JFrame().
If you do not want the Component to fill the screen then you should either make the ContentPane of the JFrame a new custom Container
myFrame.getContentPane() = new JPanel();
OR add a custom Container to the ContentPane and add everything else there.
JPanel mainPanel = new JPanel();
myFrame.getContentPane().add(mainPanel);
If you do not want to write the myFrame.getContentPane() every time then you could just keep an instance of the ContentPane.
JPanel pane = myFrame.getContentPane();
Basic Properties
The most basic properties of the JFrame are:
Size
Location
CloseOperation
You can either set the Size by using:
myFrame.setSize(new Dimension(300, 200));//in pixels
Or packing the JFrame after adding all the components (Better practice).
myFrame.pack();
You can set the Location by using:
myFrame.setLocation(new Point(100, 100));// starting from top left corner
Finally you can set the CloseOperation (what happens when X is pressed) by
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
There are 4 different actions that you can choose from:
DO_NOTHING_ON_CLOSE //Nothing happens
HIDE_ON_CLOSE //setVisible(false)
DISPOSE_ON_CLOSE //Closes JFrame, Application still runs
EXIT_ON_CLOSE //Closes Application
Using Event Dispatch Thread
You should initialize all GUI in Event Dispatch Thread, you can do this by simply doing:
class GUI implements Runnable {
public static void main(String[] args) {
EventQueue.invokeLater(new GUI());
}
#Override
public void run() {
JFrame myFrame = new JFrame("Frame Title");
myFrame.setLocation(new Point(100, 100));
myFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
myFrame.getContentPane().add(mainPanel);
mainPanel.add(new JButton("Button Text"), BorderLayout.CENTER);
myFrame.pack();
myFrame.setLocationByPlatform(true);
myFrame.setVisible(true);
}
}
//I hope this will help
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
public class JF extends JFrame
{
private JButton myButton;//Here you begin by declaring the button
public JF()//Here you create you constructor. Constructors are used for initializing variable
{
myButton = new JButton();//We initialize our variable
myButton.setText("My Button"); //And give it a name
JPanel panel1 = new JPanel();//In java panels are useful for holding content
panel1.add(myButton);//Here you put your button in the panel
add(panel1);//This make the panel visible together with its contents
setSize(300,400);//Set the size of your window
setVisible(true);//Make your window visible
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
JFrame frame = new JF();
frame.setTitle("My First Button");
frame.setLocation(400,200);
}
}

Change Jframe content without opening a new frame

I have a program that opens up a Jframe. inside this Jframe, I have a button that opens another class that has a Jframe too. Is there any way to to get the new class, and new gui opened in the same frame as the first one, and remove the existing content in the first frame?
This is the first class:
public class FirstFrame {
public FirstFrame() {
JFrame frame = new JFrame();
frame.setTitle("Title");
frame.setLayout(new BorderLayout());
frame.setSize(500,350);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Code for a button, that has an actionlistener wich opens the next
//class
frame.setVisible(true);
frame.setResizable(false);
}
public static void main(String[] args){
new FirstFrame();
}
}
The second class is almost like this one. The difference between the two frames is that they have different content.
When I run my program, everything works just fine, but I get two windows. Also, it says in the task manager that the two frames are running as two different programs.
Is there a way to make the content and even the name of the frame change, instead of having to deal with two different frames?
You can change the content pane of your JFrame. Let's say you have two JComponents called a and b. You initialize your frame:
JFrame frame = new JFrame();
frame.setContentPane(a);
Then you can just call
frame.setContentPane(b);
to change the content. You may also need to call revalidate and repaint to refresh the frame.
In the below example, pressing the button changes the content of JFrame from single JButton a to JLabel b. You can use any JComponent instead, such as JPanel containing multiple JComponents.
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setTitle("Title");
frame.setSize(500, 350);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton a = new JButton("button A");
frame.setContentPane(a);
frame.setVisible(true); // calling setVisible after content pane has been set to refresh a frame
a.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JComponent b = new JLabel("label B");
frame.setContentPane(b);
frame.revalidate();
}
});
}

The function of JPanel

I am working with Swing, trying to learn how to use it. I am doing an excercise in my book where I am supposed to make buttons (JButtons) like the ones a dvd-player has. I am adding no funcionality to the buttons at this point. The program worked just fine when I first ran it. Then I thought that I would expand it by making a second panel (JPanel) with the same buttons. When I run my code however, I just get one set of buttons (not two areas with two sets of buttons).
Have I misunderstood the concept of Panels? I have understood a Panel to be an area (a container) in my frame where I can display different output, and that I can have several panels i one frame.
Here is my code:
import javax.swing.*;
public class Oppgave91 extends JFrame
{
public Oppgave91()
{
super ("We make buttons");
setDefaultCloseOperation(EXIT_ON_CLOSE);
JButton play = new JButton("Play");
JButton stopeject = new JButton("Stop/Eject");
JButton rewind = new JButton("Rewind");
JButton fastforward = new JButton("FastForward");
JButton pause = new JButton("Pause");
JPanel panel = new JPanel();
panel.add(play);
panel.add(stopeject);
panel.add(rewind);
panel.add(fastforward);
panel.add(pause);
JPanel panel2 = new JPanel();
panel2.add(play);
panel2.add(stopeject);
panel2.add(rewind);
panel2.add(fastforward);
panel2.add(pause);
add(panel);
add(panel2);
setVisible(true);
}
public static void main(String[] args)
{
Oppgave91 showbuttons = new Oppgave91();
showbuttons.pack();
}
}
A component can have only 1 parent. See the last line of my code snippet for how it should be done
JPanel panel = new JPanel();
panel.add(play);
panel.add(stopeject);
panel.add(rewind);
panel.add(fastforward);
panel.add(pause);
//right now panel is the parent component of play, stop, eject
JPanel panel2 = new JPanel();
panel2.add(play); //play is now owned by panel2, not panel
panel2.add(stopeject); //stopeject is now owned by panel2, not panel
panel2.add(new JButton("Rewind")); // this is how you should do this

How do you to create a JFrame with simple text?

I just want to make a JFrame that will say "Hello world", nothing big, no interaction needed. How do I do this?
I can create the JFrame, however I do not know how to put a JPanel with simple text in it.
Here is what I got so far
JFrame frame = new JFrame("Relief Valve");
frame.setResizable(false);
frame.setLocation(500,300);
JPanel p1 = new JPanel();
frame.setVisible(true);
Instead of creating the JPanel, try:
JLabel label = new JLabel("this is my text");
frame.add(label);
frame.pack();
JFrame window = new JFrame("Hello World App");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(new BorderLayout());
window.add(new JLabel("Hello World"), BorderLayout.CENTER);
window.pack();
window.setVisible(true);
window.setLocationRelativeTo(null);
I'm currently on a mobile device but I'll be happy to document that when I get on a computer, feel free to ask any questions though.
You need to create a JLabel (witch is from Swing library) the code for that is:
JLabel label = new JLabel("Hello world");
if u want to set it to a specific loaction you need to create a render method :
public void render(Graphics g){
g.drawString(label,x,y);
}
the x and y is the position of the string with your label.
In order to create a JFrame with a simple text, you have to create a label and attach it to your frame.
Let's assume you have a JFrame created:
JFrame myFrame = new JFrame("My Frame");
Let's create the text label:
JLabel myLabel = new JLabel("Text");
To change a text of already created label:
myLabel.setText("New Text");
And eventually to clear the label:
myLabel.setText("");
Let's connect all the dots:
myFrame.add(myLabel, BorderLayout.CENTER);
myFrame.pack();
To learn more about JFrames, check: https://javatutorial.net/swing-jframe-basics-create-jframe

Categories

Resources