JavaSwing cycle single ping network IP address in 5 seconds, add adaptive background image, etc.

Requirements: 6 AI cameras and 1 server network status monitoring

The effect picture above is originally an adaptive background picture, but it is too cumbersome to calculate the coordinates according to the size of the window for a few buttons of single Ping IP. Simply frame the form directly, and encounter an error that ImageIO.read is null when adding a background image. Baidu has tried everything including whether the image format is webp format, etc., but it is still wrong. Finally, one of my .net C# classmates told me to try adding “/” or “./” before src;

It’s really because of the path problem, I blame myself for being too good;

Runnable path: Yes, I put the picture directly in the src directory, but never add “/” before src

Error: URL imageUrl = GAView.class.getResource("src/123.jpg");
It can be run: URL imageUrl = GAView.class.getResource("/src/123.jpg");

I wasted a lot of time because of this problem.

Attach the code directly below:

package saicmotor;

import javafx.scene.layout.Region;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;

import javax.swing.border.LineBorder;

/**Title: Demo.java
 * sample code
 *
 * @author Run
 * @date 2023-05-24 */
public class GAView{
    private static BufferedImage image;
    private static JButton button;
    private static JButton button1;
    private static Timer timer;

    public static void main(String args[]){
        SwingUtilities. invokeLater( () ->{
            //run the sample code
            AutoAdjustIconDemo();
        });
    }

