gpt4 book ai didi

java - CardLayout 对齐不正确

转载 作者:行者123 更新时间:2023-12-02 06:24:56 25 4
gpt4 key购买 nike

我是java初学者。在第二个卡片面板中,用户名和密码对齐不正确。有什么办法可以解决吗?我还想知道使用多个框架的缺点是什么。

    import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class CardLayoutTest extends JFrame {

private static final long serialVersionUID = 1L;
private JPanel cardPanel, jp1, jp2, buttonPanel;
private JLabel jl1, jl2;
private JTextField jt1;
private JPasswordField jt2;
private JButton btn1, btn2;
private CardLayout cardLayout = new CardLayout();

public CardLayoutTest() {
setTitle("Login");
setSize(400, 300);
cardPanel = new JPanel();
buttonPanel = new JPanel();
cardPanel.setLayout(cardLayout);
jp1 = new JPanel();
jp2 = new JPanel();
jt1=new JTextField();
jt2=new JPasswordField();
jl1 = new JLabel("Username");
jl2 = new JLabel("Password");
//jp1.add(jl1);
jp2.add(jl1);
jp2.add(jt2);
jp2.add(jl2);
jp2.add(jt2);
cardPanel.add(jp1, "1");
cardPanel.add(jp2, "2");
btn2 = new JButton("Show Card 2");
btn2.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
cardLayout.show(cardPanel, "2");
}
});
buttonPanel.add(btn2);
add(cardPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
}

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {

@Override
public void run() {
CardLayoutTest frame = new CardLayoutTest();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}

最佳答案

In second cardpanel the username and password alignment is not coming properly.

默认情况下,JPanel 使用 FlowLayout,因此组件显示在一行上。

Is there any way to fix it?

使用适当的布局管理器(或布局管理器的组合)来获得所需的对齐方式。

阅读 Swing 教程中关于 Layout Managers 的部分了解更多信息和示例。

关于java - CardLayout 对齐不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20627246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com