初級問題(9問)
- JFrameを作成し、タイトルを「My App」に設定して表示するコードを書いてください。
- 400×300ピクセルのJFrameを作成し、中央に配置するコードを書いてください。
- JLabelを使用して「Welcome!」というテキストを表示するコードを書いてください。
- JButtonを作成し、クリック時に「Clicked!」とコンソールに出力するコードを書いてください。
- JTextFieldを作成し、初期テキストとして「Input here」を設定するコードを書いてください。
- JOptionPaneを使用して「Hello!」というメッセージダイアログを表示するコードを書いてください。
- FlowLayoutを使用して3つのJButtonを横並びに配置するコードを書いてください。
- JPanelの背景色を緑色に設定するコードを書いてください。
- JButtonに「Press me」というツールチップを設定するコードを書いてください。
中級問題(15問)
- BorderLayoutを使用して、北側にJLabel、中央にJPanel、南側にJButtonを配置するコードを書いてください。
- 2つのJTextFieldの数値を加算し、結果をJLabelに表示するボタンを作成してください。
- JOptionPaneを使用してYes/Noダイアログを表示し、選択結果をコンソールに出力するコードを書いてください。
- GridLayoutを使用して4×4のボタングリッドを作成するコードを書いてください。
- JPanelを拡張したMyPanelクラスを作成し、背景色を青色に設定してください。
- マウスクリックの座標を表示するJLabelを作成してください。
- JTextFieldの文字数制限(最大10文字)を実装してください。
- ボタンクリックでJFrameのタイトルを変更するコードを書いてください。
- 3つのラジオボタン(JRadioButton)を作成し、ButtonGroupでグループ化してください。
- JCheckBoxの状態変化を検知し、チェック状態をコンソールに出力するコードを書いてください。
- JComboBoxを作成し、選択肢として「Red」「Green」「Blue」を追加してください。
- ボタンクリックでJOptionPaneの入力ダイアログを表示し、入力値をJLabelに表示するコードを書いてください。
- マウスがコンポーネント上に入った/出た時に背景色を変更するコードを書いてください。
- JTextAreaとJScrollPaneを使用してスクロール可能なテキストエリアを作成してください。
- キーイベントを検知し、押されたキーを表示するJLabelを作成してください。
上級問題(6問)
- ドラッグ&ドロップで移動可能なJLabelを作成してください。
- カスタムダイアログを作成し、ユーザーに入力させた値を取得するコードを書いてください。
- マウスで描画できる簡単なお絵かきアプリを作成してください。
- オブザーバーパターンを使用して、データモデルの変更を複数のJLabelに反映させるシステムを作成してください。
- カスタムレイアウトマネージャーを作成し、コンポーネントを円形に配置してください。
- タブ付きペイン(JTabbedPane)を使用して、3つの異なるパネルを切り替えられるインターフェースを作成してください。
Swing演習問題 解答例
初級問題解答
- JFrame「My App」
JFrame frame = new JFrame("My App");
frame.setVisible(true);
- 400×300ピクセルのJFrame
JFrame frame = new JFrame();
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
- JLabel「Welcome!」
JLabel label = new JLabel("Welcome!");
- JButton「Clicked!」
JButton button = new JButton("Click");
button.addActionListener(e -> System.out.println("Clicked!"));
- JTextField「Input here」
JTextField textField = new JTextField("Input here");
- JOptionPane「Hello!」
JOptionPane.showMessageDialog(null, "Hello!");
- 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"));
- JPanelの背景色を緑色に
JPanel panel = new JPanel();
panel.setBackground(Color.GREEN);
- JButtonにツールチップ「Press me」
JButton button = new JButton();
button.setToolTipText("Press me");
中級問題解答
- 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);
- 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");
}
});
- JOptionPaneでYes/Noダイアログ
int result = JOptionPane.showConfirmDialog(
null, "Continue?", "Confirm", JOptionPane.YES_NO_OPTION);
System.out.println(result == JOptionPane.YES_OPTION ? "Yes" : "No");
- 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)));
}
- JPanelを拡張したMyPanelクラスで背景色を青色
class MyPanel extends JPanel {
public MyPanel() {
setBackground(Color.BLUE);
}
}
- マウスクリックの座標を表示するJLabel
JLabel coordLabel = new JLabel();
panel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
coordLabel.setText("X: " + e.getX() + ", Y: " + e.getY());
}
});
- 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);
}
}
});
- ボタンクリックでJFrameのタイトルを変更
button.addActionListener(e -> frame.setTitle("New Title"));
- 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);
- JCheckBoxの状態変化を検知
checkBox.addItemListener(e -> {
System.out.println(e.getStateChange() == ItemEvent.SELECTED ? "Checked" : "Unchecked");
});
- JComboBoxで「Red」「Green」「Blue」
JComboBox comboBox = new JComboBox<>();
comboBox.addItem("Red");
comboBox.addItem("Green");
comboBox.addItem("Blue");
- JOptionPaneの入力ダイアログをJLabelに表示
button.addActionListener(e -> {
String input = JOptionPane.showInputDialog("Enter text:");
label.setText(input);
});
- マウスがコンポーネント上に入った/出た時に背景色を変更
panel.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
panel.setBackground(Color.YELLOW);
}
public void mouseExited(MouseEvent e) {
panel.setBackground(Color.WHITE);
}
});
- JTextAreaとJScrollPaneを使用してスクロール可能なテキストエリア
JTextArea textArea = new JTextArea(10, 30);
JScrollPane scrollPane = new JScrollPane(textArea);
- キーイベントを検知し、押されたキーを表示するJLabel
JLabel keyLabel = new JLabel();
textField.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
keyLabel.setText("Key pressed: " + e.getKeyChar());
}
});
上級問題解答
- ドラッグ&ドロップで移動可能な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);
}
});
- カスタムダイアログを作成し、ユーザーに入力させた値を取得するコード
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);
- マウスで描画できる簡単なお絵かきアプリ
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);
}
}
}
- オブザーバーパターンを使用して、データモデルの変更を複数の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");
- コンポーネントを円形に配置
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);
}
}
// 他の必要なメソッドも実装
}
- 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);