How to display one Jframe at a time? [duplicate] - java

I'm trying to make a little game that will first show the player a simple login screen where they can enter their name (I will need it later to store their game state info), let them pick a difficulty level etc, and will only show the main game screen once the player has clicked the play button. I'd also like to allow the player to navigate to a (hopefully for them rather large) trophy collection, likewise in what will appear to them to be a new screen.
So far I have a main game window with a grid layout and a game in it that works (Yay for me!). Now I want to add the above functionality.
How do I go about doing this? I don't think I want to go the multiple JFrame route as I only want one icon visible in the taskbar at a time (or would setting their visibility to false effect the icon too?) Do I instead make and destroy layouts or panels or something like that?
What are my options? How can I control what content is being displayed? Especially given my newbie skills?

A simple modal dialog such as a JDialog should work well here. The main GUI which will likely be a JFrame can be invisible when the dialog is called, and then set to visible (assuming that the log-on was successful) once the dialog completes. If the dialog is modal, you'll know exactly when the user has closed the dialog as the code will continue right after the line where you call setVisible(true) on the dialog. Note that the GUI held by a JDialog can be every bit as complex and rich as that held by a JFrame.
Another option is to use one GUI/JFrame but swap views (JPanels) in the main GUI via a CardLayout. This could work quite well and is easy to implement. Check out the CardLayout tutorial for more.
Oh, and welcome to stackoverflow.com!

Here is an example of a Login Dialog as #HovercraftFullOfEels suggested.
Username: stackoverflow Password: stackoverflow
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
public class TestFrame extends JFrame {
private PassWordDialog passDialog;
public TestFrame() {
passDialog = new PassWordDialog(this, true);
passDialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new TestFrame();
frame.getContentPane().setBackground(Color.BLACK);
frame.setTitle("Logged In");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
});
}
}
class PassWordDialog extends JDialog {
private final JLabel jlblUsername = new JLabel("Username");
private final JLabel jlblPassword = new JLabel("Password");
private final JTextField jtfUsername = new JTextField(15);
private final JPasswordField jpfPassword = new JPasswordField();
private final JButton jbtOk = new JButton("Login");
private final JButton jbtCancel = new JButton("Cancel");
private final JLabel jlblStatus = new JLabel(" ");
public PassWordDialog() {
this(null, true);
}
public PassWordDialog(final JFrame parent, boolean modal) {
super(parent, modal);
JPanel p3 = new JPanel(new GridLayout(2, 1));
p3.add(jlblUsername);
p3.add(jlblPassword);
JPanel p4 = new JPanel(new GridLayout(2, 1));
p4.add(jtfUsername);
p4.add(jpfPassword);
JPanel p1 = new JPanel();
p1.add(p3);
p1.add(p4);
JPanel p2 = new JPanel();
p2.add(jbtOk);
p2.add(jbtCancel);
JPanel p5 = new JPanel(new BorderLayout());
p5.add(p2, BorderLayout.CENTER);
p5.add(jlblStatus, BorderLayout.NORTH);
jlblStatus.setForeground(Color.RED);
jlblStatus.setHorizontalAlignment(SwingConstants.CENTER);
setLayout(new BorderLayout());
add(p1, BorderLayout.CENTER);
add(p5, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
jbtOk.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (Arrays.equals("stackoverflow".toCharArray(), jpfPassword.getPassword())
&& "stackoverflow".equals(jtfUsername.getText())) {
parent.setVisible(true);
setVisible(false);
} else {
jlblStatus.setText("Invalid username or password");
}
}
});
jbtCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
parent.dispose();
System.exit(0);
}
});
}
}

