import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
public class OmikujiGUI extends JFrame {
private final JLabel resultLabel = new JLabel("—", SwingConstants.CENTER);
private final JLabel messageLabel = new JLabel("ボタンを押して引け", SwingConstants.CENTER);
private final JLabel luckyLabel = new JLabel("ラッキー:—", SwingConstants.CENTER);
private final JTextArea historyArea = new JTextArea(10, 30);
private final Random random = new Random();
private static final String[] RESULTS = {"大吉", "中吉", "小吉", "吉", "末吉", "凶", "大凶"};
private static final String[] MESSAGES = {
"最強。今日は攻めていい。",
"良い流れ。焦らず積み上げろ。",
"小さく勝てる日。丁寧にいこう。",
"安定。普通が一番強い。",
"油断すると崩れる。慎重に。",
"無理は禁物。守りでいけ。",
"今日は撤退が正解。休め。"
};
private static final String[] COLORS = {"赤", "青", "緑", "黒", "白", "金", "紫"};
public OmikujiGUI() {
super("おみくじ(GUI版)");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setMinimumSize(new Dimension(520, 520));
setLocationRelativeTo(null);
// 全体レイアウト
JPanel root = new JPanel(new BorderLayout(12, 12));
root.setBorder(new EmptyBorder(16, 16, 16, 16));
setContentPane(root);
// 上部:タイトル
JLabel title = new JLabel("おみくじアプリ", SwingConstants.LEFT);
title.setFont(title.getFont().deriveFont(Font.BOLD, 22f));
root.add(title, BorderLayout.NORTH);
// 中央:結果表示パネル
JPanel center = new JPanel();
center.setLayout(new BoxLayout(center, BoxLayout.Y_AXIS));
root.add(center, BorderLayout.CENTER);
resultLabel.setFont(resultLabel.getFont().deriveFont(Font.BOLD, 56f));
resultLabel.setBorder(new EmptyBorder(18, 12, 10, 12));
messageLabel.setFont(messageLabel.getFont().deriveFont(Font.PLAIN, 16f));
messageLabel.setBorder(new EmptyBorder(6, 12, 6, 12));
luckyLabel.setFont(luckyLabel.getFont().deriveFont(Font.PLAIN, 15f));
luckyLabel.setBorder(new EmptyBorder(6, 12, 14, 12));
center.add(wrapCard(resultLabel));
center.add(Box.createVerticalStrut(10));
center.add(wrapCard(messageLabel));
center.add(Box.createVerticalStrut(8));
center.add(wrapCard(luckyLabel));
center.add(Box.createVerticalStrut(12));
// 履歴
JLabel historyTitle = new JLabel("履歴");
historyTitle.setFont(historyTitle.getFont().deriveFont(Font.BOLD, 16f));
historyTitle.setBorder(new EmptyBorder(4, 2, 6, 2));
center.add(historyTitle);
historyArea.setEditable(false);
historyArea.setLineWrap(true);
historyArea.setWrapStyleWord(true);
historyArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 13));
historyArea.setText("(まだありません)");
JScrollPane scroll = new JScrollPane(historyArea);
scroll.setBorder(BorderFactory.createLineBorder(new Color(220, 220, 220)));
center.add(scroll);
// 下部:ボタン
JPanel bottom = new JPanel(new GridLayout(1, 3, 10, 10));
JButton drawBtn = new JButton("引く");
JButton clearBtn = new JButton("履歴クリア");
JButton exitBtn = new JButton("終了");
drawBtn.setFont(drawBtn.getFont().deriveFont(Font.BOLD, 14f));
drawBtn.addActionListener(e -> drawOmikuji());
clearBtn.addActionListener(e -> clearHistory());
exitBtn.addActionListener(e -> dispose());
bottom.add(drawBtn);
bottom.add(clearBtn);
bottom.add(exitBtn);
root.add(bottom, BorderLayout.SOUTH);
}
private JPanel wrapCard(JComponent comp) {
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createLineBorder(new Color(225, 225, 225)),
new EmptyBorder(6, 8, 6, 8)
));
p.add(comp, BorderLayout.CENTER);
return p;
}
private void drawOmikuji() {
int idx = random.nextInt(RESULTS.length);
String result = RESULTS[idx];
String message = MESSAGES[idx];
int luckyNumber = random.nextInt(99) + 1; // 1〜99
String luckyColor = COLORS[random.nextInt(COLORS.length)];
resultLabel.setText(result);
messageLabel.setText(message);
luckyLabel.setText("ラッキーナンバー:" + luckyNumber + " / ラッキーカラー:" + luckyColor);
String time = new SimpleDateFormat("yyyy/MM/dd HH:mm").format(new Date());
String line = time + " → " + result + "(#" + luckyNumber + " / " + luckyColor + ")";
appendHistory(line);
}
private void appendHistory(String line) {
String current = historyArea.getText();
if (current.equals("(まだありません)")) current = "";
if (!current.isEmpty()) current = current + "\n";
historyArea.setText(current + line);
historyArea.setCaretPosition(historyArea.getDocument().getLength());
}
private void clearHistory() {
historyArea.setText("(まだありません)");
resultLabel.setText("—");
messageLabel.setText("ボタンを押して引け");
luckyLabel.setText("ラッキー:—");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new OmikujiGUI().setVisible(true));
}
}
カテゴリー: Java
Java クラスの継承
public class CTest11 {
public static void main(String[] args) {
Soarer soarer = new Soarer();
System.out.println(soarer.status());
// ルーフ操作
soarer.openRoof();
System.out.println(soarer.status());
// 加速
for(int i=0; i<6; i++){
soarer.accele();
}
System.out.println(soarer.status());
// 走行中にルーフを開けようとする(失敗する)
soarer.openRoof();
System.out.println(soarer.status());
// 減速して停止
for(int i=0; i<20; i++){
soarer.brake();
}
System.out.println(soarer.status());
// 停止中なら閉じられる
soarer.closeRoof();
System.out.println(soarer.status());
}
}
class Car {
private int speed = 0;
private final int maxSpeed;
public Car(int maxSpeed){
this.maxSpeed = maxSpeed;
}
public void accele(){
setSpeed(speed + 5);
}
public void brake(){
setSpeed(speed - 5);
}
protected void setSpeed(int newSpeed){
if(newSpeed < 0) newSpeed = 0;
if(newSpeed > maxSpeed) newSpeed = maxSpeed;
speed = newSpeed;
}
public int getSpeed(){
return speed;
}
public int getMaxSpeed(){
return maxSpeed;
}
public boolean isStopped(){
return speed == 0;
}
public String status(){
return "速度: " + speed + "km/h (MAX " + maxSpeed + ")";
}
}
class Soarer extends Car {
private boolean roofOpen = false;
// 例:ソアラは最高180
public Soarer(){
super(180);
}
// 車種特性:加速が少し強い
@Override
public void accele(){
setSpeed(getSpeed() + 10);
// 一定速度以上なら安全のため自動で閉じる
if(getSpeed() >= 60 && roofOpen){
roofOpen = false;
}
}
@Override
public void brake(){
setSpeed(getSpeed() - 10);
}
public void openRoof(){
// 走行中は危ないので禁止(停止中のみ)
if(isStopped()){
roofOpen = true;
}
}
public void closeRoof(){
roofOpen = false; // ←バグ修正:trueじゃなくてfalse
}
public boolean isRoofOpen(){
return roofOpen;
}
@Override
public String status(){
String roof = roofOpen ? "屋根: OPEN" : "屋根: CLOSED";
return super.status() + " / " + roof;
}
}
MusicPlayer.java
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javazoom.jl.player.Player; // JLayer
/** 超シンプル MP3 プレイヤー */
public class MusicPlayer extends JFrame {
private static final long serialVersionUID = 1L;
private JButton playBtn = new JButton("▶ 再生");
private JButton stopBtn = new JButton("■ 停止");
private JLabel status = new JLabel("ファイルを開いてください");
private File currentFile;
private Player player; // 再生用スレッド
private Thread playThread;
public MusicPlayer() {
super("Java Swing Music Player");
// 画面レイアウト
JPanel ctrl = new JPanel();
ctrl.add(playBtn);
ctrl.add(stopBtn);
add(ctrl, BorderLayout.CENTER);
add(status, BorderLayout.SOUTH);
// メニュー
JMenuBar bar = new JMenuBar();
JMenu f = new JMenu("ファイル");
JMenuItem open = new JMenuItem("開く...");
open.addActionListener(e -> chooseFile());
f.add(open);
bar.add(f);
setJMenuBar(bar);
// ボタン挙動
playBtn.addActionListener(e -> play());
stopBtn.addActionListener(e -> stop());
// ウィンドウ設定
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(320, 120);
setResizable(false);
setLocationRelativeTo(null);
}
/** ファイル選択ダイアログ */
private void chooseFile() {
JFileChooser fc = new JFileChooser();
fc.setFileFilter(new FileNameExtensionFilter("MP3 Audio", "mp3"));
if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
currentFile = fc.getSelectedFile();
status.setText("選択中: " + currentFile.getName());
}
}
/** 再生開始 */
private void play() {
if (currentFile == null) {
JOptionPane.showMessageDialog(this, "まず MP3 を選択してください");
return;
}
stop(); // 既に再生中なら停止
playThread = new Thread(() -> {
try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(currentFile))) {
player = new Player(in);
status.setText("再生中: " + currentFile.getName());
player.play(); // ブロッキング
SwingUtilities.invokeLater(() -> status.setText("停止"));
} catch (Exception ex) {
ex.printStackTrace();
SwingUtilities.invokeLater(() -> status.setText("再生失敗"));
}
});
playThread.start();
}
/** 再生停止 */
private void stop() {
if (player != null) {
player.close();
}
if (playThread != null) {
playThread.interrupt();
}
status.setText("停止");
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MusicPlayer().setVisible(true));
}
}
C:\java> dir jlayer-1.0.1.jar
2025/05/06 92,109 jlayer-1.0.1.jar ← この行が出れば OK
コンパイル
C:\java> javac -encoding UTF-8 -cp “.;jlayer-1.0.1.jar” MusicPlayer.java
Java 抽象クラス
abstract class Score {
private String subject;
protected int score;
Score(String subject, int score) {
this.subject = subject;
this.score = score;
}
protected abstract String getResult();
String getScoreString() {
return this.subject + ", " + this.score + ", " + this.getResult();
}
}
class MathScore extends Score {
MathScore(int score) {
super("Math", score);
}
@Override
protected String getResult() {
System.out.println("MathScore method");
return this.score >= 50 ? "Pass" : "Fail";
}
}
class EnglishScore extends Score {
EnglishScore(int score) {
super("English", score);
}
@Override
protected String getResult() {
System.out.println("EnglishScore method");
return this.score >= 70 ? "Pass" : "Fail";
}
}
class User {
private String name;
private Score score;
User(String name, Score score) {
this.name = name;
this.score = score;
}
String getUserString() {
return this.name + ", " + this.score.getScoreString();
}
}
public class MyApp {
public static void main(String[] args) {
User user1 = new User("Taro", new MathScore(70));
User user2 = new User("Jiro", new EnglishScore(80));
System.out.println(user1.getUserString());
System.out.println(user2.getUserString());
}
}
Java TodoList
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
class TodoItem implements Serializable {
private static final long serialVersionUID = 1L;
private static int counter = 1;
private int id;
private String description;
private String category;
private Date deadline;
private String priority;
private boolean completed;
public TodoItem(String description, String category, String deadline, String priority) throws ParseException {
this.id = counter++;
this.description = description;
this.category = category;
this.deadline = new SimpleDateFormat("yyyy-MM-dd").parse(deadline);
this.priority = priority;
this.completed = false;
}
public int getId() {
return id;
}
public String getDescription() {
return description;
}
public String getCategory() {
return category;
}
public Date getDeadline() {
return deadline;
}
public String getPriority() {
return priority;
}
public boolean isCompleted() {
return completed;
}
public void markCompleted() {
this.completed = true;
}
public boolean isOverdue() {
return !completed && deadline.before(new Date());
}
@Override
public String toString() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String status = isCompleted() ? "完了" : (isOverdue() ? "期限切れ" : "未完了");
return String.format("%-4d %-30s %-15s %-10s %-10s %-10s",
id, description, category, priority, sdf.format(deadline), status);
}
}
public class TodoListApp {
private Map<String, List<TodoItem>> userTasks = new HashMap<>();
private static final String DATA_FILE = "todo_data.ser";
private String currentUser = "default";
public TodoListApp() {
loadTasks();
}
public void addTask(String description, String category, String deadline, String priority) {
try {
userTasks.computeIfAbsent(currentUser, k -> new ArrayList<>())
.add(new TodoItem(description, category, deadline, priority));
System.out.println("タスクを追加しました。");
saveTasks();
} catch (ParseException e) {
System.out.println("無効な日付形式です。形式 yyyy-MM-dd");
}
}
public void listTasks() {
List<TodoItem> tasks = userTasks.getOrDefault(currentUser, new ArrayList<>());
if (tasks.isEmpty()) {
System.out.println("タスクがありません。");
return;
}
System.out.println(String.format("%-4s %-30s %-15s %-10s %-10s %-10s",
"ID", "タスク内容", "カテゴリ", "優先度", "期限", "状態"));
tasks.stream()
.sorted(Comparator.comparing(TodoItem::getDeadline).thenComparing(TodoItem::getPriority))
.forEach(System.out::println);
}
public void markTaskCompleted(int id) {
List<TodoItem> tasks = userTasks.getOrDefault(currentUser, new ArrayList<>());
for (TodoItem task : tasks) {
if (task.getId() == id) {
task.markCompleted();
System.out.println("タスクを完了しました。");
saveTasks();
return;
}
}
System.out.println("タスクが見つかりません。");
}
public void removeTask(int id) {
List<TodoItem> tasks = userTasks.getOrDefault(currentUser, new ArrayList<>());
if (tasks.removeIf(task -> task.getId() == id)) {
System.out.println("タスクを削除しました。");
saveTasks();
} else {
System.out.println("タスクが見つかりません。");
}
}
private void saveTasks() {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(DATA_FILE))) {
oos.writeObject(userTasks);
} catch (IOException e) {
System.out.println("タスクの保存に失敗しました。");
}
}
@SuppressWarnings("unchecked")
private void loadTasks() {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(DATA_FILE))) {
userTasks = (Map<String, List<TodoItem>>) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
System.out.println("以前のタスクを読み込めませんでした。");
}
}
public static void main(String[] args) {
TodoListApp app = new TodoListApp();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("\nTODOリスト - " + app.currentUser);
System.out.println("1. タスクを追加");
System.out.println("2. タスクを一覧表示");
System.out.println("3. タスクを完了済みにする");
System.out.println("4. タスクを削除");
System.out.println("5. 終了");
System.out.print("選択してください: ");
int choice = scanner.nextInt();
scanner.nextLine(); // 改行を消費
switch (choice) {
case 1:
System.out.print("タスク内容: ");
String description = scanner.nextLine();
System.out.print("カテゴリ: ");
String category = scanner.nextLine();
System.out.print("期限 (yyyy-MM-dd): ");
String deadline = scanner.nextLine();
System.out.print("優先度 (高, 中, 低): ");
String priority = scanner.nextLine();
app.addTask(description, category, deadline, priority);
break;
case 2:
app.listTasks();
break;
case 3:
System.out.print("完了するタスクのID: ");
int completeId = scanner.nextInt();
app.markTaskCompleted(completeId);
break;
case 4:
System.out.print("削除するタスクのID: ");
int removeId = scanner.nextInt();
app.removeTask(removeId);
break;
case 5:
System.out.println("終了します。");
scanner.close();
return;
default:
System.out.println("無効な選択です。");
}
}
}
}
javac -encoding UTF-8 TodoListApp.java
java TodoListApp
Java クラス変数
class User {
String name;
int score;
static int count = 0;
User(String name, int score) {
this.name = name;
this.score = score;
User.count++;
}
}
public class MyApp {
public static void main(String[] args) {
// int count = 0;
User user1 = new User("Taro", 70);
// count++;
User user2 = new User("Jiro", 80);
// count++;
// System.out.println(count);
System.out.println(User.count);
}
}
Java ジェネリクス
public class MyApp {
private static <T> void showThreeTimes(T n) {
System.out.println(n);
System.out.println(n);
System.out.println(n);
}
public static void main(String[] args) {
showThreeTimes(3);
showThreeTimes(5.2);
}
}
Java メソッド
public class MyApp {
private static void showAd() {
System.out.println("---------");
System.out.println("SALE! 50% OFF!");
System.out.println("---------");
}
private static void showContent() {
System.out.println("BREAKING NEWS!");
System.out.println("Two baby pandas born at our Zoo!");
}
public static void main(String[] args) {
showAd();
showContent();
showAd();
}
}
Java 処理の順序
private static int triple(int num) { // 仮引数
return num * 3;
}
public static void main(String[] args) {
System.out.println(triple(10)); // 実引数
System.out.println(triple(4) * 3); // 実引数
}
}
Java メソッド
public class MyApp {
private static int triple(int num) { // 仮引数
return num * 3;
}
public static void main(String[] args) {
System.out.println(triple(10)); // 実引数
System.out.println(triple(4) * 3); // 実引数
}
}
