在我的应用程序中,当用户单击JButton时,显示一个提示用户输入整数的JLabel,一个用户可以输入整数的JTextField,以及一个包含Double me文本的secondJButton。当用户单击第二个按钮时,整数加倍,答案显示在JTextField中。
当我点击第一个按钮时,我无法显示第二个按钮和文本字段...请帮助
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class JDouble extends JApplet implements ActionListener {
private Container container = getContentPane();
/**
* The JButton.
*/
private JButton button = new JButton("Click me");
private JButton button2 = new JButton("Double me");
/**
* The JLabel.
*/
private JLabel label = new JLabel("Enter Integer");
private JTextField textfield = new JTextField(4);
private JTextField textfield2 = new JTextField(4);
public void init() {
// set the layout to FlowLayout
container.setLayout(new FlowLayout());
// register the 'this' action listener for the button
button.addActionListener(this);
container.add(button);
}
public void init1(){
container.setLayout(new FlowLayout());
container.add(textfield);
container.add(button2);
container.add(textfield2);
button2.addActionListener(this);
}
public void actionPerformed(ActionEvent actionEvent) {
container.add(label);
}
public void actionPerformed1(ActionEvent actionEvent) {
String me = textfield.getText();
int computation = Integer.parseInt(me);
computation = computation*2;
String changecomputation = Integer.toString(computation);
textfield2.setText(changecomputation);
container.remove(button);
container.add(label);
repaint();
validate();
}
}
答案 0 :(得分:3)
你的init()方法:
public void init() {
// set the layout to FlowLayout
container.setLayout(new FlowLayout());
// register the 'this' action listener for the button
button.addActionListener(this);
container.add(button);
}
我们将使用此功能在单击“Click Me”时显示其他字段...
private showInputFields(){
container.add(textfield);
button2.addActionListener(this);
container.add(button2);
container.add(textfield2);
}
让我们修复你的动作监听器。如果您想在启动时显示“Click Me”按钮,init()
会处理此问题。当用户点击“Click Me”时,我们会调用showInputFields()
来显示其他组件;我们会处理“Double me”点击使用相同的监听器,我们只需检查事件源以便正确处理......
private boolean inputFieldsDisplayed;
public void actionPerformed(ActionEvent actionEvent) {
if( actionEvent.getSource() == button && !inputFieldsDisplayed){
showInputFields();
inputFieldsDisplayed = true;
} else if ( actionEvent.getSource() == button2){
String me = textfield.getText();
int computation = Integer.parseInt(me);
computation = computation*2;
String changecomputation = Integer.toString(computation);
textfield2.setText(changecomputation);
}
validate();
repaint();
}