Java CardLayout主菜单问题

发布于 2024-11-27 00:32:07 字数 2751 浏览 2 评论 0原文

好的,我正在用 Java 开发这个名为 8 位嵌合体的游戏。我现在正在处理主菜单,但是当我使用卡片布局时,窗口由于某种原因不会打开。这是一些代码。

import javax.swing.*;
import java.awt.*;

public class MainScreen extends JFrame{

String Title = "MainMenu";
MainMenuComp MMC = new MainMenuComp();
BreedingGround BGR = new BreedingGround();

public MainScreen() {

    setTitle("8-bit Chimera "+Title);
    setSize(800,600);
    setResizable(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
    add(MMC);
    add(BGR);

}

public static void main(String[] args){

    new MainScreen();
    }
}

这是主窗口,

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MainMenuComp extends JPanel implements ActionListener{

BreedingGround BGR = new BreedingGround();
ImageData ID = new ImageData();
Image TitleBg;
Image Title;
CardLayout CL;
JButton Play;

public MainMenuComp() {

setLayout(new GridBagLayout());
GridBagConstraints GBC = new GridBagConstraints();
ImageIcon TitleData = new ImageIcon(ID.TitleSource);
ImageIcon TitleBackGroundData = new ImageIcon(ID.TitleBackGroundSource);
ImageIcon PlayData = new ImageIcon(ID.PlaySource);
TitleBg = TitleBackGroundData.getImage();
Title = TitleData.getImage();
Play = new JButton();
Play.setIcon(PlayData);
add(Play,GBC);
add(BGR,"Breed");
}

public void actionPerformed(ActionEvent AE){

    if(AE.getSource() == Play){

        CL.show(this, "Breed");
        }
    }

public void paintComponent(Graphics g){

    g.drawImage(TitleBg,0,0,800,600,this);
    g.drawImage(Title,250,80,280,140,this);
    }
}

这是卡片布局

import javax.swing.*;
import java.awt.*;

public class BreedingGround extends JPanel{

ImageData ID = new ImageData();
Image Swamp;
CardLayout CL;

public BreedingGround(){

    setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    ImageIcon SwampData = new ImageIcon(ID.SwampSource);
    Swamp = SwampData.getImage();
}

public void paintComponent(Graphics g){

    g.drawImage(Swamp,0,0,800,600,this);
    }

}

,这就是我想要 CardLayout 打开的内容。问题是,当我尝试运行它时,窗口不会运行,并且它一直显示在编译器中。

--------------------配置:8位Chimera - JDK版本1.6.0_26 - ----------------- ---

Exception in thread "main" java.lang.IllegalArgumentException: cannot add to layout: constraints must be a GridBagConstraint
    at java.awt.GridBagLayout.addLayoutComponent(GridBagLayout.java:685)
    at java.awt.Container.addImpl(Container.java:1074)
    at java.awt.Container.add(Container.java:927)
    at MainMenuComp.<init>(MainMenuComp.java:26)
    at MainScreen.<init>(MainScreen.java:7)
    at MainScreen.main(MainScreen.java:23)

过程完成。

我真正想知道的是这到底在说什么。

Ok so im working on this game in java called 8 bit chimera. Im working on the main menu right now but when im using the card layout the window wont open for some reason. Here is some code.

import javax.swing.*;
import java.awt.*;

public class MainScreen extends JFrame{

String Title = "MainMenu";
MainMenuComp MMC = new MainMenuComp();
BreedingGround BGR = new BreedingGround();

public MainScreen() {

    setTitle("8-bit Chimera "+Title);
    setSize(800,600);
    setResizable(false);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
    add(MMC);
    add(BGR);

}

public static void main(String[] args){

    new MainScreen();
    }
}

that was the Main window

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MainMenuComp extends JPanel implements ActionListener{

BreedingGround BGR = new BreedingGround();
ImageData ID = new ImageData();
Image TitleBg;
Image Title;
CardLayout CL;
JButton Play;

public MainMenuComp() {

setLayout(new GridBagLayout());
GridBagConstraints GBC = new GridBagConstraints();
ImageIcon TitleData = new ImageIcon(ID.TitleSource);
ImageIcon TitleBackGroundData = new ImageIcon(ID.TitleBackGroundSource);
ImageIcon PlayData = new ImageIcon(ID.PlaySource);
TitleBg = TitleBackGroundData.getImage();
Title = TitleData.getImage();
Play = new JButton();
Play.setIcon(PlayData);
add(Play,GBC);
add(BGR,"Breed");
}

public void actionPerformed(ActionEvent AE){

    if(AE.getSource() == Play){

        CL.show(this, "Breed");
        }
    }

public void paintComponent(Graphics g){

    g.drawImage(TitleBg,0,0,800,600,this);
    g.drawImage(Title,250,80,280,140,this);
    }
}

this was the card layout

import javax.swing.*;
import java.awt.*;

public class BreedingGround extends JPanel{

ImageData ID = new ImageData();
Image Swamp;
CardLayout CL;

public BreedingGround(){

    setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    ImageIcon SwampData = new ImageIcon(ID.SwampSource);
    Swamp = SwampData.getImage();
}

public void paintComponent(Graphics g){

    g.drawImage(Swamp,0,0,800,600,this);
    }

}

and that was what i wanted the CardLayout to open. The problem is that when i try to run it the window wont run and this keeps showing in the compiler.

--------------------Configuration: 8-bit Chimera - JDK version 1.6.0_26 - --------------------

Exception in thread "main" java.lang.IllegalArgumentException: cannot add to layout: constraints must be a GridBagConstraint
    at java.awt.GridBagLayout.addLayoutComponent(GridBagLayout.java:685)
    at java.awt.Container.addImpl(Container.java:1074)
    at java.awt.Container.add(Container.java:927)
    at MainMenuComp.<init>(MainMenuComp.java:26)
    at MainScreen.<init>(MainScreen.java:7)
    at MainScreen.main(MainScreen.java:23)

Process completed.

All i really want to know is what this is saying.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

睡美人的小仙女 2024-12-04 00:32:07

我没有看到你在哪里将容器的布局设置为 CardLayout,如果你不将布局设置为此,你就无法神奇地使用它。如果您尚未完成 CardLayout 教程,请考虑按照那里的解释进行操作。

编辑 1
亚历山大·金评论:

当我添加cardbagLayout时,它不会加载图像,并且按钮大小填满整个屏幕。我还把网格拿走了

。您需要嵌套 JPanel 才能嵌套布局。使用单个 JPanel 作为 CardLayout 容器,其唯一功能是显示其他 JPanel(“卡片”)。这些其他 JPanel 将使用正确显示它们所持有的组件所需的任何布局,例如 JButton 或“网格”(无论它们是什么)。甚至这些 JPanel 也可能包含使用其他布局的其他 JPanel。

再次,请阅读布局教程,因为那里有很好的描述。你不会后悔这样做的。

编辑2
这是一个使用 CardLayout 的非常简单的示例。 CardLayout 使用 JPanel 显示的组件(称为 cardContainer)会根据组合框中选择的项目而变化。

下面是 CardLayout 和使用它的 JPanel:

private CardLayout cardLayout = new CardLayout();

