我在JLabel中有一个按钮列表。按钮是图像,该图像的背景是透明的,但是按钮iself比图像大,并且覆盖背景图像,这就是我的意思:
这是我的代码:
JPanel buttons = new JPanel(new GridLayout(0, 1));
JButton butoMapa = null;
try {
butoMapa = new JButton(new ImageIcon(ImageIO.read(new File("imatges/Mapa.png"))));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
butoMapa.setOpaque(false);
butoMapa.setContentAreaFilled(false);
butoMapa.setBorderPainted(false);
butoMapa.addActionListener(this);
JButton butoEtnies = null;
try {
butoEtnies = new JButton(new ImageIcon(ImageIO.read(new File("imatges/Etnies.png"))));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
butoEtnies.addActionListener(this);
JButton butoComandes = null;
try {
butoComandes = new JButton(new ImageIcon(ImageIO.read(new File("imatges/Comandes.png"))));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
butoComandes.addActionListener(this);
JButton butoSurtir = null;
try {
butoSurtir = new JButton(new ImageIcon(ImageIO.read(new File("imatges/Surtir.png"))));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
butoSurtir.addActionListener(this);
SomePanel label2 = new SomePanel();
label2.add(buttons);
frame.add(label2, BorderLayout.EAST);
buttons.add(butoMapa);
buttons.add(butoEtnies);
buttons.add(butoComandes);
buttons.add(butoSurtir);
//JPanel right = new JPanel(new BorderLayout());
// right
//right.add(buttons, BorderLayout.NORTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
SomePanel代码:
class SomePanel extends JPanel {
private BufferedImage image;
public SomePanel() {
try {
image = ImageIO.read(getClass().getResource("imatges/costat.png"));
} catch (IOException ex) {}
//add(new JButton("Hello"));
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
}
}
请注意,我在第一个地图上测试了这些命令,但是它仍然没有在右侧显示标签的背景。我想念什么?
该按钮具有默认边框。如果您不希望使用边框,则可以使用:
button.setBorderPainted( false );
您可能还想使用:
button.setFocusPainted( false );
button.setContentAreaPainted( false );
编辑:
糟糕,我刚刚注意到您确实对第一个按钮使用了上面的代码(对于其他按钮,您当然需要重复执行)。
我猜问题出在按钮面板上。您还需要使面板透明:
JPanel buttons = new JPanel(new GridLayout(0, 1));
buttons.setOpaque( false );
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句