JButton from image

2019-07-23 18:13发布

问题:

I want to make JButton from image. But when i do it like this:

private void AddMainActionsButtons(Container powZawartosci){
  JPanel mainActionButtons = new JPanel();
  JButton applyButton = createImageButton("obrazki/apply.png");
  mainActionButtons.add(applyButton);
  powZawartosci.add(mainActionButtons);
  mainActionButtons.setBounds(150,530,400,90);
}

private JButton createImageButton(String imagePath){
  ImageIcon icon = uploadImage(imagePath,"");
  JButton button = new JButton(icon);

  return button;
}

JButton looks bad, because image is inside button component, and in fact I got image on image. How can I create as big JButton as my image, and how to cover it by image in 100%. In other words: how to make my image be a Button?

回答1:

You need to take the space out of the buttons by removing the border. See this answer for details.

Seen above is the single image split into 9 parts. The N/S/E/W are buttons (East is activated - shown with a red border) and the rest are labels - each containing the relevant part of the original image.

See also this answer for a version that uses simpler images with JToggleButton instances.



回答2:

Have you tried setting the background to a transparent color? This will remove the funky grey border around your image that often looks bad.