Java Graphics - 在Jbutton上绘制形状

Chr*_*ell 1 java swing paint jbutton

我正在为Java中的类创建一个最小的绘制应用程序.我需要为用户制作几个按钮来选择不同的形状,在这些按钮上我应该放置他们正在使用的形状的图像.例如,允许用户绘制线条的按钮应该在其上具有线条的图像.一个绘制矩形的按钮,应该是一个矩形.我需要能够在程序中执行此操作,而无需使用外部图像源.

这是我当前的按钮代码示例.

lineB = new JButton();
lineB.setBounds(0, 25, 20, 20);
lineB.setBackground(Color.WHITE);
shapePanel.add(lineB);
lineB.addActionListener(this);
Run Code Online (Sandbox Code Playgroud)

Hov*_*els 5

  1. 创建所需大小的BufferedImage - BufferedImage img = new BufferedImage(biWidth, biHeight, BufferedImage.TYPE_INT_ARGB);
  2. 通过调用getGraphics()createGraphics()(更好,因为它为您提供Graphics2D对象)获取其Graphics上下文.
  3. 我将使用该setRenderingHints(...)方法将此Graphics2D对象的RenderingHints设置为all以进行抗锯齿处理.这可以消除锯齿.
  4. 用这个物体画出你的形状.
  5. 处理Graphics对象.
  6. 使用new ImageIcon(Image image)构造函数从上面的Image创建一个ImageIcon .
  7. 使用上面的图标设置按钮的图标setIcon(...).
  8. 不要打电话setBounds(...)按钮或任何东西.

例如,

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.swing.*;

@SuppressWarnings("serial")
public class ImageButton extends JPanel {
   private static final int IMG_WIDTH = 50;
   private static final Color SHAPE_COLOR = Color.RED;
   private static final int GAP = 4;
   private JButton circleButton = new JButton();
   private JButton squareButton = new JButton();

   public ImageButton() {
      BufferedImage circleImg = new BufferedImage(IMG_WIDTH, IMG_WIDTH, BufferedImage.TYPE_INT_ARGB);
      Graphics2D g2 = circleImg.createGraphics();
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      g2.setColor(SHAPE_COLOR);
      int x = GAP;
      int y = x;
      int width = IMG_WIDTH - 2 * x;
      int height = IMG_WIDTH - 2 * y;
      g2.fillOval(x, y, width, height);
      g2.dispose();
      circleButton.setIcon(new ImageIcon(circleImg));

      BufferedImage squareImg = new BufferedImage(IMG_WIDTH, IMG_WIDTH, BufferedImage.TYPE_INT_ARGB);
      g2 = squareImg.createGraphics();
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      g2.setColor(SHAPE_COLOR);
      g2.fillRect(x, y, width, height);
      g2.dispose();
      squareButton.setIcon(new ImageIcon(squareImg));

      add(circleButton);
      add(squareButton);
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("ImageButton");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new ImageButton());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
Run Code Online (Sandbox Code Playgroud)