如何在禁用的滚动窗格中添加jtextfield,其中包含文本?

时间:2012-10-30 01:00:39

标签: jpanel jscrollpane jtextfield

我的大部分代码都在运行。我只需要创建一个非常小的配置对话框(输入一些文本作为这个应用程序的路径。(日志文件监视器)

它几乎就在那里,文本字段显示在jscrollpane上(效果很好)。但是我无法在textField中输入任何文本。我无法弄明白。

请帮忙。

package vlive;
/* 
    vTABLET - a Virtual Desktop Tablet.
    http://www.splashportal.net
    Copyright (C) 2012  Aubrey Bourke.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Contact: (Author) Aubrey Bourke - aubrey@splashportal.net
    */

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.RoundRectangle2D;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.*;
import javax.imageio.ImageIO;
import javax.swing.JWindow;
import java.awt.image.*;
import  sun.audio.*;    //import the sun.audio package
import  java.io.*;
import java.util.Timer;
import java.util.*;
import javax.swing.border.Border;
import javax.swing.text.DefaultCaret;
import javax.swing.text.Document;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;

class vLive extends JPanel implements MouseListener, MouseMotionListener{

    Point location;  
    MouseEvent pressed;
      File file;
      static vLive vlc;
        //static vTablet vlive;
    //vLiveConsole var's
    Shape shape;
    Dimension arcSize;
    BufferedImage splash, logo;
    JWindow vLiveConsoleWindow;
    Float transparency = 0.00f;
    Boolean isGreenLine=false;
    int line;
    Boolean isSplash = true;
        static Boolean isLiveLog = false;
        boolean isConfig;

        JTextField input;
        JTextPane textPane;
        HTMLEditorKit htmlEditorKit;
        BufferedReader daLog;
        String LogString;
        Document document;
        JScrollPane scrollPane;

        String osVersion;
        String status;

        //CONSTRUCTOR
    //@SuppressWarnings("restriction")
    public vLive(){

            Tray();



        //create the vTablet OSD
    Dimension arcSize = new Dimension(16, 16);
    shape = new RoundRectangle2D.Double(0d, 0d, 670, 199, arcSize.width, arcSize.height);
    vLiveConsoleWindow = new JWindow();

        setSize(650, 199);

    loadImages();
        roundTheFrame();


    //add this JPanel (LiveLog)
    vLiveConsoleWindow.add(this);

    vLiveConsoleWindow.addMouseListener(this);
    vLiveConsoleWindow.addMouseMotionListener(this);
    vLiveConsoleWindow.setSize(670, 199);
    //vLiveConsoleWindow.setLocation(10, 10);
    vLiveConsoleWindow.setLocationRelativeTo(null);

        vLiveConsoleWindow.setVisible(true);



      //start a chain call!
    fadein();
        //1. fadein -> jetstart -> greenbar

         try{
        //keep logo visible after greenbar disappears
        Thread.sleep(4000);
        isSplash=false;




        isLiveLog=true;
        repaint();

        String os_version = System.getProperty("os.name").toLowerCase();
        osVersion = os_version;
        System.out.println("[System: "+os_version.toUpperCase()+"]");

        if(os_version.startsWith("win")){
        file = new File("C:/Windows/WindowsUpdate.log");
        status=file.toString();
        }

        if(os_version.startsWith("linux")) {

                file = new File("/var/log/messages");
                status = file.toString();

                if(!file.exists())
                file = new File("/var/log/syslog");
                status = file.toString();
        }










        //start Log Monitor
        TimerTask task = new FileWatcher( new File(file.getAbsolutePath()) ) {
      protected void onChange( File file ) {
        // here we code the action on a change
        //System.out.println( "File "+ file.getName() +" have changed !" );
        isLiveLog=true;
        updateLog();
      }
    };
                java.util.Timer timer = new Timer();
    // repeat the check every second
    timer.schedule( task , new Date(), 1000 );




        //load the Log to use
        //daLog = new File("/var/log/syslog");


        //add a textpane to JWindow
        textPane = new JTextPane();

        textPane.addMouseListener(this);
        textPane.addMouseMotionListener(this);

        scrollPane = new JScrollPane(textPane, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        //DefaultCaret caret = (DefaultCaret)textPane.getCaret();
        //caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

        textPane.setEditable(false);
        textPane.setOpaque(false);
        scrollPane.setOpaque(false);
        scrollPane.getViewport().setOpaque(false);


            htmlEditorKit = new HTMLEditorKit();
            textPane.setEditorKit(htmlEditorKit);
            // add some styles to the html
            StyleSheet styleSheet = htmlEditorKit.getStyleSheet();
            styleSheet.addRule("body {font: italic bold 6px Sans;}");
            styleSheet.addRule("body {color:#585858;}");
            textPane.setContentType("text/html");

                        textPane.setSize(630, 165);
                        scrollPane.setSize(631, 165);

                         scrollPane.setVisible(true);
                        this.setLayout(null);
                        this.add(scrollPane);
                        this.scrollPane.setLocation(20, 15);
       //textPane.setLocation(0, 0);
                       revalidate();
        //textPane.setText("Hello there\n anybody see this text??\n");

                        updateLog();

        }catch(InterruptedException e){System.out.println(e);}



}
        public void roundTheFrame(){
        try{
    vLiveConsoleWindow.addComponentListener(new ComponentAdapter() {
        @SuppressWarnings("restriction")
        @Override
        public void componentResized(ComponentEvent e){
            com.sun.awt.AWTUtilities.setWindowShape(vLiveConsoleWindow, shape);


        }});
        } catch (SecurityException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            } catch (IllegalArgumentException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }
        }
        public synchronized void updateLog(){
                //print the log


            Runnable updateAComponent = new Runnable() {
                public void run() { 


        if(isLiveLog){
              isLiveLog=false;

            System.out.println("[Log Update Event]".toUpperCase());
        try {
        document = textPane.getDocument();

        /*
        StyleSheet styleSheet = htmlEditorKit.getStyleSheet();
        styleSheet.addRule("body {font: italic bold 6px Sans;}");
        styleSheet.addRule("body {color:#585858;}");
        textPane.setContentType("text/html");
        */

        daLog =  new BufferedReader(new FileReader(file));
            try{
                String line = null; //not declared within while loop
                LogString = new String();

                while (( line = daLog.readLine()) != null){




  document.insertString(document.getLength(),line+"\n",null);

                                    //LogString+=line+"\n";
                }
            }finally {
                daLog.close();}
        }catch(Exception e){System.out.println(e);}

        //System.out.println(LogString);

        textPane.select(textPane.getDocument().getLength(), textPane.getDocument().getLength());

       revalidate();


         //textPane.setLocation(0, 0);

            } }
            };
            SwingUtilities.invokeLater(updateAComponent);

        }
        public void loadImages(){
        try 
     {
         String filename = "/images/vLive-Console-Logo.png";
     InputStream is = vLive.class.getResourceAsStream(filename);
         logo = ImageIO.read(is);
     }catch (IOException e) 
                           {
                System.out.println("[Image load error]");
                                }
    try 
     {
     String filename = "/images/vLive-Console.png";
     InputStream is = vLive.class.getResourceAsStream(filename);
         splash = ImageIO.read(is);      
     }catch (IOException e) 
                           {
                    System.out.println("[Image load error]");
                               }
        }

    @SuppressWarnings("restriction")
    public void sfx(){
        try {
            InputStream in;
            //in = new FileInputStream("jetstart2.wav");
            in = vLive.class.getResourceAsStream("/sounds/jetstart2.wav");  

        // Create an AudioStream object from the input stream.
        @SuppressWarnings("restriction")
        AudioStream as = new AudioStream(in);         

        // Use the static class member "player" from class AudioPlayer to play
        // clip.
        AudioPlayer.player.start(as);            
    }catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    public void fadein(){
        //chain 1 -> fade in
            while (transparency<0.9999955f){
                transparency +=0.000005f;
                //System.out.println(transparency);
                repaint();
            }
            transparency=1.0f;
            repaint();

        //chain 2 -> jetstart2.wav
            sfx();

        //chain 3 -> green barrr    
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            greenline();
    }
    public void greenline(){
        //line=80;
        line=30;
        isGreenLine = true;
        while(line<380){
            line++;
            repaint();
            try{
            Thread.sleep(4);
            }catch(InterruptedException e){System.out.println(e);}}
        try{
            Thread.sleep(2050);
            }catch(InterruptedException e){System.out.println(e);}
        isGreenLine=false;
        repaint();
    }

    public void fadeout(){
        //fade out
        while (transparency>0.01){
            transparency -=0.000007f;
            System.out.println(transparency);
            repaint();
        }
    }

    public void paintComponent(Graphics g) {

        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D)g;
        // Enable antialiasing for text
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.drawImage(splash, 0, 0, null);

                if(isSplash){
        Composite comp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, transparency);
        g2d.setComposite(comp);
        g2d.drawImage(logo, null, 0, 1);    
        if(isGreenLine){
            g2d.setColor(Color.GREEN);
            //g2d.setColor(new Color(0x1e, 0x90, 0xff));

            g2d.setStroke(new BasicStroke(7));
            g2d.drawLine(30, 158, line, 158);
            g2d.setStroke(new BasicStroke(1));
            g2d.setColor(Color.BLACK);
            g2d.drawRect(26,154, line-22, 7);


            /*g2d.setStroke(new BasicStroke(7));
            g2d.drawLine(80, 125, line, 125);
            g2d.setStroke(new BasicStroke(1));
            g2d.setColor(Color.BLACK);
            g2d.drawRect(76,121, line-72, 7);*/
        }
        }
                if(isLiveLog){
                //System.out.println("isLiveLog - Empty Paint() block!");
                    Font tmp = new Font("Sans", Font.ITALIC+Font.BOLD, 10);    
                    g2d.setFont(tmp);
                    g2d.setColor(Color.GRAY.darker());
                    g2d.drawString("SYSTEM: "+osVersion.toUpperCase(), 30, 145);

                    g2d.drawString("LOGFILE: "+status.toUpperCase(), 30, 156);
                    g2d.drawString("INITIALIZING LIVE LOG-REPORTING...", 30, 167);
                }
                if(isConfig){

                    System.out.println("[Repaint...");


                }
    }

    public void mouseMoved(MouseEvent e) {

    }
    public void mouseDragged(MouseEvent e) {

         location = vLiveConsoleWindow.getLocation(location);  
         int x = location.x - pressed.getX() + e.getX();  
        int y = location.y - pressed.getY() + e.getY();  
        vLiveConsoleWindow.setLocation(x, y);

    }
    public void mouseClicked(MouseEvent e) {
         if(e.getButton()==3){
             System.out.println("[CONFIG]");
             isConfig=true;

             JPanel p2 = new JPanel();
             p2.setBackground(Color.GRAY);
             p2.setSize(300,20);

             input = new JTextField(40);
             input.setOpaque(false);
             input.setSize(300, 20);
             input.setForeground(Color.WHITE);


             input.setLocation(0, 0);
             p2.add(input);

             //Maybe add a POPUP instead!!!!             

             vLiveConsoleWindow.add(p2);
             p2.setLocation(40, 150);
             input.requestFocusInWindow();

             System.out.println(input.isEditable() + " " +input.isEnabled());
             input.setText("your path..");




             input.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {


                String tex = input.getText();
                System.out.println(tex);
        }
      });

         }

    }
    public void mouseEntered(MouseEvent e) {
    //search.requestFocus();
    }
    public void mouseExited(MouseEvent e) {
    //search.requestFocus(); 


    }
    public void mousePressed(MouseEvent e) {

        if(e.getButton()==1) 
        pressed = e; 
    }
    public void mouseReleased(MouseEvent e) {

    }

        public void Tray(){    
            System.out.println("[ACTIVATING TRAY ICON]");
            Image kimage=null;
            final TrayIcon trayIcon;

if (SystemTray.isSupported()) {
System.out.println("[SYSTEM TRAY SUPPORTED!]");
    try {
             String filename = "/images/vLive.png";
     InputStream is = vLive.class.getResourceAsStream(filename);
         kimage = ImageIO.read(is);      


    }catch (Exception e) {

            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    SystemTray tray = SystemTray.getSystemTray();
    //timage = Toolkit.getDefaultToolkit().getImage("res/CrossOfLife.png");

    MouseListener mouseListener = new MouseListener() {

        public void mouseClicked(MouseEvent e) {
            //System.out.println("Tray Icon - Mouse clicked!");                 
        }

        public void mouseEntered(MouseEvent e) {
            //System.out.println("Tray Icon - Mouse entered!");                 
        }

        public void mouseExited(MouseEvent e) {
            //System.out.println("Tray Icon - Mouse exited!");                 
        }

        public void mousePressed(MouseEvent e) {
            //System.out.println("Tray Icon - Mouse pressed!");                 
        }

        public void mouseReleased(MouseEvent e) {
            //System.out.println("Tray Icon - Mouse released!");                 
        }
    };

    ActionListener exitListener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("[Saving vTablet Screen Co-ordinates]".toUpperCase());

                      try{
                      FileWriter fw = new FileWriter("Config");
                      BufferedWriter bw = new BufferedWriter(fw);

                     int vx = vLiveConsoleWindow.getX();
                     int vy = vLiveConsoleWindow.getY();

                      bw.write(vx+"\n");
                      bw.write(vy+"\n");

                      bw.flush();
                      fw.close();

                      }catch(IOException eyecaptain){System.out.println("[Co-ordinate save error: "+eyecaptain+"]".toUpperCase());}


                      System.out.println("[Exiting...]".toUpperCase());
                      System.out.println("");
                      System.exit(0);
        }
    };

    ItemListener cbListener = new ItemListener() {
       public void itemStateChanged(ItemEvent e) { 
           Object source = e.getItemSelectable();
System.out.println(source);
           if (e.getItem().equals("vTablet-OSD"))
               System.out.println("Chek....");

    if (e.getStateChange() == ItemEvent.SELECTED){


        }

    if (e.getStateChange() == ItemEvent.DESELECTED){

        }

        }
    };


    PopupMenu popup = new PopupMenu();

    // Create a pop-up menu components
        MenuItem aboutItem = new MenuItem("About");
        CheckboxMenuItem cb1 = new CheckboxMenuItem("vTablet-OSD");
        cb1.setActionCommand("vTablet-OSD");
        cb1.addItemListener(cbListener);
        CheckboxMenuItem cb2 = new CheckboxMenuItem("VTab");
        CheckboxMenuItem cb3 = new CheckboxMenuItem("vTablet");
        Menu displayMenu = new Menu("Configuration");
        MenuItem errorItem = new MenuItem("Error");
        MenuItem warningItem = new MenuItem("Warning");
       MenuItem infoItem = new MenuItem("Info");
       MenuItem noneItem = new MenuItem("None");
        MenuItem exitItem = new MenuItem("Exit");

        //Add components to pop-up menu
        popup.add(aboutItem);
        popup.addSeparator();
        popup.add(cb1);
        popup.add(cb2);
        popup.add(cb3);
        popup.addSeparator();
        popup.add(displayMenu);
        displayMenu.add(errorItem);
        displayMenu.add(warningItem);
        displayMenu.add(infoItem);
        displayMenu.add(noneItem);
       // popup.add(exitItem);

    MenuItem defaultItem = new MenuItem("Exit");
    defaultItem.addActionListener(exitListener);
    popup.add(defaultItem);

    Font font3=new Font("Monospace", Font.ITALIC, 14);
    popup.setFont(font3);

    trayIcon = new TrayIcon(kimage, "vLive", popup);

    ActionListener actionListenerA = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            trayIcon.displayMessage("Action Event", 
                "An Unimplemented Action Event Has Been Performed!",
                TrayIcon.MessageType.INFO);
            if(e.getActionCommand().equals("vTablet-OSD"))
            {System.out.println("[OSD Toggle!]".toUpperCase());}


        }
    };

   trayIcon.setImageAutoSize(true);
    popup.addActionListener(actionListenerA);
    trayIcon.addMouseListener(mouseListener);

    try {

        System.out.println("Tray Disabled");

    } catch (Exception e) {
        System.err.println("[TrayIcon could not be added.]".toUpperCase());
    }

} else {
    System.out.println("[Tray not supported!]".toUpperCase());

}
        }
    public static void main(String[] args){
                System.out.println("======================================");
        System.out.println("vLive Log-Report Console".toUpperCase());
                System.out.println("[Created by Aubrey Bourke]");
                System.out.println("[WEB: http://www.splashportal.net]".toUpperCase());
        System.out.println("======================================");

        Thread t = new Thread( new Runnable(){
            public void run()
            {
                vlc = new vLive(); //vTablet OSD
            }
                 });
            t.start();      
        }
}

0 个答案:

没有答案