Jump to content

Dúvida (básica) sobre Java


zephirus

Recommended Posts

Olá,

Estou a iniciar-me no java e apesar de já conseguir fazer algumas coisas, continuo a ter algumas dúvidas que me parecem básicas. Uma delas é a que coloco aqui. Se alguém me puder ajudar, agradecia.

Tenho uma janela com um botão (jButton) e ao carregar nesse botão, quero correr o código para gerar combinações de letras. O source code arranjei-o na internet.

CombinationGenerator.java

import java.math.BigInteger;
public class CombinationGenerator {
private int[] a;
private int n;
private int r;
private BigInteger numLeft;
private BigInteger total;
//------------
// Constructor
//------------
public CombinationGenerator (int n, int r) {
 if (r > n) {
	 throw new IllegalArgumentException ();
 }
 if (n < 1) {
	 throw new IllegalArgumentException ();
 }
 this.n = n;
 this.r = r;
 a = new int[r];
 BigInteger nFact = getFactorial (n);
 BigInteger rFact = getFactorial (r);
 BigInteger nminusrFact = getFactorial (n - r);
 total = nFact.divide (rFact.multiply (nminusrFact));
 reset ();
}
//------
// Reset
//------
public void reset () {
 for (int i = 0; i < a.length; i++) {
	 a[i] = i;
 }
 numLeft = new BigInteger (total.toString ());
}
//------------------------------------------------
// Return number of combinations not yet generated
//------------------------------------------------
public BigInteger getNumLeft () {
 return numLeft;
}
//-----------------------------
// Are there more combinations?
//-----------------------------
public boolean hasMore () {
 return numLeft.compareTo (BigInteger.ZERO) == 1;
}
//------------------------------------
// Return total number of combinations
//------------------------------------
public BigInteger getTotal () {
 return total;
}
//------------------
// Compute factorial
//------------------
private static BigInteger getFactorial (int n) {
 BigInteger fact = BigInteger.ONE;
 for (int i = n; i > 1; i--) {
	 fact = fact.multiply (new BigInteger (Integer.toString (i)));
 }
 return fact;
}
//--------------------------------------------------------
// Generate next combination (algorithm from Rosen p. 286)
//--------------------------------------------------------
public int[] getNext () {
 if (numLeft.equals (total)) {
	 numLeft = numLeft.subtract (BigInteger.ONE);
	 return a;
 }
 int i = r - 1;
 while (a[i] == n - r + i) {
	 i--;
 }
 a[i] = a[i] + 1;
 for (int j = i + 1; j < r; j++) {
	 a[j] = a[i] + j - i;
 }
 numLeft = numLeft.subtract (BigInteger.ONE);
 return a;
}
}
 

test.java

public class test {

/** Creates a new instance of test */
public test() {
}
/**
	* @param args the command line arguments
	*/
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "test");
	String[] elements = {"a","b","c","d","e"};
int[] indices;
CombinationGenerator x = new CombinationGenerator (elements.length, 2);
StringBuffer combination;
while (x.hasMore ()) {
combination = new StringBuffer ();
indices = x.getNext ();
for (int i = 0; i < indices.length; i++) {
combination.append (elements[indices[i]]);
}
System.out.println (combination.toString ());
}
}
}
 

E depois tenho o meu gui com um botão...

mainwindow.java

import javax.swing.JOptionPane;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
*/
public class mainwindow extends javax.swing.JFrame {
/**
 * Creates new form mainwindow
 */
public mainwindow() {
	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")


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {										
	JOptionPane.showMessageDialog(null, "Carreguei no botão");
	//<---- Código para chamar test.java ?!?!?!
}									  

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
	/*
	 * Set the Nimbus look and feel
	 */

	/*
	 * Create and display the form
	 */
	java.awt.EventQueue.invokeLater(new Runnable() {
		public void run() {
			new mainwindow().setVisible(true);
		}
	});
}
// Variables declaration - do not modify					
private javax.swing.JButton jButton1;
// End of variables declaration				  
}
 

Se correr o programa a partir do test.java, tudo funciona bem. Mas eu quero correr esse test.java quando clico no botão. Como é que faço isso??? Obrigado.

Link to comment
Share on other sites

Eu nao percebi bem algumas coisas no teu código incluindo 2 main's...

- 1º se queres dispultar uma acçao ao clicar num botao podes usar um ActionListener(Ve no google como usar);

- 2º A tua interface nao parece ter cido feita por ti, parece que usas-te um gerador de interface grafica como a disponiblizada pelo netbeans. Isso faz com que nao entendas o codigo que estas a escrever. Por outro lado ou eventos sao muitos faceis de usar nesse gerador é so clicares 2 vezes sobre o JButton e ele mostra-te o metodo que executa quando clicas no JButton, e podes meter la dentro o código que "gerador de combinações"

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.