Clicar em botao e desenhar um quadrado no NetBeans?

4 respostas
A

Salve pessoal, sou novato em java, especialmente na parte grafica. Estou usando o netbeans para criar um JPanel. O que eu quero eh ter um botao e quando eu clicar nele um quadrado seja desenhado na tela. Parece simples, mas estou me matando e nada… Segue o codigo que o NetBeans cria quando eu crio um Jframe novo com um botao e o evento pra ele:

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

/*
 * CriaQuadrado.java
 *
 * Created on 09/07/2009, 21:22:21
 */

package testes;

/**
 *
 * @author Administrador
 */
public class CriaQuadrado extends javax.swing.JFrame {

    /** Creates new form CriaQuadrado */
    public CriaQuadrado() {
        initComponents();
    }

    /** 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() {

        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(327, Short.MAX_VALUE)
                .addComponent(jButton1))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jButton1)
                .addContainerGap(277, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

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

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    // End of variables declaration

}

onde e o que eu insiro pra esse quadrado ser desenhado?
vlw ai galera

4 Respostas

F
Ve se esse codigo ajuda
package testes;  

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class CriaQuadrado extends JFrame {  

	public static void main(String args[]){
		final JFrame janela = new JFrame();
		final JPanel jp = new JPanel();
		JButton bt = new JButton("Quadrado");
		bt.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				jp.getGraphics().drawRect((int)(Math.random()*20), (int)(Math.random()*20), (int)(Math.random()*20), (int)(Math.random()*20));
			}		
		});
		janela.add(jp, BorderLayout.CENTER);
		janela.add(bt, BorderLayout.SOUTH);
		janela.setSize(200, 200);
		janela.setLocationRelativeTo(null);
		janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		janela.setVisible(true);
	}
     
}
A

Ajudou sim! Mas, como eu falei, eu to usando o netBeans e tem algumas funcionalidades dele que eu queria usar junto com isso. O grande problema é que ele nao cria o jpanel da meneira convencional (new jpanel). Se vc conseguir fazer isso utilizando o codigo que eu postei, que o netbeans gera, eu agradeceria!!

F
Usando o código do netBeans que você me passou deu pra fazer isso:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CriaQuadrado.java
 *
 * Created on 09/07/2009, 21:22:21
 */

package testes;

import javax.swing.JPanel;

/**
 *
 * @author Administrador
 */
public class CriaQuadrado extends javax.swing.JFrame {

    /** Creates new form CriaQuadrado */
    public CriaQuadrado() {
        initComponents();
    }

    /** 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")
    // &lt;editor-fold defaultstate="collapsed" desc="Generated Code"&gt;
    private void initComponents() {
    	
        jButton1 = new javax.swing.JButton();
        

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(327, Short.MAX_VALUE)
                .addComponent(jButton1))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jButton1)
                .addContainerGap(277, Short.MAX_VALUE))
        );
        pack();
    }// &lt;/editor-fold&gt;

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        this.getContentPane().getGraphics().drawRect((int)(Math.random()*50), (int)(Math.random()*50), (int)(Math.random()*50), (int)(Math.random()*50));
    }

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

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    // End of variables declaration

}
não sei se tem outro jeito melhor pois não uso o netBeans uso o eclipse
A

Cara!!! Era isso mesmo! MUITO OBRIGADO!!! VLW MESMO!!!

Criado 9 de julho de 2009
Ultima resposta 11 de jul. de 2009
Respostas 4
Participantes 2