簡體   English   中英

JButton,帶有背景圖像的JFrame

[英]JButton, JFrame with Background image

我正在嘗試用Java在JFRame中使用背景圖像,但是如果您單擊按鈕,它將出現在帶有消息的新窗口中,但是我想在背景上有一些JButton。 但是,按鈕沒有出現在JFrame中。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Prova3 extends JFrame implements ActionListener {//implementando el listener de eventos

JButton bt1, bt2, bt3;//creando variables globales de los botones
JFrame jf = new JFrame("BATTLESHIP");//creacion de ventana con el titulo

public Prova3(){//constructor de la clase
    //setVisible(true);

    //jf.setLayout(new FlowLayout());//Configurar como se dispondra el espacio del jframe
    jf.setLayout(new FlowLayout());
    jf.setContentPane(new JLabel(new ImageIcon("imageprova.jpg")));

    Dimension d = new Dimension();//objeto para obtener el ancho de la pantalla

    //imagen para el boton


    //Instanciando botones con texto
    bt1 = new JButton("HELLO");
    bt2 = new JButton("SIZE");


    //margenes para texto en boton
    bt1.setMargin(new Insets(3, 5, 3, 5));
    bt2.setMargin(new Insets(1, 1, 1, 1));

    //color de fondo del boton
    bt1.setBackground(Color.orange);

    //color de texto para el boton
    bt2.setForeground(Color.blue);

    //agregando los botones a la ventana
    jf.add(bt1); jf.add(bt2);


    //añadiendo el listener a los botones para manipular los eventos del click
    bt1.addActionListener(this);
    bt2.addActionListener(this);
   // bt3.addActionListener(this);

    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//finaliza el programa cuando se da click en la X        
    jf.setResizable(false);//para configurar si se redimensiona la ventana
    jf.setLocation((int) ((d.getWidth()/2)+290), 50);//para ubicar inicialmente donde se muestra la ventana (x, y)
    jf.setSize(680, 346);//configurando tamaño de la ventana (ancho, alto)
    jf.setVisible(true);//configurando visualización de la venta
}

public static void main(String[] args) {

    Prova3 gj = new Prova3();//uso de constructor para la ventana
}

@Override
public void actionPerformed(ActionEvent e) {//sobreescribimos el metodo del listener

    if(e.getActionCommand().equals("HELLO")){//podemos comparar por el contenido del boton
        JOptionPane.showMessageDialog(null, e.getActionCommand());
    }
    if(e.getSource()==bt2){//podemos comparar por el nombre del objeto del boton
        jf.setExtendedState(JFrame.MAXIMIZED_BOTH);//cambiamos el tamaño de la ventana
    }
}
jf.setLayout(new FlowLayout());
jf.setContentPane(new JLabel(new ImageIcon("imageprova.jpg")));

設置布局,然后用JLabel替換內容窗格。 標簽沒有默認的布局管理器。

您的代碼應為:

//jf.setLayout(new FlowLayout());
JLabel background = new JLabel(new ImageIcon("imageprova.jpg"));
background.setLayout( new FlowLayout() );
jf.setContentPane( background );

現在您可以將組件添加到標簽。

請注意,只有當圖像大於您添加到標簽中的組件的大小時,此方法才有效(否則,組件的繪制將被截斷)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM