Java 如何在CardLayout Swap上向其他卡显示一张卡的文本字段值
我试图在用户登录后在下一张卡上显示用户名,但运气不佳 我正在使用CardLayout并定义了两张卡-一张卡供用户输入姓名和密码,另一张卡用于显示带有登录用户姓名的欢迎信息。我正在学习Java&我自己的Swing,而不是专家。任何帮助,包括修复此代码或供我阅读的参考资料,都将不胜感激 这是我当前的代码(仍然需要添加代码来更新欢迎屏幕的文本字段):Java 如何在CardLayout Swap上向其他卡显示一张卡的文本字段值,java,swing,constructor,jtextfield,cardlayout,Java,Swing,Constructor,Jtextfield,Cardlayout,我试图在用户登录后在下一张卡上显示用户名,但运气不佳 我正在使用CardLayout并定义了两张卡-一张卡供用户输入姓名和密码,另一张卡用于显示带有登录用户姓名的欢迎信息。我正在学习Java&我自己的Swing,而不是专家。任何帮助,包括修复此代码或供我阅读的参考资料,都将不胜感激 这是我当前的代码(仍然需要添加代码来更新欢迎屏幕的文本字段): 每次启动JButton的操作时,您都会创建CardLayout实例,例如,只创建一次 import java.awt.*; import java.aw
每次启动
JButton的操作时,您都会创建CardLayout
实例,例如,只创建一次
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class OnTheFlyImageTest extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel cardPanel;
private CardLayout cardLayout;
public OnTheFlyImageTest() {
JPanel cp = new JPanel(new BorderLayout());
cp.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
cardLayout = new CardLayout(5, 5);
cardPanel = new JPanel(cardLayout);
cp.add(cardPanel);
for (int i = 0; i < 5; i++) {// Create random panels for testing.
String name = "ImagePanel" + (i + 1);
String image = (i & 1) == 0 ? "foo.gif" : "bar.gif";
Color clr = (i & 1) == 0 ? Color.red : Color.blue;
ImagePanel imgPanel = new ImagePanel(name, image, clr);
cardPanel.add(imgPanel, name);
cardLayout.addLayoutComponent(imgPanel, name);
}
JPanel buttonPanel = new JPanel(new GridLayout(1, 2, 5, 5));
JButton prevButton = new JButton("< Previous");
prevButton.setActionCommand("Previous");
prevButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cardLayout.previous(cardPanel);
}
});
buttonPanel.add(prevButton);
JButton nextButton = new JButton("Next >");
nextButton.setActionCommand("Next");
nextButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cardLayout.next(cardPanel);
}
});
buttonPanel.add(nextButton);
JPanel temp = new JPanel(new BorderLayout());
temp.add(buttonPanel, BorderLayout.LINE_END);
cp.add(temp, BorderLayout.SOUTH);
setContentPane(cp);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Test");
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new OnTheFlyImageTest().setVisible(true);
}
});
}
}
class ImagePanel extends JPanel {
private static final long serialVersionUID = 1L;
private String imgString;
private JLabel imgLabel;
public ImagePanel(String name, String imgString, Color backGround) {
setName(name);
this.imgString = imgString;
setLayout(new BorderLayout());
setBackground((backGround));
// Ensure size is correct even before any image is loaded.
setPreferredSize(new Dimension(400, 300));
}
@Override
public void setVisible(boolean visible) {
if (visible) {
System.err.println(getName() + ": Loading and adding image");
ImageIcon icon = new ImageIcon(imgString);
imgLabel = new JLabel(icon);
add(imgLabel);
}
super.setVisible(visible);
if (!visible) { // Do after super.setVisible() so image doesn't "disappear".
System.err.println(getName() + ": Removing image");
if (imgLabel != null) { // Before display, this will be null
remove(imgLabel);
imgLabel = null; // Hint to GC that component/image can be collected.
}
}
}
}
import java.awt.*;
导入java.awt.event.*;
导入javax.swing.*;
eflyImageTest上的公共类扩展了JFrame{
私有静态最终长serialVersionUID=1L;
私人JPanel cardPanel;
私人卡布局卡布局;
公共OnTheFlyImageTest(){
JPanel cp=newjpanel(newborderlayout());
cp.setboorder(BorderFactory.createEmptyBorder(5,5,5,5));
cardLayout=新的cardLayout(5,5);
cardPanel=新JPanel(cardLayout);
cp.add(cardPanel);
对于(inti=0;i<5;i++){//创建随机面板进行测试。
String name=“ImagePanel”+(i+1);
字符串图像=(i&1)=0?“foo.gif”:“bar.gif”;
颜色clr=(i&1)==0?颜色。红色:颜色。蓝色;
ImagePanel imgPanel=新的ImagePanel(名称、图像、clr);
cardPanel.add(imgPanel,名称);
cardLayout.addLayoutComponent(imgPanel,名称);
}
JPanel buttonPanel=新的JPanel(新的网格布局(1,2,5,5));
JButton prevButton=新JButton(“<先前”);
prevButton.setActionCommand(“上一个”);
prevButton.addActionListener(新ActionListener(){
@凌驾
已执行的公共无效操作(操作事件e){
cardLayout.previous(cardPanel);
}
});
按钮面板。添加(prevButton);
JButton nextButton=新JButton(“下一个>”);
setActionCommand(“下一步”);
addActionListener(新ActionListener(){
@凌驾
已执行的公共无效操作(操作事件e){
cardLayout.next(cardPanel);
}
});
按钮面板添加(下一个按钮);
JPanel temp=newjpanel(newborderlayout());
临时添加(按钮面板、边框布局、线条结束);
cp.add(温度,边界布局,南部);
setContentPane(cp);
setDefaultCloseOperation(关闭时退出);
设置标题(“测试”);
包装();
}
公共静态void main(字符串[]args){
SwingUtilities.invokeLater(新的Runnable(){
@凌驾
公开募捐{
新的OnTheFlyImageTest().setVisible(true);
}
});
}
}
类ImagePanel扩展了JPanel{
私有静态最终长serialVersionUID=1L;
私有字符串imgString;
私人JLabel imgLabel;
公共图像面板(字符串名称、字符串imgString、彩色背景){
集合名(名称);
this.imgString=imgString;
setLayout(新的BorderLayout());
挫折背景((背景));
//即使在加载任何图像之前,也要确保大小正确。
setPreferredSize(新尺寸(400300));
}
@凌驾
公共void集合可见(布尔可见){
如果(可见){
System.err.println(getName()+“:加载和添加图像”);
ImageIcon图标=新的ImageIcon(imgString);
imgLabel=新的JLabel(图标);
添加(imgLabel);
}
super.setVisible(可见);
如果(!visible){//在super.setVisible()之后执行,则图像不会“消失”。
System.err.println(getName()+“:删除图像”);
如果(imgLabel!=null){//在显示之前,这将是null
移除(imgLabel);
imgLabel=null;//提示GC可以收集组件/映像。
}
}
}
}
您在代码中声明和初始化JPanel卡两次,一次作为实例变量,第二次在CardLayoutLoginTest
类的构造函数中。
因为你的是一步一步的工作,所以最好将你的JPanel
作为卡片
,一个接一个地添加到卡片布局
。因为如果登录失败,您将不需要它们,只要登录有效,就可以向CardLayout添加您想要添加的内容
使用而不是setLocationRelativeTo(空)代码>。前者更好,正如@Andrew Thompson在他的一篇帖子中所解释的,
我已经修改了你的代码,请看一看,如果缺少什么,请告诉我
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardTest
{
private JFrame frame;
public static final String CARD_LOGIN = "Card Login";
public static final String CARD_WELCOME = "Card Welcome";
public static JPanel cards;
public CardLogin cardLogin = null;
public CardTest()
{
frame = new JFrame("Card LOGIN");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
cards = new JPanel();
cards.setLayout(new CardLayout(20, 20));
cardLogin = new CardLogin(this);
cards.add(cardLogin, CARD_LOGIN);
frame.getContentPane().add(cards);
frame.pack();
frame.setVisible(true);
}
public void swapView(String key)
{
CardLayout cardLayout = (CardLayout) cards.getLayout();
cardLayout.show(cards, key);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new CardTest();
}
});
}
}
class CardLogin extends JPanel
{
private ActionListener action;
CardTest cardLayoutLoginTest;
/*
* Made JTextField an instance variable so that
* ActionListener can access it or you can make
* it final.
*/
private JTextField tfUsername= null;
private String username = null;
public CardLogin(CardTest cardLayoutLoginTest)
{
this.cardLayoutLoginTest = cardLayoutLoginTest;
init();
}
private void init()
{
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.fill = GridBagConstraints.HORIZONTAL;
JLabel lbUsername = new JLabel("Username: ");
gc.gridx = 0;
gc.gridy = 0;
gc.gridwidth = 1;
panel.add(lbUsername, gc);
tfUsername = new JTextField(20);
gc.gridx = 1;
gc.gridy = 0;
gc.gridwidth = 2;
panel.add(tfUsername, gc);
JLabel lbPassword = new JLabel("Password: ");
gc.gridx = 0;
gc.gridy = 1;
gc.gridwidth = 1;
panel.add(lbPassword, gc);
JPasswordField pfPassword = new JPasswordField(20);
gc.gridx = 1;
gc.gridy = 1;
gc.gridwidth = 2;
panel.add(pfPassword, gc);
final JButton loginButton = new JButton("Login");
action = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
// Here need code to update text filed of welcome card
/*
* Here we are first checking if there is any text inside
* the JTextField for USERNAME, if found we will send it to the
* next JPanel which will be serving as a new Card.
*/
if (tfUsername.getDocument().getLength() > 0)
{
username = tfUsername.getText();
CardWelcome cardWelcome = new CardWelcome(cardLayoutLoginTest.cardLogin);
CardTest.cards.add(cardWelcome, cardLayoutLoginTest.CARD_WELCOME);
cardLayoutLoginTest.swapView(cardLayoutLoginTest.CARD_WELCOME);
}
}
};
loginButton.addActionListener(action);
JPanel bp = new JPanel();
bp.add(loginButton);
/*set size of the frame*/
setSize( 640, 480);
add(panel, BorderLayout.CENTER);
add(bp, BorderLayout.PAGE_END);
}
public String getUserName()
{
return username;
}
}
class CardWelcome extends JPanel
{
private JTextField textField;
private CardLogin cardLogin;
public CardWelcome(CardLogin cl)
{
cardLogin = cl;
init();
}
private void init()
{
setLayout(new GridLayout(1, 1));
JLabel userLabel = new JLabel("Welcome ");
textField = new JTextField();
textField.setText(cardLogin.getUserName());
System.out.println("UserName : " + cardLogin.getUserName());
add(userLabel);
add(textField);
}
}
运行时更新JLabel
的小示例程序:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class UpdateLabel extends JFrame
{
private int count = 0;
public UpdateLabel()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
final JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
final JLabel label = new JLabel("JLabel " + count);
JButton button = new JButton("UPDATE JLABEL");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
count++;
label.setText("JLabel " + count);
contentPane.revalidate(); // sometimes you require to do this and the below line.
contentPane.repaint();
}
});
contentPane.add(label, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.PAGE_END);
setContentPane(contentPane);
pack();
setVisible(true);
}
public static void main(String... args)
{
Runnable runnable = new Runnable()
{
public void run()
{
new UpdateLabel();
}
};
SwingUtilities.invokeLater(runnable);
}
}
@Arif Hameed这是你问题的答案,请不要忘记接受这个answer@Gagandeep巴厘岛,感谢您的及时回复和对重复声明的评论。我担心这个解决方案不适合实际项目,因为在GUI创建时,我有7张卡添加到卡组中,用户可以切换到任何卡,一些数据将从活动卡传递到切换卡,即使从任何卡注销,也会再次显示登录卡。我创建这个小程序是为了测试将值从一张卡传递到另一张卡的功能。正如@mKorbel所评论的,在这个示例中,我如何处理CardLayout多实例创建情况?@arifhamed:请参阅,而不是将值传递到下一张卡,这是您必须做的。无论您输入什么,该输入基本上都可以与某些内容相关(例如,学生、员工、工人等),因此您可以为该实体创建一个单独的类。因此,当您从登录移动到欢迎窗口时,请保存特定enti的用户名和密码
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class UpdateLabel extends JFrame
{
private int count = 0;
public UpdateLabel()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
final JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
final JLabel label = new JLabel("JLabel " + count);
JButton button = new JButton("UPDATE JLABEL");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
count++;
label.setText("JLabel " + count);
contentPane.revalidate(); // sometimes you require to do this and the below line.
contentPane.repaint();
}
});
contentPane.add(label, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.PAGE_END);
setContentPane(contentPane);
pack();
setVisible(true);
}
public static void main(String... args)
{
Runnable runnable = new Runnable()
{
public void run()
{
new UpdateLabel();
}
};
SwingUtilities.invokeLater(runnable);
}
}