   // *** JPanel to hold the "cards" and to use the CardLayout:
   private JPanel cardContainer = new JPanel(cardLayout); 

以下是我如何使用 JPanel 将组件添加到卡片布局:

  JPanel redPanel = new JPanel();
  //...
  String red = "Red Panel";
  cardContainer.add(redPanel, red); // add the JPanel to the container with the String

我还将字符串添加到 JComboBox,以便稍后可以使用此组合框告诉 CardLayout 在用户选择项目“Red”时显示此 JPanel (redPanel)在同一个 JComboBox 中:

  cardCombo.addItem(red); // also add the String to the JComboBox

这是 JComboBox 中的 ActionListener,它允许我使用 JPanel 更改卡片布局中显示的项目:

  cardCombo.addActionListener(new ActionListener() {

     public void actionPerformed(ActionEvent e) {
        String item = cardCombo.getSelectedItem().toString();

        // *** if combo box changes it tells the CardLayout to
        // *** swap views based on the item selected in the combo box:
        cardLayout.show(cardContainer, item);
     }
  });

这是整个 shebang:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SimpleCardLayoutDemo {
   private CardLayout cardLayout = new CardLayout();

   // *** JPanel to hold the "cards" and to use the CardLayout:
   private JPanel cardContainer = new JPanel(cardLayout); 
   private JComboBox cardCombo = new JComboBox();
   private JPanel comboPanel = new JPanel();;

   public SimpleCardLayoutDemo() {
      JPanel greenPanel = new JPanel(new BorderLayout());
      greenPanel.setBackground(Color.green);
      greenPanel.add(new JScrollPane(new JTextArea(10, 25)), BorderLayout.CENTER);
      greenPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
      greenPanel.add(new JButton("Bottom Button"), BorderLayout.PAGE_END);
      String green = "Green Panel";
      cardContainer.add(greenPanel, green);
      cardCombo.addItem(green);

      JPanel redPanel = new JPanel();
      redPanel.setBackground(Color.red);
      redPanel.add(new JButton("Foo"));
      redPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
      String red = "Red Panel";
      cardContainer.add(redPanel, red);
      cardCombo.addItem(red);

      JPanel bluePanel = new JPanel();
      bluePanel.setBackground(Color.blue);
      JLabel label = new JLabel("Blue Panel", SwingConstants.CENTER);
      label.setForeground(Color.white);
      label.setFont(label.getFont().deriveFont(Font.BOLD, 32f));
      bluePanel.add(label);
      String blue = "Blue Panel";
      cardContainer.add(bluePanel, blue);
      cardCombo.addItem(blue);

      comboPanel.add(cardCombo);
      cardCombo.addActionListener(new ActionListener() {

         public void actionPerformed(ActionEvent e) {
            String item = cardCombo.getSelectedItem().toString();

            // *** if combo box changes it tells the CardLayout to
            // *** swap views based on the item selected in the combo box:
            cardLayout.show(cardContainer, item);
         }
      });
   }

   public JPanel getCardContainerPanel() {
      return cardContainer;
   }


   public Component getComboPanel() {
      return comboPanel ;
   }

   private static void createAndShowUI() {
      SimpleCardLayoutDemo simplecardDemo = new SimpleCardLayoutDemo();

      JFrame frame = new JFrame("Simple CardLayout Demo");
      frame.getContentPane().add(simplecardDemo.getCardContainerPanel(), BorderLayout.CENTER);
      frame.getContentPane().add(simplecardDemo.getComboPanel(), BorderLayout.PAGE_END);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   // to run Swing in a thread-safe way
   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}

I don't see where you ever set the layout of a container to be CardLayout, and if you don't set the layout to this, you can't magically use it. If you haven't yet gone through the CardLayout tutorial, consider doing so as it's all explained there.

Edit 1
Comment from Alexander Kim:

when i added the cardbagLayout it wont load the image and the button size filled the whole screen. I also took away the grids

You need to nest your JPanels in order to nest layouts. Use a single JPanel as the CardLayout container whose single function it is is to display other JPanels (the "cards"). These other JPanels will use whatever layouts that are necessary to properly display the components that they hold such as your JButton or "grids" (whatever they are). And even these JPanels may hold other JPanels that use other layouts.

Again, please read the layout tutorials as it's all described well there. You will not regret doing this.

Edit 2
Here's a very simple example that uses a CardLayout. The component displayed by the CardLayout using JPanel (called the cardContainer) is changed depending on which item is selected in a combobox.

Here's the CardLayout and the JPanel that uses it:

private CardLayout cardLayout = new CardLayout();

   // *** JPanel to hold the "cards" and to use the CardLayout:
   private JPanel cardContainer = new JPanel(cardLayout); 

And here's how I add a component to the cardlayout-using JPanel:

  JPanel redPanel = new JPanel();
  //...
  String red = "Red Panel";
  cardContainer.add(redPanel, red); // add the JPanel to the container with the String

I also add the String to a JComboBox so I can use this combo box later to tell the CardLayout to display this JPanel (redPanel) if the user selects the item "Red" in this same JComboBox:

  cardCombo.addItem(red); // also add the String to the JComboBox

Here's the ActionListener in the JComboBox that lets me change the item displayed in the cardlayout using JPanel:

  cardCombo.addActionListener(new ActionListener() {

     public void actionPerformed(ActionEvent e) {
        String item = cardCombo.getSelectedItem().toString();

        // *** if combo box changes it tells the CardLayout to
        // *** swap views based on the item selected in the combo box:
        cardLayout.show(cardContainer, item);
     }
  });

And here's the whole shebang:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SimpleCardLayoutDemo {
   private CardLayout cardLayout = new CardLayout();

   // *** JPanel to hold the "cards" and to use the CardLayout:
   private JPanel cardContainer = new JPanel(cardLayout); 
   private JComboBox cardCombo = new JComboBox();
   private JPanel comboPanel = new JPanel();;

   public SimpleCardLayoutDemo() {
      JPanel greenPanel = new JPanel(new BorderLayout());
      greenPanel.setBackground(Color.green);
      greenPanel.add(new JScrollPane(new JTextArea(10, 25)), BorderLayout.CENTER);
      greenPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
      greenPanel.add(new JButton("Bottom Button"), BorderLayout.PAGE_END);
      String green = "Green Panel";
      cardContainer.add(greenPanel, green);
      cardCombo.addItem(green);

      JPanel redPanel = new JPanel();
      redPanel.setBackground(Color.red);
      redPanel.add(new JButton("Foo"));
      redPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
      String red = "Red Panel";
      cardContainer.add(redPanel, red);
      cardCombo.addItem(red);

      JPanel bluePanel = new JPanel();
      bluePanel.setBackground(Color.blue);
      JLabel label = new JLabel("Blue Panel", SwingConstants.CENTER);
      label.setForeground(Color.white);
      label.setFont(label.getFont().deriveFont(Font.BOLD, 32f));
      bluePanel.add(label);
      String blue = "Blue Panel";
      cardContainer.add(bluePanel, blue);
      cardCombo.addItem(blue);

      comboPanel.add(cardCombo);
      cardCombo.addActionListener(new ActionListener() {

         public void actionPerformed(ActionEvent e) {
            String item = cardCombo.getSelectedItem().toString();

            // *** if combo box changes it tells the CardLayout to
            // *** swap views based on the item selected in the combo box:
            cardLayout.show(cardContainer, item);
         }
      });
   }

   public JPanel getCardContainerPanel() {
      return cardContainer;
   }


   public Component getComboPanel() {
      return comboPanel ;
   }

   private static void createAndShowUI() {
      SimpleCardLayoutDemo simplecardDemo = new SimpleCardLayoutDemo();

      JFrame frame = new JFrame("Simple CardLayout Demo");
      frame.getContentPane().add(simplecardDemo.getCardContainerPanel(), BorderLayout.CENTER);
      frame.getContentPane().add(simplecardDemo.getComboPanel(), BorderLayout.PAGE_END);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   // to run Swing in a thread-safe way
   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}
从来不烧饼 2024-12-04 00:32:07

您的问题在于 add(BGR,"Breed");MainMenuComp 的布局是 GridBagLayout,因此约束必须是 GridBagConstraint,而不是 String(您有“品种” 作为约束)。

Your problem is with add(BGR,"Breed");. The layout of MainMenuComp is a GridBagLayout, so the constraint must be a GridBagConstraint, not a String (you have "Breed" as the constraint).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文