【2回目】Swing演習問題(30問)

2025-08-06

初級問題(9問)

  1. JFrameを作成し、タイトルを「My App」に設定して表示するコードを書いてください。
  2. 400×300ピクセルのJFrameを作成し、中央に配置するコードを書いてください。
  3. JLabelを使用して「Welcome!」というテキストを表示するコードを書いてください。
  4. JButtonを作成し、クリック時に「Clicked!」とコンソールに出力するコードを書いてください。
  5. JTextFieldを作成し、初期テキストとして「Input here」を設定するコードを書いてください。
  6. JOptionPaneを使用して「Hello!」というメッセージダイアログを表示するコードを書いてください。
  7. FlowLayoutを使用して3つのJButtonを横並びに配置するコードを書いてください。
  8. JPanelの背景色を緑色に設定するコードを書いてください。
  9. JButtonに「Press me」というツールチップを設定するコードを書いてください。

中級問題(15問)

  1. BorderLayoutを使用して、北側にJLabel、中央にJPanel、南側にJButtonを配置するコードを書いてください。
  2. 2つのJTextFieldの数値を加算し、結果をJLabelに表示するボタンを作成してください。
  3. JOptionPaneを使用してYes/Noダイアログを表示し、選択結果をコンソールに出力するコードを書いてください。
  4. GridLayoutを使用して4×4のボタングリッドを作成するコードを書いてください。
  5. JPanelを拡張したMyPanelクラスを作成し、背景色を青色に設定してください。
  6. マウスクリックの座標を表示するJLabelを作成してください。
  7. JTextFieldの文字数制限(最大10文字)を実装してください。
  8. ボタンクリックでJFrameのタイトルを変更するコードを書いてください。
  9. 3つのラジオボタン(JRadioButton)を作成し、ButtonGroupでグループ化してください。
  10. JCheckBoxの状態変化を検知し、チェック状態をコンソールに出力するコードを書いてください。
  11. JComboBoxを作成し、選択肢として「Red」「Green」「Blue」を追加してください。
  12. ボタンクリックでJOptionPaneの入力ダイアログを表示し、入力値をJLabelに表示するコードを書いてください。
  13. マウスがコンポーネント上に入った/出た時に背景色を変更するコードを書いてください。
  14. JTextAreaとJScrollPaneを使用してスクロール可能なテキストエリアを作成してください。
  15. キーイベントを検知し、押されたキーを表示するJLabelを作成してください。

上級問題(6問)

  1. ドラッグ&ドロップで移動可能なJLabelを作成してください。
  2. カスタムダイアログを作成し、ユーザーに入力させた値を取得するコードを書いてください。
  3. マウスで描画できる簡単なお絵かきアプリを作成してください。
  4. オブザーバーパターンを使用して、データモデルの変更を複数のJLabelに反映させるシステムを作成してください。
  5. カスタムレイアウトマネージャーを作成し、コンポーネントを円形に配置してください。
  6. タブ付きペイン(JTabbedPane)を使用して、3つの異なるパネルを切り替えられるインターフェースを作成してください。

Swing演習問題 解答例

初級問題解答

  1. JFrame「My App」
JFrame frame = new JFrame("My App");
frame.setVisible(true);
  1. 400×300ピクセルのJFrame
JFrame frame = new JFrame();
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
  1. JLabel「Welcome!」
JLabel label = new JLabel("Welcome!");
  1. JButton「Clicked!」
JButton button = new JButton("Click");
button.addActionListener(e -> System.out.println("Clicked!"));
  1. JTextField「Input here」
JTextField textField = new JTextField("Input here");
  1. JOptionPane「Hello!」
JOptionPane.showMessageDialog(null, "Hello!");
  1. FlowLayoutを使用して3つのJButtonを横並びに配置
JPanel panel = new JPanel(new FlowLayout());
panel.add(new JButton("Button 1"));
panel.add(new JButton("Button 2"));
panel.add(new JButton("Button 3"));
  1. JPanelの背景色を緑色に
JPanel panel = new JPanel();
panel.setBackground(Color.GREEN);
  1. JButtonにツールチップ「Press me」
JButton button = new JButton();
button.setToolTipText("Press me");

中級問題解答

  1. BorderLayoutを使用して、北側にJLabel、中央にJPanel、南側にJButtonを配置
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.add(new JLabel("North"), BorderLayout.NORTH);
frame.add(new JPanel(), BorderLayout.CENTER);
frame.add(new JButton("South"), BorderLayout.SOUTH);
frame.setVisible(true);
  1. JTextFieldの数値を加算し、結果をJLabel
JTextField field1 = new JTextField(5);
JTextField field2 = new JTextField(5);
JLabel resultLabel = new JLabel();
JButton button = new JButton("Add");

button.addActionListener(e -> {
    try {
        int sum = Integer.parseInt(field1.getText()) + Integer.parseInt(field2.getText());
        resultLabel.setText("Result: " + sum);
    } catch (NumberFormatException ex) {
        resultLabel.setText("Invalid input");
    }
});
  1. JOptionPaneでYes/Noダイアログ
int result = JOptionPane.showConfirmDialog(
             null, "Continue?", "Confirm", JOptionPane.YES_NO_OPTION);
System.out.println(result == JOptionPane.YES_OPTION ? "Yes" : "No");
  1. GridLayoutを使用して4×4のボタングリッド
JPanel panel = new JPanel(new GridLayout(4, 4));
for (int i = 0; i < 16; i++) {
    panel.add(new JButton("Button " + (i+1)));
}
  1. JPanelを拡張したMyPanelクラスで背景色を青色
