有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何创建垂直javax。摆动BoxLayout的组件定位?

我正在编写BoxLayout的替代方案,所以我需要测试PAGE_轴和LINE_轴。这需要在关闭HORIZ_位的情况下创建ComponentOrientation值。似乎没有这样的动物

如何为垂直布局而不是水平布局创建组件方向? (还有一个附属问题:BoxLayout是否经过彻底测试?)


共 (1) 个答案

  1. # 1 楼答案

    我第一次尝试解决这个问题。这真是太过分了。这个任务可以通过反射来完成,反射允许调用私有构造函数

    // from ComponentOrientation.java
    private static final int HORIZ_BIT = 2;
    private static final int LTR_BIT = 4;
    
    /**
     * Generate the full gamut of ComponentOrientation values.
     *
     * ComponentOrientation mentions various languages that write
     * vertically, but offers no way to construct vertical orientations.
     * The only un-deprecated way to get a ComponentOrientation
     * value is by referring to the Locale, but ComponentOrientation
     * understands only a few locales, none of them with vertical text.
     *
     * See also http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4418738
     * which describes the rationale behind lobotomizing Locale handling
     * in ComponentOrientation.
     *
     * An inability to generate vertical orientations stymies Blox
     * which relies on the orientation to resolve PAGE_AXIS and LINE_AXIS.
     *
     * @param ltr Should text lines be left-to-right? Otherwise right to left.
     * 
     * @param hor Should text lines be horizontal? Otherwise vertical.
     * 
     * @return A ComponentOrientation value with the specified values for
     *      left-to-right-ness and verticality. If an exception occurs,
     *      a default value of LEFT_TO_RIGHT is returned.
     */
    public static ComponentOrientation componentOrientationFactory(
                boolean ltr, boolean hor) {
        try {
            Class<ComponentOrientation> coClass = ComponentOrientation.class;
            Constructor<ComponentOrientation> conint
                    = coClass.getDeclaredConstructor(int.class);
            conint.setAccessible(true);
            int dir = (ltr ? LTR_BIT : 0) + (hor ? HORIZ_BIT : 0);
            return conint.newInstance(dir);
        } catch (NoSuchMethodException | InstantiationException 
                | IllegalAccessException | IllegalArgumentException 
                | InvocationTargetException | NullPointerException ex) {
            return ComponentOrientation.LEFT_TO_RIGHT;
        }
    }