I suggest you insert the following code:
JFrame f = new JFrame();
JTextField text = new JTextField(15); //the 15 sets the size of the text field
JPanel p = new JPanel();
JButton b = new JButton("Login");
f.add(p); //so you can add more stuff to the JFrame
f.setSize(250,150);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Insert that when you want to add the stuff in. Next we will add all the stuff to the JPanel:
p.add(text);
p.add(b);
Now we add the ActionListeners to make the JButtons to work:
b.addActionListener(this);
public void actionPerforemed(ActionEvent e)
{
//Get the text of the JTextField
String TEXT = text.getText();
}
Don't forget to import the following if you haven't already:
import java.awt.event*;
import java.awt.*; //Just in case we need it
import java.x.swing.*;
I hope everything i said makes sense, because sometimes i don't (especially when I'm talking coding/Java) All the importing (if you didn't know) goes at the top of your code.

Instead of adding the game directly to JFrame, you can add your content to JPanel (let's call it GamePanel) and add this panel to the frame. Do the same thing for login screen: add all content to JPanel (LoginPanel) and add it to frame. When your game will start, you should do the following:
Add LoginPanel to frame
Get user input and load it's details
Add GamePanel and destroy LoginPanel (since it will be quite fast to re-create new one, so you don't need to keep it memory).

Related

How to Add text to JTextArea

Im creating a programme using java. I want the user to enter some text, then push the button so the text entered shows in the label. However, I have 2 problems. First, the text are isn´t displaying when I execute the app. Second, I don´t know how to allow the user to type in the area. Im new in java so that´s why Im asking. Here is the code. Thank you.
import javax.swing.*;
import java.awt.event.*;
class Boton extends JFrame implements ActionListener {
JButton boton;
JTextArea textArea = new JTextArea();
JLabel etiqueta = new JLabel();
public Boton() {
setLayout(null);
boton = new JButton("Escribir");
boton.setBounds(100, 150, 100, 30);
boton.addActionListener(this);
add(boton);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == boton) {
try {
String texto = textArea.getText();
etiqueta.setText(texto);
Thread.sleep(3000);
System.exit(0);
} catch (Exception excep) {
System.exit(0);
}
}
}
}
public class Main{
public static void main(String[] ar) {
Boton boton1 =new Boton();
boton1.setBounds(0,0,450,350);
boton1.setVisible(true);
boton1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Problems:
You never add the JTextArea into your GUI, and if it doesn't show, a user cannot directly interact with it.
You are calling Thread.sleep on the Swing event thread, and this will put the entire application to sleep, meaning the text that you added will not show.
Other issues include use of null layouts and setBounds -- avoid doing this.
Solutions:
Set the JTextArea's column and row properties so that it sizes well.
Since your JTextArea's text is going into a JLabel, a component that only allows a single line of text, I wonder if you should be using a JTextArea at all. Perhaps a JTextField would work better since it allows user input but only one line of text.
Add the JTextArea to a JScrollPane (its viewport actually) and add that to your GUI. Then the user can interact directly with it. This is most easily done by passing the JTextArea into a JScrollPane's constructor.
Get rid of the Thread.sleep and instead, if you want to use a delay, use a Swing Timer. check out the tutorial here
For example:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Window;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class Main2 {
public static void main(String[] args) {
// create GUI in a thread-safe manner
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
BotonExample mainPanel = new BotonExample();
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
class BotonExample extends JPanel {
private JLabel etiqueta = new JLabel(" ");
private JButton boton = new JButton("Escribir");
// jtext area rows and column properties
private int rows = 5;
private int columns = 30;
private JTextArea textArea = new JTextArea(rows, columns);
public BotonExample() {
// alt-e will activate button
boton.setMnemonic(KeyEvent.VK_E);
boton.addActionListener(e -> {
boton.setEnabled(false); // prevent button from re-activating
String text = textArea.getText();
etiqueta.setText(text);
// delay for timer
int delay = 3000;
Timer timer = new Timer(delay, e2 -> {
// get current window and dispose ofit
Window window = SwingUtilities.getWindowAncestor(boton);
window.dispose();
});
timer.setRepeats(false);
timer.start(); // start timer
});
// create JPanels to add to GUI
JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 5, 5));
topPanel.add(new JLabel("Etiqueta:"));
topPanel.add(etiqueta);
JPanel bottomPanel = new JPanel();
bottomPanel.add(boton);
JScrollPane scrollPane = new JScrollPane(textArea);
// use layout manager and add components
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
}
textarea.setText("Text"); // this will insert text into the text area
textarea.setVisable(true); // this will display the text area so you can type in it
textarea.setSize(500,500); // set size of the textarea so it actually shows
The user should be able to type in the TA when it is displayed and just do a getText to pull the text

How to use buttons to switch to a specific JPanel?

Instead of going to the next panel using JPanel().next and JPanel().previous I'd like to switch to a specific panel using a button.
Say I have 3 pages, by using the button labelled 'Go to page 3', it will take me to a panel I have created for page 3; and on that page I'd have more buttons that would take me back to page 1, or page 2 even. Say if I had a tenth page, a button could take me straight to it and I wouldn't have to click a next button.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/* Here we are first declaring our class that will act as the
* base for other panels or in other terms the base for CardLayout.
*/
public class CardLayoutExample
{
private static final String CARD_JBUTTON = "Card JButton";
private static final String CARD_JTEXTFIELD = "Card JTextField";
private static final String CARD_JRADIOBUTTON = "Card JRadioButton";
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Card Layout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
// This JPanel is the base for CardLayout for other JPanels.
final JPanel contentPane = new JPanel();
contentPane.setLayout(new CardLayout(20, 20));
/* Here we are making objects of the Window Series classes
* so that, each one of them can be added to the JPanel
* having CardLayout.
*/
Window1 win1 = new Window1();
contentPane.add(win1, CARD_JBUTTON);
Window2 win2 = new Window2();
contentPane.add(win2, CARD_JTEXTFIELD);
Window3 win3 = new Window3();
contentPane.add(win3, CARD_JRADIOBUTTON);
/* We need two JButtons to go to the next Card
* or come back to the previous Card, as and when
* desired by the User.
*/
JPanel buttonPanel = new JPanel();
final JButton page1Button = new JButton("Go to page 1");
final JButton page5Button = new JButton("Go to Page 5");
final JButton page10Button = new JButton("Go to Page 10");
buttonPanel.add(page1Button);
buttonPanel.add(page5Button);
buttonPanel.add(page10Button);
/* Adding the ActionListeners to the JButton,
* so that the user can see the next Card or
* come back to the previous Card, as desired.
*/
page1Button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.previous(contentPane);
}
});
page5Button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.next(contentPane);
}
});
//page10Button.addActionListener(new ActionListener();
//Code to navigate to page 10...
// Adding the contentPane (JPanel) and buttonPanel to JFrame.
frame.add(contentPane, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
I have my methods set up for when I click a button, but it only navigates to the next page, not the one I want.
What other alternatives of .next and .previous are there? I want to go to a specific page.
Thanks for your help.
When adding to a card layout, you can specify a "key" that you can reference later when attempting to show a specific panel.
The sample below should get you started:
CardLayout myCardLayout = new CardLayout();
JPanel myCardLayoutPanel = new JPanel(myCardLayout);
myCardLayoutPanel.add(myComponent, "A_KEY");
myCardLayout.show(myCardLayoutPanel,"A_KEY");
Additionally you should check out the docs

Java - How to make contents of JFrame appear in the same Window instead of multiple windows

I am new to java and am getting to the advanced level of it, i have a problem in the GUI Controls, i made a button that when clicked opens up a new window like this:
JButton b = new JButton("Open New Window");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Window w = new Window();
w.setVisible(true);
}
});
this window contains other objects but i have been thinking of making the button in such a way that instead of opening a new JFrame, it opens everything in that same window without opening a new window, honestly i dont know how to do so please could i get some professional help
I think you want a card layout for this situation. Here is some code which should point you in the right direction.
class MyFrame extends JFrame {
public MyFrame() {
JComponent allMyStuff = new JComponent();
JComponent allMyOtherStuff = new JComponent();
this.getContentPane().setLayout(new CardLayout());
this.getContentPane().add(allMyStuff, "1");
this.getContentPane().add(allMyOtherStuff, "2");
CardLayout cl = (CardLayout) (this.getContentPane().getLayout());
cl.show(this.getContentPane(), "1");
JButton b = new JButton("Open New Window"); //add somewhere to first compoonent
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout) (this.getContentPane().getLayout());
cl.show(this.getContentPane(), "2");
}
});
}
}
I doubt the code runs but generally it holds the idea. You have stuff in one panel, and stuff in another panel, and you just want to switch between the two. The button of course needs to be added in the first panel (allMyStuff) somewhere.
I"m not clear on what it is exactly that you want to show in the GUI when the button is pressed, but perhaps you should consider creating different JPanel "views" and swap these views in the GUI using a CardLayout.
For example, check out these StackOverflow questions and answers:
Java CardLayout Main Menu Problem
Change size of JPanel using CardLayout
Java CardLayout JPanel moves up, when second JPanel added
Java swing; How to toggle panel's visibility?
Clear components of JFrame and add new componets on the same JFrame
gui multiple frames switch
JLabel displaying countdown, java
Within the action listener that you have introduced, you have the possibility to access to instance variables. Therefore you can add further elements to your GUI if you want. I've done a small demo, maybe this is kind of, what you want to do. In order to make your GUI better, you should consider of using layout managers.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class GUI {
JFrame frame;
JButton btn;
JButton compToAdd;
public GUI() {
frame = new JFrame("Testwindow");
frame.setSize(500, 500);
frame.setLayout(null);
btn = new JButton("test btn");
btn.setBounds(20, 20, 200, 200);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
compToAdd = new JButton("new Button");
compToAdd.setBounds(20, 220, 200, 200);
frame.add(compToAdd);
frame.repaint();
}
});
frame.add(btn);
frame.setVisible(true);
}
public static void main(String[] args) {
GUI gui = new GUI();
}
}

