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
import java.awt.*; import javax.swing.*; class ImageDisplayEvt extends JFrame implements ActionListener{ JLabel lb1; JButton bt1,bt2,bt3; ImageIcon img1,img3_base,img4_base; public ImageDisplayEvt(String title) { setTitle(title); setLocation(100,100); setSize(640,600); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new FlowLayout(FlowLayout.LEFT,20,20)); //1枚目(Label) img1=new ImageIcon("img/sakura1.jpg"); int width=img1.getIconWidth(); int height=img1.getIconHeight(); JLabel lb1=new JLabel(new ImageIcon("img/sakura1.jpg")); add(lb1); //2枚目(Button1) Image img2=img1.getImage().getScaledInstance((int) (width/(height/100.0)), 100, Image.SCALE_SMOOTH); bt1=new JButton(new ImageIcon(img2)); bt1.setPreferredSize(new Dimension((int) (width/(height/100.0)),100)); add(bt1); bt1.addActionListener(this); //3枚目(Button2) img3_base=new ImageIcon("img/sakura2.jpg"); Image img3=img3_base.getImage().getScaledInstance( (int) ((img3_base.getIconWidth())/(( img3_base.getIconHeight()/100))), 100, Image.SCALE_SMOOTH); bt2=new JButton(new ImageIcon(img3)); bt2.setPreferredSize(new Dimension( (int) ((img3_base.getIconWidth())/(( img3_base.getIconHeight()/100))) ,100)); add(bt2); bt2.addActionListener(this); //4枚目(Button3) img4_base=new ImageIcon("img/sakura3.png"); Image img4=img4_base.getImage().getScaledInstance( (int) ((img4_base.getIconWidth()/(img4_base.getIconHeight()/100.0))), 100, Image.SCALE_SMOOTH); bt3=new JButton(new ImageIcon(img4)); bt3.setPreferredSize(new Dimension( (int) ((img4_base.getIconWidth()/(img4_base.getIconHeight()/100.0))), 100)); add(bt3); bt3.addActionListener(this); } public static void main(String[] args) { (new ImageDisplayEvt("ImageDisplayEvent")).setVisible(true); } public void actionPerformed(ActionEvent e) { if(e.getSource().equals(bt1)) { System.out.println("bt1 was pushed!"); JLabel lb2=new JLabel(img3_base); this.lb1=lb2;//エラーはないが画像が変わらない } if(e.getSource().equals(bt2)) { System.out.println("bt2 was pushed!"); JLabel lb2=new JLabel(img3_base); remove(0);add(lb2,0);//画面が止まる } if(e.getSource().equals(bt3)) { System.out.println("bt3 was pushed!"); this.lb1.setIcon(img4_base);//大量のエラー } } }
(追記)
それぞれの画像のサイズがバラバラですので、getIconWidth()とgetIconHeight()を用いて、高さが100になるように縮小しています。
まだ回答がついていません
会員登録して回答してみよう