1

我有一个 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 ) );
}

你能帮我继续这个工作吗?

4

2 回答 2

1

如果您注意到,它们不会改变文本图像。相反,他们只显示了一半。这是简单的图像处理。一个很好的例子,看这个

于 2011-09-28T19:55:26.120 回答
1

您可以在纸上绘制图像并随时缩放图像。因此,您将覆盖 JComponent 的 paintComponent() 方法以执行以下操作:

g.drawImage(image, x, y, width, height, null);

x - 将是左边距
y - 将是上边距
宽度 - 将是 (maxWidth - leftMargin - rightMargin)
高度 - 将是 (maxHeight - topMargin - bottomMargin)

如果您不喜欢缩放图像,您始终可以使用 BufferedImage,然后使用 getSubImage(...) 方法来获取要绘制的所需大小的图像。

于 2011-09-28T20:26:43.933 回答