【发布时间】:2020-05-03 23:31:51
【问题描述】:
我下面的 java 代码试图将图像和文本字段放在同一个类中。我是 java 编程的新手,我知道用另一种语言我只会 descale var pic = image 和 var text = textfield。这就是我在这个java代码中寻找的全部。只需声明一个文本字段和图像并让它显示在同一个窗口中。
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.*;
class Main extends JFrame {
public static void main(String[] args0) {
try {
JFrame frame = new JFrame();
File imageFile = new File("/Users/johnzalubski/Desktop/j/gg.jpg");
Image i = ImageIO.read(imageFile);
ImageIcon image = new ImageIcon(i);
JLabel imageLabel = new JLabel(image);
frame.add(imageLabel);
frame.setLayout(null);
imageLabel.setLocation(0, 0);
imageLabel.setSize(300, 250);
imageLabel.setVisible(true);
frame.setVisible(true);
frame.setSize(1000, 750);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Javatpoint.");
t1.setBounds(50,100, 200,30);
t2=new JTextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
frame.add(t1); f.add(t2);
frame.setSize(4000,400);
frame.setLayout(null);
frame.setVisible(true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
【问题讨论】:
-
frame.setLayout(null);将是您的第一个错误。你应该先通读Laying Out Components Within a Container -
1)
File imageFile = new File("/Users/johnzalubski/Desktop/j/gg.jpg");应用程序资源将在部署时成为嵌入式资源,因此明智的做法是立即开始访问它们。 embedded-resource 必须通过 URL 而不是文件访问。请参阅info. page for embedded resource 了解如何形成 URL。 2)frame.setSize(4000,400);什么..?你真的有一个屏幕资源。跨越 4000 像素?
标签: java image swing jframe textfield