class MyPanel extends JPanel {
    public MyPanel() {
        setBackground(Color.BLUE);
    }
}
  1. マウスクリックの座標を表示するJLabel
JLabel coordLabel = new JLabel();
panel.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
        coordLabel.setText("X: " + e.getX() + ", Y: " + e.getY());
    }
});
  1. JTextFieldの文字数制限(最大10文字)
textField.setDocument(new PlainDocument() {
    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        if (getLength() + str.length() <= 10) {
            super.insertString(offs, str, a);
        }
    }
});
  1. ボタンクリックでJFrameのタイトルを変更
button.addActionListener(e -> frame.setTitle("New Title"));
  1. JRadioButtonをButtonGroupでグループ化
ButtonGroup group = new ButtonGroup();
JRadioButton rb1 = new JRadioButton("Option 1");
JRadioButton rb2 = new JRadioButton("Option 2");
JRadioButton rb3 = new JRadioButton("Option 3");

group.add(rb1);
group.add(rb2);
group.add(rb3);
  1. JCheckBoxの状態変化を検知
checkBox.addItemListener(e -> {
    System.out.println(e.getStateChange() == ItemEvent.SELECTED ? "Checked" : "Unchecked");
});
  1. JComboBoxで「Red」「Green」「Blue」
JComboBox comboBox = new JComboBox<>();
comboBox.addItem("Red");
comboBox.addItem("Green");
comboBox.addItem("Blue");
  1. JOptionPaneの入力ダイアログをJLabelに表示
button.addActionListener(e -> {
    String input = JOptionPane.showInputDialog("Enter text:");
    label.setText(input);
});
  1. マウスがコンポーネント上に入った/出た時に背景色を変更
panel.addMouseListener(new MouseAdapter() {
    public void mouseEntered(MouseEvent e) {
        panel.setBackground(Color.YELLOW);
    }
    
    public void mouseExited(MouseEvent e) {
        panel.setBackground(Color.WHITE);
    }
});
  1. JTextAreaとJScrollPaneを使用してスクロール可能なテキストエリア
JTextArea textArea = new JTextArea(10, 30);
JScrollPane scrollPane = new JScrollPane(textArea);
  1. キーイベントを検知し、押されたキーを表示するJLabel
JLabel keyLabel = new JLabel();
textField.addKeyListener(new KeyAdapter() {
    public void keyPressed(KeyEvent e) {
        keyLabel.setText("Key pressed: " + e.getKeyChar());
    }
});

上級問題解答

  1. ドラッグ&ドロップで移動可能なJLabel
label.addMouseMotionListener(new MouseMotionAdapter() {
    public void mouseDragged(MouseEvent e) {
        label.setLocation(label.getX() + e.getX() - label.getWidth()/2, 
                         label.getY() + e.getY() - label.getHeight()/2);
    }
});
  1. カスタムダイアログを作成し、ユーザーに入力させた値を取得するコード
JDialog dialog = new JDialog(frame, "Input Dialog", true);
JTextField inputField = new JTextField(20);
JButton okButton = new JButton("OK");

okButton.addActionListener(e -> {
    String value = inputField.getText();
    // 値を使用
    dialog.dispose();
});

dialog.setLayout(new FlowLayout());
dialog.add(inputField);
dialog.add(okButton);
dialog.pack();
dialog.setVisible(true);
  1. マウスで描画できる簡単なお絵かきアプリ
class DrawingPanel extends JPanel {
    private List points = new ArrayList<>();
    
    public DrawingPanel() {
        addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent e) {
                points.add(e.getPoint());
                repaint();
            }
        });
    }
    
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setStroke(new BasicStroke(3));
        
        for (int i = 1; i < points.size(); i++) {
            Point p1 = points.get(i-1);
            Point p2 = points.get(i);
            g2.drawLine(p1.x, p1.y, p2.x, p2.y);
        }
    }
}
  1. オブザーバーパターンを使用して、データモデルの変更を複数のJLabelに反映させるシステム
class ObservableModel {
    private String data;
    private List> listeners = new ArrayList<>();

    public void setData(String data) {
        this.data = data;
        notifyListeners();
    }

    public void addListener(Consumer listener) {
        listeners.add(listener);
    }

    private void notifyListeners() {
        listeners.forEach(l -> l.accept(data));
    }
}

// 使用例
ObservableModel model = new ObservableModel();
JLabel label1 = new JLabel();
JLabel label2 = new JLabel();

model.addListener(text -> {
    label1.setText(text);
    label2.setText("Length: " + text.length());
});

model.setData("Sample");
  1. コンポーネントを円形に配置
class CircleLayout implements LayoutManager {
    public void layoutContainer(Container parent) {
        int radius = Math.min(parent.getWidth(), parent.getHeight()) / 3;
        Point center = new Point(parent.getWidth()/2, parent.getHeight()/2);
        double angle = 2 * Math.PI / parent.getComponentCount();
        
        for (int i = 0; i < parent.getComponentCount(); i++) {
            Component c = parent.getComponent(i);
            int x = (int)(center.x + radius * Math.cos(i * angle) - c.getWidth()/2;
            int y = (int)(center.y + radius * Math.sin(i * angle) - c.getHeight()/2);
            c.setBounds(x, y, c.getPreferredSize().width, c.getPreferredSize().height);
        }
    }
    
    // 他の必要なメソッドも実装
}
  1. 3つの異なるパネルを切り替えられるインターフェース
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Tab 1", new JPanel());
tabbedPane.addTab("Tab 2", new JPanel());
tabbedPane.addTab("Tab 3", new JPanel());
frame.add(tabbedPane);