• 締切済み

addActionListenerについて

ボタンbtn1をクリックした時の処理をさせたいと思っています。 そこで、addActionListenerを使って新しくクラスを作っています。 そこでe.getSouce()==btn1とすればbtn1が押された時の処理が通ると思ったのですが、 System.out.println()で確認してもどうも処理が通っていません。 コンストラクタ内でbtn1.addActionListenerとすればうまくいきましたが、 クラスごとに分けていきたいのであまりそういうことはしたくありません。 新しくクラスを作る方法でも出来ると思ったのですが、このソースでは何が原因で動かないのでしょうか? import java.awt.*; import java.awt.event.*; public class click2 extends Frame{ public static void main(String args[]){ click2 myfra=new click2(); myfra.show(); } Button btn1=new Button("start"); click2(){ setSize(300,200); setBackground(Color.white); setLayout(null); btn1.setBounds(50,70,40,20); add(btn1); } class Listener implements ActionListener{ public void actionPerformed(ActionEvent e){ if(e.getSource() == btn1){ System.out.println("btn1"); } } } }

  • Java
  • 回答数1
  • ありがとう数2

みんなの回答

  • shige_70
  • ベストアンサー率17% (168/946)
回答No.1

> コンストラクタ内でbtn1.addActionListenerとすればうまくいきましたが、 そもそも、これをしないのが原因です。 リスナを登録しなければリスナは呼ばれません。 > クラスごとに分けていきたいのであまりそういうことはしたくありません。 意味がよく分かりません。。。

usui323
質問者

お礼

失礼しました。解決しました。 コンストラクタ内に全てかいたらできましたが、 一行で宣言してクラスを作ってそこにアクションをかけばできました。 コンストラクタ内にアクションまで全部書いてると だらだらと長いわかりにくいソースになるので、 クラスごとに役割を持たせて簡潔に書きたかったんです。