is it possible to point to a particular JPanel

I have this program in which I'm using CardLayout. I have different panels with different attributes. I have a button called "Enter" that I decided to reuse on every panel, however each panel performs a different operation when the button is clicked. Is there a way to say, when button is clicked but I am at a specific panel, then do this. How can I point directly to a panel?
First thing you must consider is: You can't add one button to many panels, every panel should have it's own component(s).
If you add one button to many panels say :
JButton b = new JButton("Button");
//....
pan1.add(b);
pan2.add(b);
pan3.add(b);
In such case, the button will be added to the last panel means pan3, the other won't show the button.
Second, I would like to mention a #trashgod's good example from comments, and also in case confusing, look at this example:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class CardLayoutDemo extends JFrame implements ActionListener {
private CardLayout cardLayout;
private JButton pan1,pan2;
private JPanel mainPanel;
public CardLayoutDemo(){
cardLayout = new CardLayout();
mainPanel = new JPanel(cardLayout);
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
pan1 = new JButton("To Second Panel");
pan2= new JButton ("To First Panel");
pan1.addActionListener(this);
pan2.addActionListener(this);
p1.setBackground(Color.green);
p2.setBackground(Color.BLUE.brighter());
p1.add(pan1);
p2.add(pan2);
mainPanel.add(p1,"1");
mainPanel.add(p2,"2");
cardLayout.show(mainPanel, "1");
add(mainPanel);
setDefaultCloseOperation(3);
setLocationRelativeTo(null);
setVisible(true);
pack();
}
#Override
public void actionPerformed(ActionEvent ev){
if(ev.getSource()==pan1)
cardLayout.show(mainPanel, "2");
else if(ev.getSource()==pan2)
cardLayout.show(mainPanel, "1");
}
public static void main(String...args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new CardLayoutDemo().setVisible(true);
}
});
}
}
You can let the panel assign an ActionListener to the button each time the card is created. That way the constructor for a specific panel can determine what the functionality of the button will be.

