我需要重复使用面板中的文本字段来存储值。
请参阅冗长但非常简单的代码。
基本上我正在做的是
class Holder
{
String name;
}
public class Yummy12 extends Holder {
int t;
public static void main(String args[])
{
new Yummy12();
}
Holder[] obj=new Holder[5];
JButton button1=new JButton("add another one");
JButton button2=new JButton("exit");
JPanel panel=new JPanel();
JTextField textfield=new JTextField("Enter some text here");
JLabel label1=new JLabel();
JFrame frame=new JFrame();
Yummy12()
{
for(int i=0;i<5;i++)
{
obj[i]=new Holder();
}
//set component bounds (only needed by Absolute Positioning)
label1.setBounds (165, 75, 100, 25);
textfield.setBounds (350, 75, 100, 25);
button1.setBounds (170, 230, 100, 25);
button2.setBounds (360, 230, 100, 25);
panel.add(label1);
panel.add(textfield);
panel.add(button1);
panel.add(button2);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
ListenForButton1 lrbutton1=new ListenForButton1();
ListenForButton1 lrbutton2=new ListenForButton1();
button1.addActionListener((ActionListener)lrbutton1);
button2.addActionListener((ActionListener)lrbutton2);
}
private class ListenForButton1 implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button1)
{
obj[t].name=textfield.getText();
t++;
//what code should come here so that i reuse the same panel again???
if(e.getSource()==button2)
{
System.exit(0);
}
}
}
}
答案 0 :(得分:0)
您的if块需要像这样进行修改才能使其正常工作:
if(e.getSource()==button1) {
obj[t].name=textfield.getText();
t++;
//what code should come here so that i reuse the same panel again???
textfield.setText(""); // clears the textfield for re-use
} else if(e.getSource()==button2){
System.exit(0);
}
希望这有帮助