JFrame will not load new screen - java

I have a class that extends JFrame and works by adding in 2 panels with BoxLayout buttons, and one JTabbedPane in the center which displays graphs.
I want one of the buttons to remove all current components in the frame and add new ones.
Here are the methods used.
private void createAndShowGraphs() {
ImageIcon createImageIcon(lsuLettersPath); //simple png file to fill one tab
final JTabbedPane jtp = new JTabbedPane();
JLabel iconLabel = new JLabel();
iconLabel.setOpaque(true);
jtp.addTab(null, icon, iconLabel);
//Here is where the errors begin
JPanel menu = new JPanel();
menu.setLayout(new BoxLayout(menu, BoxLayout.Y_AXIS));
//I want this button to remove all components currently in the JFrame and replace them with new components specified in the createAndShowIntro() method
menu.add(new JButton(new AbstractAction("Intro Pane") {
public void actionPerformed(ActionEvent e) {
//I've also tried putting removeAll in the Intro method
removeAll();
createAndShowIntro();
}
}));
add(jtp, BorderLayout.CENTER);
add(menu, BorderLayout.WEST);
pack();
setVisible(true);
}
private void createAndShowIntro() {
System.out.println("Made it to Intro");
//all I want is a blank JLabel with the String "test" to show up
JPanel test = new JPanel();
test.setLayout(new BorderLayout());
JLabel label = new JLabel();
label.setText("test");
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setVerticalAlignment(SwingConstants.CENTER);
test.add(label);
add(test, BorderLayout.CENTER);
test.revalidate();
label.revalidate();
validate();
test.repaint();
label.repaint();
repaint();
pack();
setVisible(true);
}
When I call createAndShowGraphs() in main() and then hit the 'Intro' button, everything freezes and nothing is actually removed. I know it makes it the Intro method because of the "Made it to Intro" string output to the terminal.
I've tried all kinds of combinations of invalidate(), validate(), revalidate(), repaint() on the labels and on the frame itself. Really frustrated because I don't know how else I'm going to be able to display 3 different screens to switch back and forth between while only actually displaying one at a time.
Thanks for your time.

Related

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

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).

Problems with BorderLayout() in Java