    /** Image adaptive component size
     * @date 2023-05-24 */
    public static void AutoAdjustIconDemo() {
        JFrame frame=new JFrame("IRS Network Monitoring Kanban");
        JPanel panel=new JPanel((new GridLayout(1, 1, 10, 10)));
        frame.setResizable(false);//Whether the size of the form can be changed
        panel.setOpaque(false);
        //Import image
        button = new JButton("T0 station");
        button1 = new JButton("T1001");
// JButton souBtnT0 = new JButton("T0 station");
// JButton souBtnT1 = new JButton("T1001");
        JButton souBtnT2 = new JButton("T2001");
        JButton souBtnC1 = new JButton("C1001");
        JButton souBtnC2 = new JButton("C2001");
        JButton souBtnC3 = new JButton("C3001");
        JButton souBtnIRS = new JButton("10.72.20.93 server");
        button. setBounds(970, 440, 100, 70);
        button1.setBounds(620, 340, 100, 70);
        souBtnT2.setBounds(1100, 255, 100, 70);
        souBtnC1.setBounds(140, 280, 100, 70);
        souBtnC2.setBounds(347, 580, 100, 70);
        souBtnC3.setBounds(347, 100, 100, 70);
        souBtnIRS.setBounds(10, 10, 300, 50);
        button.setBackground(Color.BLACK);
        button1.setBackground(Color.BLACK);
        souBtnT2.setBackground(Color.BLACK);
        souBtnC1.setBackground(Color.BLACK);
        souBtnC2.setBackground(Color.BLACK);
        souBtnC3.setBackground(Color.BLACK);
        souBtnIRS.setBackground(Color.BLACK);
        button. addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ping();
            }
        });
        // Create a Timer that executes every 5 seconds
        timer = new Timer(5000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ping();
            }
        });
        timer. start();
        try {
            URL imageUrl = GAView.class.getResource("/src/123.jpg");
            image = ImageIO. read(imageUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //Isometric JLabel
// JLabel ratioLabel = new JLabel();
// ratioLabel.setIcon(SwingUtil.createAutoAdjustIcon(image, true));
// ratioLabel.setBorder(new LineBorder(Color.RED));
// ratioLabel.setAlignmentX(0.5F);
// ratioLabel. setAlignmentY(0.5F);
        //Unequal ratio JLabel
        JLabel filledLabel = new JLabel();
        filledLabel.setIcon(SwingUtil.createAutoAdjustIcon(image, false));
        filledLabel.setBorder(new LineBorder(Color.ORANGE));


        //regular style JLabel
// JLabel normalLabel = new JLabel();
// normalLabel.setIcon(new ImageIcon(image));
// normalLabel.setBorder(new LineBorder(Color.BLUE));
        //JPanel content
// panel.add(ratioLabel);
        panel. add(filledLabel);
// panel.add(normalLabel);
        //JFrame content
        frame.getContentPane().add(panel);
        frame.setSize(1280,720);
        filledLabel. add(button);
        filledLabel.add(button1);
        filledLabel.add(souBtnT2);
        filledLabel.add(souBtnC1);
        filledLabel.add(souBtnC2);
        filledLabel.add(souBtnC3);
        filledLabel.add(souBtnIRS);
        //JFrame property
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame. setVisible(true);
    }
    private static void ping(){
        try {
            // Use the isReachable method of the InetAddress class to determine whether the IP address is connected
            InetAddress address = InetAddress.getByName("need a single ping ID");
            boolean reachable = address. isReachable(5000);
            // Set the button color according to the Ping result
            if (reachable) {
                button.setBackground(Color.GREEN);
                System.out.println(reachable);
            } else {
                button.setBackground(Color.RED);
                System.out.println(reachable);
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
    }


}



//
/**Swing tool class
 *
 * @author Run
 * @date 2023-05-24 */
class SwingUtil {

    /** Create an ImageIcon object that can adapt to the size of the component
     * @param image Create ImageIcon from <code>Image </code> object
     * @param constrained Whether to scale proportionally. When it is <code> true </code>, it can be passed
     * {@link javax.swing.JComponent#setAlignmentX(float)} and
     * The {@link javax.swing.JComponent#setAlignmentY(float)} method sets the alignment of the component.
     * @date 2023-05-24 */
    public static ImageIcon createAutoAdjustIcon(Image image, boolean constrained) {
        ImageIcon icon = new ImageIcon(image) {
            @Override
            public synchronized void paintIcon(java.awt.Component cmp, Graphics g, int x, int y) {
                //Initialization parameters
                Point startPoint = new Point(0, 0);//Default drawing starting point
                Dimension cmpSize = cmp.getSize();//Get component size
                Dimension imgSize = new Dimension(getIconWidth(), getIconHeight());//Get image size

                //Calculate the drawing starting point and area
                if(constrained) {//scale proportionally
                    //Calculate the aspect ratio of the image
                    double ratio = 1.0*imgSize.width/imgSize.height;
                    //Calculate the area size after proportional scaling
                    imgSize.width = (int) Math.min(cmpSize.width, ratio*cmpSize.height);
                    imgSize. height = (int) (imgSize. width/ratio);
// Calculate the starting point of drawing
                    startPoint.x = (int)
                            (cmp. getAlignmentX()*(cmpSize. width - imgSize. width));
                    startPoint.y = (int)
                            (cmp. getAlignmentY()*(cmpSize. height - imgSize. height));
                } else {//completely filled
                    imgSize = cmpSize;
                }

                / / Draw according to the starting point and the size of the area
                if(getImageObserver() == null) {
                    g. drawImage(getImage(), startPoint.x, startPoint.y,
                            imgSize. width, imgSize. height, cmp);
                } else {
                    g. drawImage(getImage(), startPoint.x, startPoint.y,
                            imgSize. width, imgSize. height, getImageObserver());
                }
            };
        };
        return icon;
    }

    /** Create an Icon object that can adapt to the size of the component
     * @param filename A string specifying the file name or path
     * @param constrained Whether to scale proportionally. When it is <code> true </code>, it can be passed
     * {@link javax.swing.JComponent#setAlignmentX(float)} and
     * The {@link javax.swing.JComponent#setAlignmentY(float)} method sets the alignment of the component.
     * @date 2023-05-24 */
    public static ImageIcon createAutoAdjustIcon(String filename, boolean constrained) {
        return createAutoAdjustIcon(new ImageIcon(filename).getImage(), constrained);
    }

    /** Create an ImageIcon object that can adapt to the size of the component
     * @param url Create ImageIcon from the specified <code> URL </code> object
     * @param constrained Whether to scale proportionally. When it is <code> true </code>, it can be passed
     * {@link javax.swing.JComponent#setAlignmentX(float)} and
     * The {@link javax.swing.JComponent#setAlignmentY(float)} method sets the alignment of the component.
     * @date 2023-05-24 */
    public static ImageIcon createAutoAdjustIcon(URL url, boolean constrained) {
        return createAutoAdjustIcon(new ImageIcon(url).getImage(), constrained);
    }

}

The operation effect is the same as the top picture, and there are still several AI camera IPs that need to be monitored by Ping; the method of batch pin has not been written yet, and there are some ideas at present, using for loop and list array to loop through, before controlling written on the stage;

There are 7 buttons in total, only one is implemented at present;

There are three adaptive layout methods for the background image, I used one of them, and hard-coded the window;

If you are interested, you can read the adaptive method written by this brother, which is very comprehensive;

As an operation and maintenance personnel, there are many tools for monitoring network and server monitoring status, such as Beita, zabbix, Pandora, etc.; this AI camera is used to identify cars. It is a project of the company in the first two years, but it has been dragging If the application cannot be implemented correctly, we are now required to independently develop a monitoring and AI recognition rate; let’s take it one step at a time. . . .

Java Swing: Scale the image proportionally or fill it completely, and adapt to the size of JLabel and other components The .getAutoAdjustedIcon(Image, boolean) method creates an ImageIcon object that can adapt to the size of the component. Then call the setIcon(Icon) method of JLabel or JButton to make the image adapt to the size of JLabel. import java.awt.Dimensi…https://blog.csdn.net/run068/article/details/99876609?spm=1001.2014.3001.5506