所以我有以下代码,每当我按下方形工具按钮时,它应该绘制一个JTextFields应该是的正方形。但由于某种原因,JTextField值不起作用,并且无法绘制正方形...这是方形代码和JTextField:
JTextFields的初始化
squareX = new JTextField(3);
squareY = new JTextField(3);
squareW = new JTextField(3);
squareH = new JTextField(3);
ActionListeners:
squareX.addActionListener(listener);
squareY.addActionListener(listener);
squareW.addActionListener(listener);
squareH.addActionListener(listener);
这是我将其值设置为文本的地方:
x = Integer.parseInt(op.squareX.getText());
y = Integer.parseInt(op.squareY.getText());
w = Integer.parseInt(op.squareW.getText());
h = Integer.parseInt(op.squareH.getText());
g.fillRect(x,y,w,h);
如果重要的是错误说的话
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:470)
at java.lang.Integer.parseInt(Integer.java:499)
at com.theDevCorner.Game$GridPane.paintComponent(Game.java:155)
at javax.swing.JComponent.paint(JComponent.java:1037)
at javax.swing.JComponent._paintImmediately(JComponent.java:5106)
at javax.swing.JComponent.paintImmediately(JComponent.java:4890)
at javax.swing.RepaintManager$3.run(RepaintManager.java:814)
at javax.swing.RepaintManager$3.run(RepaintManager.java:802)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:802)
at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:745)
at javax.swing.RepaintManager.prePaintDirtyRegions(RepaintManager.java:725)
at javax.swing.RepaintManager.access$1000(RepaintManager.java:46)
at javax.swing.RepaintManager$ProcessingRunnable.run(RepaintManager.java:1684)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:708)
at java.awt.EventQueue.access$400(EventQueue.java:82)
at java.awt.EventQueue$2.run(EventQueue.java:669)
at java.awt.EventQueue$2.run(EventQueue.java:667)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:678)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
答案 0 :(得分:4)
构造函数JTextField(int)
指定列数而不是初始值。因此,JTextComponent's
文本值在传递给Integer#parseInt
时仍为空。因此,您可以使用指定初始值的构造函数:
squareX = new JTextField("3");
squareY = new JTextField("3");
squareW = new JTextField("3");
squareH = new JTextField("3");