我有一个 Java Swing 应用程序,我想在其中创建一个很好的组件,就像 Microsoft Word 中的组件一样。在 Microsoft Word 中,您可以更改文档的页边距,如下所示:
这里的技巧是,如果您将顶部边距更改为(比方说)1.5 英寸,则预览图像将更改以显示此内容,因此线条将在图像中向下移动一点以显示边距的变化,以便用户可以感觉到他的文档将受到此更改的影响。例如,如果我将左边距更改为(4.0“),则图像将如下所示:
我所做的是创建 2 个图像,一个空白页图像 + 另一个仅包含线条的图像(线条图像),就像这 2 个图像:
我将 JLabel 中的每个图像插入到彼此上方,现在当我更改 JSpinner 上边距值时,我保持“空白页”图像固定,但更改“线条图像”的边框以将其向下移动一点点。这个技巧对于上边距效果很好,但如果我更改下/右/左边距,行为就会完全错误。
这是我在更改任何 JSpinner 值时应用的代码:
private void marginSpinnerStateChanged() {
//1. Get the approximate values of all margins :
int topMargin = (int)( Float.valueOf( topSpinner.getValue().toString() ) * 8 );
int bottomMargin = (int)( Float.valueOf( bottomSpinner.getValue().toString() ) * 8 );
int leftMargin = (int)( Float.valueOf( leftSpinner.getValue().toString() ) * 8 );
int rightMargin = (int)( Float.valueOf( rightSpinner.getValue().toString() ) * 8 );
//2. Apply all specified margins to the lines label :
linesLabel.setBorder( new EmptyBorder( topMargin, leftMargin, bottomMargin, rightMargin ) );
}
你能帮助我继续正常工作吗?
最佳答案
您可以将图像绘制在纸张上,然后随时缩放图像。因此,您可以重写 JComponent 的 PaintComponent() 方法来执行以下操作:
g.drawImage(image, x, y, width, height, null);
x - 左边距
y - 将是上边距
宽度 - 将是(maxWidth - leftMargin - rightMargin)
高度 - 将为 (maxHeight - topMargin - BottomMargin)
如果您不喜欢缩放图像,您始终可以使用 BufferedImage,然后使用 getSubImage(...) 方法来获取要绘制的所需尺寸的图像。
关于java - 创建一个类似于 Microsoft Word 中的页边距编辑器组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7588783/