【问题标题】:Multiple JTextFields?多个 JTextFields?
【发布时间】:2013-11-28 05:55:20
【问题描述】:

如果您可以在单个 JPanel 中拥有多个 JtextField,我会感到困惑?如果是,那么如何使用下面提供的代码。

我的代码:

private JPanel jp;
private JTextField jt;

jt = new JTextField();
jt.setBounds(1, 25, 60, 20);
jp.add(jt);
jt.setColumns(10);

JLabel npcId = new JLabel("npcId");
npcId.setBounds(15, 11, 92, 14);
jp.add(npcId);

我正在构建的内容:

我在这里想要完成的是有 5 个JTextField 对象:npcId、npcLocation、npcReg、npcAH、npcAA。

【问题讨论】:

  • 当然可以。您尝试了哪些方法,又是如何失败的?
  • 请看一下 Swing Layout Manager 相关的文档docs.oracle.com/javase/tutorial/uiswing/layout/using.html 这是一种非常灵活的方式来控制 GUI 元素的位置
  • Don't use setBounds(). 你在哪里找到了那个例子,把它去掉。您应该按照上面的建议使用布局管理器。
  • Java GUI 可能必须在多个平台、不同的屏幕分辨率和使用不同的 PLAF 上工作。因此,它们不利于组件的精确放置。要为强大的 GUI 组织组件,请改用布局管理器或 combinations of them,以及 white space 的布局填充和边框。
  • 我就像一年前在 java 文档中读到的一样,我找不到我在其中看到的书,把它丢在家里的某个地方。但是@john 我尝试复制 npcId 并更改它...失败了。

标签: java swing jpanel jtextfield layout-manager


【解决方案1】:

是的,很简单,你需要使用合适的布局管理器。

看看,A Visual Guide to Layout Managers

我可能会建议从 GridLayout 开始,但最终,你会想看看 GridBagLayout。

别忘了,您可以使用复合布局来创建复杂的布局

【讨论】:

    【解决方案2】:

    另外,您可以考虑以下基本方法:

    // Use of Textfield
    usernameField = new JTextField(8);
    usernameField.setLocation(0, 0);
    usernameField.setSize(100, 30);
    

    【讨论】:

    • 那么jt = new JTextField(); jt.setLocation(0,0); jt.setSize(100, 30); 我将如何复制它以制作更多文本字段......?
    • 例如jt2 = new JTextField();
    【解决方案3】:

    是的,你可以轻松做到,你真正需要的是 1) 声明你所有的 JTextFields,比如:

    jt = new JTextField();
    jt.setBounds(1, 25, 60, 20);
    jp.add(jt);
    jt.setColumns(10);
    

    2) 像这样声明你的 JPanel

    private JPanel jp;
    
    jp = new JPanel();// here you have to set a layout manager for this panel
    //for exampl:
    jp.setLayout(new FlowLayout());
    

    检查来自here 的布局管理器。

    3) 将所有声明的 JTextFields 添加到您的面板:

    jp.add(jt);
    jp.setVisible(true);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-22
      • 1970-01-01
      • 2017-02-10
      • 2018-10-23
      • 1970-01-01
      • 1970-01-01
      • 2014-05-19
      相关资源
      最近更新 更多