SWTでボタンの処理の記述方法について教えてください

このQ&Aのポイント
  • SWTを使用してGUIを作成しています。ボタンが押されるとテキストボックスに入力された値を計算し、結果を表示する処理を行いたいです。
  • addSelectionListenerを使用してボタンが押されたときの処理を記述しましたが、異なるメソッドで定義されたインナー・クラス内で非 final 変数を参照できず、エラーが発生しています。
  • addSelectionListener内でテキストボックスの値を使用する方法について教えてください。
回答を見る
  • ベストアンサー

SWTです。ボタンの処理の記述の仕方がわかりません

現在SWTにて簡単なGUIの作成を行っています。 流れとしては、mainにてシェルを作ってボタンが押された場合、テキストボックスに入力された値を計算して返す、というものです。 public static void main(String[] args) { Display display = new Display (); Shell shell = new Shell(display); shell.setLayout(new GridLayout(1,true)); shell.setText("集計"); shell.setSize(250, 200); Label label1 = new Label(shell,SWT.NULL); label1.setText("値1"); Text text1 = new Text(shell,SWT.SINGLE|SWT.BORDER); GridData gridData1 = new GridData(); gridData1.horizontalAlignment = GridData.FILL; gridData1.grabExcessHorizontalSpace = true; text1.setLayoutData(gridData1); Label label2 = new Label(shell,SWT.NULL); label2.setText("値2"); Text text2 = new Text(shell,SWT.SINGLE|SWT.BORDER); GridData gridData2 = new GridData(); gridData2.horizontalAlignment = GridData.FILL; gridData2.grabExcessHorizontalSpace = true; text2.setLayoutData(gridData2); Label label3 = new Label(shell,SWT.NULL); label3.setText("値3"); Text text3 = new Text(shell,SWT.SINGLE|SWT.BORDER); GridData gridData3 = new GridData(); gridData3.horizontalAlignment = GridData.FILL; gridData3.grabExcessHorizontalSpace = true; text3.setLayoutData(gridData3); Button button1 = new Button(shell,SWT.NULL); button1.setText("集計"); shell.open(); while (!shell.isDisposed ()){ if (!display.readAndDispatch ()){ display.sleep (); } } display.dispose (); } ここで、調べたところ、ボタンが押された場合の処理としてaddSelectionListenerを定義すると良い、というのもわかりました。 button1.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { System.out.println("widgetDefaultSelected"); } public void widgetSelected(SelectionEvent e) { keisan(値1, 値2, 値3); } }); ここで、このaddSelectionListener内で上記テキストボックスtext1~3の値をkeisanメソッドに渡したいのですが、どうしても 「異なるメソッドで定義されたインナー・クラス内で非 final 変数 text1 を参照できません」 とエラーが出てしまいます。 addSelectionListener内でテキストボックスに入力された値を使うにはどうすれば良いのでしょうか。

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

質問者が選んだベストアンサー

  • ベストアンサー
  • salsberry
  • ベストアンサー率69% (495/711)
回答No.1

試さずに回答しますが、変数text1などにfinal宣言を追加してみてください。 final Text text1 = new Text(shell,SWT.SINGLE|SWT.BORDER);

mifu223
質問者

お礼

スコープの問題だったとは・・・ありがとうございます! 調べが足りなかったようでした。お騒がせしました。

