Javaで画像を表示する方法とは
Javaで画像を表示する方法にはさまざまな選択肢がありますが、その中には以下のような一般的なメソッドがあります。
- SwingのJLabelとImageIconコンポーネントを利用する:
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class DisplayImage extends JFrame {
public DisplayImage() {
ImageIcon imageIcon = new ImageIcon("path/to/your/image.jpg");
JLabel label = new JLabel(imageIcon);
add(label);
pack();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new DisplayImage();
}
}
- Graphics クラスを使用し、JPanel から継承したコンポーネント
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class DisplayImage extends JPanel {
private Image image;
public DisplayImage() {
try {
image = ImageIO.read(new File("path/to/your/image.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
JFrame frame = new JFrame();
frame.add(this);
frame.setSize(image.getWidth(null), image.getHeight(null));
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
public static void main(String[] args) {
new DisplayImage();
}
}
- JavaFXのImageViewコンポーネントを使用する。
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class DisplayImage extends Application {
@Override
public void start(Stage primaryStage) {
Image image = new Image("file:path/to/your/image.jpg");
ImageView imageView = new ImageView(image);
StackPane root = new StackPane(imageView);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
1番目と2番目の方法はSwingベース、3番目の方法はJavaFXベースです。どちらを選択するかはプロジェクトの要件や開発環境に依存します。