我最近開始Java編程,正在嘗試創建登錄屏幕。但是,我無法弄清楚如何創建一個新行來放置我的按鈕和文本。另外,我想將它們移到JPanel的右下角。我爲我可憐的措辭表示歉意,希望你能從我的代碼中看到我的意思。請提前幫助並感謝您。將按鈕和文本放在新行上並將它們移動到java屏幕的底部
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutDemo implements ItemListener {
JPanel cards;
final static String BUTTONPANEL = "Card with JButtons";
public void addComponentToPane(Container pane) {
JPanel card1 = new JPanel();
card1.add(new JLabel("Username:"));
card1.add(new JTextField("Username", 10));
card1.add(new JButton("Login")); //end line here
//New line
card1.add(new JLabel("Password:"));
card1.add(new JTextField("Password", 10));
card1.add(new JButton("Register")); //end line here
//New line
card1.add(new JCheckBox());
card1.add(new JLabel("Remember credentials"));
cards = new JPanel(new CardLayout());
cards.add(card1, BUTTONPANEL);
pane.add(cards, BorderLayout.BOTTOM_RIGHT);// Add cards to bottom right hand corner.
}
public void itemStateChanged(ItemEvent evt) {
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, (String)evt.getItem());
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Login");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CardLayoutDemo demo = new CardLayoutDemo();
demo.addComponentToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
UIManager.put("swing.boldMetal", Boolean.FALSE);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
這不會在我的Java 6系統上編譯; BorderLayout.BOTTOM_RIGHT無法識別。如果我將BOTTOM_RIGHT更改爲PAGE_END,我會將您的控件置於屏幕的底部,以框架爲中心。不幸的是,我不能確定你想要什麼,而你的代碼只有你所做的,而不是你想做的。你想在不同的行上輸入用戶名和密碼嗎? – arcy
我知道BOTTOM_RIGHT不是一個正確的命令,我只是用它作爲例子。是的,你擊中了頭部,這正是我想要的。 – DIOS
+1更新和[sscce](http://sscce.org/),模仿@rcook評論。 – trashgod