0

シンプルなswingアプリケーションでは、TrayIconを使用しています

trayMenu = new PopupMenu();
MenuItem closeMenuItem = new MenuItem("Exit");
closeMenuItem.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        closeApp();
    }
});
trayMenu.add(closeMenuItem);
trayIcon = new TrayIcon(ImageIO.read(Window.class.getResource("/res/chat.png")), "Msg", trayMenu);
trayIcon.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent e) {
        if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 1) {
            setState(JFrame.NORMAL);
            setVisible(true);
            toFront();
        }
    }
});
if (SystemTray.isSupported()) {
    SystemTray.getSystemTray().add(trayIcon);
}

コードは普通で、トレイを作成し、アイコンを設定し、イベントを追加します。ただし、アプリケーションがシステム トレイで実行されている場合、CPU 使用率は最大 50% です。システム トレイ コードが使用されていない場合、CPU 使用率は問題ありません。この問題を解決するには?

編集:コードは次のとおりです。完全なソースではありませんが、主な2つのJavaファイルは次のとおりです。

package ui;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTabbedPane;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import msg.HighlightInterface;

/**
 *
 * @author user
 */
public class Window extends JFrame implements HighlightInterface {

    private HashMap<Integer, ChatPanel> tabMap;
    private About aboutDialog;
    private Window thisWindow;
    private TrayIcon trayIcon;
    private PopupMenu trayMenu;

    @Override
    public void messageReceived(String text) {
        if (trayIcon != null && !isFocused()) {
            trayIcon.displayMessage("Msg", text, TrayIcon.MessageType.INFO);
        }
    }

    private class ServerDaemon extends Thread {

        private ServerSocket serverSocket;

        @Override
        public void run() {
            try {
                serverSocket = new ServerSocket(7777);
                System.out.println("Listening for connections : ");
                while (true) {
                    Socket client;
                    while ((client = serverSocket.accept()) != null) {
                        ChatPanel chatPanel = new ChatPanel(client);
                        chatPanel.addHighlightListener(thisWindow);
                        tabPane.add(client.getInetAddress().toString(), chatPanel);
                        System.out.println(client.getRemoteSocketAddress() + " -> connected.");
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                Dialogs.showErrorDialog("This application is already running or error while initialization.");
                System.exit(-1);
            }
        }
    }
    private NewDialog newDialog;

    /**
     * Creates new form Window
     */
    public Window() {
        thisWindow = this;
        initComponents();
        setComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tabPane = new JTabbedPane();
        menuBar = new JMenuBar();
        fileMenu = new JMenu();
        newMenuItem = new JMenuItem();
        closeMenuItem = new JMenuItem();
        exitMenuItem = new JMenuItem();
        helpMenu = new JMenu();
        aboutMenuItem = new JMenuItem();

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        getContentPane().add(tabPane, BorderLayout.CENTER);

        fileMenu.setText("Msg");

        newMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK));
        newMenuItem.setText("New");
        newMenuItem.setToolTipText("New chat.");
        newMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                newMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(newMenuItem);

        closeMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_MASK));
        closeMenuItem.setText("Close");
        closeMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                closeMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(closeMenuItem);

        exitMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, InputEvent.ALT_MASK));
        exitMenuItem.setText("Exit");
        exitMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText("Help");

        aboutMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
        aboutMenuItem.setText("About");
        aboutMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                aboutMenuItemActionPerformed(evt);
            }
        });
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        setJMenuBar(menuBar);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void newMenuItemActionPerformed(ActionEvent evt) {//GEN-FIRST:event_newMenuItemActionPerformed
        showNewDialog();
    }//GEN-LAST:event_newMenuItemActionPerformed

    private void closeMenuItemActionPerformed(ActionEvent evt) {//GEN-FIRST:event_closeMenuItemActionPerformed
        closeWindow();
    }//GEN-LAST:event_closeMenuItemActionPerformed

    private void exitMenuItemActionPerformed(ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
        closeApp();
    }//GEN-LAST:event_exitMenuItemActionPerformed

    private void aboutMenuItemActionPerformed(ActionEvent evt) {//GEN-FIRST:event_aboutMenuItemActionPerformed
        showAbout();
    }//GEN-LAST:event_aboutMenuItemActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            final Window window = new Window();
            window.new ServerDaemon().start();
            java.awt.EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    window.setVisible(true);
                }
            });
        } catch (Exception ex) {
            ex.printStackTrace();
            Dialogs.showErrorDialog(ex.getMessage());
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private JMenuItem aboutMenuItem;
    private JMenuItem closeMenuItem;
    private JMenuItem exitMenuItem;
    private JMenu fileMenu;
    private JMenu helpMenu;
    private JMenuBar menuBar;
    private JMenuItem newMenuItem;
    private JTabbedPane tabPane;
    // End of variables declaration//GEN-END:variables

    private void setComponents() {
        try {
            trayMenu = new PopupMenu();
            MenuItem closeMenuItem = new MenuItem("Exit");
            closeMenuItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    closeApp();
                }
            });
            trayMenu.add(closeMenuItem);
            trayIcon = new TrayIcon(ImageIO.read(Window.class.getResource("/res/chat.png")), "Msg", trayMenu);
            trayIcon.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 1) {
                        setState(JFrame.NORMAL);
                        setVisible(true);
                        toFront();
                    }
                }
            });
            if (SystemTray.isSupported()) {
                SystemTray.getSystemTray().add(trayIcon);
            }

            newDialog = new NewDialog(this);
            aboutDialog = new About(this);
            tabMap = new HashMap<Integer, ChatPanel>();

            addWindowListener(new WindowAdapter() {

                @Override
                public void windowIconified(WindowEvent e) {
                    setVisible(false);
                }

            });
            setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
            setTitle("Msg");
            setSize(400, 380);
            setLocationRelativeTo(null);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void showNewDialog() {
        newDialog.setVisible(true);
    }

    public void connectToClient(String ip, String name) {
        if (name.length() == 0) {
            name = System.getProperty("user.name");
        }
        try {
            Socket socket = new Socket(ip, 7777);
            ChatPanel chatPanel = new ChatPanel(socket);
            tabPane.add(ip, chatPanel);
            tabMap.put(tabPane.indexOfComponent(chatPanel), chatPanel);
        } catch (Exception ex) {
            ex.printStackTrace();
            Dialogs.showErrorDialog("Connection not established !, May be this application "
                    + "is not running in other system or it may be a network error !");
        }
    }

    private void closeWindow() {
        if (tabPane.getTabCount() > 0) {
            Component component = tabPane.getSelectedComponent();
            if (component instanceof ChatPanel) {
                ((ChatPanel) component).closeConnection();
                tabPane.remove(tabPane.getSelectedIndex());
            }
        }
    }

    private void showAbout() {
        aboutDialog.setVisible(true);
    }

    private void closeApp() {
        System.exit(0);
    }
}