関連するQ&A

  • GUI入門書のサンプルコード

    JavaのGUIをやってみようと思い中古で本を買ってきたのですが、 その中のサンプルコードが意味がわからない上にコンパイルエラーを起こすので 誰か解説をお願いします。 OS:Win Vista、それとJDK7です。 以下がソースコードとコンパイルエラーになります。 import java.awt.*; import javax.swing.*; import java.awt.event.*;    //サンプルではActionListenerを使うのに抜けていた public class MyButton { ____JButton button; ________//※1 何故ここで宣言しているのか ____public static void main(String[] args) { ________JFrame frame = new JFrame("MyFrame"); ________Container pane = frame.getContentPane(); ________JButton button = new JButton("MyButton");________//※1 何故ここにもあるのか ________button.addActionListener(new MyActionListener()); //※2 MyActionListenerクラスはstaticでないので使用できない ________pane.add(button); ________frame.setBounds(100, 50, 300, 200); ________frame.setVisible(true); ________frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ____} ____class MyActionListener implements ActionListener { ________public void actionPerformed(ActionEvent e) ________//サンプルではpublicが抜けていた ____________if(e.getSource() == button) ________________System.out.println("button was pressed"); ________} ____} } /* MyButton.java:13: static でない 変数 this を static コンテキストから参照すること はできません。 button.addActionListener(new MyActionListener()); ^ エラー 1 個 */

    • ベストアンサー
    • Java
  • HTMLファイルを開きたい

    こんにちは、いつもお世話になっています。 質問があります。 アプレットでボタンを押すと、 HTMLファイル「c:/test_folder/test.html」 を開きたいのですが、 下記コードの(☆) のところに何を書いていいかわかりません。 どなたかご存知でしたら教えていただけないでしょうか? よろしくお願いします。 ============================================================= import javax.swing.*; import java.awt.*; import java.applet.Applet; import java.awt.event.*; import java.net.*; public class situmon extends Applet implements ActionListener { JPanel panel; JButton button; public void init() { panel=new JPanel(); button=new JButton("次へ"); button.addActionListener(this); panel.add(button); this.add(panel); } public void actionPerformed(ActionEvent e) { if(e.getSource()==button) { (☆); } } }

    • ベストアンサー
    • Java
  • イベント処理がうまくいきません。

    java初心者です。 スタートボタンをクリックするとトランプ52枚表示されるようにしたいのですが、 1枚も表示されず、原因もよく分からないため苦労してます。 よろしくお願い致します。 以下は、プログラムです。 import java.awt.Color; import java.awt.Dimension; import java.awt.*; import javax.swing.*; import java.io.*; import javax.imageio.*; import java.awt.Graphics; import java.awt.Font; import javax.swing.JButton; import java.awt.Container; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.event.*; public class narabi2 extends JPanel{ JButton btn1,btn2,btn3; static Image img[] = new Image[52]; public static void main(String[] args) { JFrame f = new JFrame(); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.setResizable(true); f.setVisible(true); new narabi2(); } public narabi2(){ btn1 = new JButton("スタート"); this.add(btn1); btn1.addActionListener(new ev()); btn2 = new JButton("ランキング"); this.add(btn2); btn2.addActionListener(new ev()); btn3 = new JButton("ログアウト"); this.add(btn3); btn3.addActionListener(new ev()); JFrame f = new JFrame(); f.setSize(900,840); f.getContentPane().setBackground(new Color(0,100,0)); f.setDefaultCloseOperation(f.EXIT_ON_CLOSE); f.setResizable(true); f.setVisible(true); f.add(this); } public void paintComponent(Graphics g){ super.paintComponent(g); btn1 = new JButton("スタート"); this.add(btn1); btn1.addActionListener(new ev()); btn2 = new JButton("ランキング"); this.add(btn2); btn2.addActionListener(new ev()); btn3 = new JButton("ログアウト"); this.add(btn3); btn3.addActionListener(new ev()); setBackground(new Color(0,100,0)); int i;               //カードを並べる処理 int x = 0,y=0; for (i = 0; i < 52; i++) { g.drawImage(img[i], x, y, null); x = x + 100; if(x>=900){ x=0; y=y+140; } } } class ev implements ActionListener{ public void actionPerformed(ActionEvent m){ if(m.getSource()==btn1) //スタート { //public static void main(String[] args) { // 画像ファイルの読み込み int i, j; int no = 0; String c[] = {"s","h","c","d"}; try { for(i = 0; i < 4; i++) { for(j = 1; j <= 13; j++) { //String filename = "cards.png"; String filename = String.format("cards/%s%02d.png", c[i], j); img[no] = ImageIO.read(new File(filename)); no++; } } } catch(Exception e) { System.out.println(e); System.exit(0); } // シャッフル Image w; for (i = 51; i >= 0; i--) { j = (int)(Math.random() * (i + 1)); w = img[i]; img[i] = img[j]; img[j] = w; } } /*public void paintComponent(Graphics g) { super.paintComponent(g); int i; int x = 0,y=0; for (i = 0; i < 52; i++) { g.drawImage(img[i], x, y, null); x = x + 100; if(x>=900){ x=0; y=y+140; } } }*/ } /*else if(m.getSource()==btn2) //ランキング { } else if(m.getSource()==btn3) //ログアウト { } }*/ } }

  • main()メソッドが無いコード

    最近、Javaアプレット等を勉強してるのですが 今まではmain()メソッドの中に処理を書いて来たのですが、 下記の様なコードにはmain()メソッドが有りません。 import java.applet.Applet; import java.awt.Button; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Sample6 extends Applet implements ActionListener { Button bt; public void init() { bt = new Button("開始"); add(bt); bt.addActionListener(this); } public void actionPerformed(ActionEvent ae) { bt.setLabel("中止"); } } これはどう言う事なんでしょうか?

    • ベストアンサー
    • Java
  • javaのmainの中のループに割込を掛ける

    毎度、お世話になります。 javaのmainの中のループに割込を掛ける方法をお教えください。 添付コードの『Thread.currentThread().interrup()』は、旨く機能しません。 以上、宜しくお願いします。 =========== import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class T_try_loop extends JFrame{ JFrame frame=new JFrame(); T_try_loop(){ System.out.println("aaaa"); JPanel p1=new JPanel(); JButton button1=new JButton("button1"); button1.addActionListener(new TimButton1()); p1.add(button1); getContentPane().add(p1, BorderLayout.CENTER); } public static void main(String args[]){ T_try_loop frame=new T_try_loop(); frame.setTitle("TTTT"); frame.setBounds(10,10,400,300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); for(int j = 0;j < 80; j++){ try{ Thread.sleep(80); System.out.print("*"); } catch(InterruptedException e){ System.out.println(": main_loopに、今割り込まれました"); } } }//public static void main public class TimButton1 implements ActionListener{ @Override public void actionPerformed(ActionEvent ae){ String cmd =ae.getActionCommand(); if(cmd.equals("button1")){ Thread.currentThread().interrupt(); System.out.println("Button clicked"); } } }//public class TimButton1 }

    • ベストアンサー
    • Java
  • なんかエラーがでた

    とあるプログラムをeclipseで作ったら問題なく動きました。しかし学校のPCでやると実行時にエラーがでました。それが以下です。 class javax.swing.JFrameにはExit_ON_CLOSEは定義されていません ちなみにソースは以下です import javax.swing.*; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.event.*; import java.util.Vector; import java.awt.event.* ; public class f_sotu3 extends JFrame { JPanel p; JButton btn1; JTextField tx1; public f_sotu3(){ p = new JPanel(); p.setLayout(null); btn1 = new JButton("検索"); tx1 = new JTextField(); setTitle("卒論"); setBounds( 10, 10, 1100, 1100); btn1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event){ System.out.println(tx1.getText()); } } ); btn1.setBounds(500,50,100,60); tx1.setBounds(50,170,900,60); tx1.setFont(new Font("MS ゴシック",Font.BOLD,18)); p.add(tx1); p.add(btn1); getContentPane().add(p); } public static void main(String[] args){ /* 自分自身を作成 */ f_sotu3 test = new f_sotu3(); /* 終了処理を追加 */ test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); test.setVisible(true); /* 実際に表示する */ } }

    • ベストアンサー
    • Java
  • jcpad

    『長方形をあらかじめ置き、、縮小、拡大のボタンを押すことで  縦横を1/1.05倍に縮小できるようにする』 という問題が教科書にあり、拡大、縮小ボタンを作るまではできたのですがそれ以降がうまく考えることができません。 //<applet code= "Counter3.class" width=300 height=150></applet> import java.awt.*; import java.applet.*; import java.awt.event.*; public class Counter3 extends Applet implements ActionListener { Font font; Button kakudaiButton, syukushoButton; public void init() { font = new Font("Serif", Font.BOLD, 72); kakudaiButton = new Button("拡大"); kakudaiButton.addActionListener(this); add(kakudaiButton); syukushoButton = new Button("縮小"); syukushoButton.addActionListener(this); add(syukushoButton); } public void paint(Graphics g) { g.drawOval(); } public void actionPerformed(ActionEvent e) { if (e.getSource() == kakudaiButton) { ; } else if (e.getSource() == syukushoButton) { ; } repaint(); } }

  • java.lang.OutOfMemoryErrorというエラーがでる。

    javaを勉強しています。タイトルのように java.lang.OutOfMemoryErrorというエラーが出てしまいます。少し調べてみたらどうやらメモリーの使いすぎ(?)のようなのですが、プログラムの方に問題があるのでしょうか?それとも使えるメモリーを増やすといった解決策を取ったほうがいいのでしょうか? よろしくお願いします。プログラムはまず画像が表示されて、左クリックすると次の画像へ変わる、といった処理をするアプレットです。 package jibundesukosidutu; import java.applet.Applet; import java.awt.Graphics; import java.awt.MediaTracker; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class Main extends Applet implements MouseListener{ File[] imagelist; File image = new File("image"); BufferedImage drawImage; static int i = 0; MediaTracker mt = new MediaTracker(this); public void init(){ imagelist = image.listFiles();//ディレクトリの画像ファイルたちを配列に入れていく。 addMouseListener(this); try { drawImage = ImageIO.read(imagelist[i]);//drawImageメソッドで画像ファイルとして引数を取れるように、型変換しておく。 } catch (IOException e) { e.printStackTrace(); } } public void paint(Graphics g){//drawImageファイルを表示するだけ int w, h; w = getSize().width; h = getSize().height; mt.addImage(drawImage,0); try { mt.waitForID(0); } catch (InterruptedException e) { e.printStackTrace(); } g.drawImage(drawImage,0,0,w,h,this);//imagelist[0]を表示したい。 } public void mouseClicked(MouseEvent e) { int btn = e.getButton(); if(btn == MouseEvent.BUTTON1){//左クリック=進め System.out.println("左クリック"); i++; //searchFile(true); try { drawImage = ImageIO.read(imagelist[i]); } catch (IOException e1) { e1.printStackTrace(); } repaint(); }else if(btn == MouseEvent.BUTTON2){ System.out.println("右クリック"); //searchFile(false); } } public void searchFile(boolean next){ //next→次の画像、false→前の画像 } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } }

    • ベストアンサー
    • Java
  • 画像処理についておしえてください!

    ここに新たに表示した画像を消去するボタンを 追加したいので教えてください! import java.awt.*; import java.awt.event.*; import java.io.*; import java.applet.Applet; public class k202 extends Frame implements ActionListener { MyCanvas c1; Button b1; Button e1; Image img; Button btnClear; int flag; public k202() { super(); setTitle("Hello"); setSize(500,500); setLayout(null); c1 = new MyCanvas(); c1.setBounds(25,25,250,150); this.add(c1); b1 = new Button("Read"); b1.setBounds(25,200,100,25); b1.addActionListener(this); this.add(b1); e1 = new Button("Clear"); e1.setBounds(50,250,150,50); //ボタンのイベント処理メソッドを定義 e1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ flag = 0; repaint(); } }); } public static void main (String args []) { new k202().show(); } public void actionPerformed(ActionEvent ev) { if (ev.getSource() == b1) { this.readImageFromFile(); } } void readImageFromFile() { try { FileDialog fd = new FileDialog(this,"Select Image File.",FileDialog.LOAD); fd.setVisible(true); String fname = fd.getDirectory() + fd.getFile(); Toolkit tk = Toolkit.getDefaultToolkit(); img = tk.getImage(fname); c1.repaint(); } catch(Exception e) { System.out.println(e); } } class MyCanvas extends Canvas { public void paint(Graphics g) { if (img != null) { g.drawImage(img,0,0,this); } } } }

  • AWTのアプレットにおいてのイベント処理

    javaのAWTでアプレット作成をしているのですがイベント処理部分をどう記述したらいいか解りません。 組み込みたいイベント処理は 1、アプレット起動時に「単語<tab>数字:数字,数字:数字,.......」という形のデータが入っているファイルを読み込んで数字列が一番多い単語(ただし二字熟語~四字熟語)を多い順に9つのボタンのラベルに格納していく。(どの位置のボタンのラベルに格納するかは自由) 2、ボタンを押すと1に書いているファイルを読み込みボタンのラベルに対応した数字列を見つけそれをテキストフィールドに全て出力させる。 ヒントだけでも宜しければ教えてください。お願いします。 /*<HTML> <BODY> <APPLET CODE="Tagcloud.class" WIDTH=400 HEIGHT=350> </APPLET> </BODY> </HTML>*/ //java.appletパッケージをimport宣言 //java.awtパッケージもimport宣言 import java.applet.*; import java.awt.*; import java.awt.event.*; public class Tagcloud extends Applet implements ActionListener{ //AWTのGUIコンポーネントクラスの作成 Button bu1 = new Button(""); Button bu2 = new Button(""); Button bu3 = new Button(""); Button bu4 = new Button(""); Button bu5 = new Button(""); Button bu6 = new Button(""); Button bu7 = new Button(""); Button bu8 = new Button(""); Button bu9 = new Button(""); TextField tf=new TextField(20);//テキストフィールド public void init(){ setBackground(new Color(0,190,221)); //レイアウトを自由に変更 setLayout(null); //アプレット領域にGUIコンポーネント(部品)の追加(載せる) add(bu1); add(bu2); add(bu3); add(bu4); add(bu5); add(bu6); add(bu7); add(bu8);   add(bu9);   add(tf); //コンポーネントの配置 bu1.setBounds(50,50,80,20); bu2.setBounds(150,50,80,20); bu3.setBounds(250,50,80,20); bu4.setBounds(50,120,80,20); bu5.setBounds(150,120,80,20); bu6.setBounds(250,120,80,20); bu7.setBounds(50,190,80,20); bu8.setBounds(150,190,80,20); bu9.setBounds(250,190,80,20); tf.setBounds(50,250,250,20); //ボタンにActionListenerを登録します。 bu1.addActionListener(this); bu2.addActionListener(this); bu3.addActionListener(this); bu4.addActionListener(this); bu5.addActionListener(this); bu6.addActionListener(this); bu7.addActionListener(this); bu8.addActionListener(this); bu9.addActionListener(this); tf.addActionListener(this); } public void actionPerformed(ActionEvent e){ //ここにイベント処理をする部分を記述 } }

専門家に質問してみよう