Graysull
Graysull

Reputation: 109

JFrame Won't Display Multiple JPanels

once again I am working on a simple Java program and I have some problems. I have only 2 panels in a JFrame, but it will only show the second one. If I removed the second one, the first one works. How can I have these two show at the same time?

Here is the code:

package counter.main;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.net.URL;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Main extends JFrame {

public static JTextField fieldName;
private JLabel labelMessage;
private JButton buttonSubmit;
private JButton buttonDerp;
private JLabel derps;
private JLabel space1;
private JLabel space2;
private JLabel space3;
private JLabel askName;
private JLabel space4;
int clicks = 0;
File MarioCoin;

//Key to access automatic "system crash" - keyDerp134
//Note - Keys are extremely useful when wanting to bypass a type of task and debugging.

JFrame frame = new JFrame("Enter Your Name");
public Main() {
    createView();

    setTitle("Enter your name");
    setSize(500, 100);
    setResizable(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    revalidate();
    repaint();
} 

private void createView() {
    final JPanel panel = new JPanel();
    getContentPane().add(panel);
    panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 20));

    space1 = new JLabel("                ");
    space2 = new JLabel("                      ");
    space3 = new JLabel("                      ");
    space4 = new JLabel("            ");

    askName = new JLabel("Please enter your name");
    panel.add(askName);

    derps = new JLabel("0/100 Derps");
    derps.setFont(new Font( "Arial", Font.PLAIN, 18));

    fieldName = new JTextField();
    fieldName.setPreferredSize(new Dimension(150, 30));
    panel.add(fieldName);

    buttonSubmit = new JButton("Submit");
    buttonSubmit.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String derpKey = "keyDerp134";
            String name = fieldName.getText();
            if(name.isEmpty()) {
                labelMessage.setText("Your name can't be nothing, now can it?");
                setSize(500, 135);
            } else {
                askName.setText("                      Hi, " + name + ".");
                SelectionFrame.select.setText("Select Your Material, " + name + ".");
                setSize(500, 100);
                try {
                    Thread.sleep(1000);   
                } catch(InterruptedException ex) {
                    Thread.currentThread().interrupt();
                }
                    if (name.equals(derpKey)) { 
                    clicks = 101;
                    updateCounter();
                }
                SelectionFrame.frame1.setVisible(true);    
                setVisible(false);
                buttonSubmit.setEnabled(false);
                fieldName.setEnabled(false);
                labelMessage.setText("                  " + name + ", Click -->");
                setTitle("Collect 100 Derps!");
                revalidate();
                repaint();
                buttonDerp = new JButton("Derp");
                buttonDerp.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        clicks++;
                        updateCounter();
                        URL soundURL = Main.class.getResource("/counter/main/MarioCoin.wav");
                        try {
                            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundURL);
                            Clip clip = AudioSystem.getClip();
                            clip.open(audioInputStream);
                            clip.start();
                            if (clicks >= 100) {
                                clip.stop();
                                buttonDerp.setEnabled(false);
                            }
                        } catch (IOException | UnsupportedAudioFileException | LineUnavailableException x) {
                            x.printStackTrace();
                        }
                    }
                }); 

        panel.add(buttonDerp);
        panel.add(derps);
        panel.add(space4);


        }
    }}); 
    panel.add(buttonSubmit);
    panel.add(space1);

    labelMessage = new JLabel("");
    panel.add(labelMessage);
    pack();
}

public static void main(String[] args) { 
    new Main();
    SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        new Main().setVisible(true);
        new CrashReportFrame();
        new SelectionFrame();
    }
});
}


