【问题标题】:Change the direction of growth for a JTexField object更改 JTextField 对象的增长方向
【发布时间】:2010-12-16 00:04:08
【问题描述】:

当添加更多字符时,我需要更改 JTextField 对象的增长方向。目前,当我向其中添加更多内容时,它会从左到右增长,但我需要 JTextField 的边界从右到左增长。 例如当我将“StackOverflow”添加到这个 JTextField 时,o/p 是,

<empty space>StackOverflow

但我想要,

StackOverflow<empty space>

你们能帮我解决这个问题吗?我试过 setHorizo​​ntalAlignment。但它不起作用。 感谢您的帮助。

编辑:添加 SSCCE 以获得更好的解释。

导入 java.awt.Container; 导入 javax.swing.BoxLayout; 导入 javax.swing.JButton; 导入 javax.swing.JFrame; 导入 javax.swing.JTextField;

公共类 JTextFieldExample { 公共静态无效 addComponentsToPane(容器窗格){ pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));

    JTextField transitionEditorJTextField = new JTextField("StackOverFlow");
    pane.add(transitionEditorJTextField);

    System.out.println("If I add text to JTextFiled notice that it grows towards Right - which is normal. " 
                        + "But I want it to grow towards left.");
    JButton button = new JButton("Button.I.Am");
    pane.add(button);



}

/**
 * Create the GUI and show it.  For thread safety,
 * this method should be invoked from the
 * event-dispatching thread.
 */
private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("BoxLayoutDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Set up the content pane.
    addComponentsToPane(frame.getContentPane());

    //Display the window.
    frame.pack();
    frame.setVisible(true);
}

public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
        }
    });
}

}

【问题讨论】:

    标签: java swing jtextfield direction


    【解决方案1】:
    textField.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    

    【讨论】:

    • 这在 SSCCE 中有效,但不知何故在我的实际应用程序中不起作用。这很奇怪。
    【解决方案2】:

    我不确定我是否理解您的问题。通常,您使用以下代码创建 JTextField:

    JTextField textField = new JTextField(10);
    

    这为文本字段提供了一个固定的首选大小,该大小取决于所使用的布局管理器。

    听起来你正在做类似的事情:

    JTextField textField = new JTextField();
    

    在这种情况下,我认为文本字段没有大小。您甚至可以为其添加角色吗?好吧,在这种情况下,解决方案可能是在文本字段中添加一个 ComponentListener 并跟踪原始大小。每次大小更改时,您都会根据大小的差异更改文本字段的位置。同样,这可能会也可能不会起作用,具体取决于布局管理器。

    如果您需要更多帮助,请发布您的 SSCCE 以显示问题。

    【讨论】:

    • 我根据您的要求添加了 SSCCE。我不希望给出示例中的当前行为。我希望它向左生长。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2017-02-17
    • 2011-03-23
    • 1970-01-01
    • 2011-12-02
    • 2011-04-04
    • 1970-01-01
    • 2014-07-03
    • 1970-01-01
    相关资源
    最近更新 更多