JavaのGUIの練習でテキスト入力から受け取った文字列を下のNew String:の後に表示されるということをやっているのですが、テキスト入力を表示させて文字を入れてMove!ボタンを押してみたのですがNew String:のあとに表示させることができませんでした。
現状のGUIでは
_____________(テキスト入力)
Move! (ボタン)
New String:
このテキスト入力に文字を入力しMove!ボタンを押すと
_____________(テキスト入力)
Move! (ボタン)
New String:
このままになってしまいます。
理想はこのテキスト入力にaaaという文字を入力してMove!ボタンを押すと
_____________(テキスト入力)
Move! (ボタン)
New String:aaa
となるようにしたいです。テキスト入力で文字列を受け取ってそれを表示させようとしたのですが文字列を受け取るところがうまくいっていないのか表示させることができませんでした。
かなり初歩的な質問だと思われますが、なんとか自力で解決しようと邁進したのですが、解決の糸が見つからなかったので質問させていただきました。
java
1import javax.swing.*; 2import java.awt.*; 3import java.awt.event.*; 4 5public class Prob93 { 6 private static String labelPrefix = "New String: "; 7 private String newString; 8 private JLabel label; 9 10 class ButtonAction implements ActionListener { 11 public void actionPerformed(ActionEvent e) { 12 label.setText(labelPrefix + newString); 13 } 14 } 15 16 public Component createComponents() { 17 18 19 label = new JLabel(labelPrefix); 20 JTextField text = new JTextField(20); 21 JButton button = new JButton("Move!"); 22 ButtonAction buttonListener = new ButtonAction(); 23 button.addActionListener( buttonListener ); 24 25 26 JPanel pane = new JPanel(); 27 pane.setBorder(BorderFactory.createEmptyBorder( 30, 30, 10, 30 )); 28 pane.setLayout(new GridLayout(0, 1)); 29 pane.add(text); 30 pane.add(button); 31 pane.add(label); 32 33 return pane; 34 } 35 36 public static void main(String[] args) { 37 JFrame frame = new JFrame("SwingApplication"); 38 Prob93 app = new Prob93(); 39 Component contents = app.createComponents(); 40 frame.getContentPane().add(contents, BorderLayout.CENTER); 41 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 42 frame.pack(); 43 frame.setVisible(true); 44 } 45}
回答1件
あなたの回答
tips
プレビュー