ChatPanel.java

package ui;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import javax.swing.GroupLayout;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.LayoutStyle;
import msg.HighlightInterface;

/**
 *
 * @author user
 */
public class ChatPanel extends JPanel {

    private static ArrayList<HighlightInterface> highlightListeners;

    static{
        highlightListeners=new ArrayList<HighlightInterface>();
    }

    public static void addHighlightListener(HighlightInterface h){
        highlightListeners.add(h);
    }

    private class EnterListener extends KeyAdapter {

        @Override
        public void keyReleased(KeyEvent e) {
            if (e.getKeyChar() == KeyEvent.VK_ENTER && msg.getText().length() > 0) {
                sendMsg(msg.getText());
                inbox.setText(inbox.getText() + "me : " + msg.getText());
                msg.setText("");
            }
        }
    }
    private Socket socket;
    private DataInputStream in;
    private DataOutputStream out;
    private boolean showError = true;

    /**
     * Creates new form ChatPanel
     */
    public ChatPanel(Socket socket) {
        this.socket = socket;
        initComponents();
        setComponents();
    }

    private void setComponents() {
        try {
            if (socket != null) {
                in = new DataInputStream(socket.getInputStream());
                out = new DataOutputStream(socket.getOutputStream());
                new Thread() {
                    @Override
                    public void run() {
                        try {
                            String text = null;
                            while (true) {
                                while (in.available() > 0) {
                                    text = in.readUTF();
                                    if (text != null) {
                                        text = socket.getInetAddress().toString() + " : " + text;
                                        inbox.setText(inbox.getText() + text);
                                        informToAll(text);
                                    }
                                }
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            if (showError) {
                                Dialogs.showErrorDialog(ex.getMessage());
                            }
                        }
                    }
                }.start();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            Dialogs.showErrorDialog(ex.getMessage());
        }
        inbox.setEditable(false);
        msg.addKeyListener(new EnterListener());
        msg.requestFocus();
    }

    private void sendMsg(String text) {
        try {
            if (out != null) {
                out.writeUTF(text);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            Dialogs.showErrorDialog("I can't send your message :(");
        }
    }

    public void closeConnection() {
        try {
            if (socket != null) {
                showError = false;
                in.close();
                out.close();
                socket.close();
                System.out.println("connection closed!");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            Dialogs.showErrorDialog(ex.getMessage());
        }
    }

    private void informToAll(String text){
        if(highlightListeners!=null){
            for(HighlightInterface h :highlightListeners)
                h.messageReceived(text);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new JScrollPane();
        inbox = new ChatPane();
        jScrollPane2 = new JScrollPane();
        msg = new ChatPane();

        jScrollPane1.setViewportView(inbox);

        jScrollPane2.setViewportView(msg);

        GroupLayout layout = new GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE)
                    .addComponent(jScrollPane2))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 191, GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, GroupLayout.DEFAULT_SIZE, 52, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    public ChatPane inbox;
    private JScrollPane jScrollPane1;
    private JScrollPane jScrollPane2;
    public ChatPane msg;
    // End of variables declaration//GEN-END:variables
}

これらは主な 2 つのファイルです。

4

0 に答える 0