我正在编写BoxLayout的替代品,所以我需要测试PAGE_AXIS和LINE_AXIS。这需要在关闭HORIZ_BIT的情况下创建ComponentOrientation值。似乎没有这样的动物。
如何为垂直布局而不是水平布局创建ComponentOrientation? (以及附属问题:BoxLayout已经过彻底测试了吗?)
答案 0 :(得分:0)
我解决问题的第一次尝试利用了序列化。这是大规模的矫枉过正。该任务可以通过反射来完成,这允许调用私有构造函数。
// 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;
}
}