/** * Create possibly volatile scratch image for fast painting. A scratch image can become * invalidated, when this happens any actions involving it are ignored, and it needs to be * recreated. Use isScratchImageValid() to check this. */ public static Image createScratchImage(int width, int height) { try { Image img = (Image) tryMethod( output_comp, "createVolatileImage", new Object[] {new Integer(width), new Integer(height)}); if (img == null) { // no such method -> create regular image return output_comp.createImage(width, height); } // if (img.validate(output_comp.getGraphicsConfiguration()) // == VolatileImage.IMAGE_INCOMPATIBLE) { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice gs = ge.getDefaultScreenDevice(); GraphicsConfiguration gc = gs.getDefaultConfiguration(); Integer valid = (Integer) tryMethod(img, "validate", new Object[] {gc}); // output_comp.getGraphicsConfiguration() }); if (valid.intValue() == 2) { // I checked, IMAGE_INCOMPATIBLE=2 // Hmm, somehow it didn't work. Create regular image. return output_comp.createImage(width, height); } return img; } catch (java.security.AccessControlException e) { // we're not allowed to do this (we're probably an applet) return output_comp.createImage(width, height); } }
public void paint(Graphics g) { if (comp != null) { width = comp.getWidth() / 6; height = comp.getHeight() * 2 / 3; } g.setColor(bgColor); g.fillRect(x, y, width, height); g.setColor(fgColor); g.setFont(font); g.drawString(strTray, x / 2 + width / 2, y + height + 10); super.paint(g); }
/** * Load image from resource path (using getResource). Note that GIFs are loaded as _translucent_ * indexed images. Images are cached: loading an image with the same name twice will get the * cached image the second time. If you want to remove an image from the cache, use purgeImage. * Throws JGError when there was an error. */ @SuppressWarnings({"deprecation", "unchecked"}) public JGImage loadImage(String imgfile) { Image img = (Image) loadedimages.get(imgfile); if (img == null) { URL imgurl = getClass().getResource(imgfile); if (imgurl == null) { try { File imgf = new File(imgfile); if (imgf.canRead()) { imgurl = imgf.toURL(); } else { imgurl = new URL(imgfile); // throw new JGameError( // "File "+imgfile+" not found.",true); } } catch (MalformedURLException e) { // e.printStackTrace(); throw new JGameError("File not found or malformed path or URL '" + imgfile + "'.", true); } } img = output_comp.getToolkit().createImage(imgurl); loadedimages.put(imgfile, img); } try { ensureLoaded(img); } catch (Exception e) { // e.printStackTrace(); throw new JGameError("Error loading image " + imgfile); } return new JREImage(img); }
public JGImage crop(int x, int y, int width, int height) { @SuppressWarnings("unused") JGPoint size = getSize(); int[] buffer = getPixels(x, y, width, height); return new JREImage( output_comp.createImage(new MemoryImageSource(width, height, buffer, 0, width))); }
public JGImage flip(boolean horiz, boolean vert) { @SuppressWarnings("unused") Image flipped = null; JGPoint size = getSize(); int[] buffer = getPixels(); int[] flipbuf = new int[size.x * size.y]; if (vert && !horiz) { for (int y = 0; y < size.y; y++) { for (int x = 0; x < size.x; x++) { flipbuf[(size.y - y - 1) * size.x + x] = buffer[(y * size.x) + x]; } } } else if (horiz && !vert) { for (int y = 0; y < size.y; y++) { for (int x = 0; x < size.x; x++) { flipbuf[y * size.x + (size.x - x - 1)] = buffer[(y * size.x) + x]; } } } else if (horiz && vert) { for (int y = 0; y < size.y; y++) { for (int x = 0; x < size.x; x++) { flipbuf[(size.y - y - 1) * size.x + (size.x - x - 1)] = buffer[(y * size.x) + x]; } } } return new JREImage( output_comp.createImage(new MemoryImageSource(size.x, size.y, flipbuf, 0, size.x))); }
/** for angle, only increments of 90 are allowed */ public JGImage rotate(int angle) { @SuppressWarnings("unused") Image rot = null; JGPoint size = getSize(); int[] buffer = getPixels(); int[] rotate = new int[size.x * size.y]; int angletype = (angle / 90) & 3; if (angletype == 0) return this; if (angletype == 1) { /* 1 2 3 4 9 5 1 * 5 6 7 8 => a 6 2 * 9 a b c b 7 3 * c 8 4 */ for (int y = 0; y < size.y; y++) { for (int x = 0; x < size.x; x++) { rotate[x * size.y + (size.y - 1 - y)] = buffer[(y * size.x) + x]; } } return new JREImage( output_comp.createImage(new MemoryImageSource(size.y, size.x, rotate, 0, size.y))); } if (angletype == 3) { /* 1 2 3 4 4 8 c * 5 6 7 8 => 3 7 b * 9 a b c 2 6 a * 1 5 9 */ for (int y = 0; y < size.y; y++) { for (int x = 0; x < size.x; x++) { rotate[(size.x - x - 1) * size.y + y] = buffer[(y * size.x) + x]; } } return new JREImage( output_comp.createImage(new MemoryImageSource(size.y, size.x, rotate, 0, size.y))); } if (angletype == 2) { /* 1 2 3 4 c b a 9 * 5 6 7 8 => 8 7 6 5 * 9 a b c 4 3 2 1 */ for (int y = 0; y < size.y; y++) { for (int x = 0; x < size.x; x++) { rotate[((size.y - y - 1) * size.x) + (size.x - x - 1)] = buffer[(y * size.x) + x]; } } } return new JREImage( output_comp.createImage(new MemoryImageSource(size.x, size.y, rotate, 0, size.x))); }
// These is some wierd problem such that sometimes, the vnmrj command // area gets the focus and these items in the login box do not get // the focus. Even clicking in these items does not bring focus to // them. Issuing requestFocus() does not bring focus to them. // I can however, determing if either the operator entry box or // the password box has focus and if neither does, I can unshow and // reshow the panel and that fixes the focus. So, I have added this // to the mouseClicked action. If neither has focus, it will // take focus with setVisible false then true. public void mouseClicked(MouseEvent e) { boolean pfocus = m_passwordField.hasFocus(); boolean ofocus = comboTextField.hasFocus(); if (!pfocus && !ofocus) { setVisible(false); setVisible(true); } }
/** * Turn a (possibly) translucent or indexed image into a display-compatible bitmask image using * the given alpha threshold and render-to-background colour, or display-compatible translucent * image. The alpha values in the image are set to either 0 (below threshold) or 255 (above * threshold). The render-to-background colour bg_col is used to determine how the pixels * overlapping transparent pixels should be rendered. The fast algorithm just sets the colour * behind the transparent pixels in the image (for bitmask source images); the slow algorithm * actually renders the image to a background of bg_col (for translucent sources). * * @param thresh alpha threshold between 0 and 255 * @param fast use fast algorithm (only set bg_col behind transp. pixels) * @param bitmask true=use bitmask, false=use translucent */ public JGImage toDisplayCompatible(int thresh, JGColor bg_col, boolean fast, boolean bitmask) { Color bgcol = new Color(bg_col.r, bg_col.g, bg_col.b); int bgcol_rgb = (bgcol.getRed() << 16) | (bgcol.getGreen() << 8) | bgcol.getBlue(); JGPoint size = getSize(); int[] buffer = getPixels(); // render image to bg depending on bgcol BufferedImage img_bg; if (bitmask) { img_bg = createCompatibleImage(size.x, size.y, Transparency.BITMASK); } else { img_bg = createCompatibleImage(size.x, size.y, Transparency.TRANSLUCENT); } int[] bg_buf; if (!fast) { Graphics g = img_bg.getGraphics(); g.setColor(bgcol); // the docs say I could use bgcol in the drawImage as an // equivalent to the following two lines, but this // doesn't handle translucency properly and is _slower_ g.fillRect(0, 0, size.x, size.y); g.drawImage(img, 0, 0, null); bg_buf = new JREImage(img_bg).getPixels(); } else { bg_buf = buffer; } // g.dispose(); // ColorModel rgb_bitmask = ColorModel.getRGBdefault(); // rgb_bitmask = new PackedColorModel( // rgb_bitmask.getColorSpace(),25,0xff0000,0x00ff00,0x0000ff, // 0x1000000, false, Transparency.BITMASK, DataBuffer.TYPE_INT); // ColorSpace space, int bits, int rmask, int gmask, int bmask, int amask, boolean // isAlphaPremultiplied, int trans, int transferType) int[] thrsbuf = new int[size.x * size.y]; for (int y = 0; y < size.y; y++) { for (int x = 0; x < size.x; x++) { if (((buffer[y * size.x + x] >> 24) & 0xff) >= thresh) { thrsbuf[y * size.x + x] = bg_buf[y * size.x + x] | (0xff << 24); } else { // explicitly set the colour of the transparent pixel. // This makes a difference when scaling! // thrsbuf[y*size.x+x]=bg_buf[y*size.x+x]&~(0xff<<24); thrsbuf[y * size.x + x] = bgcol_rgb; } } } return new JREImage( output_comp.createImage( new MemoryImageSource( size.x, size.y, // rgb_bitmask, img_bg.getColorModel(), // display compatible bitmask bitmask ? thrsbuf : bg_buf, 0, size.x))); }
/* Constructor */ public MovingObject( int radius, int x, int y, double vx, double vy, double mass, double k, Planet planet, Color color, AudioClip collision, Component parent, int panelHeight) { this.radius = radius; pos_x = x; pos_y = y; x_speed = vx; y_speed = vy; ballMass = mass; this.k = k; // arbitrary constant used for gravity this.planet = planet; this.parent = parent; this.panelHeight = panelHeight; x_leftout = radius; x_rightout = parent.getSize().width - radius; y_upout = radius + panelHeight; y_downout = parent.getSize().height - radius; this.color = color; img = ((Applet) parent).getImage(((Applet) parent).getCodeBase(), "earth.gif"); this.collision = collision; }
/** Behaves like loadImage(String). Returns null if there was an error. */ @SuppressWarnings("unchecked") public static JGImage loadImage(URL imgurl) { Image img = (Image) loadedimages.get(imgurl); if (img == null) { img = output_comp.getToolkit().createImage(imgurl); loadedimages.put(imgurl, img); } try { ensureLoaded(img); } catch (Exception e) { System.err.println("Error loading image " + imgurl); return null; } return new JREImage(img); }
@Override public void paintIcon(Component c, Graphics g, int x, int y) { Graphics2D g2 = (Graphics2D) g.create(); g2.setPaint(Objects.nonNull(c) ? c.getBackground() : Color.WHITE); g2.fillRect(x, y, getIconWidth(), getIconHeight()); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(ELLIPSE_COLOR); g2.translate(x, y); int size = list.size(); for (int i = 0; i < size; i++) { float alpha = isRunning ? (i + 1) / (float) size : .5f; g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha)); g2.fill(list.get(i)); } // g2.translate(-x, -y); g2.dispose(); }
/** * Create a UPnP candidate. * * @param socket local socket * @param externalIP external IP address * @param port local port * @param component parent component * @param device the UPnP gateway device * @return a new <tt>UPNPCandidate</tt> instance which represents the specified * <tt>TransportAddress</tt> * @throws Exception if something goes wrong during candidate creation */ private List<LocalCandidate> createUPNPCandidate( IceSocketWrapper socket, String externalIP, int port, Component component, GatewayDevice device) throws Exception { List<LocalCandidate> ret = new ArrayList<>(); TransportAddress addr = new TransportAddress(externalIP, port, Transport.UDP); HostCandidate base = new HostCandidate(socket, component); UPNPCandidate candidate = new UPNPCandidate(addr, base, component, device); IceSocketWrapper stunSocket = candidate.getStunSocket(null); candidate.getStunStack().addSocket(stunSocket); component.getComponentSocket().add(candidate.getCandidateIceSocketWrapper()); ret.add(candidate); ret.add(base); return ret; }
public synchronized void paintIcon(Component c, Graphics g, int x, int y) { g.setColor(Color.white); g.fillRect(0, 0, c.getWidth(), c.getHeight()); if (getImageObserver() == null) { g.drawImage( getImage(), c.getWidth() / 2 - getIconWidth() / 2, c.getHeight() / 2 - getIconHeight() / 2, c); } else { g.drawImage( getImage(), c.getWidth() / 2 - getIconWidth() / 2, c.getHeight() / 2 - getIconHeight() / 2, getImageObserver()); } }
/** * Gathers UPnP candidates for all host <tt>Candidate</tt>s that are already present in the * specified <tt>component</tt>. This method relies on the specified <tt>component</tt> to already * contain all its host candidates so that it would resolve them. * * @param component the {@link Component} that we'd like to gather candidate UPnP * <tt>Candidate</tt>s for * @return the <tt>LocalCandidate</tt>s gathered by this <tt>CandidateHarvester</tt> */ public synchronized Collection<LocalCandidate> harvest(Component component) { Collection<LocalCandidate> candidates = new HashSet<>(); int retries = 0; logger.fine("Begin UPnP harvesting"); try { if (device == null) { // do it only once if (finishThreads == 0) { try { UPNPThread wanIPThread = new UPNPThread(stIP); UPNPThread wanPPPThread = new UPNPThread(stPPP); wanIPThread.start(); wanPPPThread.start(); synchronized (rootSync) { while (finishThreads != 2) { rootSync.wait(); } } if (wanIPThread.getDevice() != null) { device = wanIPThread.getDevice(); } else if (wanPPPThread.getDevice() != null) { device = wanPPPThread.getDevice(); } } catch (Throwable e) { logger.info("UPnP discovery failed: " + e); } } if (device == null) return candidates; } InetAddress localAddress = device.getLocalAddress(); String externalIPAddress = device.getExternalIPAddress(); PortMappingEntry portMapping = new PortMappingEntry(); IceSocketWrapper socket = new IceUdpSocketWrapper(new MultiplexingDatagramSocket(0, localAddress)); int port = socket.getLocalPort(); int externalPort = socket.getLocalPort(); while (retries < MAX_RETRIES) { if (!device.getSpecificPortMappingEntry(port, "UDP", portMapping)) { if (device.addPortMapping( externalPort, port, localAddress.getHostAddress(), "UDP", "ice4j.org: " + port)) { List<LocalCandidate> cands = createUPNPCandidate(socket, externalIPAddress, externalPort, component, device); logger.info("Add UPnP port mapping: " + externalIPAddress + " " + externalPort); // we have to add the UPNPCandidate and also the base. // if we don't add the base, we won't be able to add // peer reflexive candidate if someone contact us on the // UPNPCandidate for (LocalCandidate cand : cands) { // try to add the candidate to the component and then // only add it to the harvest not redundant if (component.addLocalCandidate(cand)) { candidates.add(cand); } } break; } else { port++; } } else { port++; } retries++; } } catch (Throwable e) { logger.info("Exception while gathering UPnP candidates: " + e); } return candidates; }
/** * Renders a table cell in the main JTable. As a TableCellRenderer, we have to implement this * method, but we use it to colour different types of matches in different ways. Remember that * this is run every time a cell is displayed on the screen, so it needs to be as fast as can be. * * @param table The table which needs rendering. * @param value The object which needs rendering. For now, this can only be a Name object, but * later on we might colour different types of cells in different ways. * @param isSelected Is this cell selected, i.e. is the row selected? * @param hasFocus Is this cell focused, i.e. is this individual cell selected? * @param row The row coordinate of this cell. * @param column The column coordinate of this cell. * @return A component representing this cell. */ @Override public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { // TODO: Check if we can get a saving out of this by just rendering a JLabel/JTextField // directly. Component c = defTableCellRenderer.getTableCellRendererComponent( table, value, isSelected, hasFocus, row, column); // Set all backgrounds to white. c.setBackground(Color.WHITE); if (value == null) { // Null values look null-ish. c.setBackground(COLOR_NULL); return c; } else if (hasFocus) { // ANY cell with focus should look focussed. c.setBackground(COLOR_FOCUS); return c; } else if (Name.class.isAssignableFrom(value.getClass())) { // Aha, a Name! Color it special. Name name = (Name) value; int str_length = name.toString().length(); if (currentMatch == null) { // No current match? Then just colour blank cells blank, // and unmatched name colours special so people know that // they have been recognized as names. if (str_length == 0) { c.setBackground(COLOR_BLANK_CELL); } else { c.setBackground(COLOR_NAME_UNMATCHED); } } else { // So which RowIndex is the match against? RowIndex against = currentMatch.getAgainst(); // System.err.println("Checking against: " + against); if (str_length == 0) { // Mark blank cells as such. c.setBackground(COLOR_BLANK_CELL); } else if (against.hasName(name)) { // Perfect match! c.setBackground(COLOR_NAME_FULL_MATCH); } else if (against.hasName(name.getGenus())) { // Genus-match. c.setBackground(COLOR_NAME_GENUS_MATCH); } else { // No match! c.setBackground(COLOR_NAME_NO_MATCH); } } } else { // Not a name? Note that Strings will NOT make it here: we don't // push Strings through this. So this is really just for later. c.setBackground(COLOR_NULL); } // If the row is selected, make it darker. if (isSelected) c.setBackground(c.getBackground().darker()); return c; }
protected void dolayout(String strDir, String strFreq, String strTraynum) { // TopBar String strTitle = gettitle(strFreq); Color color = DisplayOptions.getColor("Heading3"); // Center Panel JPanel panelCenter = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints( 0, 0, 1, 1, 0.2, 0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 0), 0, 0); ImageIcon icon = getImageIcon(); // panelCenter.add(new JLabel(icon)); addComp(panelCenter, new JLabel(icon), gbc, 0, 0); strTitle = getSampleName(strDir, strTraynum); m_lblSampleName = new JLabel(strTitle); if (strTitle == null || !strTitle.trim().equals("")) strTitle = "3"; Font font = m_lblSampleName.getFont(); font = DisplayOptions.getFont(font.getName(), Font.BOLD, 300); m_lblSampleName.setFont(font); m_lblSampleName.setForeground(color); // panelCenter.add(m_lblSampleName); m_pnlSampleName = new JPanel(new CardLayout()); m_pnlSampleName.add(m_lblSampleName, OTHER); addComp(panelCenter, m_pnlSampleName, gbc, 1, 0); m_pnlSampleName.setVisible(false); m_pnlTrays = new JPanel(new GridLayout(1, 0)); // Vast panels VBox pnlVast1 = new VBox(m_pnlTrays, "1"); m_pnlTrays.add(pnlVast1); m_pnlVast[0] = pnlVast1; VBox pnlVast2 = new VBox(m_pnlTrays, "2"); m_pnlTrays.add(pnlVast2); m_pnlVast[1] = pnlVast2; VBox pnlVast3 = new VBox(m_pnlTrays, "3"); m_pnlTrays.add(pnlVast3); m_pnlVast[2] = pnlVast3; VBox pnlVast4 = new VBox(m_pnlTrays, "4"); m_pnlTrays.add(pnlVast4); m_pnlVast[3] = pnlVast4; VBox pnlVast5 = new VBox(m_pnlTrays, "5"); m_pnlTrays.add(pnlVast5); m_pnlVast[4] = pnlVast5; m_pnlSampleName.add(m_pnlTrays, VAST); // Login Panel JPanel panelThird = new JPanel(new BorderLayout()); JPanel panelLogin = new JPanel(new GridBagLayout()); gbc = new GridBagConstraints(); panelThird.add(panelLogin); Object[] aStrUser = getOperators(); m_cmbUser = new JComboBox(aStrUser); BasicComboBoxRenderer renderer = new BasicComboBoxRenderer(); m_cmbUser.setRenderer(renderer); m_cmbUser.setEditable(true); m_passwordField = new JPasswordField(); // *Warning, working around a Java problem* // When we went to the T3500 running Redhat 5.3, the JPasswordField // fields sometimes does not allow ANY entry of characters. Setting // the enableInputMethods() to true fixed this problem. There are // comments that indicate that this could cause the typed characters // to be visible. I have not found that to be a problem. // This may not be required in the future, or could cause characters // to become visible in the future if Java changes it's code. // GRS 8/20/09 m_passwordField.enableInputMethods(true); m_lblLogin = new VLoginLabel(null, "Incorrect username/password \n Please try again ", 0, 0); m_lblLogin.setVisible(false); okButton.setActionCommand("enter"); okButton.addActionListener(this); cancelButton.setActionCommand("cancel"); cancelButton.addActionListener(this); helpButton.setActionCommand("help"); helpButton.addActionListener(this); m_passwordField.addKeyListener( new KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) enterLogin(); } }); // These is some wierd problem such that sometimes, the vnmrj command // area gets the focus and these items in the login box do not get // the focus. Even clicking in these items does not bring focus to // them. Issuing requestFocus() does not bring focus to them. // I can however, determing if either the operator entry box or // the password box has focus and if neither does, I can unshow and // reshow the panel and that fixes the focus. So, I have added this // to the mouseClicked action. If neither has focus, it will // take focus with setVisible false then true. comboTextField = m_cmbUser.getEditor().getEditorComponent(); m_passwordField.addMouseListener(this); comboTextField.addMouseListener(this); m_lblUsername = new JLabel(Util.getLabel("_Operator")); addComp(panelLogin, m_lblUsername, gbc, 0, 0); addComp(panelLogin, m_cmbUser, gbc, 1, 0); m_lblPassword = new JLabel(Util.getLabel("_Password")); addComp(panelLogin, m_lblPassword, gbc, 0, 1); addComp(panelLogin, m_passwordField, gbc, 1, 1); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.gridheight = GridBagConstraints.REMAINDER; addComp(panelLogin, m_lblLogin, gbc, 2, 0); setPref(); Container container = getContentPane(); JPanel panelLoginBox = new JPanel(new BorderLayout()); panelLoginBox.add(panelCenter, BorderLayout.CENTER); panelLoginBox.add(panelThird, BorderLayout.SOUTH); container.add(panelLoginBox, BorderLayout.CENTER); }