2012-05-27 3 views
1

Я использую API-интерфейс Native Swing для использования JWebBrowser.JWebBrowser (расширяет JPanel) Показывает выше стеклянную панель

public class GUI extends JPanel { 

    Robot robot; 
    JComponent glassPane; 

    public GUI(final Bot bot) { 
     super(new BorderLayout()); 
     try { 
      robot = new Robot(); 
     } catch (AWTException e) { 
      e.printStackTrace(); 
     } 
     JPanel webBrowserPanel = new JPanel(new BorderLayout()); 
     JWebBrowser webBrowser = new JWebBrowser(JWebBrowser.constrainVisibility()); 
     webBrowser.setBarsVisible(false); 
     webBrowser.setButtonBarVisible(false); 
     webBrowser.setMenuBarVisible(false); 
     webBrowser.navigate("http://google.com"); 
     webBrowserPanel.add(webBrowser, BorderLayout.CENTER); 
     add(webBrowserPanel, BorderLayout.CENTER); 

     JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 4, 4)); 
     final JButton button = new JButton("Start"); 
     button.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       if (bot.isRunning()) { 
        button.setText("Start"); 
       } else { 
        button.setText("Stop"); 
       } 
       bot.setRunning(!bot.isRunning()); 
      } 
     }); 
     buttonPanel.add(button, BorderLayout.WEST); 
     add(buttonPanel, BorderLayout.NORTH); 

     JFrame mainFrame = new JFrame("Bot"); 
     mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     mainFrame.getContentPane().add(this, BorderLayout.CENTER); 

     glassPane = new JComponent() 
     { 
      public void paintComponent(Graphics g) 
      { 
       g.setColor(new Color(1, 0, 0, 0.5f)); 
       g.fillRect(10, 10, 815, 775); 
      } 
     }; 
     glassPane.setSize(815,775); 
     glassPane.setOpaque(false); 
     mainFrame.setGlassPane(glassPane); 
     glassPane.setVisible(true); 


     mainFrame.setSize(815, 775); 
     mainFrame.setLocationRelativeTo(null); 
     mainFrame.setVisible(true); 
    } 
} 

Когда я запустил это, я ожидаю увидеть красный прямоугольник по всему графическому интерфейсу. Это не то, что происходит. Это то, что я вижу (извините, это не позволит мне отправлять прямые изображения): http://i.stack.imgur.com/ZAe51.png

Почему JWebBrowser появляется над стеклянным стеклом? Я думал, что Стеклянная панель должна быть ВСЕ.

JWebBrowser расширяет JPanel. Вот документация: Javadoc

Моей целью для этой стеклянной панели является возможность получить положение мыши, когда пользователь использует графический интерфейс пользователя. По какой-то причине позиция мыши возвращает нуль (даже если она находится над компонентом), используя webBrowser.getMousePosition() или webBrowserPanel.getMousePosition().

ответ

2

Почему JWebBrowser появляется над стеклянным стеклом? Я думал, что Стеклянная панель должна быть ВСЕ.

потому, что вы установили mainFrame.setGlassPane(glassPane);

Моя цель на этой стеклянной панели, чтобы иметь возможность получить позицию мыши, когда пользователь с помощью графического интерфейса. По какой-то причине позиция мыши возвращает нуль (даже если она находится над компонентом), используя webBrowser.getMousePosition() или webBrowserPanel.getMousePosition().

GlassPane по умолчанию потреблять MouseEvents, но вы можете переотправки те события

EDIT

, если я использую пример кода из codersource

import java.awt.Image; 
import java.awt.Toolkit; 
import java.util.Arrays; 

import javax.swing.ImageIcon; 
import javax.swing.JFrame; 
import javax.swing.SwingUtilities; 

import chrriis.common.UIUtils; 
import chrriis.dj.nativeswing.swtimpl.NativeInterface; 
import javax.swing.JRootPane; 

/** 
* @author Christopher Deckers 
*/ 
public class DemoFrame { 

    public static void main(String[] args) { 
     UIUtils.setPreferredLookAndFeel(); 
     NativeInterface.open(); 
     Toolkit.getDefaultToolkit().setDynamicLayout(true); 
     SwingUtilities.invokeLater(new Runnable() { 

      public void run() { 
       JFrame demoFrame = new JFrame("The DJ Project - NativeSwing (SWT)"); 
       Class<DemoFrame> clazz = DemoFrame.class; 
       if (System.getProperty("java.version").compareTo("1.6") >= 0) { 
        demoFrame.setIconImages(Arrays.asList(new Image[]{ 
           new ImageIcon(clazz.getResource("resource/DJIcon16x16.png")).getImage(), 
           new ImageIcon(clazz.getResource("resource/DJIcon24x24.png")).getImage(), 
           new ImageIcon(clazz.getResource("resource/DJIcon32x32.png")).getImage(), 
           new ImageIcon(clazz.getResource("resource/DJIcon48x48.png")).getImage(), 
           new ImageIcon(clazz.getResource("resource/DJIcon256x256.png")).getImage(),})); 
       } else { 
        demoFrame.setIconImage(new ImageIcon(clazz.getResource("resource/DJIcon32x32Plain.png")).getImage()); 
       } 
       demoFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       demoFrame.getContentPane().add(new DemoPane()); 
       demoFrame.setSize(800, 600); 
       demoFrame.setLocationByPlatform(true); 


       MyGlassPane glassPane = new MyGlassPane(); 
       JRootPane rootPane = SwingUtilities.getRootPane(demoFrame); 
       rootPane.setGlassPane(glassPane); 
       glassPane.activate(""); 


       demoFrame.setVisible(true); 
      } 
     }); 
     NativeInterface.runEventPump(); 
    } 
} 