Using Actionlistener to create new frame with JRadioButtons

Hi I'm having some trouble creating an actionlistener which creates a new frame with JRadioButtons used as selections.
Ultimately it will be a flashcard quiz program I am creating for fun.
Here's what where I am stuck:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class FlashCard extends JFrame {
private ImageIcon myIcon = new ImageIcon("src/Resources/DNA.png");
public FlashCard(){
//Consider using CardLayout format for flashcards.
setLayout(new GridLayout(1, 4, 5, 5));
JButton startButton = new JButton("Begin");
add(startButton);
startButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
//Execute when button is pressed THIS IS THE PART WHERE I AM STUCK
JFrame frameAction = new JFrame();
frameAction.setTitle("Questions");
frameAction.setSize(350, 150);
frameAction.setLocationRelativeTo(null);
frameAction.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frameAction.setVisible(true);
frameAction.
// JRadioButton jrb1 = new JRadioButton("Student", true);
// jrb1.setForeground(Color.RED);
// jrb1.setBackground(Color.WHITE);
// jrb1.setMnemonic('S');
//
// ButtonGroup group = new ButtonGroup();
// add(jrb1);
}
});
}
and here is my main method:
public static void main(String[] args){
//Create a frame and set its properties.
JFrame frame = new FlashCard();
frame.setTitle("Genetics FlashCard Quiz");
frame.setSize(350,150);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
//Create a second frame for when the user
// clicks begin.
JFrame question = new JFrame();
}
Given that both your JFrames are the same size & dimensions, your other idea (in the code) of using CardLayout was the correct one. Currently your 2nd frame appears over the first giving you the overhead of managing the latter as it is still accessible. If you use CardLayout you will be able to easily navigate between multiple flashcard panels while maintaining a single interaction area for the user.
See:
How to Use CardLayout
CardLayout Example

Categories