JTextFieldのgetTextについて

このQ&Aのポイント
  • JTextFieldのgetTextメソッドでnullを返せない問題について
  • 「NULL入力」と書かれたダイアログが出ない原因について
  • 解決方法についての質問
回答を見る
  • ベストアンサー

JTextFieldのgetTextについて

javaプログラミング初心者です。 javaのGUIプログラミングについて少し分からないところがあるので質問させて頂きます。 import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TextTest extends JFrame implements ActionListener{ private static final long serialVersionUID = 1L; JTextField text = new JTextField(null, 10); JPanel p1 = new JPanel(); public static void main(String[] args){ TextTest frame = new TextTest(); frame.setVisible(true); } public TextTest(){ setBounds(10, 10, 460, 310); setDefaultCloseOperation(EXIT_ON_CLOSE); setTitle("Test"); GridBagLayout layout1 = new GridBagLayout(); p1.setLayout(layout1); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; layout1.setConstraints(text, gbc); p1.add(text); JButton decidebutton = new JButton("決定"); gbc.gridy = 1; layout1.setConstraints(decidebutton, gbc); p1.add(decidebutton); getContentPane().add(p1, BorderLayout.CENTER); decidebutton.addActionListener(this); decidebutton.setActionCommand("決定"); } public void actionPerformed(ActionEvent e){ String cmd = e.getActionCommand(); if(cmd.equals("決定")){ String str = text.getText(); if(str == null){ JOptionPane.showMessageDialog(null, "NULL入力"); } else{ JOptionPane.showMessageDialog(null, "それ以外"); } } } } 以上のプログラムを実行したとき、「決定」ボタンを押した際に「NULL入力」と書かれたダイアログが出てくるのが望ましいのですが、 実際には「それ以外」と書かれたダイアログが出てきてしまいます。 getTextメソッドではnullを返せないのか、と思い、テキストフィールドに「あ」、「NULL入力」と書かれたダイアログを表示させる条件をif(str == "あ")にしたのですがそれでも駄目・・・。 独学では限界があると思い質問させて頂きました。 これについての解決の方法を知っている方、よろしくお願いいたします。

  • vatch
  • お礼率100% (1/1)
  • Java
  • 回答数1
  • ありがとう数1

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

  • ベストアンサー
  • LancerVII
  • ベストアンサー率51% (1060/2054)
回答No.1

こんにちは。 文字列の=評価はequalsを利用します。 ボタンの判別を行なっている所と同じです(cmd.equals("決定")) if ( str.equals("") ) { } にすれば空白であるかの評価ができます。 "あ"であるか調べるには str.equals("あ")です。

vatch
質問者

お礼

ありがとうございます。 無自覚ですでに使っていたのですね^^; 勉強になりました。

