如何在图像上放置JButton? [英] how can i put a JButton on an image?
问题描述
我正在尝试修复一个JFrame,该JFrame上将有一个背景图像,并且在图像JButton上将执行一些命令.我尝试不使用布局就这样做,因为我想在JFrame的某些特定位置放置小按钮,但是每次执行此操作时,背景图像就会移到最前面,或者JFrame的大小等于JFrame的大小.使用以下代码,JButton的大小与JFrame相同.我试图更改JButton的大小和位置,但是什么也没有.你能帮我吗?
I am trying to fix a JFrame where there will be a background image and on the image JButtons which will do some commands. I try to do it without layout because i want to put small buttons in some specific locations on the JFrame but every time i do it, the background image comes to the front or the JFrame has size equal to the JFrame size. With the following code, the JButton has the same size to JFrame. I have tried to change the size and location of the JButton but nothing. Can you help me please?
这是代码
public final class Test extends JComponent
{
private Image background;
private JFrame frame;
private Dimension dimension;
public Test()
{
dimension = new Dimension(15, 15);
frame = new JFrame("Iphone");
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(this);
frame.setBounds(641, 0, 344, 655);
frame.setVisible(true);
test = displayButton("tigka");
frame.getContentPane().add(test);
}
public void update(Graphics g)
{
paint(g);
}
public void paintComponent(Graphics g)
{
super.paintComponents(g);
g.drawImage(background, 0, 25, null); // draw background
//label();
// label();
推荐答案
您需要更改content pane
以获得Frame
的背景.
You need to change the content pane
to get a background for your Frame
.
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame("Test");
frame.setContentPane(new JPanel() {
BufferedImage image = ImageIO.read(new URL("http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png"));
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, 300, 300, this);
}
});
frame.add(new JButton("Test Button"));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}
输出:
这篇关于如何在图像上放置JButton?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!