Olá, o povo aqui já deve tá de saco cheio de gente perguntando como colocar imagem de fundo em um JPanel, e em todos os tópicos deste sempre recomendaram a biblioteca towel, baixei um .jar 1.2.2 no github mas não sei como usá-lo, como faço pra importar - visto que não existe uma “pasta de libs java” - o arquivo para que assim fique disponível pra qualquer projeto?
e como usá-la?
Sou leigo nisso, agradeço quem ajudar!
Boa tarde amigo primeiramente vc gera o .JAR da biblioteca e importa no seu projeto ou se desejar importa o projeto assim ele gera o .JAR automaticamente, após isso é só fazer o bom uso da lib.
um exemplo simples.
[code]
AnnotationResolver resolver = new AnnotationResolver(Pessoa.class);
final ObjectTableModel<Pessoa> tableModel = new ObjectTableModel<Pessoa>(resolver, “nome:Nome,cpf:Cpf,estado:Estado”);
public void carrega_table() {
tableModel.setData(getDados());
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setAutoResizeMode(table.AUTO_RESIZE_OFF);
TableCellRenderer renderer = new MyCellRenderer();
table.setDefaultRenderer(Integer.class, renderer);
table.setDefaultRenderer(Double.class, renderer);
table.setDefaultRenderer(Object.class, renderer);
table.setDefaultRenderer(Date.class, renderer);
// table.setDefaultRenderer(Boolean.class, renderer);
table.setModel(tableModel);
table.getColumnModel().getColumn(0).setPreferredWidth(100);
table.getColumnModel().getColumn(1).setPreferredWidth(250);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
}
// Just for create a default List to show.
private List<Pessoa> getDados() {
List<Pessoa> list = new ArrayList<Pessoa>();
try {
for(int i=0; i<=10; i++){
Pessoa pp = new Pessoa();
pp.setNome("Pessoa"+i);
pp.setCpf("Cpf"+i);
if(i/2!=0){
pp.setEstado(true);
}
list.add(pp);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return list;
}[/code]
junto ao projeto Towel tem muitos outros exemplos só da uma estuda nele blz.
já baixei o .jar do towel e já importei pro meu projeto.
Eu tenho uma JFrame principal que quando compilo o java ele carrega, e é justamente esse JFrame que eu quero inserir a imagem, mas quero saber em que parte da minha função eu uso a função do towel?
Inclusive eu tinha colocado ela mas toda vez que mandava executar aparecia dois JFrame, o meu normal e o do towel carregando as imagens, então deixei comentando a parte em que uso a JImagePanel, como resolve isso?
Minha função principal do JFRame
[code]package Gui;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.towel.swing.img.JImagePanel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
/**
*
-
@author Ruan-Alex
*/
public class Main_Interface extends javax.swing.JFrame {
/**
- Creates new form Main_Interface
*/
public Main_Interface() {
initComponents();
/try
{
JImagePanel panel = new JImagePanel(10, new BufferedImage[] {
loadImage(“C:\\Users\\Ruan-Alex\\Downloads\\content_gatinho.jpg”),
loadImage(“C:\\Users\\Ruan-Alex\\Downloads\\pirata.jpg”),
loadImage(“C:\\Users\\Ruan-Alex\\Downloads\\india.jpg”)});
JFrame frame = new JFrame();
frame.setPreferredSize(new Dimension(718, 545));
frame.add(panel);
frame.setJMenuBar(jMenuBar1);//.add(jMenuBar1);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
catch(IOException e)
{
JOptionPane.showMessageDialog(null, "Erro ao gerar tela inicial: " + e);
}/
setLocationRelativeTo(null);
}
private static BufferedImage loadImage(String file) throws IOException {
return ImageIO.read(new File(file));
}
/**
-
This method is called from within the constructor to initialize the form.
-
WARNING: Do NOT modify this code. The content of this method is always
-
regenerated by the Form Editor.
*/
@SuppressWarnings(“unchecked”)
//
private void initComponents() {
jMenuBar1 = new javax.swing.JMenuBar();
Arquivo = new javax.swing.JMenu();
Agenda_Cad = new javax.swing.JMenuItem();
Cadastro = new javax.swing.JMenu();
Clien_Cad = new javax.swing.JMenuItem();
Func_Cad = new javax.swing.JMenuItem();
Serv_Cad = new javax.swing.JMenuItem();
Consultas = new javax.swing.JMenu();
Agen_Consu = new javax.swing.JMenuItem();
Clien_Consu = new javax.swing.JMenuItem();
Func_Consu = new javax.swing.JMenuItem();
Sair = new javax.swing.JMenuItem();
Editar = new javax.swing.JMenu();
Excluir = new javax.swing.JMenu();
Clien_Exc = new javax.swing.JMenuItem();
Func_Exc = new javax.swing.JMenuItem();
Ajuda = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle(“Salão de Beleza - Que Charme!”);
setResizable(false);
getContentPane().setLayout(null);
Arquivo.setText(“Arquivo”);
Agenda_Cad.setText(“Agendar Serviço”);
Agenda_Cad.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Agenda_CadActionPerformed(evt);
}
});
Arquivo.add(Agenda_Cad);
Cadastro.setText(“Cadastro”);
Clien_Cad.setText(“Cliente”);
Clien_Cad.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Clien_CadActionPerformed(evt);
}
});
Cadastro.add(Clien_Cad);
Func_Cad.setText(“Funcionário”);
Func_Cad.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Func_CadActionPerformed(evt);
}
});
Cadastro.add(Func_Cad);
Serv_Cad.setText(“Serviços”);
Serv_Cad.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Serv_CadActionPerformed(evt);
}
});
Cadastro.add(Serv_Cad);
Arquivo.add(Cadastro);
Consultas.setText(“Consultas”);
Agen_Consu.setText(“Agenda”);
Agen_Consu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Agen_ConsuActionPerformed(evt);
}
});
Consultas.add(Agen_Consu);
Clien_Consu.setText(“Cliente”);
Clien_Consu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Clien_ConsuActionPerformed(evt);
}
});
Consultas.add(Clien_Consu);
Func_Consu.setText(“Funcionário”);
Func_Consu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
Func_ConsuActionPerformed(evt);
}
});
Consultas.add(Func_Consu);
Arquivo.add(Consultas);
Sair.setText(“Sair”);
Sair.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SairActionPerformed(evt);
}
});
Arquivo.add(Sair);
jMenuBar1.add(Arquivo);
Editar.setText(“Editar”);
Excluir.setText(“Excluir”);
Clien_Exc.setText(“Cliente”);
Excluir.add(Clien_Exc);
Func_Exc.setText(“Funcionário”);
Excluir.add(Func_Exc);
Editar.add(Excluir);
jMenuBar1.add(Editar);
Ajuda.setText(“Ajuda”);
jMenuBar1.add(Ajuda);
setJMenuBar(jMenuBar1);
setBounds(0, 0, 718, 545);
}//
private void Clien_CadActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Cadastro_Cliente obj = new Cadastro_Cliente();
obj.setVisible(true);
this.setVisible(false);
}
private void Func_CadActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Cadastro_Funcionario obj = new Cadastro_Funcionario();
obj.setVisible(true);
this.setVisible(false);
}
private void Serv_CadActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Cadastro_Servicos obj = new Cadastro_Servicos();
obj.setVisible(true);
this.setVisible(false);
}
private void SairActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}
private void Agenda_CadActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Cadastro_Agenda obj = new Cadastro_Agenda();
obj.setVisible(true);
this.setVisible(false);
} [/code]
O JImagePanel é equivalente a um JPanel. Então, use-o como se fosse um JPanel, exatamente igual você faria.
Por exemplo, se você quer que ele fique no fundo de todos os seus componentes, adicione ele ao JFrame e os componentes nele.
O outro JFrame que está aparecendo não é o do Towel, é o JFrame que você declarou e criou nas linhas 31 até 38 do código que você postou. Ao invés de criar esse frame a mais, use o JImagePanel no seu próprio JFrame.
[quote=ViniGodoy]O JImagePanel é equivalente a um JPanel. Então, use-o como se fosse um JPanel, exatamente igual você faria.
Por exemplo, se você quer que ele fique no fundo de todos os seus componentes, adicione ele ao JFrame e os componentes nele.
O outro JFrame que está aparecendo não é o do Towel, é o JFrame que você declarou e criou nas linhas 31 até 38 do código que você postou. Ao invés de criar esse frame a mais, use o JImagePanel no seu próprio JFrame.[/quote]
O problema é que não to entendendo como fazer isso em código.
Eu apago as linhas de código do 31 a 38, é isso?
EDIT:
Comentei as linhas de 31 a 38, o outro JFrame não aparece mais, mas e agora como faço pra usar o JImagePanel que já declarei ser usado pelo JFrame atual?
Eu tenho o método o qual faço essa manipulação ai chamo o mesmo no construtor do meu JFrame
[code]
//Metodo que redefine uma imagem no panel
private void setar_imagem_de_fundo() {
imagePanel.setBorder(new EtchedBorder(EtchedBorder.RAISED, null, null));
// Seta a cor de fundo para azul marinho
// imagePanel.setBackground(new Color(176, 196, 222));
try {
// busca o plano de fundo
BufferedImage img = ImageIO.read(View_Menu_Principal.class
.getResource("/br/com/jimagepanel/img/imagem_fundo.png"));
// seta o plano de fundo no sistama
imagePanel.setImage(img);
// Centraliza a imagem
imagePanel.setStyle(JXImagePanel.Style.CENTERED);
// Redimenciona a imagem para o tamanho da tela
//imagePanel.setStyle(JXImagePanel.Style.SCALED);
// Redimenciona a imagem para o tamanho da tela 2
//imagePanel.setStyle(JXImagePanel.Style.TILED);
} catch (Exception e) {
e.printStackTrace();
}
}[/code]
Lembrando esse método faz uso do SwingX com o componente JXImagePanel
@Resplandes
Cara sei que vc tá tentando ajudar, mas vc tá me confundindo ainda mais, nunca vi esse JXImagePanel!
Você faria isso no initComponents. Esse código é automaticamente gerado pelo Netbeans?
Sim, é gerado automaticamente pelo netbeans e não posso alterá-lo, já que toda essa minha classe é um Form Jframe.
E agora como faço? =/
Não conheço o construtor visual do Netbeans, pois uso outras IDEs.
Dei umas pesquisadas e resolvi usar o eclipse com o WindowsBuilder, realmente o código fica mais limpo e consegui usar o Towel com no meu JFrame, infelizmente já está em cima da hora pra eu refazer tudo.
Enfim, vlw pela ajuda, tópico encerrado.