JLabelで1つディスプレイを用意し、その下に3つのJButtonを用意します。
3つのJButtonにはそれぞれ画像が張り付けてあり、各ボタンを押すと、そのボタンの画像がディスプレイに表示されるというプログラムです。
actionPerformed(ActionEvent e)に画像変更の方法を3つ思い付き、if文で分けて実行してみましたが、どれもうまくいきませんでした。
その3つの案は
1, 新しくJLabelを作り、ディスプレイ用に代入して入れ替える
2, ディスプレイは最初にaddしているので、remove(0)で削除してから新しいLabelをaddする
3, JlabelのsetIconで画像を指定して変更する
それぞれの実行結果は
1, 何も変わらない
2, 画面がバグる(フリーズしてしまう)
3, 大量のエラー(エラーをみても理由がわかりませんでした)
この3つの方法がうまくいかない理由と改善案をご教授していただきたいです。よろしくお願いします。
Java
1import java.awt.*; 2import javax.swing.*; 3class ImageDisplayEvt extends JFrame implements ActionListener{ 4 JLabel lb1; 5 JButton bt1,bt2,bt3; 6 ImageIcon img1,img3_base,img4_base; 7 8 public ImageDisplayEvt(String title) { 9 setTitle(title); 10 setLocation(100,100); 11 setSize(640,600); 12 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 13 setLayout(new FlowLayout(FlowLayout.LEFT,20,20)); 14 15 //1枚目(Label) 16 img1=new ImageIcon("img/sakura1.jpg"); 17 int width=img1.getIconWidth(); 18 int height=img1.getIconHeight(); 19 JLabel lb1=new JLabel(new ImageIcon("img/sakura1.jpg")); 20 add(lb1); 21 22 //2枚目(Button1) 23 Image img2=img1.getImage().getScaledInstance((int) (width/(height/100.0)), 24 100, Image.SCALE_SMOOTH); 25 bt1=new JButton(new ImageIcon(img2)); 26 bt1.setPreferredSize(new Dimension((int) (width/(height/100.0)),100)); 27 add(bt1); 28 bt1.addActionListener(this); 29 30 //3枚目(Button2) 31 img3_base=new ImageIcon("img/sakura2.jpg"); 32 Image img3=img3_base.getImage().getScaledInstance( 33 (int) ((img3_base.getIconWidth())/(( img3_base.getIconHeight()/100))), 34 100, Image.SCALE_SMOOTH); 35 bt2=new JButton(new ImageIcon(img3)); 36 bt2.setPreferredSize(new Dimension( 37 (int) ((img3_base.getIconWidth())/(( img3_base.getIconHeight()/100))) 38 ,100)); 39 add(bt2); 40 bt2.addActionListener(this); 41 42 //4枚目(Button3) 43 img4_base=new ImageIcon("img/sakura3.png"); 44 Image img4=img4_base.getImage().getScaledInstance( 45 (int) ((img4_base.getIconWidth()/(img4_base.getIconHeight()/100.0))), 46 100, Image.SCALE_SMOOTH); 47 bt3=new JButton(new ImageIcon(img4)); 48 bt3.setPreferredSize(new Dimension( 49 (int) ((img4_base.getIconWidth()/(img4_base.getIconHeight()/100.0))), 50 100)); 51 add(bt3); 52 bt3.addActionListener(this); 53 54 } 55 56 public static void main(String[] args) { 57 (new ImageDisplayEvt("ImageDisplayEvent")).setVisible(true); 58 } 59 60 public void actionPerformed(ActionEvent e) { 61 if(e.getSource().equals(bt1)) { 62 System.out.println("bt1 was pushed!"); 63 64 JLabel lb2=new JLabel(img3_base); 65 this.lb1=lb2;//エラーはないが画像が変わらない 66 } 67 if(e.getSource().equals(bt2)) { 68 System.out.println("bt2 was pushed!"); 69 70 JLabel lb2=new JLabel(img3_base); 71 remove(0);add(lb2,0);//画面が止まる 72 } 73 if(e.getSource().equals(bt3)) { 74 System.out.println("bt3 was pushed!"); 75 76 this.lb1.setIcon(img4_base);//大量のエラー 77 } 78 } 79} 80
(追記)
それぞれの画像のサイズがバラバラですので、getIconWidth()とgetIconHeight()を用いて、高さが100になるように縮小しています。

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/04/24 12:09