public void updateCounter() {
    derps.setText(clicks + "/100 Derps");
    if (clicks >= 1 && clicks < 10) {
        labelMessage.setText("               Keep Going!");
    }

    if (clicks >= 10 && clicks < 50) {
        labelMessage.setText("     Keep 'em Comin'!");
    }

    if (clicks >= 50 && clicks < 70) {
        labelMessage.setText("                       Okay...");
    }

    if (clicks >= 70 && clicks < 80) {
        labelMessage.setText("  Slow down a little");
    }

    if (clicks >= 80 && clicks < 90) {
        labelMessage.setText("               Slow down, " + fieldName.getText() + "!");
    }

    if (clicks >= 90 && clicks < 100) {
        labelMessage.setText("    Stop! The system-");
    }

    if (clicks >= 100) {
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        try {
            Thread.sleep(3000);                 //1000 milliseconds is one second.
        } catch(InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
        setVisible(false);
        JOptionPane.showMessageDialog(null, "You Crashed The System!");
        //CrashReportFrame.frame2.setVisible(true);
    }
}



public void paint(Graphics g) {
    super.paint(g);
}

}

Note that most of the code within this class ^ is actually not active, as I am taking this from a previous program of mine.

Here is the code for the class with the 2 panels

package counter.main;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class SelectionFrame extends JFrame {

public static JLabel select = new JLabel("");
private JButton stone;
private JButton wood;
private JButton coin;
private JButton food;

static JFrame frame1 = new JFrame("Select Your Material");
public SelectionFrame() {
    createView();

    frame1.setTitle("Select Your Material");
    frame1.setResizable(false);
    frame1.setDefaultCloseOperation(EXIT_ON_CLOSE);
    frame1.setSize(400, 120);
    frame1.setLocationRelativeTo(null);

}

private void createView() {

    frame1.getContentPane().setBackground(Color.black);
    frame1.repaint();

    JPanel panel3 = new JPanel();
    frame1.getContentPane().add(panel3);
    panel3.setLayout(new FlowLayout(FlowLayout.CENTER));

    JPanel panel4 = new JPanel();
    frame1.getContentPane().add(panel4);
    panel4.setLayout(new FlowLayout(FlowLayout.CENTER, 25, 55));

    select.setFont(new Font( "Dialog", Font.PLAIN, 18));
    panel3.add(select);

    stone = new JButton("Stone");
    panel4.add(stone);

    wood = new JButton("Wood");
    panel4.add(wood);

    coin = new JButton("Coin");
    panel4.add(coin);

    food = new JButton("Food");
    panel4.add(food);

    frame1.revalidate();
    frame1.repaint();

}

    public void paint(Graphics g3) {
    super.paint(g3);
}

}

Help is appreciated :)

Upvotes: 1

Views: 786

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

You will want to learn about the Java Swing/AWT layout managers including the BorderLayout which is the default layout for top level window contentPanes. When adding a component to a BorderLayout-using container, if you don't specify a constraint, then by default the component is added BorderLayout.CENTER. This means that the last component added this way will cover any other components added to the same position. Solutions include:

  1. Adding components to your BorderLayout-using container (the contentPane here) using BorderLayout constraints so that they go to different BorderLayout positions.
  2. Using a different layout manager such as a BoxLayout or GridBagLayout.
  3. Nesting JPanels, each using its own layout manager. This could allow you to create complex GUI's with pretty simple code.

You can find links to the Swing tutorials including the layout manager tutorials and other Swing resources here: Swing Info

Other suggestions:

  • Avoid setting the sizes of anything. Instead let the layout managers and the component's own preferred sizes set their own sizes.
  • Your current code throws several JFrames at the user, and this can be somewhat annoying to the user, especially if over done. Instead consider creating one JFrame and swapping JPanel "views" using a CardLayout.
  • You have a class that extends JFrame and also has a JFrame field, with at least one of these guys being redundant.
  • You may be painting yourself in a corner by having your class extend JFrame, forcing you to create and display JFrames, when often more flexibility is called for. In fact, I would venture that most of the Swing GUI code that I've created and that I've seen does not extend JFrame, and in fact it is rare that you'll ever want to do this. More commonly your GUI classes will be geared towards creating JPanels, which can then be placed into JFrames or JDialogs, or JTabbedPanes, or swapped via CardLayouts, wherever needed. This will greatly increase the flexibility of your GUI coding.

Upvotes: 3

Related Questions