Code – die besten Beiträge

Video abspielen und korrekt beenden (Java programmieren)?

Hallo,

ich probiere gerade mit der Programmiersprache Java einen Video-Player zu programmieren, welcher ein Video abspielen kann und per Button wieder beendet.

Allerdings, wenn ich es ein weiteres Mal öffnen will, wird es nicht mehr angezeigt und nichts passiert mehr. Wie kann ich das lösen? Ich komme einfach nicht mehr weiter oder gibt es eine einfache Möglichkeit?

Danke für eure Kommentare im Voraus.

import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javax.swing.*;
import java.awt.*;
import java.io.File;

public class VideoOpener {
  private static JDialog videoDialog;
  private static MediaPlayer mediaPlayer;
  private static JFXPanel jfxPanel;

  public static void main(String[] args) {
    // Initialisiere JavaFX im Swing-Thread
    SwingUtilities.invokeLater(() -> {
      new JFXPanel(); // Initialisiert JavaFX (damit der JavaFX-Thread startet)
      playVideo(); // Startet das Video nach der Initialisierung
    });
  }

  public static void playVideo() {
    // Erstelle das JDialog für das Video
    videoDialog = new JDialog((Frame) null, "Video", true);
    videoDialog.setUndecorated(true);
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    videoDialog.setSize(screenSize.width, screenSize.height); // Setzt das Fenster auf Vollbild
    videoDialog.setLocation(0, 0); // Positioniert das Fenster oben links
    JPanel videoPanel = new JPanel(new BorderLayout());
    jfxPanel = new JFXPanel(); // JFXPanel für JavaFX
    videoPanel.add(jfxPanel, BorderLayout.CENTER);

    // Schließen-Button (Fenster schließen)
    JButton closeButton = new JButton("Schließen");
    closeButton.addActionListener(e -> {
      stopVideo(); // Stoppt das Video
      videoDialog.dispose(); // Schließt das Dialog-Fenster
      Platform.exit(); // Beendet den JavaFX-Thread
    });
    // Setze den Button unten im JPanel
    videoPanel.add(closeButton, BorderLayout.SOUTH);

    // Lade und starte das Video im JavaFX-Thread
    Platform.runLater(() -> {
      File videoFile = new File("C:/Users/nikla/Pictures/Screenshots/Spiel/Film1.mp4");

      if (!videoFile.exists()) {
        System.err.println("Die Videodatei existiert nicht: " + videoFile.getAbsolutePath());
        return;
      }

      // Wenn der MediaPlayer bereits existiert, stoppen und freigeben
      if (mediaPlayer != null) {
        mediaPlayer.stop();
        mediaPlayer.dispose();
      }

      // Erstelle den neuen MediaPlayer
      Media media = new Media(videoFile.toURI().toString());
      mediaPlayer = new MediaPlayer(media);
      MediaView mediaView = new MediaView(mediaPlayer);
      mediaView.setFitWidth(screenSize.width);
      mediaView.setFitHeight(screenSize.height);

      // StackPane für das Layout
      StackPane stackPane = new StackPane();
      stackPane.getChildren().add(mediaView);

      // Setze die Scene für den JFXPanel
      Scene scene = new Scene(stackPane);
      jfxPanel.setScene(scene);

      // Spiele das Video ab
      mediaPlayer.play();
    });

    // Zeige das Video-Fenster an
    videoDialog.setContentPane(videoPanel);
    videoDialog.setVisible(true);
  }

  // Methode zum Stoppen des Videos und Freigeben des MediaPlayers
  private static void stopVideo() {
    if (mediaPlayer != null) {
      mediaPlayer.stop();
      mediaPlayer.dispose();
      mediaPlayer = null;
    }
  }
}
App, Java, Code, Programmiersprache

Website lädt Datei nicht hoch, warum?

Moin, kennt sich vielleicht jemand mit PHP und Html aus und weiß warum beim Upload der Datei nicht das Script "upload.php" ausgeführt wird? Versuche mich gerade beim Scripten, stehe allerdings gerade voll auf dem Schlauch... Danke!

<?php include 'header.php'; ?>
<?php
if(!isset($_SESSION['email'])){
  header('location:login.php');
  $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
}
 ?>
      <div class="breadcrumb">
        <div class="container">
            <a class="breadcrumb-item" href="index.php">Home</a>
            <span class="breadcrumb-item active">Welecome <?php echo $_SESSION['email'] ?></span>
            <span class="breadcrumb-item active">Upload Video</span>
        </div>
    </div>
    <section class="static about-sec">
        <div class="container">
            <h1>Upload Video</h1>
            <div class="form">
                <form class="" action="videoUpload.php" method="post">
                    <div class="row">
                        <div class="col-md-6">
                            <input type="hidden" name="id" value="">
                            <label for="name">Name of Video:</label>
                            <input type="text" name="name" value="" placeholder="Fantasy World" required>
                            <label for="video_url">Video URL</label>
                            <input type="file" name="video_url" required>
                            <label for="description">Description</label>
                            <input type="text" name="description" value="" placeholder="">
                            <label for="category">Category</label>
                            <select name="category">
                              <option value="Classic">Classic</option>
                              <option value="Adventerous">Adventerous</option>
                              <option value="Nature">Nature</option>
                              <option value="Others">Others</option>
                            </select>
                          </div>
                        </div>
							<div class="col-lg-8 col-md-12">
							<form action="upload.php" method="post" enctype="multipart/form-data">
							<input type="submit" class="btn black" value="Upload Image" name="submit">
							</form>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </section>


    <?php include 'footer.php';?>
