0
我試圖使用佈局管理器創建一個簡單的卡片顯示程序,但我仍然沒有正確使用佈局管理器的竅門。這是我的代碼,它使用BorderLayout();
作爲contentPane的佈局管理器,GridLayout();
用於buttonPanel,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
感謝您的輸入,但我得到它....在這裏做了一個愚蠢的錯誤靜態的JPanel buttonPanel =新JPanel(新的GridLayout(9,1)); //以前的FlowLayout(); static JPanel labelPanel = new JPanel(new FlowLayout()); //先前GridLayout(9,1) – 2014-12-04 07:19:28
我們都犯了愚蠢的錯誤,我的男人。你把它修好了嗎? – 2014-12-04 07:20:16
確實沒有先生,我使用的按鈕面板而不是gridlayout的flowlayout,因爲我最初寫在我的psedocode。它有趣,我沒有發現它。謝謝 – 2014-12-04 07:23:11