с кодом по @camickr

import java.awt.*; 
import java.awt.event.*; 
import java.util.*; 
import javax.swing.*; 
import javax.swing.border.*; 

/* 
* Simple implementation of a Glass Pane that will capture and ignore all 
* events as well paint the glass pane to give the frame a "disabled" look. 
* 
* The background color of the glass pane should use a color with an 
* alpha value to create the disabled look. 
*/ 
public class MyGlassPane extends JComponent 
     implements KeyListener { 

    private final static Border MESSAGE_BORDER = new EmptyBorder(10, 10, 10, 10); 
    private JLabel message = new JLabel(); 

    public MyGlassPane() { 
     // Set glass pane properties 

     setOpaque(false); 
     Color base = UIManager.getColor("inactiveCaptionBorder"); 
     Color background = new Color(base.getRed(), base.getGreen(), base.getBlue(), 128); 
     setBackground(background); 
     setLayout(new GridBagLayout()); 

     // Add a message label to the glass pane 

     add(message, new GridBagConstraints()); 
     message.setOpaque(true); 
     message.setBorder(MESSAGE_BORDER); 

     // Disable Mouse, Key and Focus events for the glass pane 

     addMouseListener(new MouseAdapter() { 
     }); 
     addMouseMotionListener(new MouseMotionAdapter() { 
     }); 

     addKeyListener(this); 

     setFocusTraversalKeysEnabled(false); 
    } 

    /* 
    * The component is transparent but we want to paint the background 
    * to give it the disabled look. 
    */ 
    @Override 
    protected void paintComponent(Graphics g) { 
     g.setColor(getBackground()); 
     g.fillRect(0, 0, getSize().width, getSize().height); 
    } 

    /* 
    * The background color of the message label will be the same as the 
    * background of the glass pane without the alpha value 
    */ 
    @Override 
    public void setBackground(Color background) { 
     super.setBackground(background); 

     Color messageBackground = new Color(background.getRGB()); 
     message.setBackground(messageBackground); 
    } 
// 
// Implement the KeyListener to consume events 
// 

    public void keyPressed(KeyEvent e) { 
     e.consume(); 
    } 

    public void keyTyped(KeyEvent e) { 
    } 

    public void keyReleased(KeyEvent e) { 
     e.consume(); 
    } 

    /* 
    * Make the glass pane visible and change the cursor to the wait cursor 
    * 
    * A message can be displayed and it will be centered on the frame. 
    */ 
    public void activate(String text) { 
     if (text != null && text.length() > 0) { 
      message.setVisible(true); 
      message.setText(text); 
      message.setForeground(getForeground()); 
     } else { 
      message.setVisible(false); 
     } 

     setVisible(true); 
     setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); 
     requestFocusInWindow(); 
    } 

    /* 
    * Hide the glass pane and restore the cursor 
    */ 
    public void deactivate() { 
     setCursor(null); 
     setVisible(false); 
    } 
} 

тогда выход будет

enter image description here

чем я не могу согласился, что GlassPane является сильфонным любым из JComponent, ни JWebBrowser, история закончилась,

EDIT Correction, я не могу нашел альтернативу (правоальтернативная) для GlassPane для SWT, то вы правы JWebBrowser находится над AWT/Swing GlassPane

выход будет

enter image description here

+0

"потому что вы устанавливаете mainFrame.setGlassPane (glassPane);" не следует ли это ставить стеклянную панель над всем JFrame, то есть стеклянная панель будет над компонентами JFrame? –

+0

@Sam Pepose [вы тоже здесь видите] (http://stackoverflow.com/a/9734016/714968) – mKorbel

+0

Я не понимаю, что вы хотите, чтобы я видел там. –

1

JWebBrowser - тяжеловесный компонент. DJ Native Swing упрощает эту интеграцию в Swing, применяя все виды правил отсечения, но не может выполнять альфа-смешивание.

Ближе всего вы можете достичь того, что продемонстрирует демонстрационное приложение в разделе «Дополнительные функции» Pseudo Transparency ».К сожалению, похоже, что в Windows 7 есть эффект мигания для каждого обновления, но это может не быть проблемой в вашем случае, если вы не часто обновляете.

+0

В демо-версии он использует JLabel. Можно ли использовать JPanel размер прозрачного браузера? Моя главная цель из всего этого состоит в том, чтобы иметь возможность вывести положение мыши над JWebBrowser из другого потока, а также имитировать MouseEvents в JWebBroswer из этого другого потока. –

+0

@Sam Pepose вы можете поместить boolean isAble во все MouseXxxEvent, если isAble будет устанавливать false, тогда вы можете просто «MouseXxxEvent.consume()», – mKorbel

+0

@ Кристофер Декирс, в чем причина создания супертяжелого компонента ??? – mKorbel

Смежные вопросы