こんな感じですか
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Title extends JFrame implements ActionListener {
boolean inAnApplet = true;
JPanel cards;
JButton kirikae;
final static String TEST_PANEL = "てすと";
final static String TEST2_PANEL = "てすと2";
String currentPanel = TEST_PANEL;
public Title() {
Container contentPane = getContentPane();
kirikae = new JButton("切替");
kirikae.setActionCommand("change");
kirikae.addActionListener(this);
JPanel bp = new JPanel();
bp.add(kirikae);
// Use the default layout manager, BorderLayout
contentPane.add(bp, BorderLayout.SOUTH);
cards = new JPanel();
cards.setLayout(new CardLayout() );
DrawPanel p1 = new DrawPanel ("テストプログラム" , "今回は、CardLayoutを使用して"
, "画像表示のプログラムを作ってみました", "test.jpg" );
DrawPanel p2 = new DrawPanel ("どうでした?" , "皆さんも一度画像表示のプログラムを"
, "作ってみてはいかがでしょうか?", "test2.jpg") ;
cards.add(p1, TEST_PANEL);
cards.add(p2, TEST2_PANEL);
contentPane.add(cards, BorderLayout.CENTER);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
if (inAnApplet) {
dispose();
} else {
System.exit(0);
}
}
} );
}
public void actionPerformed (ActionEvent e) {
CardLayout cl = (CardLayout)(cards.getLayout() );
if (e.getActionCommand().equals("change")) {
if (currentPanel == TEST_PANEL) {
cl.show(cards, TEST2_PANEL );
currentPanel = TEST2_PANEL;
} else {
cl.show(cards, TEST_PANEL );
currentPanel = TEST_PANEL;
}
}
}
public static void main(String[] argv) {
Title window = new Title();
window.inAnApplet = false;
window.setTitle("CardLayout");
window.pack();
window.setVisible(true);
}
public Dimension getMinimumSize() {
return new Dimension(640,480);
}
public Dimension getPreferredSize() {
return getMinimumSize();
}
}
class DrawPanel extends JPanel{
String message1, message2, message3 ;
String path ;
Image image;
public DrawPanel(String m1, String m2, String m3, String fileName) {
//ImageIcon icon = new ImageIcon(path);
Toolkit toolkit = Toolkit.getDefaultToolkit();
this.path = fileName;
this.message1 = m1;
this.message2 = m2;
this.message3 = m3;
image = toolkit.getImage (path);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
g.setFont(new Font("TimesRoman",Font.ITALIC,30));
g.setColor(Color.red);
g.drawString(this.message1 , 60, 230);
g.drawString(this.message2 , 60, 260);
g.drawString(this.message3 , 60, 290);
}
public Dimension getMinimumSize() {
return new Dimension(640,400);
}
public Dimension getPreferredSize() {
return getMinimumSize();
}
}
お礼
実行してみましたら、ちゃんと画像と文字が同時に表示しました! とても助かりましたよ。 本当に有難うございます。