我创建了这个脚本。我的问题是我想结束一行并继续下一行。我在这段特定的代码中使用了 flowlayout,并尝试了其他布局,例如网格,但没有占上风。请帮助,非常感谢示例,并在此先感谢您。这是我的代码:
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(new FlowLayout(FlowLayout.RIGHT));
card1.add(new JLabel("Username:"));
card1.add(new JTextField("Username", 10));
card1.add(new JButton("Login")); //end line here
card1.add(new JLabel("Password:"));
card1.add(new JTextField("Password", 10));
card1.add(new JButton("Register")); //end line here
card1.add(new JCheckBox());
card1.add(new JLabel("Remember credentials"));
cards = new JPanel(new CardLayout());
cards.add(card1, BUTTONPANEL);
pane.add(new JPanel() {
@Override
public Dimension getPreferredSize() {
return new Dimension(800, 200);
}
}, BorderLayout.CENTER);
pane.add(cards, BorderLayout.PAGE_END);
}
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();
ImageIcon img = new ImageIcon("C:\\Users\\********\\Pictures\\settings-file-icon-2.png");
frame.setIconImage(img.getImage());
frame.setSize(850, 650);
frame.setLocationRelativeTo(null);
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();
}
});
}
}
这是 jframe 当前的样子:
这就是我希望它看起来的样子: