国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Create an AND door panel
Create the main JFrame
Use images instead of text tags
Summarize
Home Java javaTutorial Java Swing implements logic gates with check boxes and images

Java Swing implements logic gates with check boxes and images

Sep 05, 2025 pm 12:27 PM

Java Swing implements logic gates with check boxes and images

This article will guide you to create a simple GUI program using Java Swing to simulate an AND logic gate. The program contains two check boxes and a label. When both check boxes are selected, the label will be displayed in green; otherwise, it will be displayed in red. We will update the display of the tag dynamically by listening to the status change event of the checkbox, and provide a complete code example.

Create an AND door panel

First, create a class called AndGate, which inherits from JPanel and implements the ChangeListener interface. The ChangeListener interface is used to listen for state change events of check boxes.

 import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class AndGate extends JPanel implements ChangeListener {
    private JCheckBox in1;
    private JCheckBox in2;
    private JLabel result;

    public AndGate() {
        super();
        setLayout(new FlowLayout());

        in1 = new JCheckBox("Input 1");
        in1.addChangeListener(this);
        add(in1);

        in2 = new JCheckBox("Input 2");
        in2.addChangeListener(this);
        add(in2);

        result = new JLabel("Red"); // The initial state is Red
        result.setForeground(Color.RED);
        add(result);
    }

    @Override
    public void stateChanged(ChangeEvent e) {
        updateResult();
    }

    private void updateResult() {
        if (in1.isSelected() && in2.isSelected()) {
            result.setText("Green");
            result.setForeground(Color.GREEN);
        } else {
            result.setText("Red");
            result.setForeground(Color.RED);
        }
    }
}

Code explanation:

  • The AndGate class inherits from JPanel and can therefore be added as a component to a JFrame.
  • in1 and in2 are two JCheckBox objects representing two inputs to the AND gate.
  • result is a JLabel object that displays the output results of the AND gate.
  • FlowLayout is used to set the layout of the panel so that components are arranged in the order they are added.
  • addChangeListener(this) is used to register the current object as a listener for checkbox. When the state of the checkbox changes, the stateChanged method will be called.
  • In the stateChanged method, check whether both check boxes are selected. If both are selected, set the text of result to "Green", otherwise set to "Red".

Create the main JFrame

Next, create a main JFrame and add the AndGate panel to it.

 import javax.swing.*;
import java.awt.*;

public class MainFrame extends JFrame {

    public MainFrame() {
        setTitle("AND Gate Example");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        AndGate andGate = new AndGate();
        add(andGate, BorderLayout.CENTER);

        pack(); // Automatically adjust the window size to suit the component setLocationRelativeTo(null); // center the window to display setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new MainFrame());
    }
}

Code explanation:

  • The MainFrame class inherits from JFrame and is used to create the main window.
  • The setTitle method is used to set the title of the window.
  • The setDefaultCloseOperation method is used to set the operation when the window is closed. It is set to JFrame.EXIT_ON_CLOSE, which means exiting the program when the window is closed.
  • BorderLayout is used to set how the window is laid out, adding the AndGate panel to the center of the window.
  • The pack() method is used to automatically resize the window to fit the component.
  • The setLocationRelativeTo(null) method is used to center the window to display.
  • The setVisible(true) method is used to display the window.
  • The SwingUtilities.invokeLater method is used to execute Runnable objects in the event distribution thread to ensure the thread safety of the GUI.

Use images instead of text tags

If you want to use an image instead of a text label, you can load the image using the ImageIcon class and set it to the icon of the JLabel.

 import javax.swing.*;
import java.awt.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class AndGate extends JPanel implements ChangeListener {
    private JCheckBox in1;
    private JCheckBox in2;
    private JLabel result;
    private ImageIcon greenIcon;
    private ImageIcon redIcon;

    public AndGate() {
        super();
        setLayout(new FlowLayout());

        in1 = new JCheckBox("Input 1");
        in1.addChangeListener(this);
        add(in1);

        in2 = new JCheckBox("Input 2");
        in2.addChangeListener(this);
        add(in2);

        // Load the image try {
            greenIcon = new ImageIcon(getClass().getResource("/green.png")); // Replace with your green image path redIcon = new ImageIcon(getClass().getResource("/red.png")); // Replace with your red image path} catch (Exception e) {
            System.err.println("Error loading images: " e.getMessage());
            greenIcon = null;
            redIcon = null;
        }

        result = new JLabel();
        if (redIcon != null) {
            result.setIcon(redIcon); // The initial state is Red
        } else {
            result.setText("Red");
            result.setForeground(Color.RED);
        }
        add(result);
    }

    @Override
    public void stateChanged(ChangeEvent e) {
        updateResult();
    }

    private void updateResult() {
        if (in1.isSelected() && in2.isSelected()) {
            if (greenIcon != null) {
                result.setIcon(greenIcon);
                result.setText("");
            } else {
                 result.setText("Green");
                 result.setForeground(Color.GREEN);
            }

        } else {
            if (redIcon != null) {
                result.setIcon(redIcon);
                 result.setText("");
            } else {
                result.setText("Red");
                result.setForeground(Color.RED);
            }
        }
    }
}

