下面列出了怎么用java.awt.Canvas的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void init() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final Image image1 = getImage(getCheckBox("Deselected", false));
final Image image2 = getImage(getCheckBox("Selected", true));
Canvas canvas = new Canvas() {
@Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(image1, 0, 0, scaledWidth, scaledHeight, this);
g.drawImage(image2, 0, scaledHeight + 5,
scaledWidth, scaledHeight, this);
}
};
getContentPane().add(canvas, BorderLayout.CENTER);
}
});
}
@Override
public void doLayout() {
try {
layingOut = true;
int tmpPopupWidth = 1;
Canvas c = new Canvas();
FontMetrics fontMetrics = c.getFontMetrics(this.getFont());
for (int i = 0; i < super.getItemCount(); i++) {
String item = super.getItemAt(i);
tmpPopupWidth = Integer.max(fontMetrics.stringWidth(item), tmpPopupWidth);
}
tmpPopupWidth += 15;
this.popupWidth = Optional.of(tmpPopupWidth);
super.doLayout();
}
finally {
layingOut = false;
}
}
private void createDisplay(){
frame = new JFrame(title);
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
canvas = new Canvas();
canvas.setPreferredSize(new Dimension(width, height));
canvas.setMaximumSize(new Dimension(width, height));
canvas.setMinimumSize(new Dimension(width, height));
canvas.setFocusable(false);
frame.add(canvas);
frame.pack();
}
@Override
public void init() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final Image image1 = getImage(getCheckBox("Deselected", false));
final Image image2 = getImage(getCheckBox("Selected", true));
Canvas canvas = new Canvas() {
@Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(image1, 0, 0, scaledWidth, scaledHeight, this);
g.drawImage(image2, 0, scaledHeight + 5,
scaledWidth, scaledHeight, this);
}
};
getContentPane().add(canvas, BorderLayout.CENTER);
}
});
}
private void createDisplay(){
frame = new JFrame(title);
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
canvas = new Canvas();
canvas.setPreferredSize(new Dimension(width, height));
canvas.setMaximumSize(new Dimension(width, height));
canvas.setMinimumSize(new Dimension(width, height));
canvas.setFocusable(false);
frame.add(canvas);
frame.pack();
}
@Override
public void init() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final Image image1 = getImage(getCheckBox("Deselected", false));
final Image image2 = getImage(getCheckBox("Selected", true));
Canvas canvas = new Canvas() {
@Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(image1, 0, 0, scaledWidth, scaledHeight, this);
g.drawImage(image2, 0, scaledHeight + 5,
scaledWidth, scaledHeight, this);
}
};
getContentPane().add(canvas, BorderLayout.CENTER);
}
});
}
@Override
public void init() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final Image image1 = getImage(getCheckBox("Deselected", false));
final Image image2 = getImage(getCheckBox("Selected", true));
Canvas canvas = new Canvas() {
@Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(image1, 0, 0, scaledWidth, scaledHeight, this);
g.drawImage(image2, 0, scaledHeight + 5,
scaledWidth, scaledHeight, this);
}
};
getContentPane().add(canvas, BorderLayout.CENTER);
}
});
}
public static Mat drawNonAscii(String watermark) {
Font font = new Font("Default", Font.PLAIN, 64);
FontMetrics metrics = new Canvas().getFontMetrics(font);
int width = metrics.stringWidth(watermark);
int height = metrics.getHeight();
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
Graphics2D graphics = bufferedImage.createGraphics();
graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
graphics.setFont(font);
graphics.setColor(Color.WHITE);
graphics.drawString(watermark, 0, metrics.getAscent());
graphics.dispose();
byte[] pixels = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData();
Mat res = new Mat(bufferedImage.getHeight(), bufferedImage.getWidth(), CV_8U);
res.put(0, 0, pixels);
return res;
}
@Override
public void init() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final Image image1 = getImage(getCheckBox("Deselected", false));
final Image image2 = getImage(getCheckBox("Selected", true));
Canvas canvas = new Canvas() {
@Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(image1, 0, 0, scaledWidth, scaledHeight, this);
g.drawImage(image2, 0, scaledHeight + 5,
scaledWidth, scaledHeight, this);
}
};
getContentPane().add(canvas, BorderLayout.CENTER);
}
});
}
private void createDisplay(){
frame = new JFrame(title);
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
canvas = new Canvas();
canvas.setPreferredSize(new Dimension(width, height));
canvas.setMaximumSize(new Dimension(width, height));
canvas.setMinimumSize(new Dimension(width, height));
canvas.setFocusable(false);
frame.add(canvas);
frame.pack();
}
private void createDisplay(){
frame = new JFrame(title);
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
canvas = new Canvas();
canvas.setPreferredSize(new Dimension(width, height));
canvas.setMaximumSize(new Dimension(width, height));
canvas.setMinimumSize(new Dimension(width, height));
canvas.setFocusable(false);
frame.add(canvas);
frame.pack();
}
@Override
public void init() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final Image image1 = getImage(getCheckBox("Deselected", false));
final Image image2 = getImage(getCheckBox("Selected", true));
Canvas canvas = new Canvas() {
@Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(image1, 0, 0, scaledWidth, scaledHeight, this);
g.drawImage(image2, 0, scaledHeight + 5,
scaledWidth, scaledHeight, this);
}
};
getContentPane().add(canvas, BorderLayout.CENTER);
}
});
}
private void createDisplay(){
frame = new JFrame(title);
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
canvas = new Canvas();
canvas.setPreferredSize(new Dimension(width, height));
canvas.setMaximumSize(new Dimension(width, height));
canvas.setMinimumSize(new Dimension(width, height));
canvas.setFocusable(false);
frame.add(canvas);
frame.pack();
}
@Override
public void init() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
final Image image1 = getImage(getCheckBox("Deselected", false));
final Image image2 = getImage(getCheckBox("Selected", true));
Canvas canvas = new Canvas() {
@Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(image1, 0, 0, scaledWidth, scaledHeight, this);
g.drawImage(image2, 0, scaledHeight + 5,
scaledWidth, scaledHeight, this);
}
};
getContentPane().add(canvas, BorderLayout.CENTER);
}
});
}
private void createDisplay(){
frame = new JFrame(title);
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
canvas = new Canvas();
canvas.setPreferredSize(new Dimension(width, height));
canvas.setMaximumSize(new Dimension(width, height));
canvas.setMinimumSize(new Dimension(width, height));
canvas.setFocusable(false);
frame.add(canvas);
frame.pack();
}
/**
* Creates a <CODE>java.awt.Image</CODE>. A successful call to the method
* <CODE>generate()</CODE> before calling this method is required.
*
* @param foreground the color of the bars
* @param background the color of the background
* @return the image
*/
public java.awt.Image createAwtImage(Color foreground, Color background) {
if (image == null) {
return null;
}
int f = foreground.getRGB();
int g = background.getRGB();
Canvas canvas = new Canvas();
int w = width + 2 * ws;
int h = height + 2 * ws;
int pix[] = new int[w * h];
int stride = (w + 7) / 8;
int ptr = 0;
for (int k = 0; k < h; ++k) {
int p = k * stride;
for (int j = 0; j < w; ++j) {
int b = image[p + j / 8] & 0xff;
b <<= j % 8;
pix[ptr++] = (b & 0x80) == 0 ? g : f;
}
}
java.awt.Image img = canvas.createImage(new MemoryImageSource(w, h, pix, 0, w));
return img;
}
private void createDisplay(){
frame = new JFrame(title);
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
canvas = new Canvas();
canvas.setPreferredSize(new Dimension(width, height));
canvas.setMaximumSize(new Dimension(width, height));
canvas.setMinimumSize(new Dimension(width, height));
frame.add(canvas);
frame.pack();
}
/**
* Create a new browser as dev tools
*/
protected final void createDevTools(CefBrowser parent,
CefClientHandler clientHandler,
long windowHandle,
boolean transparent,
Canvas canvas) {
if (getNativeRef("CefBrowser") == 0 && !isPending_) {
try {
isPending_ = N_CreateDevTools(parent,
clientHandler,
windowHandle,
transparent,
canvas);
} catch (UnsatisfiedLinkError err) {
err.printStackTrace();
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Mickey Mouse");
Canvas canvas = new Mickey();
canvas.setSize(400, 400);
canvas.setBackground(Color.white);
frame.add(canvas);
frame.pack();
frame.setVisible(true);
}
@SuppressWarnings("deprecation")
public static boolean shouldFocusOnClick(Component component) {
boolean acceptFocusOnClick = false;
// A component is generally allowed to accept focus on click
// if its peer is focusable. There're some exceptions though.
// CANVAS & SCROLLBAR accept focus on click
if (component instanceof Canvas ||
component instanceof Scrollbar)
{
acceptFocusOnClick = true;
// PANEL, empty only, accepts focus on click
} else if (component instanceof Panel) {
acceptFocusOnClick = (((Panel)component).getComponentCount() == 0);
// Other components
} else {
ComponentPeer peer = (component != null ? component.getPeer() : null);
acceptFocusOnClick = (peer != null ? peer.isFocusable() : false);
}
return acceptFocusOnClick &&
AWTAccessor.getComponentAccessor().canBeFocusOwner(component);
}
@SuppressWarnings("deprecation")
public static boolean shouldFocusOnClick(Component component) {
boolean acceptFocusOnClick = false;
// A component is generally allowed to accept focus on click
// if its peer is focusable. There're some exceptions though.
// CANVAS & SCROLLBAR accept focus on click
if (component instanceof Canvas ||
component instanceof Scrollbar)
{
acceptFocusOnClick = true;
// PANEL, empty only, accepts focus on click
} else if (component instanceof Panel) {
acceptFocusOnClick = (((Panel)component).getComponentCount() == 0);
// Other components
} else {
ComponentPeer peer = (component != null ? component.getPeer() : null);
acceptFocusOnClick = (peer != null ? peer.isFocusable() : false);
}
return acceptFocusOnClick &&
AWTAccessor.getComponentAccessor().canBeFocusOwner(component);
}
public static void main(String[] args) {
// make the frame
JFrame frame = new JFrame("Card Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add the CardTable
String cardset = "cardset-oxymoron";
Canvas canvas = new CardTable(cardset);
frame.getContentPane().add(canvas);
// show the frame
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
// make the frame
JFrame frame = new JFrame("Card Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add the CardTable
String cardset = "cardset-oxymoron";
Canvas canvas = new CardTable(cardset);
frame.getContentPane().add(canvas);
// show the frame
frame.pack();
frame.setVisible(true);
}
/**
* @see java.applet.Applet#init()
*/
public void init() {
removeAll();
setLayout(new BorderLayout());
setIgnoreRepaint(true);
try {
Game game = (Game) Class.forName(getParameter("game")).newInstance();
container = new Container(game);
canvas = new ContainerPanel(container);
displayParent = new Canvas() {
public final void addNotify() {
super.addNotify();
startLWJGL();
}
public final void removeNotify() {
destroyLWJGL();
super.removeNotify();
}
};
displayParent.setSize(getWidth(), getHeight());
add(displayParent);
displayParent.setFocusable(true);
displayParent.requestFocus();
displayParent.setIgnoreRepaint(true);
setVisible(true);
} catch (Exception e) {
Log.error(e);
throw new RuntimeException("Unable to create game container");
}
}
/**
* function emulate the overflow hidden behavior on table cell
*
* @param text
* String to check
* @param style
* style of the text
* @param fontFamily
* fond of the text
* @param cellWidth
* the width of the container in points
* @return String with truncated words that surpasses the cell width
*/
public String cropOverflowString( String text, IStyle style,
String fontFamily, int cellWidth )
{// TODO: retrieve font type and replace plain with corresponding
Font font = new Font( fontFamily, Font.PLAIN,
WordUtil.parseFontSize( PropertyUtil.getDimensionValue( style
.getProperty( StyleConstants.STYLE_FONT_SIZE ) ) ) );
Canvas c = new Canvas( );
FontMetrics fm = c.getFontMetrics( font );
// conversion from point to advancement point from sample linear
// regression:
int cellWidthInPointAdv = ( cellWidth * (int) WordUtil.PT_TWIPS - 27 )
/ 11;
StringBuilder sb = new StringBuilder( text.length( ) + 1 );
int wordEnd = INDEX_NOTFOUND;
do
{
wordEnd = text.indexOf( SPACE );
if ( wordEnd != INDEX_NOTFOUND ) // space found
{
String word = text.substring( 0, wordEnd );
word = cropOverflowWord( word, fm, cellWidthInPointAdv );
sb.append( word );
sb.append( SPACE );
text = text.substring( wordEnd + 1 );
}
} while ( wordEnd != INDEX_NOTFOUND && !EMPTY_STRING.equals( text ) );
sb.append( cropOverflowWord( text, fm, cellWidthInPointAdv ) );
return sb.toString( );
}
private void initializeGUI() {
frame = new Frame("Test frame");
canvas = new Canvas();
canvas.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent event) { focusGained = true; }
});
canvas.addKeyListener(this);
frame.setLayout(new BorderLayout());
frame.add(canvas);
frame.setSize(200, 200);
frame.setVisible(true);
}
/**
* Creates a <CODE>java.awt.Image</CODE>.
*
* @param foreground the color of the bars
* @param background the color of the background
* @return the image
*/
public java.awt.Image createAwtImage(Color foreground, Color background) {
int f = foreground.getRGB();
int g = background.getRGB();
Canvas canvas = new Canvas();
paintCode();
int h = (int) yHeight;
int pix[] = new int[bitColumns * codeRows * h];
int stride = (bitColumns + 7) / 8;
int ptr = 0;
for (int k = 0; k < codeRows; ++k) {
int p = k * stride;
for (int j = 0; j < bitColumns; ++j) {
int b = outBits[p + j / 8] & 0xff;
b <<= j % 8;
pix[ptr++] = (b & 0x80) == 0 ? g : f;
}
for (int j = 1; j < h; ++j) {
System.arraycopy(pix, ptr - bitColumns, pix, ptr + bitColumns * (j - 1), bitColumns);
}
ptr += bitColumns * (h - 1);
}
java.awt.Image img = canvas.createImage(new MemoryImageSource(bitColumns, codeRows * h, pix, 0, bitColumns));
return img;
}
/** Creates a <CODE>java.awt.Image</CODE>. This image only
* contains the bars without any text.
* @param foreground the color of the bars
* @param background the color of the background
* @return the image
*/
public java.awt.Image createAwtImage(Color foreground, Color background) {
int f = foreground.getRGB();
int g = background.getRGB();
Canvas canvas = new Canvas();
String bCode = code;
if (extended)
bCode = getCode39Ex(code);
if (generateChecksum)
bCode += getChecksum(bCode);
int len = bCode.length() + 2;
int nn = (int)n;
int fullWidth = len * (6 + 3 * nn) + (len - 1);
byte bars[] = getBarsCode39(bCode);
boolean print = true;
int ptr = 0;
int height = (int)barHeight;
int pix[] = new int[fullWidth * height];
for (int k = 0; k < bars.length; ++k) {
int w = (bars[k] == 0 ? 1 : nn);
int c = g;
if (print)
c = f;
print = !print;
for (int j = 0; j < w; ++j)
pix[ptr++] = c;
}
for (int k = fullWidth; k < pix.length; k += fullWidth) {
System.arraycopy(pix, 0, pix, k, fullWidth);
}
Image img = canvas.createImage(new MemoryImageSource(fullWidth, height, pix, 0, fullWidth));
return img;
}
public long create(Canvas canvas, VKData data) throws AWTException {
MemoryStack stack = MemoryStack.stackGet();
int ptr = stack.getPointer();
JAWTDrawingSurface ds = JAWT_GetDrawingSurface(canvas, awt.GetDrawingSurface());
try {
int lock = JAWT_DrawingSurface_Lock(ds, ds.Lock());
if ((lock & JAWT_LOCK_ERROR) != 0)
throw new AWTException("JAWT_DrawingSurface_Lock() failed");
try {
JAWTDrawingSurfaceInfo dsi = JAWT_DrawingSurface_GetDrawingSurfaceInfo(ds, ds.GetDrawingSurfaceInfo());
try {
JAWTWin32DrawingSurfaceInfo dsiWin = JAWTWin32DrawingSurfaceInfo.create(dsi.platformInfo());
long hwnd = dsiWin.hwnd();
VkWin32SurfaceCreateInfoKHR sci = VkWin32SurfaceCreateInfoKHR.callocStack(stack)
.sType(VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR)
.hinstance(WinBase.GetModuleHandle((ByteBuffer) null))
.hwnd(hwnd);
long surfaceAddr = stack.nmalloc(8, 8);
int err = nvkCreateWin32SurfaceKHR(data.instance, sci.address(), 0L, surfaceAddr);
long surface = MemoryUtil.memGetLong(surfaceAddr);
stack.setPointer(ptr);
if (err != VK_SUCCESS) {
throw new AWTException("Calling vkCreateWin32SurfaceKHR failed with error: " + err);
}
return surface;
} finally {
JAWT_DrawingSurface_FreeDrawingSurfaceInfo(dsi, ds.FreeDrawingSurfaceInfo());
}
} finally {
JAWT_DrawingSurface_Unlock(ds, ds.Unlock());
}
} finally {
JAWT_FreeDrawingSurface(ds, awt.FreeDrawingSurface());
}
}
/** Creates a <CODE>java.awt.Image</CODE>.
* @param foreground the color of the bars
* @param background the color of the background
* @return the image
*/
public java.awt.Image createAwtImage(Color foreground, Color background) {
int f = foreground.getRGB();
int g = background.getRGB();
Canvas canvas = new Canvas();
paintCode();
int h = (int)yHeight;
int pix[] = new int[bitColumns * codeRows * h];
int stride = (bitColumns + 7) / 8;
int ptr = 0;
for (int k = 0; k < codeRows; ++k) {
int p = k * stride;
for (int j = 0; j < bitColumns; ++j) {
int b = outBits[p + (j / 8)] & 0xff;
b <<= j % 8;
pix[ptr++] = (b & 0x80) == 0 ? g : f;
}
for (int j = 1; j < h; ++j) {
System.arraycopy(pix, ptr - bitColumns, pix, ptr + bitColumns * (j - 1), bitColumns);
}
ptr += bitColumns * (h - 1);
}
java.awt.Image img = canvas.createImage(new MemoryImageSource(bitColumns, codeRows * h, pix, 0, bitColumns));
return img;
}