我需要制作GUI,使用链接列表保存用户的输入,并让他/她浏览"通过保存的数据。我做了一个更简单的代码版本,我在下面包含了它。我的问题是如何更新"用户输入并保存文本后,浏览卡中的按钮。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class sampleDemo extends JPanel {
NodeSample newNode = new NodeSample();
SampleSave s = new SampleSave();
public static final String CARD_ADD = "Card Add";
public static final String CARD_BROWSE = "Card Browse";
public static CardLayout cardLayout = new CardLayout();
public static JPanel card = new JPanel(cardLayout);
public static sampleDemo sd = new sampleDemo();
public sampleDemo() {
WindowAdd wina = new WindowAdd();
card.add(wina, CARD_ADD);
WindowBrowse winb = new WindowBrowse();
card.add(winb, CARD_BROWSE);
setLayout(new BorderLayout());
add(card, BorderLayout.PAGE_END);
}
public static void createAndShowGUI() {
JPanel buttonPanel = new JPanel();
JButton addButton = new JButton("Add");
JButton browseButton = new JButton("Browse");
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
cardLayout.show(card, "Card Add");
}
});
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
cardLayout.show(card, "Card Browse");
}
});
buttonPanel.add(addButton);
buttonPanel.add(browseButton);
JFrame frame = new JFrame("Sample Demo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(buttonPanel, BorderLayout.PAGE_END);
frame.getContentPane().add(sd);
frame.setSize(300, 200);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
class WindowAdd extends JPanel {
public ActionListener action;
public WindowAdd() {
init();
}
public void init() {
JTextField textField = new JTextField(10);
NodeSample newNode = new NodeSample();
JPanel content = new JPanel(new FlowLayout());
JButton saveButton = new JButton("Save");
saveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newNode.textContent = textField.getText();
s.insert(newNode);
}
});
content.add(textField);
content.add(saveButton);
textField.setText(null);
add(content);
}
}
class WindowBrowse extends JPanel {
public WindowBrowse() {
init();
}
public void init() {
setLayout(new GridLayout(1, 3));
JButton a = new JButton();
JButton b = new JButton();
JButton c = new JButton();
try {
a = new JButton(s.head.textContent);
b = new JButton(s.head.next.textContent);
c = new JButton(s.head.next.next.textContent);
}catch (NullPointerException e) {
//
}
add(a);
add(b);
add(c);
}
}
class NodeSample {
String textContent;
NodeSample next;
}
class SampleSave {
NodeSample head;
NodeSample tail;
public void insert(NodeSample add) {
if(head == null){
head = add;
tail = add;
}else {
add.next = head;
head = add;
}
}
}
}
答案 0 :(得分:2)
为了更改JButton上的文本,请在动作侦听器中使用与此类似的内容
btn.setText(textfield.getText());
这会将任何按钮的文本更改为在文本字段中输入的文本