the*_*ton -1 java user-interface swing netbeans
先生们,
作为练习更多关于类和函数可访问性(例如公共,私有,静态等)的练习,我想编写一个具有以下属性的Java GUI(在Netbeans IDE中):
jButton无法从jTextField获取现有文本,读取/解析文本,获取最新数字,然后递增数字.
例如:
String someString = jTextField.getText();
int someInt = String.valueOf(someString);
someInt++;
String newString = new String();
newString = String.valueOf(someInt);
jTextField.setText()
Run Code Online (Sandbox Code Playgroud)
不被允许.
鉴于上述要求,该项目比看上去困难得多.根据要求,我将不得不在其他地方创建一个可以跟踪计数器值的类(请记住,禁止从TextField中提取当前计数器值).但是,由于Netbeans似乎不允许调用在别处(按钮外)实例化的对象的类方法,这似乎是不可能的.
在所有尝试之后,鉴于其限制,似乎在Netbeans中不可能满足上述4标准的GUI.
我最好的失败尝试 - 因此到目前为止(如果有意义的话)是这样的:
private void IncrementButtonActionPerformed(...){
CountObject C = new CountObject();
int i = C.IncrementCounter();// CountObject has a method for this.
// line or two here to typecast i into a String
jTextField.setText("i");
Run Code Online (Sandbox Code Playgroud)
但是,这不起作用,因为每次重新按下IncrementButton时,它都会简单地实例化一个新的CountObject.在此IncrementButtonActionPerformed事件处理程序之外实例化CountObject,然后从事件处理程序中调用CountObject.IncrementCounter()方法是不允许的,或者看起来如此.
我是否正确地认为上述要求1-4根本无法在Java Netbeans中完成?
谢谢,the_photon
只需创建一个counter int字段并在按钮的ActionListener中递增它 - 无需从JTextField获取文本.然后JTextField的文本带有计数器的值.编辑:实际上符合您的要求,反过来:使用当前计数器的值设置JTextFields文本,然后递增计数器.
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class SimpleGui extends JPanel {
private int counter = 0;
private JTextField textField = new JTextField(5);
private JButton incrementButton = new JButton(new IncrementAction("Increment", KeyEvent.VK_I));
public SimpleGui() {
textField.setFocusable(false);
add(textField);
add(incrementButton);
}
private class IncrementAction extends AbstractAction {
public IncrementAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
@Override
public void actionPerformed(ActionEvent e) {
textField.setText(String.valueOf(counter));
counter++;
}
}
private static void createAndShowGui() {
SimpleGui mainPanel = new SimpleGui();
JFrame frame = new JFrame("SimpleGui");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
136 次 |
| 最近记录: |