gpt4 book ai didi

java - 在 JDeskopPane 上写入文本

转载 作者:行者123 更新时间:2023-12-01 17:55:45 24 4
gpt4 key购买 nike

我想在 JDesktopPane 的右下角写入多行文本(3-4 行即可),我该怎么做?
文本不是固定的,每次启动 swing 应用程序时它都会更改,但应用程序启动后它保持不变,我不需要从应用程序更新。

我的第一个想法是创建一个图像,将其作为 JDesktopPane 的背景,然后在其上书写,但这似乎不是一个简单的解决方案。

感谢您的帮助。

最佳答案

结合看到的例子herehere ,下面变体中的 print() 方法说明了如何使用 FontMetricsJDesktopPane 右下角的多行文本右对齐。

image

import java.awt.*;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;

/** @see http://stackoverflow.com/a/45055215/230513 */
public class JDPTest extends JDesktopPane {

private MyFrame one = new MyFrame("One", 100, 100);

public JDPTest() {
this.setPreferredSize(new Dimension(640, 480));
this.add(one);
}

@Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.lightGray);
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.setColor(Color.BLACK);
g2d.setFont(new Font(Font.SERIF, Font.BOLD, 16));
print(g2d, 3, "Hello, world!");
print(g2d, 2, "This is a test.");
print(g2d, 1, "This is another test.");
print(g2d, 0, "This is still another test.");
}

private void print(Graphics2D g2d, int line, String s) {
FontMetrics fm = g2d.getFontMetrics();
int x = this.getWidth() - fm.stringWidth(s) - 5;
int y = this.getHeight() - fm.getDescent()
- line * (fm.getHeight() + fm.getLeading());
g2d.drawString(s, x, y);
}

private final class MyFrame extends JInternalFrame {

MyFrame(String name, int x, int y) {
super(name, true, true, true, true);
this.setSize(320, 240);
this.setLocation(x, y);
this.setVisible(true);
}
}

private void display() {
JFrame f = new JFrame("JDPTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {

@Override
public void run() {
new JDPTest().display();
}
});
}
}

关于java - 在 JDeskopPane 上写入文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45052346/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com