我制作了两个面板,然后在第三个面板中添加。如何添加面板以显示在屏幕上?
这是我目前的代码:
import javax.swing.*;
import java.awt.*;
public class LibraryFront {
public static void main(String[] args)
{
JFrame f1 = new JFrame();
JPanel cards;
final String BUTTONPANEL = "Card with JButtons";
final String TEXTPANEL = "Card with JTextField";
JPanel card1 = new JPanel();
JPanel card2 = new JPanel();
// Create the panel that contains the "cards".
cards = new JPanel(new CardLayout());
cards.add(card1, BUTTONPANEL);
cards.add(card2, TEXTPANEL);
Container c = getContentPane(); //this gives error
}
答案 0 :(得分:1)
LibraryFront不是容器。 JFrame
f1是,f1.getContentPane()
应该可以使用,您还需要将面板添加到JFrame并将其设置为可见(如果不可见)。
答案 1 :(得分:1)
修改强>
我现在注意到您从http://download.oracle.com/javase/tutorial/uiswing/layout/card.html获取了代码段(部分)并将其直接放入主方法中。该代码只是CardLayoutDemo.java完整计划实施的一部分。您需要查看该代码。
您的代码存在很多小错误。这是一个有效的实现
//it is good practice to only import the packages you need
//so that you know exactly what you are dealing with
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LibraryFront {
public static void main(String[] args) {
//f1 is the JFrame
//f1.getContentPane() would return the Container
//but you do not actually need to add directly to it
JFrame f1 = new JFrame();
JPanel cards;
final String BUTTONPANEL = "Card with JButtons";
final String TEXTPANEL = "Card with JTextField";
JPanel card1 = new JPanel();
JPanel card2 = new JPanel();
// Create the panel that contains the "cards".
cards = new JPanel(new CardLayout());
cards.add(card1, BUTTONPANEL);
cards.add(card2, TEXTPANEL);
//adjust background colors just so you can see what is happening
cards.setBackground(Color.GREEN);
card1.setBackground(Color.RED);
card2.setBackground(Color.BLUE);
//set the layout to BorderLayout
// add the cards JPanel to the center
f1.setLayout(new BorderLayout());
f1.add(cards, BorderLayout.CENTER);
f1.setSize(400, 300);
f1.setTitle("Test Frame");
f1.setVisible(true);
}
}
答案 2 :(得分:0)
尝试:
Container c = f1.getContentPane();
在JFrame
上调用该方法,而不是在您自己的LibraryFront
班级。
答案 3 :(得分:0)
它会给您一个错误,因为您的班级LibraryFront
不包含getContentPane()
方法。而是在框架上调用该方法。
做类似的事情:
f1.getContentPane().add(cards);