Notes:

  • Make sure to place the image files (such as green.png and red.png) in the project's resources directory, or specify the correct image path.
  • If the image fails to load, the code falls back to the use text label.

Summarize

Through the above steps, you have successfully created a simple Java Swing program, emulating an AND logic gate. You can extend this program as needed, such as adding more logic gates, or using more complex GUI components. The key is to understand the event listening mechanism and how to use JCheckBox and JLabel components.

The above is the detailed content of Java Swing implements logic gates with check boxes and images. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is a deadlock in Java and how can you prevent it? What is a deadlock in Java and how can you prevent it? Aug 23, 2025 pm 12:55 PM

AdeadlockinJavaoccurswhentwoormorethreadsareblockedforever,eachwaitingforaresourceheldbytheother,typicallyduetocircularwaitcausedbyinconsistentlockordering;thiscanbepreventedbybreakingoneofthefournecessaryconditions—mutualexclusion,holdandwait,nopree

How to implement a simple TCP client in Java? How to implement a simple TCP client in Java? Aug 08, 2025 pm 03:56 PM

Importjava.ioandjava.net.SocketforI/Oandsocketcommunication.2.CreateaSocketobjecttoconnecttotheserverusinghostnameandport.3.UsePrintWritertosenddataviaoutputstreamandBufferedReadertoreadserverresponsesfrominputstream.4.Usetry-with-resourcestoautomati

Correct posture for handling non-UTF-8 request encoding in Spring Boot application Correct posture for handling non-UTF-8 request encoding in Spring Boot application Aug 15, 2025 pm 12:30 PM

This article discusses the mechanism and common misunderstandings of Spring Boot applications for handling non-UTF-8 request encoding. The core lies in understanding the importance of the charset parameter in the HTTP Content-Type header, as well as the default character set processing flow of Spring Boot. By analyzing the garbled code caused by wrong testing methods, the article guides readers how to correctly simulate and test requests for different encodings, and explains that Spring Boot usually does not require complex configurations to achieve compatibility under the premise that the client correctly declares encoding.

How to use Optional in Java? How to use Optional in Java? Aug 22, 2025 am 10:27 AM

UseOptional.empty(),Optional.of(),andOptional.ofNullable()tocreateOptionalinstancesdependingonwhetherthevalueisabsent,non-null,orpossiblynull.2.CheckforvaluessafelyusingisPresent()orpreferablyifPresent()toavoiddirectnullchecks.3.Providedefaultswithor

Exploring Common Java Design Patterns with Examples Exploring Common Java Design Patterns with Examples Aug 17, 2025 am 11:54 AM

The Java design pattern is a reusable solution to common software design problems. 1. The Singleton mode ensures that there is only one instance of a class, which is suitable for database connection pooling or configuration management; 2. The Factory mode decouples object creation, and objects such as payment methods are generated through factory classes; 3. The Observer mode automatically notifies dependent objects, suitable for event-driven systems such as weather updates; 4. The dynamic switching algorithm of Strategy mode such as sorting strategies improves code flexibility. These patterns improve code maintainability and scalability but should avoid overuse.

How to send and receive messages over a WebSocket in Java How to send and receive messages over a WebSocket in Java Aug 16, 2025 am 10:36 AM

Create a WebSocket server endpoint to define the path using @ServerEndpoint, and handle connections, message reception, closing and errors through @OnOpen, @OnMessage, @OnClose and @OnError; 2. Ensure that javax.websocket-api dependencies are introduced during deployment and automatically registered by the container; 3. The Java client obtains WebSocketContainer through the ContainerProvider, calls connectToServer to connect to the server, and receives messages using @ClientEndpoint annotation class; 4. Use the Session getBasicRe

How to deploy a Java application How to deploy a Java application Aug 17, 2025 am 12:56 AM

PrepareyourapplicationbyusingMavenorGradletobuildaJARorWARfile,externalizingconfiguration.2.Chooseadeploymentenvironment:runonbaremetal/VMwithjava-jarandsystemd,deployWARonTomcat,containerizewithDocker,orusecloudplatformslikeHeroku.3.Optionally,setup

Java Cryptography Architecture (JCA) for Secure Coding Java Cryptography Architecture (JCA) for Secure Coding Aug 23, 2025 pm 01:20 PM

Understand JCA core components such as MessageDigest, Cipher, KeyGenerator, SecureRandom, Signature, KeyStore, etc., which implement algorithms through the provider mechanism; 2. Use strong algorithms and parameters such as SHA-256/SHA-512, AES (256-bit key, GCM mode), RSA (2048-bit or above) and SecureRandom; 3. Avoid hard-coded keys, use KeyStore to manage keys, and generate keys through securely derived passwords such as PBKDF2; 4. Disable ECB mode, adopt authentication encryption modes such as GCM, use unique random IVs for each encryption, and clear sensitive ones in time

See all articles