関連するQ&A

  • javaのボタン表示等に関する質問

    下記のコードはフォームをNORTH、CENTER、SOUTHEに分割して、それぞれのpaneに ラベルとボタンを表示するものです。 Q1)myFrame.setBounds(350,0, total_x, total_y)をコンストラクターの最初に記述しますと  フォームの表示が正常でなく、コンストラクターの最後では、正常に行なわれます。  この理由等について、コメント頂けますと有り難いです。 Q2)mainに記述してある、下記のコードは無くても、Xでクロースできますが,このコード  の記述は正しいでしょうか GridLayout_new frame = new GridLayout_new(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 以上お手数ですが、コメント頂けますと大変助かります。 //============================================= import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.LineBorder; public class GridLayout_new extends JFrame{ int panelA_x=200, panelA_y=50; int panelB_x=200, panelB_y=200; int panelC_x=200, panelC_y=50; int total_x=panelA_x; int total_y=panelA_y+panelB_y+panelC_y; public static void main(String[] args){ GridLayout_new frame = new GridLayout_new(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } GridLayout_new(){ JFrame myFrame=new JFrame(); myFrame.setTitle("panelA"); // myFrame.setBounds(350,0, total_x, total_y); //正常なformの表示が出来ない myFrame.setVisible(true); LineBorder border = new LineBorder(Color.BLACK, 1, true); //======================== JLabel button1=new JLabel("Label1"); GLabel_Layout(button1, border); JButton button2 = new JButton("button2"); button_Layout(button2, border); //======================== JLabel button3=new JLabel("Label3"); GLabel_Layout(button3, border); JButton button4 = new JButton("button4"); button_Layout(button4, border); //======================== JLabel button5=new JLabel("Label5"); GLabel_Layout(button5, border); JButton button6 = new JButton("button6"); //======================== JLabel button7=new JLabel("Label7"); GLabel_Layout(button7, border); JButton button8 = new JButton("button8"); //======================== JLabel button9=new JLabel("Label9"); GLabel_Layout(button9, border); JButton button10 = new JButton("button10"); button_Layout(button10, border); //======================== JLabel button11=new JLabel("Label11"); GLabel_Layout(button11, border); JButton button12 = new JButton("button12"); button_Layout(button12, border); //================================== JPanel p1 = new JPanel(); GridLayout layout1 = new GridLayout(2,2); //2行、2列の設定 layout1.setHgap(2); layout1.setVgap(10); p1.setLayout(layout1); p1.setBackground(Color.GREEN); p1.add(button1); p1.add(button2); p1.add(button3); p1.add(button4); myFrame.setSize(panelA_x, panelA_y); myFrame.getContentPane().add(p1, BorderLayout.NORTH); //============================== JPanel p2 = new JPanel(); GridLayout layout2 = new GridLayout(2,2); //2行、2列の設定 layout2.setHgap(2); layout2.setVgap(10); p2.setLayout(layout2); p2.setBackground(Color.GREEN); p2.add(button5); p2.add(button6); p2.add(button7); p2.add(button8); myFrame.setSize(panelB_x, panelB_y); myFrame.getContentPane().add(p2, BorderLayout.CENTER); //================================== JPanel p3 = new JPanel(); GridLayout layout3 = new GridLayout(2,2); //2行、2列の設定 layout3.setHgap(2); layout3.setVgap(10); p3.setLayout(layout3); p3.setBackground(Color.GREEN); p3.add(button9); p3.add(button10); p3.add(button11); p3.add(button12); myFrame.setSize(panelC_x, panelC_y); myFrame.getContentPane().add(p3, BorderLayout.SOUTH); myFrame.setBounds(350,0, total_x, total_y); //正常なformの表示 } //constructor void GLabel_Layout(JLabel label, LineBorder border){ label.setPreferredSize(new Dimension(80,20)); label.setBorder(border); label.setBackground(Color.lightGray); label.setOpaque(true); } void button_Layout(JButton button, LineBorder border){ button.setPreferredSize(new Dimension(80,20)); button.setBorder(border); } } //main class....GridLayout_new

    • ベストアンサー
    • Java
  • SWTのStyledTextを使用したコンソールの開発

    SWTのStyledTextを使って、コマンドプロンプトのSWT版を作ろうと考えています。 具体的には、Google Androidの「adb shell logcat」の内容をSWTのStyledTextに表示したいのですが、実行するとGUIが固まってしまいます。 期待している動作は、「adb shell logcat」をStyleTextから実行後すると、一度、ログの内容が出力され、そのまま待機します。 その後、ログが出力されてるたびにStyleTextにログが追記されるというものです。 以下は該当箇所のソースです。 String command = "C:/android-sdk-windows-1.5_r1/tools/adb.exe shell logcat"; Display.getCurrent().asyncExec(new Runnable() { @Override public void run() { exec(command); } }); protected boolean exec(String command) { Process process = null; ProcessBuilder pb = new ProcessBuilder("cmd", "/C", command); try { process = pb.start(); InputStream in = process.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8")); String line; while ((line = br.readLine()) != null) { if (line.length() == 0) { line = br.readLine(); } // 次も空行なら終了 if (line.length() == 0) { break; } styledText.append(line); styledText.append("\n"); // スクロールバーを下に動かす styledText.setTopIndex(styledText.getLineCount()); } br.close(); } catch (Exception e) { e.printStackTrace(); return false; } return true; }

    • ベストアンサー
    • Java
  • java修正

    以下のDentaku.javaのソースコードには引き算と割り算の部分が抜けてしまっているのですが引き算と割り算の部分を付け加えてくれる方お願いします。。(うまく手を加えることができませんでした) // Dentaku.java import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Dentaku extends JFrame implements ActionListener { JTextField text1, text2; JButton button1, button2, button3; JLabel label; // コンストラクタ public Dentaku() { // コンテントペインを取得 Container contentPane = getContentPane(); // レイアウトマネージャーを設定 contentPane.setLayout(new GridLayout(6,1)); // テキストフィールド生成 text1 = new JTextField("", 20); text2 = new JTextField("", 20); // テキストフィースドを追加 contentPane.add(text1); contentPane.add(text2); // ボタンを作成 button1 = new JButton("+"); button2 = new JButton("x"); button3 = new JButton("Clear"); // アクションリスナーを登録 button1.addActionListener(this); button2.addActionListener(this); button3.addActionListener(this); // ボタンを追加 contentPane.add(button1); contentPane.add(button2); contentPane.add(button3); // ラベルを生成 label = new JLabel(""); // 文字を真ん中に表示 label.setHorizontalAlignment(JLabel.CENTER); // ラベルを追加 contentPane.add(label); // ウインドウが閉じられたときにアプリケーションを終了するように設定 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // サブコンポーネントの推奨サイズおよびレイアウトに合わせて // この Window をサイズ変更するように設定 pack(); // 表示します setVisible(true); } public static void main(String[] args) { // フレームを作成 Dentaku frame = new Dentaku(); } /** * アクションが発生すると呼び出されます。 */ public void actionPerformed(ActionEvent ae){ // イベントが指定されたボタンで発生した場合 //足し算 if (ae.getSource().equals(button1)) { try{ String tx1=text1.getText(); String tx2=text2.getText(); double d1=Double.parseDouble(tx1); double d2=Double.parseDouble(tx2); String answer=Double.toString(d1+d2); label.setText(answer); }catch (NumberFormatException e) { label.setText("数字を正しく入力してください。"); } } //掛け算 if (ae.getSource().equals(button2)) { try{ String tx1=text1.getText(); String tx2=text2.getText(); double d1=Double.parseDouble(tx1); double d2=Double.parseDouble(tx2); String answer=Double.toString(d1*d2); label.setText(answer); }catch (NumberFormatException e) { label.setText("数字を正しく入力してください。"); } } if (ae.getSource().equals(button3)) { text1.setText(""); text2.setText(""); label.setText(""); } } }

  • java アプレット

    学校の授業でアプレットを学んでいます。 しかし・・・ 下のプログラムで、計算した結果をlabel3にはりつけたいのですが、計算結果がでてくれません・・・ボタンを押しても何もでてきません。 コマンドプロンプトで、エラーはでてきません。 お手数ですが、誰かどこがいけないのか教えて下さい。 import java.awt.*; import java.awt.event.*; public class B extends java.applet.Applet implements ActionListener { Label label3 = new Label(); Button button2 = new Button(); TextField textfield1= new TextField(10); TextField textfield2= new TextField(10); public void init() { button2.setLabel("入力したらクリック!"); button2.setBounds(new Rectangle(50, 465, 120, 20)); this.setLayout(null); label3.setBackground(Color.blue); label3.setBounds(new Rectangle(325, 80, 200, 35)); textfield1.setBounds(100, 425, 100, 25); textfield2.setBounds(150, 350, 100, 25); this.add(textfield2, null); this.add(label3, null); this.add(textfield1, null); this.add(button2, null);} public void actionPerformed(ActionEvent event) {if(event.getSource() == button2) {int diff = Integer.parseInt(textfield1.getText()) - Integer.parseInt(textfield2.getText()); String otsuri; otsuri ="お釣りは"+ diff +"円です。"; label3.setText(otsuri);} }} よろしくお願いします。

    • ベストアンサー
    • Java
  • event処理の初期化について

    クリックすると数字が1つづ増えていく処理はできるのですが、 別ボタンをクリックすると、最初の0に戻したいのですがどのようにすればいいのでしょうか・・ 仮に、b.setText("0");として0が表示できたとしても、そのあと上の増幅ボタンを押すとそれまで増えていた数から1ずつ増えてしまいます つまり、リセットする!というようなことをしたいのですが考え方も方法もわからないのです。どなたかご回答よろしくお願いいたします import java.awt.*; import java.awt.event.*; class click_a extends Frame{ Button a1,a2; Label b; Panel c; int d=0; click_a(){ setSize(300,300); setVisible(true); a1=new Button("ボタンを押すと数字が足し算されます"); a2=new Button("初期値に戻します"); b=new Label(""+d); c=new Panel(); c.setLayout(new GridLayout(3,1)); add(c); c.add(a1); c.add(a2); c.add(b); a1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ b.setText(""+d); d++; } }); a2.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ b.setText("0"); } }); } public static void main(String[] args){ new click_a(); } }

    • ベストアンサー
    • Java
  • java起動時にボタンが表示されない

    Javaの初心者です。以下のプログラムを起動するとJTextAreaとJLabel は、表示されるのですが、JButtonが表示されません。起動後にボタンの配置したところを触るとボタンが表示されるようになるのですが、ボタンのアクションリスナーが動作してしまいます。起動時にボタンも表示できるようにするには、どうしたらよいでしょうか? public class test_pro extends JFrame{ private static final long serialVersionUID = 1L; private JLabel label1;     JButton buton1,button2;     public JTextArea lt1; public test_pro() { this.setUndecorated(true);    GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); device.setFullScreenWindow(this); Container contentPane = getContentPane(); contentPane.setLayout(null); label1 = new JLabel("menu"); Font f1=new Font("Serif",1,22); label1.setFont(f1); label1.setForeground(Color.red);     contentPane.add(label1); lt1=new JTextArea(3,3); JScrollPane pane=new JScrollPane(lt1); pane.setBounds(new Rectangle(50,300,550,150)); contentPane.add(pane);     button1 = new JButton("SendRequestTest!"); button2 = new JButton("ReceiveResponseTest!"); label1.setBounds(new Rectangle(50,20,200,20)); button1.setBounds(new Rectangle(50,80,230,20)); button2.setBounds(new Rectangle(50,110,230,20));  contentPane.add(button1); contentPane.add(button2); button1.addActionListener(new MyJsendActionAdapter()); button2.addActionListener(new MyJreceiveActionAdapter());     this.setDefaultCloseOperation(EXIT_ON_CLOSE);     this.setVisible(true);    } /*以下省略*/

  • C# 計算処理中に実行中ウィンドウを表示させたい。

    アドバイスをお願いいたします。 やりたいこと: (1)メインウィンドウで「計算始めるボタン」を押す。 (2)すると計算中には「実行中」の文字が別ウィンドウで立ち上がる。 (3)計算が終わると別ウィンドウが閉じる。 下記プログラムの不具合: 別ウィンドウで「実行中」の文字を出させたいが、文字部分が描画されない。 注意:  下記プログラムはAthlon3000+で1秒ほどかかります。 CPUが遅いマシンで試す場合は「//計算処理」部分のfor重みを軽減させて実行して下さい。 using System; using System.Drawing; using System.Windows.Forms; //メインウィンドウ public class MainForm : Form { private Button button; private Label label; public MainForm() { button = new Button(); button.Text = "計算GO!!"; button.Click += new System.EventHandler(button_click); label = new Label(); label.Location = new Point(50,50); label.Text = "メインウィンドウ!"; Controls.Add(button); Controls.Add(label); Text = "MainForm"; BackColor = Color.Blue; } static void Main() { Application.Run(new MainForm()); } //計算GOボタンをクリックした時の処理 private void button_click(object sender, System.EventArgs e) { double z; SubForm Sub = new SubForm(); Sub.Show(); //計算処理 for(int i=0; i<=500000000; i++) z = double.MaxValue * double.MinValue; Sub.Close(); MessageBox.Show("計算終了"); } } //計算中を通知するウィンドウ public class SubForm : Form { private Label label; public SubForm(){ label = new Label(); label.Text = "実行中!"; label.Location = new Point(50,50); Text = "計算中通知ウィンドウ"; BackColor = Color.Red; Controls.Add(label); } }

  • tagの値

    ボタン1を押すと変数に1を ボタン2を押すと変数に2を・・・ という具合にしたいのですが、いろいろしてみましたが、分かりません。分かる方教えてくだい。 (tagには値を入れてあります。) Button1_Click、Button2.Click~ Label1.Text = Tag や Button1_Click、Button2.Click~ Label1.Text = Me.Tag だと、なぜかフォームのtagの値が入ってしまいます。 Button1_Click~ Label1.Text = Button1.Tag Button2.Click~ Label1.Text = Button2.Tag だとソースが長くなってしまいます。 ちなみにVB.NETです。

  • フレームの×ボタンを押しても閉じることが出来ない

    JAVAアプレットでプログラムを作成していまして、FileInputStreamで 取り込んだデータをフレームに表示させたんですが、表示させたフレーム のボタン(ウィンドウ右上の×ボタンなど)何を押しても終了できないんです。 それで色んな所で探していて、フレームを閉じる処理が見つかったので、 それを追加してみましたが、それもだめです。 これはどのようにすればよろしいのでしょうか? 下記にソースを記述しておきますので、悪い点がございましたら教えてください。 import java.applet.Applet; import java.awt.*; import java.awt.event.*; import java.io.*; import java.lang.*; class frame extends Frame implements WindowListener { Color bgcolor; Font font; Label lab_1,lab_2; frame() { super("title"); setLayout(null); bgcolor = new Color(240,248,255); setBackground(bgcolor); setForeground(Color.black); addWindowListener(this); font = new Font("Serif",Font.PLAIN,13); /* Labelを作成 */ lab_1 = new Label(); lab_2 = new Label(); lab_1.setFont(font); lab_1.setText("TEST1"); lab_1.setBounds(20,20,60,30); add (lab_1); lab_2.setFont(font); lab_2.setText("TEST2"); lab_2.setBounds(80,20,60,30); add (lab_2); } protected void processWindowEvent(WindowEvent endEvent) { System.exit(0); } }

    • ベストアンサー
    • Java
  • イベント処理

    javaでプログラムを作り始めて間がないのですが、イベント処理に関して行き詰ってしまいました。望む動作は、メニュー→ゲーム→じゃんけんと選択すると、初期の状態として「じゃんけん・・・・」という文字とボタンが表示され、どれかボタンを押すと対応して「~ボタンが押されました」と表示させたいのですが、作ったプログラムだと、ボタンを押しても反応しません。後々メニューにもいくつかアイテムを追加したり、最終的にはコンピュータとじゃんけんをするプログラムを書きたいと思っています。ifを使った方法しか思いつかないのですが、どこがおかしいのでしょうか? import javax.swing.*; import java.awt.event.*; import java.awt.BorderLayout; public class question extends JFrame implements ActionListener{       JLabel label1;       JPanel p2;       public static void main(String[] args){            question test = new question("質問");            test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);            test.setVisible(true);       }       question(String title){            setTitle(title);            setBounds( 10, 10, 300, 250);            JMenuBar menuBar = new JMenuBar();            JMenu menu = new JMenu("メニュー");            JMenu submenu = new JMenu("ゲーム");            JMenuItem subitem1 = new JMenuItem("じゃんけん");            subitem1.addActionListener(this);            subitem1.setActionCommand("Start");            submenu.add(subitem1);            menu.add(submenu);            menuBar.add(menu);            setJMenuBar(menuBar);            JPanel p1 = new JPanel();            p2 = new JPanel();            label1 = new JLabel("");            JButton btn1 = new JButton("グー");            btn1.addActionListener(this);            btn1.setActionCommand("goo");            JButton btn2 = new JButton("チョキ");            btn2.addActionListener(this);            btn2.setActionCommand("cyoki");            JButton btn3 = new JButton("パー");            btn3.addActionListener(this);            btn3.setActionCommand("paa");            p1.add(label1);            p2.add(btn1);            p2.add(btn2);            p2.add(btn3);            getContentPane().add(p1, BorderLayout.PAGE_START);            getContentPane().add(p2, BorderLayout.PAGE_END);            p2.setVisible(false);      }      public void actionPerformed(ActionEvent e){            String cmd = e.getActionCommand();            if (cmd.equals("Start")){                 p2.setVisible(true);                 label1.setText("じゃんけん・・・・");                 if (cmd.equals("goo")){                      label1.setText("グーが押されました");                 }else if (cmd.equals("cyoki")){                      label1.setText("チョキが押されました");                 }else if (cmd.equals("paa")){                      label1.setText("パーが押されました");                 }            }       } }

    • ベストアンサー
    • Java

専門家に質問してみよう