HTML, Webseite, HTML5, Code, Datenbank, MySQL, PHP, Programmiersprache, Webdesign, Webentwicklung

Wie kann ich die Warenkorb-Logik erweitern??

Der Warenkorb überschreibt aktuell die vorhandene Menge, wenn ein Produkt erneut hinzugefügt wird. Wie könnte ich ?

<?php
session_start();
include 'db.php';


// Check if a product_id is set in the URL
if (isset($_GET['id_product'])) {
    $id_product = $_GET['id_product'];
    
    // Prepare and execute query to fetch product details
    $stmt = $conn->prepare("SELECT * FROM products WHERE id_product = ?");
    $stmt->bind_param("i",$id_product);
    $stmt->execute();
    $result = $stmt->get_result();
    $product = $result->fetch_assoc();
    
    // If product not found, redirect to the main page
    if (!$product) {
        header("Location: index.php");
        exit();
    }
} else {
    header("Location: index.php");
    exit();
}


// Handle the add to cart functionality
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $quantity = isset($_POST['anzahl']) ? (int)$_POST['anzahl'] : 1;


    // Ensure a valid quantity is added
    if ($quantity > 0) {
        // Add to cart (store in session)
        $_SESSION['cart'][$id_product] = [
            'product_name' => $product['produktname'],
            'price' => $product['preis_pro_prod'],
            'quantity' => $quantity,
            'pid' => $id_product
        ];


        // Redirect to the cart page or display success message
        header(header: "Location: cart.php");
        exit();
    }
}
?>


<!DOCTYPE html>
<html>
<head>
    <title><?= htmlspecialchars($product['product_name']) ?> - Product Details</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f9;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 20px;
        }


        .product-detail {
            background-color: #fff;
            border: 1px solid #ddd;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
            padding: 20px;
            max-width: 500px;
            text-align: center;
        }


        .product-detail img {
            width: 100%;
            height: auto;
            border-radius: 8px;
            margin-bottom: 20px;
        }


        .product-detail h2 {
            color: #333;
            margin-bottom: 10px;
        }


        .product-detail p {
            color: #666;
            margin-bottom: 10px;
        }


        .product-detail .price {
            font-weight: bold;
            color: #2a9d8f;
            font-size: 1.2em;
            margin-top: 10px;
        }
.addtocart
{
    color:#2a9d8f;
    background-color: white;
    border-color:#2a9d8f ;
    border-width: 2px;
    font-weight: bold;
}


.anzahl
{
    background-color: white;
    border-color:#2a9d8f ;
    color:#2a9d8f;
    border-width: 2px;
    font-weight: bold;
    text-align: center;
    
}
        


     
    </style>
</head>
<body>
    <div class="product-detail">
        <img src="<?= htmlspecialchars($product['image_url']) ?>" alt="<?= htmlspecialchars($product['produktname']) ?>">
        <h2><?= htmlspecialchars($product['produktname']) ?></h2>
        <p><?= htmlspecialchars($product['produktbeschreibung']) ?></p>
        <p class="price">Price: €<?= htmlspecialchars($product['preis_pro_prod']) ?></p>
        <form method="post">
            <input type="number" name="anzahl" value="1" min="1" placeholder="Anzahl" class="anzahl">
            <br>
            <br>
            <button type="submit" class="addtocart">In den Warenkorb</button>
        </form>
    </div>
</body>
</html>




Homepage, Code

Wie könnte ich die Datenbankabfragen oder das Programm optimieren?

<?php
include 'db.php';


// Five Most Frequently Ordered Products
$query_highesttotalquantity = "
    SELECT 
        id_product, 
        SUM(anzahl) total_quantity
    FROM 
        bestellungen_products
    GROUP BY 
        id_product
    ORDER BY 
        total_quantity DESC
    LIMIT 5
";
$highesttotalquantity = $conn->query($query_highesttotalquantity);
if (!$highesttotalquantity) {
    die("Query Error (highesttotalquantity): " . $conn->error);
}


// Five Products with the Highest Number of Orders
$query_highesnumb = "
    SELECT 
        id_product, 
        COUNT(DISTINCT id_bestellung) order_count
    FROM 
        bestellungen_products
    GROUP BY 
        id_product
    ORDER BY 
        order_count DESC
    LIMIT 5
