JFrame不会显示多个JPanel

时间:2015-01-26 03:00:18

标签: java swing background jframe jpanel

我再次研究一个简单的Java程序,但是我遇到了一些问题。我在JFrame中只有2个面板,但它只显示第二个面板。如果我删除了第二个,第一个工作。我怎么能同时拥有这两个节目?

以下是代码:

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);
}

}

请注意,此类中的大多数代码^实际上都不是活动的,因为我从我之前的程序中获取此代码。

以下是具有2个面板的类的代码

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);
}

}

帮助表示赞赏:)

1 个答案:

答案 0 :(得分:3)

您将需要了解Java Swing / AWT布局管理器,包括BorderLayout,它是顶级窗口contentPanes的默认布局。将组件添加到BorderLayout使用容器时,如果您没有指定约束,则默认情况下会将组件添加到BorderLayout.CENTER中。这意味着以这种方式添加的最后一个组件将覆盖添加到同一位置的任何其他组件。解决方案包括:

  1. 使用BorderLayout约束将组件添加到BorderLayout使用容器(此处为contentPane),以便它们转到不同的BorderLayout位置。
  2. 使用其他布局管理器,例如BoxLayout或GridBagLayout。
  3. 嵌套JPanels,每个都使用自己的布局管理器。这可以让您使用非常简单的代码创建复杂的GUI。
  4. 您可以在此处找到Swing教程的链接,包括布局管理器教程和其他Swing资源:Swing Info

    其他建议:

    • 避免设置任何尺寸。相反,让布局管理器和组件自己的首选大小设置自己的大小。
    • 您当前的代码会向用户抛出几个JFrame,这对用户来说可能有些烦人,特别是如果过度完成。而是考虑创建一个 JFrame并交换JPanel&#34;视图&#34;使用CardLayout。
    • 你有一个扩展JFrame的类,还有一个JFrame字段,其中至少有一个是冗余的。
    • 您可能通过让您的类扩展JFrame来强迫您创建和显示JFrame,而通常需要更多的灵活性。事实上,我冒昧地说,我已经创建的大部分Swing GUI代码都是扩展JFrame,事实上你很少&#39 ;我会想要这样做。更常见的是,您的GUI类将面向创建JPanels,然后可以将其放置到JFrames或JDialogs或JTabbedPanes中,或者在需要时通过CardLayouts交换。这将大大提高GUI编码的灵活性。