関連するQ&A

  • GridBagLayoutについての質問

    ウィンドウ上のjContentPane上にJPanelを配置し、レイアウトをGridBagLayoutにしてそのJPanel上にJTextFieldを置くとそのJTextFieldの幅がほぼ0になります。下記のプログラムがその一部です。gridBagConstraints2.fill をnullにしたままJTextFieldの幅を広げたいのですがどうしたらいいでしょうか?教えてください。 private JPanel getJPanel() { if (jPanel == null) { GridBagConstraints gridBagConstraints2 = new GridBagConstraints(); jPanel = new JPanel(); jPanel.setLayout(new GridBagLayout()); jPanel.setPreferredSize(new java.awt.Dimension(200,150)); gridBagConstraints2.gridx = 0; gridBagConstraints2.gridy = 0; gridBagConstraints2.weightx = 1.0; gridBagConstraints2.fill = java.awt.GridBagConstraints.NONE; gridBagConstraints2.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints2.gridwidth = 4; jPanel.add(getJTextField(), gridBagConstraints2); } return jPanel; } private JTextField getJTextField() { if (jTextField == null) { jTextField = new JTextField(); jTextField.setColumns(32); } return jTextField; }

    • ベストアンサー
    • Java
  • javaプログラムについて

    javaのプログラムで入力項目をDBに書き込むというプログラムを作成しているのですが、 コンソール形式だと成功するのですが、テキストボックスなどをおいて、GUI形式でやろうとするとキーイベントの中の変数ににうまく値が参照されません 以下ソース import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingConstants; import java.awt.Container; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.Date; class meibo3 extends JFrame implements KeyListener { public static void main(String args[]) { meibo3 frame = new meibo3("タイトル"); frame.setVisible(true); } // private String name; // private String shu; // private int id; // private int su; meibo3(String title) { setTitle(title); setBounds(100, 100, 300, 250); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel p = new JPanel(); p.setLayout(null); JLabel lmeibo = new JLabel("【名簿入力】", SwingConstants.CENTER); lmeibo.setBounds(100, 10, 80, 30); JLabel lgakuno = new JLabel("学生番号", SwingConstants.CENTER); lgakuno.setBounds(30, 40, 80, 30); JLabel lname = new JLabel("氏 名", SwingConstants.CENTER); lname.setBounds(200, 40, 80, 30); JLabel lshu = new JLabel("入力を終了しますか?(Y/N)"); lshu.setBounds(30, 120, 200, 30); JTextField gaku = new JTextField(4); gaku.setBounds(30, 70, 80, 30); JTextField namae = new JTextField(20); namae.setBounds(200, 70, 80, 30); JTextField y = new JTextField(20); y.setBounds(200, 120, 20, 30); y.addKeyListener(this); ; p.add(lmeibo); p.add(lgakuno); p.add(lname); p.add(gaku); p.add(namae); p.add(y); p.add(lshu); Container contentPane = getContentPane(); contentPane.add(p, BorderLayout.CENTER); int id = Integer.valueOf(gaku.getText()).intValue(); String name = namae.getText(); int nsu = namae.getText().length(); String yn =y.getText(); //method(id,name,nsu,yn); } public void keyPressed(KeyEvent ke) { // TODO 自動生成されたメソッド・スタブ if (ke.getKeyCode() == ke.VK_ENTER) { //private void method(int id, String name, int nsu, String yn){ Date d = new Date(); SimpleDateFormat dfd = new SimpleDateFormat("yyyy-MM-dd"); Connection con = null; String day = dfd.format(d); // System.out.print(day); PreparedStatement ps = null; try { // ドライバクラスをロード Class.forName("com.mysql.jdbc.Driver"); // データベースへ接続 con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/hellodb", "root", "root"); Statement stmt = (Statement) con.createStatement(); // name,bloodType,ageのデータを検索するSQL文を作成 String sql = "INSERT INTO hellodb.meibo VALUES(" + id + ",'" + name + "','" + day + "');"; System.out.println(sql); if (id > 4 && nsu > 20) { // JOptionPane.showMessageDialog(this, "学生番号が4桁以上、氏名が20文字以上になっています。", "Error", // JOptionPane.ERROR_MESSAGE); } else { if (id < 5) { // JOptionPane.showMessageDialog(this, // "学生番号が4桁以上になっています", "Error", // JOptionPane.ERROR_MESSAGE); } else { if (nsu > 20) { // JOptionPane.showMessageDialog(this, // "氏名が20文字以上になっています。", "Error", // JOptionPane.ERROR_MESSAGE); } else { if (yn.equals("y") || yn.equals("y") || yn.equals("Y") || yn.equals("Y")) { // ps = con.prepareStatement(sql); stmt.execute(sql); // JOptionPane.showMessageDialog(this, // "成功しました", "Info", // JOptionPane.INFORMATION_MESSAGE); } else if (yn.equals("n") || yn.equals("n") || yn.equals("N") || yn.equals("N")) { } } } } } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { try { // close処理 if (ps != null) { ps.close(); } // close処理 if (con != null) { con.close(); } } catch (SQLException e) { e.printStackTrace(); } } } } public void keyReleased(KeyEvent arg0) { // TODO 自動生成されたメソッド・スタブ } public void keyTyped(KeyEvent arg0) { // TOD

  • javaのJTextFieldにマウスフォーカス

    お世話になります。 Q1)下記のコードに於きまして、JTextFieldにマウスフォーカス が当りますと、その旨、System.out.println("JTextField_tt")と表示する方法をお教えください。 import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.border.LineBorder; public class EObjectTest extends JFrame implements ActionListener { public static JButton b1; public static JButton b2; public static JTextField tt; static EObjectTest frame; public static void main(String args[]){ frame=new EObjectTest("AAAA"); frame.setVisible(true); } EObjectTest(String title) { setTitle(title); setBounds(100, 100, 300, 250); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel p = new JPanel(); // ボタン作成・追加 b1 = new JButton("One"); b2 = new JButton("Two"); tt = new JTextField("aaa"); LineBorder border = new LineBorder(Color.RED, 2, true); tt.setBorder(border); tt.setColumns(15); p.add(b1); p.add(b2); p.add(tt); Container contentPane = getContentPane(); contentPane.add(p, BorderLayout.CENTER); // リスナ登録 b1.addActionListener(this); b2.addActionListener(this); tt.addActionListener(this); } public void actionPerformed(ActionEvent e) { // getSource() でイベントソースのオブジェクトを獲得し // Button クラスにキャストする JButton b = (JButton)e.getSource(); // JTextField ttt = (JTextField)e.getSource(); if (b==b1) { System.out.println("Oneのボタン"); } if (b==b2) { System.out.println("Twoのボタン"); } /* if (ttt==tt) { System.out.println("JTextField_tt"); } */ } } 以上

    • ベストアンサー
    • Java
  • comboBoxのデータの右づめ表示

    GridBagLayoutでデーターの右づめ表示が出来ません。 Q1)下記のコードで、変更方法をお教えください。 import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.LineBorder; public class comboBox_Right extends JFrame { public static JComboBox[] combo=new JComboBox[4]; static comboBox_Right frame; public static void main(String args[]){ frame=new comboBox_Right("AAAA"); frame.setVisible(true); } comboBox_Right(String title) { setTitle(title); setBounds(100, 100, 300, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel p = new JPanel(); //=========================== GridBagLayout layout=new GridBagLayout(); GridBagConstraints gbc=new GridBagConstraints(); p.setBackground(Color.GREEN); //GRREN-->BLUE back ground color of West panel p.setLayout(layout); //これが効いた <--- layout=new GridBagLayout(); LineBorder border = new LineBorder(Color.BLACK, 1, true); //ComboBox data String[][] combodata = { {"A0", "B0", "C0", "D0"}, //No.1 Combo {"A1", "B1", "C1", "D1"}, //No.1 Combo {"A2", "B2", "C2", "D2"}, //No.1 Combo {"A3", "B3", "C3", "D3"}, //No.1 Combo }; int wx=100, wy=25; for(int i=0; i<4; i++){ combo[i] = new JComboBox(combodata[i]); //make 4 comboBox ((JLabel)combo[i].getRenderer()).setHorizontalAlignment(JLabel.RIGHT); setComboBox(combo[i], layout, gbc, 0, i, wx, wy); //0:index } for(int i=0; i<4; i++) p.add(combo[i]); //add 4 comboBox Container contentPane = getContentPane(); contentPane.add(p, BorderLayout.CENTER); } void setComboBox( JComboBox combo, GridBagLayout layout, GridBagConstraints gbc, int px, int py, int wx, int wy){ combo.setEditable(true); GCombo_Layout(layout, combo, gbc, px, py, wx, wy); } void GCombo_Layout(GridBagLayout layout, JComboBox combo, GridBagConstraints gbc, int x, int y, int wx, int wy){ combo.setPreferredSize(new Dimension(wx,wy)); gbc.gridx = x; gbc.gridy = y; gbc.gridheight = 1; gbc.weightx = 1.0d; gbc.weighty = 1.0d; gbc.fill = GridBagConstraints.NONE; gbc.insets = new Insets(0, 0, 0, 0); layout.setConstraints(combo, gbc); } } //以上

  • JOptionPaneでのフォーカスのトラブル

     今晩は。  私はJOptionPaneを、親コンポーネントをnullにして使っていたのですが モーダルなままで消えてしまうことがあります。次の方法で再現出来ます。 1.下記コードをJOptionPane.showMessageDialog(null, "test");の方で動かす。 2.ダイアログが出たままにして、タスクバーからデスクトップを表示する 3.再びタスクバーのアイコンからjavaのフレームを表示する。 4.タスクマネージャーで停止しないとフレームが消えない。  これはjavaのバグではないかと思うのですが、そうでしょうか。  また、別なクラスのダイアログから親コンポーネントを指定する時は、参照変数がなくても良いように、いつも引数nullで使っていたのですが、もし無理なら、何かそれに変わる便利な方法はないでしょうか。教えて下さい。 import java.awt.*; import javax.swing.*; public class BugTest{ public static void main(String[] args){ JFrame fr=new JFrame(); fr.setDefaultCloseOperation(fr.EXIT_ON_CLOSE); fr.setVisible(true); fr.setExtendedState(fr.MAXIMIZED_BOTH); JOptionPane.showMessageDialog(fr, "test"); //JOptionPane.showMessageDialog(null, "test"); } }

    • ベストアンサー
    • Java
  • java通信について

    アプレットビューアは 通信成功できますが HTMLから実行すると失敗します so = new Socket( "localhost", 80 ); この部分が失敗してるようです なぜ起こるんでしょうか ? 解決方法を教えてください。 //html <html><body> <applet code = "a.class" width = "370" height ="530"></applet> </body></html>   //<applet code = "a.class" width="400" height = "200"></applet> import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; public class a extends java.applet.Applet implements ActionListener{ TextField tf; Button b; TextArea t; Panel p, p1; String str = "http://localhost/cgi-bin/a.cgi"; public void init(){ tf = new TextField( 32 ); b = new Button( "Post" ); t = new TextArea( 20, 48 ); b.addActionListener( this ); p = new Panel(); p.add( new Label( "String" ) ); p.add( tf ); p.add( b ); p1 = new Panel(); p1.add( t ); add( p ); add( p1 ); } public void actionPerformed( ActionEvent e ){ String str; if( e.getSource() == b ){ t.setText( sen( tf.getText() ) ); } } private String sen( String a ){   Socket so = null; InputStreamReader in = null; OutputStream os = null; String str1 = new String(); try { t.setText( "aa" ); so = new Socket( "localhost", 80 ); t.setText( "bb" ); in = new InputStreamReader( so.getInputStream() ); os = so.getOutputStream(); }catch( Exception e ){ return "Error!"; } String H = "POST " + str + " HTTP/1.0\n"; H += "Content-Length:" + String.valueOf( a.length() ) + "\n\n"; String st = new String( H + a ); try{ os.write( st.getBytes() ); }catch( Exception e ){ return "Error!"; } str1 = "Send:\n" + st; boolean bo = true; StringBuffer sb = new StringBuffer(); int s; while( bo ){ try{ s = in.read();   if( s == -1 ) bo = false; else sb.append( (char)s ); }catch( Exception e ){ bo = false; } } str1 += "\nResv:\n" + sb.toString(); return str1; } }

    • ベストアンサー
    • Java
  • ファイルから正しい文字が読み取れない

    こんにちは いつもこちらでお世話になっています。 テキストファイルからすべての文字列を読み込んで フレーム上のtextAreaに読み込んだ文字列を書き込みたいのですが 文字化けしてしまって、正しく表示されません。 どなたか、正しく表示する方法を教えていただけないでしょうか。 よろしくおねがいします。 ちなみに、テキストボックスのパスとファイル名は(c:/test.txt)です。 ================================================= import java.awt.*; import javax.swing.*; import java.io.*; class labeltest { public static void main(String args[]) { JFrame frame=new JFrame("test"); JPanel panel=new JPanel(); JTextArea ta=new JTextArea(20,30); String buff; ta.setLineWrap(true); panel.add(ta); Container ct=frame.getContentPane(); ct.add(panel); try { FileReader fr=new FileReader("c:/test.txt"); BufferedReader br=new BufferedReader(fr); while((buff=br.readLine())!=null) { ta.append(buff); JOptionPane.showMessageDialog(null,buff,"", JOptionPane.PLAIN_MESSAGE); } br.close(); fr.close(); } catch(FileNotFoundException e) { JOptionPane.showMessageDialog(null, "見つからない","失敗",JOptionPane.PLAIN_MESSAGE); } catch(IOException e) { JOptionPane.showMessageDialog(null,"読めない","失敗" ,JOptionPane.PLAIN_MESSAGE); } frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } }

    • ベストアンサー
    • Java
  • JAVAの正解・誤解判定の宣言が分かりません

    class ListPanel extends JPanel implements ActionListener{ JButton button1; JList list1; String[] data = {"( A )","( B )" ,"( C )" ,"( D )" }; ListPanel() { button1 = new JButton("選択OK"); button1.addActionListener(this); list1 = new JList(data); list1.setFixedCellWidth(100); JScrollPane scroll1 = new JScrollPane(list1); scroll1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); scroll1.setPreferredSize(new Dimension(150,80)); scroll1.setBorder(BorderFactory.createEtchedBorder() ); scroll1.setBorder(BorderFactory.createTitledBorder("選択肢") ); JPanel p1 = new JPanel(); p1.add(scroll1); JPanel p2 = new JPanel(); p2.add(button1); this.add(p1); this.add(p2); } public void actionPerformed(ActionEvent e1) { if (e1.getSource() == button1) { if (list1.getSelectedItem() == ( C ) ) { JOptionPane.showMessageDialog(null, "あなたが選択した解答" , " 正解です!",JOptionPane.INFORMATION_MESSAGE); } else if (list1.getSelectedItem() != ( C ) ){ JOptionPane.showMessageDialog(null, "あなたが選択した解答", "間違いです!解答は( C )です" , JOptionPane.INFORMATION_MESSAGE); list1.getSelectedItem() == ( C ) ) { の宣言が間違っているようです。何卒よろしくお願いいたします。どこが間違っているか指摘していただければ幸いです。どうか、よろしくお願いします。

  • [java初心者です]ボタンのイベントの追加

    javaで、複数ボタンを表示し、クリックするとそれぞれのダイアログが表示されるプログラムを作っています。 サンプルを利用して、ボタンを追加するところまで出来たのですが そこからがうまくできません。 アクションリスナーがthisにしてあるため、どのボタンでも 同じダイアログが表示されてしまうのだと思いますが、 this以外にすることはできるのでしょうか? import javax.swing.*; import java.awt.BorderLayout; import java.awt.event.*; public class JOptionPaneTest8 extends JFrame implements ActionListener{ JLabel ansLabel; public static void main(String[] args){ JOptionPaneTest8 frame = new JOptionPaneTest8(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(10, 10, 300, 200); frame.setTitle("タイトル"); frame.setVisible(true); } JOptionPaneTest8(){ JButton ichiButton = new JButton("○○○な時"); ichiButton.addActionListener(this); JButton niButton = new JButton("○○●な時"); niButton.addActionListener(this); JPanel p = new JPanel(); p.add(ichiButton); p.add(niButton); ansLabel = new JLabel("今の気分をクリック!"); JPanel ansPanel = new JPanel(); ansPanel.add(ansLabel); getContentPane().add(p, BorderLayout.CENTER); getContentPane().add(ansPanel, BorderLayout.PAGE_END); } public void actionPerformed(ActionEvent e){ ImageIcon icon = new ImageIcon("aka.gif"); int option = JOptionPane.showConfirmDialog(this, "赤を身の回りに置いて元気に!", "OK?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, icon); if (option == JOptionPane.YES_OPTION){ ansLabel.setText("ほかには?"); }else if (option == JOptionPane.NO_OPTION){ ansLabel.setText("今の気分をクリック!"); } } 気分をボタンとして表示して そのボタンをクリックすると効果的な色のアイコン(gif)と解決策?を ダイアログとして表示させたいです。 高校でついこの間javaを始めた初心者です(>_<) 提出期限が近づいていて焦っています; お手数ですが回答お願いいたします・・・!!

  • 質問

    javaのswingで、自由に線を引くにはどうすればいいのですか? import javax.swing.*; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.event.*; import java.util.Vector; class hoge{ JPanel p public hoge{ p = new JPanel(); p.setLayout(null); getContentPane().add(p); } public static void main(String args[]){ hoge tr = new hoge(); } } みたいな(細かいところは省略)したプログラムを実行したときに 任意の座標から座標へ線を引くにはどうすれいいのですか? appletviewerのdrawStringのようなメソッドはないのですか?

専門家に質問してみよう