gpt4 book ai didi

java - 带有图像的 JLabel?

转载 作者:行者123 更新时间:2023-11-29 03:17:38 25 4
gpt4 key购买 nike

老实说,我对 GUI 不是很熟悉,而且我还在研究它。我的问题是,如何组合图像和标签?我想要一个图片上方有文字的输出。这是我从引用中获得的代码

import java.awt.Container; 
import java.awt.EventQueue;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

class JavaApplication2 extends JFrame {


public JavaApplication2(String title, String imageFileName) {
setTitle("title");
ImageIcon icon = new ImageIcon(imageFileName);
Container pane = getContentPane();
JLabel label = new JLabel(icon);
pane.add(label);
}


public static void main(String[] args) {

EventQueue.invokeLater(new Runnable() {
public void run() {

JFrame f = new JavaApplication2("Orca","C:/Users/Balmaceda/Desktop/Naomi
/Capture.png"); //change pic here
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);

}
});

}
}

还有这里的东西:

JLabel label = new JLabel(icon);

每次我把(icon)改成("icon"),窗口上只显示icon这个词。图片已不存在。

我想要发生的是图片上方的文字图标。

最佳答案

先看看 How to Use LabelsThe JavaDocs for `javax.swing.JLabel

基本上,您有多种选择。

你可以使用

JLabel label = new JLabel("This is an Icon", icon, JLabel.CENTER);

你可以使用

JLabel label = new JLabel();
label.setText("This is an icon");
label.setIcon(icon);

你可以使用

JLabel label = new JLabel("This is an icon");
label.setIcon(icon);

你可以使用

JLabel label = new JLabel(icon);
label.setText("This is an icon");

要使文本在图像上居中,您可以使用类似...

label.setVerticalTextPosition(JLabel.TOP);
label.setHorizontalTextPosition(JLabel.CENTER);

关于java - 带有图像的 JLabel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25591324/

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