我正在尝试使用布局管理器创建一个简单的卡片显示程序,但我仍然无法正确使用布局管理器。这是我的代码,它使用BorderLayout();
作为contentPane的布局管理器,使用button {GridLayout();
作为cardPanel,CardLayout();
作为cardPanel,FlowLayout();
作为labelPanel。
public class TestClass // implements ActionListener
{
static JPanel content = new JPanel(new BorderLayout());
static JPanel cardPanel = new JPanel();
static CardLayout cardLayout;
static JPanel buttonPanel = new JPanel(new FlowLayout());
static JPanel labelPanel = new JPanel(new GridLayout(9,1));
static JButton jack, king, queen, ace;
static JButton first, last, prev, next;
public static void main(String[] args) {
JFrame window = new JFrame("Window");
//------Creates the Label Panel --//
JLabel label = new JLabel("SELECT A CARD");
label.setFont(new Font("Georgia",Font.BOLD,18));
labelPanel.add(label, FlowLayout.LEFT);
//-----Creates the Button Panel --//
jack = new JButton("Jack");
queen = new JButton("Queen");
king = new JButton("King");
ace = new JButton("Ace");
first = new JButton("First");
last = new JButton("Last");
prev = new JButton("Previous");
next = new JButton("Next");
JLabel sep = new JLabel("-------");
buttonPanel.add(jack);
buttonPanel.add(queen);
buttonPanel.add(king);
buttonPanel.add(ace);
buttonPanel.add(sep);
buttonPanel.add(first);
buttonPanel.add(last);
buttonPanel.add(prev);
buttonPanel.add(next);
//-------Creates the cardPanel --//
JLabel card1 = new JLabel("JACK");
JLabel card2 = new JLabel("QUEEN");
JLabel card3 = new JLabel("KING");
JLabel card4 = new JLabel("ACE");
cardPanel.add(card1, "jack");
cardPanel.add(card2, "queen");
cardPanel.add(card3, "king");
cardPanel.add(card4, "ace");
cardPanel.setLayout(cardLayout = new CardLayout());
cardLayout.first(cardPanel);
// ----- Adds the panels to the contentPane ---//
content.add(labelPanel, BorderLayout.NORTH);
content.add(buttonPanel, BorderLayout.WEST);
content.add(cardPanel, BorderLayout.CENTER);
window.setContentPane(content);
window.setLocation(300,100);
window.pack();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
window.setResizable(true);
}
}
但是输出并不像预期的那样。我希望左上角的标签,左边的按钮(使用网格布局),然后是中心的cardLabel。
编辑:问题解决了,我犯了一个愚蠢的错误
static JPanel buttonPanel = new JPanel(new GridLayout(9,1)); //previously FlowLayout
static JPanel labelPanel = new JPanel(new FlowLayout()); //previously GridLayout
答案 0 :(得分:1)
您的网格布局(labelPanel)中唯一的内容是:
JLabel label = new JLabel("SELECT A CARD");
其他所有内容都在buttonPanel中,这是一个流程布局。
检查出来:https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html