2012-04-12 9 views
20

Me gustaría obtener el tamaño de pantalla efectivo. Es decir: el tamaño de la pantalla sin la barra de tareas (o su equivalente en Linux/Mac).Obtenga un tamaño de pantalla efectivo de Java

Actualmente estoy usando ...

component.getGraphicsConfiguration().getBounds() 

... y restando el tamaño de la barra de tareas de forma predeterminada en función del sistema operativo, pero me gustaría una manera que incluso si el usuario ha cambiado el tamaño/movido la barra de tareas .

Respuesta

37

Esto podría determinar el tamaño de la pantalla en píxeles sin la barra de tareas

//size of the screen 
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 

//height of the task bar 
Insets scnMax = Toolkit.getDefaultToolkit().getScreenInsets(getGraphicsConfiguration()); 
int taskBarSize = scnMax.bottom; 

//available size of the screen 
setLocation(screenSize.width - getWidth(), screenSize.height - taskBarSize - getHeight()); 

EDITAR

Por favor alguien puede ejecutar este código en Xx_nix y Mac OS X y comprobar si JDialog es realmente coloca en la esquina inferior derecha ?

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 
import javax.swing.UIManager.LookAndFeelInfo; 

public class NotificationPopup { 

    private static final long serialVersionUID = 1L; 
    private LinearGradientPaint lpg; 
    private JDialog dialog = new JDialog(); 
    private BackgroundPanel panel = new BackgroundPanel(); 

    public NotificationPopup() { 
     Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 
     Insets scnMax = Toolkit.getDefaultToolkit(). 
       getScreenInsets(dialog.getGraphicsConfiguration()); 
     int taskBarSize = scnMax.bottom; 
     panel.setLayout(new GridBagLayout()); 
     GridBagConstraints constraints = new GridBagConstraints(); 
     constraints.gridx = 0; 
     constraints.gridy = 0; 
     constraints.weightx = 1.0f; 
     constraints.weighty = 1.0f; 
     constraints.insets = new Insets(5, 5, 5, 5); 
     constraints.fill = GridBagConstraints.BOTH; 
     JLabel l = new JLabel("You have got 2 new Messages."); 
     panel.add(l, constraints); 
     constraints.gridx++; 
     constraints.weightx = 0f; 
     constraints.weighty = 0f; 
     constraints.fill = GridBagConstraints.NONE; 
     constraints.anchor = GridBagConstraints.NORTH; 
     JButton b = new JButton(new AbstractAction("x") { 

      private static final long serialVersionUID = 1L; 

      @Override 
      public void actionPerformed(final ActionEvent e) { 
       dialog.dispose(); 
      } 
     }); 
     b.setOpaque(false); 
     b.setMargin(new Insets(1, 4, 1, 4)); 
     b.setFocusable(false); 
     panel.add(b, constraints); 
     dialog.setUndecorated(true); 
     dialog.setSize(300, 100); 
     dialog.setLocation(screenSize.width - dialog.getWidth(), 
       screenSize.height - taskBarSize - dialog.getHeight()); 
     lpg = new LinearGradientPaint(0, 0, 0, dialog.getHeight()/2, 
       new float[]{0f, 0.3f, 1f}, new Color[]{new Color(0.8f, 0.8f, 1f), 
        new Color(0.7f, 0.7f, 1f), new Color(0.6f, 0.6f, 1f)}); 
     dialog.setContentPane(panel); 
     dialog.setVisible(true); 
    } 

    private class BackgroundPanel extends JPanel { 

     private static final long serialVersionUID = 1L; 

     BackgroundPanel() { 
      setOpaque(true); 
     } 

     @Override 
     protected void paintComponent(final Graphics g) { 
      final Graphics2D g2d = (Graphics2D) g; 
      g2d.setPaint(lpg); 
      g2d.fillRect(1, 1, getWidth() - 2, getHeight() - 2); 
      g2d.setColor(Color.BLACK); 
      g2d.drawRect(0, 0, getWidth() - 1, getHeight() - 1); 
     } 
    } 

    public static void main(final String[] args) { 
     try { 
      for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { 
       System.out.println(info.getName()); 
       if ("Nimbus".equals(info.getName())) { 
        UIManager.setLookAndFeel(info.getClassName()); 
        break; 
       } 
      } 
     } catch (UnsupportedLookAndFeelException e) { 
     } catch (ClassNotFoundException e) { 
     } catch (InstantiationException e) { 
     } catch (IllegalAccessException e) { 
     } 
     SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 

       NotificationPopup notificationPopup = new NotificationPopup(); 
      } 
     }); 
    } 
} 
+0

Luce bien en Ubuntu/OpenJDK. –

+1

Probablemente se puede arreglar, pero parece que esto no funcionará en una configuración de pantallas múltiples. –

+0

hay dos niveles, ¿significan? '1)' un contenedor llena dos o más multi_monitors (no probados en Java7, pero Java6 no es compatible), o '2)' un contenedor colocado en uno de los multi_monitors (respondidos por alain.janinm), – mKorbel

51

GraphicsEnvironment tiene un método que devuelve el tamaño máximo disponible, lo que representa todas las barras de tareas, etc. sin importar dónde se encuentren alineados:

GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds() 

Nota: En los sistemas multi-monitor getMaximumWindowBounds(), devuelve los límites de toda el área de visualización. Para obtener los límites utilizables de una sola pantalla, use GraphicsConfiguration.getBounds() y Toolkit.getScreenInsets() como se muestra en otras respuestas.

+2

En mi caso, devuelve la altura total. (cuando la barra de tareas es transparente y las ventanas pueden ir más abajo) – Lukino

10

Este es el código que terminé usando:

GraphicsConfiguration gc = // ... 

Rectangle bounds = gc.getBounds(); 

Insets screenInsets = Toolkit.getDefaultToolkit().getScreenInsets(gc); 

Rectangle effectiveScreenArea = new Rectangle(); 

effectiveScreenArea.x = bounds.x + screenInsets.left; 
effectiveScreenArea.y = bounds.y + screenInsets.top; 
effectiveScreenArea.height = bounds.height - screenInsets.top - screenInsets.bottom;   
effectiveScreenArea.width = bounds.width - screenInsets.left - screenInsets.right; 
+1

@mKorbel: Lo he probado en Ubuntu, OS X y Windows 7. Se probará en varias plataformas más una vez que la aplicación se mueva a prueba (y estaré seguro de que aquí, si encontramos problemas en cualquier lugar). –

2

Aquí es un método que escribí que ver con rapidez los cálculos restando los márgenes y centrado en la pantalla.

public void setToEffectiveScreenSize() { 
    double width, height, x, y; 

    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 
    Insets bounds = Toolkit.getDefaultToolkit().getScreenInsets(frmMain.getGraphicsConfiguration()); 

    // Calculate the height/length by subtracting the margins 
    // (x,y) = ((screenHeight-windowHeight)/2, (screenWidth - windowWidth)/2) 

    width = screenSize.getWidth() - bounds.left - bounds.right; 
    height = screenSize.getHeight() - bounds.top - bounds.bottom; 

    // Now center the new rectangle inside the screen 
    x = (screenSize.getHeight() - height)/2.0; 
    y = (screenSize.getWidth() - width)/2.0; 

    frmMain.setBounds((int)x,(int)y,(int)width,(int)height); 
} 
Cuestiones relacionadas