I've tried a lot of different ways, but I will explain two and what was happening (no error messages or anything, just not showing up like they should or just not showing up at all):
First, I created a JPanel called layout and set it as a BorderLayout. Here is a snippet of how I made it look:
JPanel layout = new JPanel();
layout.setLayout(new BorderLayout());
colorChoice = new JLabel("Choose your color: ");
layout.add(colorChoice, BorderLayout.NORTH);
colorBox = new JComboBox(fireworkColors);
colorBox.addActionListener(this);
layout.add(colorBox, BorderLayout.NORTH);
In this scenario what happens is they don't show up at all. It just continues on with whatever else I added.
So then I just tried setLayout(new BorderLayout()); Here is a snippet of that code:
setLayout(new BorderLayout());
colorChoice = new JLabel("Choose your color: ");
add(colorChoice, BorderLayout.NORTH);
colorBox = new JComboBox(fireworkColors);
colorBox.addActionListener(this);
add(colorBox, BorderLayout.NORTH);
In this scenario they are added, however, the width takes up the entire width of the frame and the textfield (not shown in the snippet) takes up basically everything else.
Here is what I have tried:
setPreferredSize() & setSize()
Is there something else that I am missing? Thank you.
I also should note that this is a separate class and there is no main in this class. I only say this because I've extended JPanel instead of JFrame. I've seen some people extend JFrame and use JFrame, but I haven't tried it yet.
You created a JPanel, but didn't add it to any container. It won't be visible until it is added to something (a JFrame, or another panel that is in a frame somewhere up the hierarhcy)
You added two components to the same position in the BorderLayout. The last one added is the one that will occupy that position.
Update:
You do not need to extend JFrame. I never do, instead I always extend JPanel. This makes my custom components more flexible: they can be added in another panel, or they can be added to a frame.
So, to demonstrate the problem I will make an entire, small, program:
public class BadGui
{
public static void main(String[] argv)
{
final JFrame frame = new JFrame("Hello World");
final JPanel panel = new JPanel();
panel.add(new JLabel("Hello"), BorderLayout.NORTH);
panel.add(new JLabel("World"), BorderLayout.SOUTH);
frame.setVisible(true);
}
}
In this program I created a panel, but did not add it to anything so it never becomes visible.
In the next program I will fix it by adding the panel to the frame.
public class FixedGui
{
public static void main(String[] argv)
{
final JFrame frame = new JFrame("Hello World");
final JPanel panel = new JPanel();
panel.add(new JLabel("Hello"), BorderLayout.NORTH);
panel.add(new JLabel("World"), BorderLayout.SOUTH);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}
Note that in both of these, when I added something to the panel, I chose different layout parameters (one label I put in 'North' and the other in 'South').
Here is an example of a JPanel with a BorderLayout that adds a JPanel with a button and label to the "North"
public class Frames extends JFrame
{
public Frames()
{
JPanel homePanel = new JPanel(new BorderLayout());
JPanel northContainerPanel = new JPanel(new FlowLayout());
JButton yourBtn = new JButton("I Do Nothing");
JLabel yourLabel = new JLabel("I Say Stuff");
homePanel.add(northContainerPanel, BorderLayout.NORTH);
northContainerPanel.add(yourBtn);
northContainerPanel.add(yourLabel);
add(homePanel);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setTitle("Cool Stuff");
pack();
setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(Frames::new);
}
}
The below suggestion is assuming that your extending JFrame.
Testing
First of all, without seeing everything, theres always a numerous amount of things you can try.
First off, after you load everything, try adding this in (Again, assuming your extending JFrame:
revalidate();
repaint();
I add this into my own Swing projects all the time, as it refreshes and checks to see that everything is on the frame.
If that doesn't work, make sure that all your JComponent's are added to your JPanel, and ONLY your JPanel is on your JFrame. Your JFrame cannot sort everything out; the JPanel does that.
JPanel window = new JPanel();
JButton button = new JButton("Press me");
add(window);
window.add(button); // Notice how it's the JPanel that holds my components.
One thing though, you still add your JMenu's and what-not through your JFrame, not your JPanel.

Why won't my buttons appear when I run this JFrame?

I am trying to make a Rock, Paper, Scissors game and I have added 3 buttons to the frame, however when I launch the program two of the buttons don't appear until you hover over them, anyone have any idea why?
import javax.swing.*;
import java.awt.event.*;
import java.util.Random;
import java.awt.FlowLayout;
import javax.swing.JOptionPane;
public class RPSFrame extends JFrame {
public static void main(String [] args){
new RPSFrame();
}
public RPSFrame(){
JFrame Frame1 = new JFrame();
this.setSize(500,500);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Rock, Paper or Scissors game");
this.setLocationRelativeTo(null);
ClickListener cl1 = new ClickListener();
ClickListener cl2 = new ClickListener();
ClickListener cl3 = new ClickListener();
JPanel panel1 = new JPanel();
JLabel label1 = new JLabel("Result:");
panel1.setLayout(new FlowLayout(FlowLayout.CENTER, 25, 25));
this.add(panel1);
this.setVisible(false);
JPanel panel2 = new JPanel();
JButton Rock = new JButton("Rock");
Rock.addActionListener(cl1);
panel2.setLayout(new FlowLayout(FlowLayout.LEFT));
panel2.add(Rock);
this.add(panel2);
this.setVisible(true);
JPanel panel3 = new JPanel();
JButton Paper = new JButton("Paper");
Paper.addActionListener(cl2);
panel3.setLayout(new FlowLayout(FlowLayout.CENTER));
panel3.add(Paper);
this.add(panel3);
this.setVisible(true);
JPanel panel4 = new JPanel();
JButton Scissors = new JButton("Scissors");
Scissors.addActionListener(cl3);
panel4.setLayout(new FlowLayout(FlowLayout.RIGHT));
panel4.add(Scissors);
this.add(panel4);
this.setVisible(true);
}
private class ClickListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource() == "Rock"){
int AI = new Random().nextInt(3) + 1;
JOptionPane.showMessageDialog(null, "I have been clicked!");
}
}
}
}
The setVisible(true) statement should be invoked AFTER all the components have been added to the frame.
You currently have two setVisible(...) statements, so you need to get rid of the first one.
Edit:
Took a second look at the code. You have multiple setVisible(...) statements. Get rid of them all except for the last one.
Don't create separate panels for each button. Instead you create one panel (called buttonPanel) for all the buttons. In your case you might use a horizontal BoxLayout. Add a button to the panel, then add glue then add a button, then add glue and then add your final button. Then add this buttonPanel to the NORTH of the frame. ie. this.add(buttonPanel, BorderLayout.NORTH). Read the section from the Swing tutorial on How to Use Box Layout for more information on how the layout works and on what glue is.
The problem is that JFrame has a default BorderLayout. When you just add(component) without specifying a BorderLayout.[POSITION] e.g add(panel, BorderLayout.SOUTH), then the component will get added to the CENTER. The problem with that is each POSITION can only have one component. So the only component you see id the last one you add.
Now I don't know after specifying the positions, if you will get your desired result. A BorderLayout may not be the right fit. But just to see a change, you can set the layout to GridLayout(0, 1) and you will see the component.
this.setLayout(new GridLayout(0, 1));
If this is not the result you want, then you should look over Laying out Components within a Container to learn the different layouts available to you.
Also as I pointed out in my comment
if(e.getSource() == "Rock"){
with the above, you are trying to compare an object (ultimately a button) with a String. Instead you will want to compare the actionCommand
String command = e.getActionCommand();
if("Rock".equals(command)){

How to make JLabel consume space when not visible?

I have a program which creates 2 Panels and then places a label and two buttons in them. The label is set to invisible setVisible(false) and then the two buttons are added and the frame is packed. When i click the first button, the label is shown, setVisible(true), and the seccond one hides it again, setVisible(false). When i click each button, they move to fill the space of the label as it hides, and move again to get out of the way of the label as it is shown. I want to stop this from happening and have the buttons stay in the same place even when the label is hidden.
Here is the code:
public class MainFrame extends JFrame{
public JLabel statusLabel;
public JButton show;
public JButton hide;
public MainFrame(){
super("MagicLabel");
JPanel topPanel = new JPanel(); //Create Top Panel
statusLabel = new JLabel(""); //Init label
statusLabel.setVisible(false); //Hide label at startup
topPanel.setSize(400, 150); //Set the size of the panel, Doesn't work
topPanel.add(statusLabel); //Add label to panel
JPanel middlePanel = new JPanel(); //Create Middle Panel
show= new JButton("Show"); //Create show button
hide= new JButton("Hide"); //Create hide button
middlePanel.setSize(400, 50); //Set the size of the panel, Doesn't work
middlePanel.add(show); //Add show button
middlePanel.add(hide); //Add hide button
this.add(topPanel, "North"); //Add Top Panel to North
this.add(middlePanel, "Center"); //Add Middle Panel to Center
addActionListeners(); //void:adds action listeners to buttons
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(100, 100, 512, 400);
this.setPreferredSize(new Dimension(400,200)); //Set size of frame, Does work
this.pack();
this.setVisible(true);
}
public void animateInstall(boolean var0){ //Void to show and hide label from action listeners
statusLabel.setVisible(var0);
sendWorkingMessage("Boo!");
}
public void sendWorkingMessage(String message){ //Void to set text of label
this.statusLabel.setForeground(new Color(225, 225, 0));
this.statusLabel.setText(message);
}
void addActionListeners(){
show.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
animateInstall(true);
}
});
hide.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
animateInstall(false);
}
});
}
this.setPreferredSize(new Dimension(400,200));
this.setMinimumSize(new Dimension(400,200));
So pack() cannot interfere.
Use CardLayout. Add the JLabel and empty JPanel. Instead of seting it visible/invisible swap the cards showing the JLabel or the JPanel when necesary.
Extending JFrame is not advisable, better extend JPanel put all your components inside and then add it to a JFrame
You need to learn how to use SwingUtilities.invokeLater(): See example how your should look like
You need to learn about Layout: Tutorial
Very dumb and easy approach in your code would be:
this.statusLabel.setForeground(bgColor); //background color
this.statusLabel.setText(" "); //some number of characters
By default for you frame you are using BorderLayout. You can try to have like:
this.add(topPanel, BorderLayout.NORTH); //Add Top Panel to North
this.add(middlePanel, BorderLayout.SOUTH); //Add Middle Panel to South
rather than at center.
Or you can create an intermediate container panel for these 2 panels, or consider other layout managers like BoxLayout, etc

