我创建了一个小例子,我认为它展示了你想要什么。它使用一个按钮,按下该按钮将删除JTextField
并添加JLabel
,反之亦然,然后在每次单击按钮后调用revalidate()
并repaint()
显示对框架的更改:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class JLabelToJTextField extends JFrame {
JLabel jLabel;
JTextField jTextField;
JButton jButton;
JPanel mainPanel;
public JLabelToJTextField() {
jLabel = new JLabel("Name");
jTextField = new JTextField(15);
jButton = new JButton("Edit");
mainPanel = new JPanel(new BorderLayout());
createUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new JLabelToJTextField().setVisible(true);
}
});
}
private void createUI() {
setTitle("JLabel to JtextField");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPanel();
setLocationRelativeTo(null);
pack();
}
private void addComponentsToPanel() {
mainPanel.add(jLabel, BorderLayout.CENTER);
mainPanel.add(jButton, BorderLayout.SOUTH);
addActionListeners();
getContentPane().add(mainPanel);
}
private void addActionListeners() {
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
switch (jButton.getText()) {
case "Edit":
mainPanel.remove(jLabel);//remove component
mainPanel.add(jTextField, BorderLayout.CENTER);//add new component
jButton.setText("Done");
//refresh JFrame
revalidate();
repaint();
break;
case "Done":
mainPanel.remove(jTextField);//remove component
mainPanel.add(jLabel, BorderLayout.CENTER);//add new component
jButton.setText("Edit");//set button text to original
//refresh JFrame
revalidate();
repaint();
break;
}
}
});
}
}