• 締切済み

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
  • 回答数1
  • ありがとう数1

みんなの回答

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

meibo3(String title)の中でint id = Integer.valueOf(gaku.getText()).intValue();などを実行していますが、この時点ではJTextFieldにまだ何も入力されていないはずです。入力が終わってからJTextFieldの内容を参照してください。 それから、KeyListenerをセットしていないのでkeyPressed(KeyEvent ke)は呼ばれることがありません。

yukey2
質問者

お礼

なるほどです。 ありがとうございます。 あれから、いろいろぐぐってみたら、アクションイベントで実装することができました。

関連するQ&A

  • javaでスタート画面を作っていて困っています。

    現在javaでゲームのスタート画面を作っているのですが、パネルが透過されずに困っています。 プログラムソースは import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.ImageIcon; import java.awt.Container; import java.awt.BorderLayout; import javax.swing.*; import java.awt.Font; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.*; import java.awt.event.*; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.ImageIcon; import java.awt.Container; import java.awt.BorderLayout; import javax.swing.border.LineBorder; import javax.swing.border.EtchedBorder; import java.awt.Color; import java.awt.Container; class Start最新版 extends JFrame{ public static void main(String args[]){ Start最新版 frame = new Start最新版("タイトル"); frame.setVisible(true); } Start最新版(String title){ setTitle(title); setBounds(10, 10, 1024, 768); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel p = new JPanel(); p.setOpaque( false ); ImageIcon icon1 = new ImageIcon("Start.jpg"); JLabel label1 = new JLabel(icon1); JLabel label2 = new JLabel(); p.add(label1); Container contentPane = getContentPane(); contentPane.add(p, BorderLayout.CENTER); JButton button1 = new JButton("ゲームを始める"); button1.setFont(new Font("Mairyo", Font.PLAIN, 30)); JPanel n = new JPanel(); n.setOpaque(false); n.setLayout(new BoxLayout(n, BoxLayout.Y_AXIS)); n.add(Box.createRigidArea(new Dimension(290,30))); n.add(button1); となっています。「ゲームを始める」ボタンだけを残して、周りのパネルを透過して画像を表示させたいのですが、うまくいきません!解決方法をご存知の方どうか教えていただきたいです!よろしくお願いします。

  • javaのタイマープログラムの時間について

    下記のjavaのプログラムは、タイマー動作の確認プログラムです。 タイマーの起動時間を1msにし、1000回タイマーを起動しており トータルのタイマー時間は1秒と考えましたが、実際のタイマー時間は 20秒くらいかかります。 この件に関しまして、コメント頂けますと大変助かります。 import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.Timer; public class TimerTest1 extends JFrame implements ActionListener{ Timer timer; JLabel label; int sec; public static void main(String[] args){ TimerTest1 frame = new TimerTest1(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(10, 10, 300, 200); frame.setTitle("タイトル"); frame.setVisible(true); } TimerTest1(){ sec = 0; label = new JLabel(); JPanel labelPanel = new JPanel(); labelPanel.add(label); timer = new Timer(1, this); getContentPane().add(labelPanel, BorderLayout.CENTER); timer.start(); } public void actionPerformed(ActionEvent e){ label.setText(sec + " sec"); if (sec >= 1000){ timer.stop(); label.setText(" timer_stop"); }else{ sec++; } } } 以上、宜しくお願いします。

    • ベストアンサー
    • Java
  • JAVAでの背景画像表示

    現在javaでゲームのメニュー画面を作っているのですが、ボタンを配置する所まではできたんですが、背景に画像を表示することができなくて困っています! import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.ImageIcon; import java.awt.Container; import java.awt.BorderLayout; import javax.swing.border.LineBorder; import javax.swing.border.EtchedBorder; import java.awt.Color; import java.awt.Container; public class Mati extends JFrame{ public static void main(String[] args){ Mati frame = new Mati(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(10, 10,650,650); frame.setTitle("街"); frame.setVisible(true); JPanel h = new JPanel(); h.setOpaque(false); ImageIcon icon1 = new ImageIcon("Mati.jpg"); JLabel label1 = new JLabel(icon1); JLabel label2 = new JLabel(); h.add(label1); } Mati(){ JButton button1 = new JButton("宿屋"); button1.setFont(new Font("Mairyo", Font.PLAIN, 30)); JButton button2 = new JButton("道具屋"); button2.setFont(new Font("Mairyo", Font.PLAIN, 30)); JButton button3 = new JButton("武器屋"); button3.setFont(new Font("Mairyo", Font.PLAIN, 30)); JButton button4 = new JButton("街を出る"); button4.setFont(new Font("Mairyo", Font.PLAIN, 30)); JPanel p = new JPanel(); p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS)); p.add(Box.createRigidArea(new Dimension(10,30))); p.add(button1); p.add(Box.createRigidArea(new Dimension(5,8))); p.add(button2); p.add(Box.createRigidArea(new Dimension(5,8))); p.add(button3); p.add(Box.createRigidArea(new Dimension(5,8))); p.add(button4); getContentPane().add(p, BorderLayout.CENTER); } } ソースはこのようになっています。これからどうすれば背景画像が表示されるか教えていただきたいです。 よろしくお願いします。

  • Javaのプログラミング手伝ってください

    以下のソースコードを応用して、添付画像のような数字のかかれた画像を3つ並べてそれを回して7を揃えるというゲームを作りたいのですが全く進みません。どなたか完成させてくださいm(__)m使用する画像のファイル名は「slot1.jpeg」~「slot7.jpeg」です。 import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.Timer; public class OneSlot extends JFrame implements ActionListener { private static final long serialVersionUID = 1L; final int MAX = 7; Timer timer = new Timer(150 , this); JLabel label= new JLabel("スタートで始まるよ",JLabel.CENTER); JButton[] bt = {new JButton("スタート"),new JButton("ストップ")}; JLabel slot= new JLabel(new ImageIcon("Slot1.jpg"),JLabel.CENTER); ImageIcon[] slot_icon = new ImageIcon[MAX]; int iCount = 0; OneSlot(String title) { super(title); timer.setActionCommand("timer"); setBounds(200, 200, 230, 150); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); for(int i = 0;i < slot_icon.length; i++) slot_icon[i] = new ImageIcon("Slot" + (i+1) + ".jpg"); add("North",label); add("Center",slot); JPanel p = new JPanel(); for (int i = 0; i < bt.length;i++) { bt[i].addActionListener(this); p.add(bt[i]); } add("South",p); setVisible(true); } public static void main(String[] args) { new OneSlot("スロットマシン"); } public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if(cmd.equals("timer")) { if(++iCount == slot_icon.length) iCount = 0; slot.setIcon(slot_icon[iCount]); } if(e.getSource() == bt[0] && !timer.isRunning()) { label.setText("7が当たりだよ"); timer.start(); } else if(e.getSource() == bt[1] && timer.isRunning()) { if(iCount+1 == MAX) label.setText("やった!!おめでとう"); else label.setText("残念でした"); timer.stop(); } } }

  • 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
  • javaのBoxlayoutについて

    下記はBoxLayout用ののコードです。 Q1)Buttonのサイズを設定する方法がありますか? Q2)Buttonの配置を設定する方法がありますか? //===================================== import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.LayoutManager; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class AlignmentX extends JFrame{ JButton button1; JButton button2; JButton button3; public static void main(String[] args){ AlignmentX frame = new AlignmentX(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("タイトル"); frame.setVisible(true); } AlignmentX(){ button1 = new JButton("AAAAA"); button1.setAlignmentY(0.5f); button1.setPreferredSize(new Dimension(80,20)); button2 = new JButton("BBB"); button2.setAlignmentY(0.5f); button2.setPreferredSize(new Dimension(80,20)); button3 = new JButton("CC"); button3.setAlignmentY(0.5f); button3.setPreferredSize(new Dimension(80,20)); JPanel p = new JPanel(); p.setLayout((LayoutManager) new BoxLayout(p, BoxLayout.Y_AXIS)); p.add(button1); p.add(button2); p.add(button3); getContentPane().add(p, BorderLayout.CENTER); setBounds(10, 10, 300, 200); } } //以上,宜しくお願いします。

    • ベストアンサー
    • Java
  • javaアプレットについて質問です

    本の通りにソースを記入し、コンパイラしました。 その後実行したら Exception in thread"main"java.lang.NoSuchMethodError:main とコマンドプロンプトに表示されました。 何が原因ですか? 因みに下記がソースコードです import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Sample13 extends JApplet { private JLabel lb; private JTextField tf; public void init() { //コンポーネントの作成 lb = new JLabel("お選びください。"); tf = new JTextField(); //コンテナへ追加 add(lb, BorderLayout.NORTH); add(tf, BorderLayout.SOUTH); //リスナの登録 tf.addActionListener(new SampleActionListener()); } //リスナクラス class SampleActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { JTextField tmp = (JTextField) e.getSource(); lb.setText(tmp.getText() + "ですね。"); } } }

  • 参照されない

    クラスSentenceActionperformedのtext1,textの部分がエラーとなります。クラスは呼ばれています。二つとも参照?されていないのです。 参考になるページをみると同じような書き方しているのに問題ないのでどこが違うのかわかりません。この書き方では参照でなきないのだと思いますが正しい書き方がわかりません。別のクラスにしていく方法でいきたいです。 うまく行けばtextの文字がtext1に表示されます。 よろしくお願いします。 import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JTextArea; import javax.swing.JTextField; public class sample extends javax.swing.JFrame{ public sample() { init(); } private void init() { JTextField text = new JTextField(25); JTextArea text1 = new JTextArea(10,25); Container mainFrame = getContentPane(); mainFrame.setLayout(new FlowLayout()); mainFrame.add(text); mainFrame.add(text1); mainFrame.setBounds(0, 0, 500, 500); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); SentenceActionPerformed aa = new SentenceActionPerformed(); text.addActionListener(aa); } class SentenceActionPerformed implements ActionListener{ public void actionPerformed(ActionEvent evt) { text1.setText(text.getText()); } } public static void main(String args[]) { new sample().setVisible(true); } }

    • ベストアンサー
    • Java
  • JAVAプログラミング

    プログラミングについて質問があります 割り勘ソフトを作りたいのですが button1を押したときに int i = Integer.parseInt(kazu.getText()); int e = Integer.parseInt(kane.getText()); int a = e/i; String s = String.valueOf(a); this.an.setText(s); というプログラムを実行したいのですが button1のクリック処理?イベント処理?というのはどのように書けばいいのでしょうか レイアウトは完成しているので ↓に付け足すような形でお願いします プログラミングの質問をするのは初めてなので何かおかしなところや足りないところがあれば教えてください public class jFram { public static void main(String[] args) { JFrame mainFrame = new JFrame("1"); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainFrame.setSize(500,500); mainFrame.setResizable(false); mainFrame.setVisible(true); Container cont = mainFrame.getContentPane(); JButton button1 = new JButton("計算"); final JTextField kane = new JTextField(); final JTextField kazu = new JTextField(); JLabel mony = new JLabel("料金"); JLabel ninz = new JLabel("人数"); JLabel an = new JLabel("a"); button1.setLayout(null); cont.add(button1); button1.setBounds(40,380,100,30); button1.setBackground(Color.blue); kane.setLayout(null); cont.add(kane); kane.setBounds(160,340,100,30); kazu.setLayout(null); cont.add(kazu); kazu.setBounds(160,300,100,30); mony.setLayout(null); cont.add(mony); mony.setBounds(40,340,100,30); ninz.setLayout(null); cont.add(ninz); ninz.setBounds(40,300,100,30); an.setLayout(null); cont.add(an); an.setBounds(160,380,100,30); cont.setLayout(null); JPanel a = new JPanel(); a.setLayout(null); mainFrame.setVisible(true); } }

    • ベストアンサー
    • Java
  • javaのpanelが表示されません

    下記のプログラムを作ったんですが、eclipseで実行するとフレームは表示されますが、空のフレームのような状態で、panelやボタンなどは表示されません。mainとは別のクラスで作成してるからなんでしょうか?よろしくお願いします。 import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class Table0 { public static void main(String[] args) { new Frame0(); } } class Frame0{ JFrame frame; JPanel panel; JScrollPane jsp; JTable table; DefaultTableModel dtm; public Frame0(){ frame=new JFrame("table"); frame.setBounds(30, 30, 300, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); table=new JTable(8,5); jsp=new JScrollPane(table); jsp.setPreferredSize(new Dimension(250, 70)); panel=new JPanel(); panel.add(jsp); Container c=frame.getContentPane(); c.add(panel,BorderLayout.CENTER); } }

    • ベストアンサー
    • Java

専門家に質問してみよう