Centering JButton in BoxLayout, JTextField padding

I've created simple JDialog to gain initial data for my application. Elements (JLabel, JTextField and JButton) are arranged by BoxLayout inside the BorderLayout. (Code at the end). So far it looks like this:
I have two problems:
I would like to center JButton in it's row. I tried startBtn.setAlignmentX(Component.CENTER_ALIGNMENT);, but it doesn't work properly, mess appears.
I want to add some left/right padding to TextField. First solution from this topic works fine, but other elements are moved right left padding value.
Can anybody give a hint how to place it? I'm new to Java and have no idea.
Here's code of my InitDialog class:
public class InitDialog extends JDialog {
JTextField dataTF;
JButton startBtn;
public InitDialog(JFrame owner) {
super(owner, "Rozpocznij test", Dialog.ModalityType.DOCUMENT_MODAL);
initUI();
}
public final void initUI() {
System.out.println("InitDialog::initUI");
JPanel outer = new JPanel(new BorderLayout());
JPanel inner = new JPanel();
outer.setBorder(new EmptyBorder(new Insets(20, 20, 20, 20)));
JLabel msg = new JLabel("<html>Podaj ilości liczb w zestawach testowych<br />(przedzielone średnikiem):");
inner.add(msg);
inner.add(Box.createVerticalStrut(15));
dataTF = new JTextField();
dataTF.setBorder(null);
dataTF.setText("50; 100; 200");
inner.add(dataTF);
inner.add(Box.createVerticalStrut(15));
startBtn = new JButton("Rozpocznij test");
inner.add(startBtn);
inner.setLayout(new BoxLayout(inner, BoxLayout.Y_AXIS));
outer.add(inner);
add(outer);
setSize(300, 180);
//setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(new WindowAdapter() {
#Override public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setResizable(false);
setLocationRelativeTo(getRootPane());
}
}
BoxLayout alignment is not what you think it is.
To get what you want this is the line you need
msg.setAlignmentX(Component.CENTER_ALIGNMENT);

Categories