Я не вижу, где вы когда-либо устанавливали макет контейнера как CardLayout, и если вы не установите макет на это, вы не сможете волшебным образом использовать его.Если вы еще не прошли учебник CardLayout , подумайте об этом, поскольку все там объяснено.
Редактировать 1
Комментарий Александра Кима:
когда я добавил cardbagLayout, он не будет загружать изображение, а размер кнопки заполняет весь экран.Я также убрал сетки
Вам нужно вложить свои JPanels, чтобы вложить макеты.Используйте один JPanel в качестве контейнера CardLayout, единственной функцией которого является отображение других JPanel («карт»).Эти другие JPanels будут использовать любые макеты, которые необходимы для правильного отображения компонентов, которые они содержат, таких как ваш JButton или «сетки» (какими бы они ни были).И даже эти JPanels могут содержать другие JPanels, которые используют другие макеты.
Опять же, пожалуйста, прочитайте учебники по макету, так как там все хорошо описано.Вы не пожалеете об этом.
Edit 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
Я также добавляю String к JComboBox, чтобы я мог использоватьэто поле со списком позже, чтобы указать CardLayout отображать этот JPanel (redPanel), если пользователь выбирает элемент «Red» в этом же JComboBox:
cardCombo.addItem(red); // also add the String to the JComboBox
Вот ActionListener в JComboBox, который позволяет мне изменить элементотображается в карточной раскладке с использованием 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);
}
});
А вот и весь шебанг:
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();
}
});
}
}