";
$highesnumb = $conn->query($query_highesnumb);
if (!$highesnumb) {
    die("Query Error (highesnumb): " . $conn->error);
}


// Five Least Frequently Ordered Products
$query_lowest5 = "
    SELECT 
        id_product, 
        SUM(anzahl) total_quantity
    FROM 
        bestellungen_products
    GROUP BY 
        id_product
    ORDER BY 
        total_quantity ASC
    LIMIT 5
";
$lowest5 = $conn->query($query_lowest5);
if (!$lowest5) {
    die("Query Error (lowest5): " . $conn->error);
}


// Order History Over the Last Four Weeks
$query_last4weeks = "
    SELECT 
        YEARWEEK(bestelldatum, 1) week, 
        SUM(bp.anzahl) total_quantity
    FROM 
        bestellungen b
    JOIN 
        bestellungen_products bp ON b.id_bestellung = bp.id_bestellung
    WHERE 
        bestelldatum >= CURDATE() - INTERVAL 4 WEEK
    GROUP BY 
        week
    ORDER BY 
        week DESC
";
$last4weeks = $conn->query($query_last4weeks);
if (!$last4weeks) {
    die("Query Error (last4weeks): " . $conn->error);
}
?>


<!DOCTYPE html>
<html>
<head>
    <title>Admin Statistics</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
        }
        h1, h2 {
            color: #333;
        }
        .stat-section {
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <h1>Admin Statistics</h1>


    <div class="stat-section">
        <h2>Five Most Frequently Ordered Products</h2>
        <?php while ($product = $highesttotalquantity->fetch_assoc()): ?>
            <p>Product ID: <?= htmlspecialchars($product['id_product']) ?> - Total Quantity: <?= htmlspecialchars($product['total_quantity']) ?></p>
        <?php endwhile; ?>
    </div>


    <div class="stat-section">
        <h2>Five Products with the Highest Number of Orders</h2>
        <?php while ($product = $highesnumb->fetch_assoc()): ?>
            <p>Product ID: <?= htmlspecialchars($product['id_product']) ?> - Order Count: <?= htmlspecialchars($product['order_count']) ?></p>
        <?php endwhile; ?>
    </div>


    <div class="stat-section">
        <h2>Five Least Frequently Ordered Products</h2>
        <?php while ($product = $lowest5->fetch_assoc()): ?>
            <p>Product ID: <?= htmlspecialchars($product['id_product']) ?> - Total Quantity: <?= htmlspecialchars($product['total_quantity']) ?></p>
        <?php endwhile; ?>
    </div>


    <div class="stat-section">
        <h2>Order History Over the Last Four Weeks</h2>
        <?php while ($week = $last4weeks->fetch_assoc()): ?>
            <p>Week: <?= htmlspecialchars($week['week']) ?> - Total Quantity Ordered: <?= htmlspecialchars($week['total_quantity']) ?></p>
        <?php endwhile; ?>
    </div>
</body>
</html>


programmieren, Code

Python discord NonType Error?

Ich habe einen Error in meinem Code:

async def on_submit(self, interaction2: discord.Interaction):
    response = await sendRequests(str(self.username), str(self.email), str(self.password))
    if response == "email":
        await interaction2.response.send_message("Incorrect email format", ephemeral=True)
        return
    if response == "password":
        await interaction2.response.send_message("Incorrect password format. The password must meet these requirements: \nOne Uppercase letter \nOne lowercase letter \nOne number\n A special character ", ephemeral=True)
        return
    if response == "maintenance":
        await interaction2.response.send_message("The system is currently under maintenance. Please look in #news for more infos.", ephemeral=True)
    query = "INSERT INTO users VALUES (?, ?, ?, ?)"
    main.cursor.execute(query, (interaction2.user.id, str(self.username), str(self.email), str(self.password)))
    main.database.commit()
    await interaction2.response.send_message("You are now in the registration process. This can take up to one hour.", ephemeral=True)
    channel = main.bot.get_channel(1309925591146958933)
    await channel.send("make a recaptcha, registration from user : " + str(interaction2.user.name) + " with id: " + str(interaction2.user.id))

Error:
[2024-11-23 19:32:43] [ERROR  ] discord.ui.modal: Ignoring exception in modal <RegisterModal timeout=None children=3>:

Traceback (most recent call last):

 File ".venv\Lib\site-packages\discord\ui\modal.py", line 189, in _scheduled_task

   await self.on_submit(interaction)

 File "TestButton.py", line 41, in on_submit

   await channel.send("make a recaptcha, registration from user : " + str(interaction2.user.name) + " with id: " + str(interaction2.user.id))

         ^^^^^^^^^^^^

AttributeError: 'NoneType' object has no attribute 'send'

Bot, Code, Programmiersprache, Python, Webentwicklung, Python 3, Pycharm, Discord, Discord Bot

Meistgelesene Beiträge zum Thema Code