2012-04-10 118 views

回答

5

Swing没有像文本框这样的动物 - 你的意思是JTextField?如果是这样,...

  • 你会被简单地做只是创建一个JTextField - new JTextField()
  • 然后会通过比如JPanel适当的容器调用add(...)它添加到您的GUI。
  • 然后,您可以通过简单地拨打getText()来阅读文本,JTextField tutorials将解释所有这些。
  • 由于接受JTextField的容器必须具有可容纳新组件的布局,因此您还需要阅读布局管理器上的教程。
  • 在添加或删除组件后,您还需要在容器上调用revalidate()repaint(),以便容器布局管理器知道更新其布局并重新绘制自己。

这只是一个需要做的事情的一般要点。如果您需要更具体的建议,请告诉我们您的问题的细节,您迄今为止所尝试的内容以及工作或失败的内容。

编辑
你问:

但是我怎么做到这一点,这样的文本框是一个“弹出”,而不是除了目前的容器。我拥有它,因此它增加了当前的容器...但这不是我所需要的。

  • 做到这一点,最简单的方法是通过显示JOptionPane.showInputDialog(...)。

例如:

// myGui is the currently displayed GUI 
    String foo = JOptionPane.showInputDialog(myGui, "Message", "Title", 
     JOptionPane.PLAIN_MESSAGE); 
    System.out.println(foo); 

这看起来就像这样:
enter image description here

  • 这样做的一个更复杂的方法是创建一个图形用户界面,并在JOptionPane中显示出来,并查询GUI的内容。

例如:

JTextField fooField = new JTextField(15); 
    JTextField barField = new JTextField(15); 
    JPanel moreComplexPanel = new JPanel(new GridBagLayout()); 
    GridBagConstraints gbc = new GridBagConstraints(); 
    gbc.insets = new Insets(5, 5, 5, 5); 
    gbc.weightx = 1.0; 
    gbc.weighty = 1.0; 
    gbc.anchor = GridBagConstraints.WEST; 
    moreComplexPanel.add(new JLabel("Foo:"), gbc); 
    gbc.gridx = 1; 
    gbc.anchor = GridBagConstraints.EAST; 
    moreComplexPanel.add(fooField, gbc); 
    gbc.gridx = 0; 
    gbc.gridy = 1; 
    gbc.anchor = GridBagConstraints.WEST; 
    moreComplexPanel.add(new JLabel("Bar:"), gbc); 
    gbc.gridx = 1; 
    gbc.anchor = GridBagConstraints.EAST; 
    moreComplexPanel.add(barField, gbc); 

    int result = JOptionPane.showConfirmDialog(myGui, moreComplexPanel, 
     "Foobars Forever", JOptionPane.OK_CANCEL_OPTION, 
     JOptionPane.PLAIN_MESSAGE); 
    if (result == JOptionPane.OK_OPTION) { 
    System.out.println("foo = " + fooField.getText());; 
    System.out.println("bar = " + barField.getText());; 
    } 

这将是这样的:
enter image description here

+1

@ user1261445:有一个相关的例子[这里](http://stackoverflow.com/a/5812981/ 230513)可能会让你开始使用[sscce](http://sscce.org/)。 – trashgod 2012-04-10 01:15:47

+0

但我该如何做到这一点,使textField是一个“弹出”,而不是当前容器的添加。我拥有它,因此它增加了当前的容器...但这不是我所需要的。 – user1261445 2012-04-10 02:06:34

+0

@ user1261445:请参阅上面的编辑回答。 – 2012-04-10 03:32:14