生物屋さんのためのゼロからのプログラミング

―忘れないための覚書 (たま~に更新)―

スクリーンサイズのJFrameの作成とJInternalFrameの枠線の除去と配置の固定

ソースコードを書きに記す。

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
import javax.swing.plaf.basic.BasicInternalFrameUI;

public class InterTest extends JFrame implements ActionListener  {

	int w;
	int h;
	BufferedImage img;
	MyPanel mypane;

	//スクリーンサイズのフレームを作成
	public void OpenFrame () {
		JFrame frame1 = new JFrame ("Test");
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		int sw = screenSize.width;
		int sh = screenSize.height;
		frame1.setSize(sw, sh);
		frame1.setVisible (true);

		try {
			 File openFile = new File("開く画像");
			 img = ImageIO.read(openFile);
			 h = img.getHeight();
			 w = img.getWidth();
		} catch (IOException ex) {
			System.out.println("miss");
		}

		JDesktopPane deskPane = new JDesktopPane();
		JInternalFrame iFrame1 = new JInternalFrame();
		iFrame1.setBorder(BorderFactory.createEmptyBorder());
		BasicInternalFrameUI ui = (BasicInternalFrameUI) iFrame1.getUI();
		ui.setNorthPane(null);
		iFrame1.setBounds(600, 100, w, h);
		iFrame1.setVisible(true);

		mypane = new MyPanel(w, h);
		iFrame1.getContentPane().add(mypane, BorderLayout.CENTER);
		deskPane.add(iFrame1);
		frame1.getContentPane().add(deskPane);
	}

	public class MyPanel extends JPanel {
		public MyPanel(int width, int height) {
			setSize(width, height);
		}

		public void paintComponent(Graphics g) {
			g.drawImage(img, 0, 0, this);
		}
	}

	public void actionPerformed (ActionEvent e ) {
		String cmd = e.getActionCommand ();

		if (cmd.equals("push")) {
			OpenFrame();
		}
	}

	InterTest () {
		JButton button = new JButton ("Push");
		button.setBounds(40, 10, 90, 30);
		button.addActionListener (this);
		button.setActionCommand("push");
		JPanel pane = new JPanel ();
		pane.setLayout(null);
		pane.add(button);
		getContentPane().add(pane, BorderLayout.CENTER);
	}

	public static void main(String[] args) {
		InterTest frame = new InterTest ();
		frame.setTitle ("Title");
		frame.setBounds(10, 10, 180, 90);
		frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
		frame.setVisible (true);
	}
}

スクリーンサイズのJFrameを作成するために、

	Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
	int sw = screenSize.width;
	int sh = screenSize.height;

の部分でスクリーンサイズを取得している。

また、JInternalFrameの枠線の除去は、

	iFrame1.setBorder(BorderFactory.createEmptyBorder());

で行い、このInternalFrameの固定は、

	BasicInternalFrameUI ui = (BasicInternalFrameUI) iFrame1.getUI();
	ui.setNorthPane(null);

で行っている。

JInternalFrameの確認のために、今回は画像をJInternalFrameに張り付けた。