Como fazer isso

9 respostas
G

Eu gostaria de uma informação, que funções eu utilizaria para criar uma janela, botões e inserir imagens?

Exemplo: Azul são botões e o preto seria uma imagem, ao clicar em um dos botões azuis a imagem mudaria:

9 Respostas

ViniGodoy
  1. Se são botões padrão, use o Swing;
  2. Se os botões são imagens bonitinhas, use Java 2D;
  3. Se for em web, use HTML, css e Javascript.
B

http://java.sun.com/docs/books/tutorial/uiswing/TOC.html

G

OLá, obrigado por responder, eu aindo gostaria de saber como criar aplicativos em fomato .jnlp, obrigado desde já.

B

JNLP = Java Web Start

Ou seja, basicamente é uma aplicação Desktop.

Em aplicações Desktop, costuma-se usar o Swing (embora, com um bocadinho de esforço, você possa tentar usar o SWT - cuja documentação está em http://www.eclipse.org/swt/ ).

Tem gente que usa o framework do NetBeans (que usa Swing), principalmente se sua aplicação é grande e complexa. Veja: http://platform.netbeans.org/tutorials/nbm-htmleditor.html )

Veja o tutorial de Swing e arranje algum livro de Swing (na Internet, por exemplo).

M

Depende de como você vai fazer isso. Se for fazer “na unha” você pode user um BorderLayout na janela principal.

Na parte [color=red]oeste, você coloca um JPanel[/color] com um BoxLayout (Y_AXIS) e dentro dele adiciona [color=darkblue]os JButtons[/color].

Já na parte [color=green]central, você coloca[/color] o seu [color=orange]JLabel contendo a imagem[/color].

Uma referência importante: http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html

Marlon_Meneses

oi!!
fiz um exemplo em anexo
seria isso?

M

Inicialmente eu tinha pensado bem parecido. Apenas trocaria a linha 65 por:

panelBotoes.setLayout(new BoxLayout(panelBotoes, BoxLayout.Y_AXIS));

E removeria a linha 66.

Mas a sua solução dá praticamente o mesmo resultado. Então é isso mesmo.

G

Olha usei a parte gráfica do NetBeans para montar o GUI, e depois escrevi o código baseado no exemplo que foi enviado...

Meu código:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * RP.java
 *
 * Created on 13/09/2002, 00:25:14
 */

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

/**
 *
 * @author User
 */
public class RP extends javax.swing.JFrame {

    String nome;
    String sexo;        
    boolean isGarçom;
    boolean isGari;
    int rpp;

    String pic = "img";
    
    /** Creates new form RP */
    public RP() {
        initComponents();
    }

    public void selecItem(ActionEvent evt){
		if(evt.getSource().equals(jComboBox1.getSelectedItem() == "Parque Central")){
			try {
				picture.setIcon(new ImageIcon(new URL(RP.class.getResource("espelho.jpg").toString())));
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
		}else if(evt.getSource().equals(jComboBox1.getSelectedItem() == "Cafeteria")){
			try {
				picture.setIcon(new ImageIcon(new URL(RP.class.getResource("espaco.jpg").toString())));
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
		}else{
			try {
				picture.setIcon(new ImageIcon(new URL(RP.class.getResource("ilusao.jpg").toString())));
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
                    }
                }
    /** 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")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
        
        nome = "Gustavo";
        sexo = "Masculino";
        rpp = 150;
        isGarçom = true;
        
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        JLabel picture = new javax.swing.JLabel();
        picture.setHorizontalAlignment(JLabel.CENTER);
        jComboBox1 = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBackground(new java.awt.Color(0, 100, 150));
        jPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jPanel1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        nome = "Gustavo";
        jLabel2.setText("Nome: " + nome);

        sexo = "Masculino";
        jLabel3.setText("Sexo: " + sexo);

        rpp = 150;
        jLabel4.setText("RP-Points: " + rpp + "$");

        isGarçom = true;
        if(isGarçom == true) {
            jLabel6.setText("Profissão: Garçom/Garçonete");
        } else if(isGari == true) {
            jLabel6.setText("Profissão: Gari");
        }

        jLabel5.setText("Ação:");

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel1.setText("Escolha um espaço público:");

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Parque Central", "Cafeteria", "Empregos e CIA" }));
         
        jComboBox1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				selecItem(e);
			}
		});
              
        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel4))
                        .addGap(75, 75, 75)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel6))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 86, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(15, 15, 15))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(31, 31, 31))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addContainerGap(395, Short.MAX_VALUE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE)
                .addComponent(jLabel5)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(271, 271, 271)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
     
        pack();
    }// </editor-fold>

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new RP().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel picture;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration

}

Mas recebo toneladas de erros quando clico em alguma coisa na combo box :/

E não compreendo o que está errado, sou novato desculpem pela minha ignorância.

Erros:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at RP.selecItem(RP.java:50) at RP$1.actionPerformed(RP.java:112) at javax.swing.JComboBox.fireActionEvent(JComboBox.java:1240) at javax.swing.JComboBox.setSelectedItem(JComboBox.java:567) at javax.swing.JComboBox.setSelectedIndex(JComboBox.java:603) at javax.swing.plaf.basic.BasicComboPopup$Handler.mouseReleased(BasicComboPopup.java:816) at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:273) at java.awt.Component.processMouseEvent(Component.java:6263) at javax.swing.JComponent.processMouseEvent(JComponent.java:3255) at javax.swing.plaf.basic.BasicComboPopup$1.processMouseEvent(BasicComboPopup.java:480) at java.awt.Component.processEvent(Component.java:6028) at java.awt.Container.processEvent(Container.java:2041) at java.awt.Component.dispatchEventImpl(Component.java:4630) at java.awt.Container.dispatchEventImpl(Container.java:2099) at java.awt.Component.dispatchEvent(Component.java:4460) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168) at java.awt.Container.dispatchEventImpl(Container.java:2085) at java.awt.Window.dispatchEventImpl(Window.java:2475) at java.awt.Component.dispatchEvent(Component.java:4460) at java.awt.EventQueue.dispatchEvent(EventQueue.java:599) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161) at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
M

O problema é que a variável ‘picture’, que deveria carregar a imagem não é instanciada em lugar algum! Dentro de ‘initComponents’ você declara e instancia uma variável local com o mesmo nome, ou seja isso está errado.

Além disso, o JLabel ‘picture’ não é adicionado ao painel em momento algum. Ou seja, mesmo que você conserte a instanciação, a imagem não aparecerá do jeito que está.

Depois de corrigir o problema do JLabel, seu método selecItem ficaria assim:

public void selecItem(ActionEvent evt) {
	// verfica se o que gerou o evento foi o jComboBox1
	if (evt.getSource().equals(jComboBox1)) {
		String caminhoDaImagem;
		// agora, vamos ver qual item está selecionado
		if ("Parque Central".equals(jComboBox1.getSelectedItem())) {  
			caminhoDaImagem = "/espelho.jpg";
		} else if ("Cafeteria".equals(jComboBox1.getSelectedItem())) {
			caminhoDaImagem = "/espaco.jpg";
		} else {                                                      
			caminhoDaImagem = "/ilusao.jpg";
		}                                                             
		// e, por fim, vamos trocar a imagem
		picture.setIcon(new ImageIcon(getClass().getResource(caminhoDaImagem)));
	}         
}
Criado 2 de dezembro de 2009
Ultima resposta 9 de dez. de 2009
Respostas 9
Participantes 5