Visualizzazione dei risultati da 1 a 7 su 7
  1. #1

    [JAVA] GridBagLayout e JButton

    Ciao a tutti!!
    Sto cercando di scrivere un GridBagLayout per una calcolatrice, ma mi trovo in difficoltà... non riesco a capire dove sbaglio esattamente! Se qualcuno ci capisce qualcosa da una mano anche a me a capirci qualcosa?
    codice:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.JFrame;
    
    public class Calcola {
        final static boolean shouldFill = true;
        final static boolean shouldWeightX = true;
        final static boolean RIGHT_TO_LEFT = false;
    
        public static void addComponentsToPane(Container pane) {
            if (RIGHT_TO_LEFT) {
                pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
            }
    
    //	JButton button;
    
    	pane.setLayout(new GridBagLayout());
    	GridBagConstraints c = new GridBagConstraints();
    
    	button = new JButton[15];
    
    	String[] nomeBottone = {"1", "2", "3", "4", "5", "6", "7", "8",
    				"9", "0", "+", "-", "*", "/", ".", "="};
    
    	for (int i = 0; i < button.length; i++) {
    	    button[i] = new JButton(nomeBottone[i]);
    	    c.add(bott[i]);}
    
    	if (shouldFill) {
    	c.fill = GridBagConstraints.HORIZONTAL;
    	}
    
    //	button = new JButton("2");
    	c.fill = GridBagConstraints.HORIZONTAL;
    	c.ipadx = 40;      //larghezza del componente
    	c.weightx = 0.5;
    	c.insets = new Insets(5,0,0,0);
    	c.gridx = 1;
    	c.gridy = 1;
    	pane.add(button("2"), c);
    
    //	button = new JButton("1");
    	if (shouldWeightX) {
    	c.weightx = 0.5;
    	}
    	c.fill = GridBagConstraints.HORIZONTAL;
    	c.ipadx = 40;      //larghezza del componente
    	c.insets = new Insets(5,5,0,0);
    	c.gridx = 0;
    	c.gridy = 1;
    	pane.add(button("1"), c);
    
    //	button = new JButton("3");
    	c.fill = GridBagConstraints.HORIZONTAL;
    	c.ipadx = 40;      //larghezza del componente
    	c.weightx = 0.5;
    	c.insets = new Insets(5,0,0,5);
    	c.gridx = 2;
    	c.gridy = 1;
    	pane.add(button("3"), c);
    
    //	button = new JButton("4");
    	c.fill = GridBagConstraints.HORIZONTAL;
    	c.weightx = 0.5;
    	c.insets = new Insets(0,5,0,0);
    	c.gridx = 0;
    	c.gridy = 2;
    	pane.add(button("4"), c);
    
    //	button = new JButton("5");
    	c.fill = GridBagConstraints.HORIZONTAL;
    	c.weightx = 0.5;
    	c.insets = new Insets(0,0,0,0);
    	c.gridx = 1;
    	c.gridy = 2;
    	pane.add(button("5"), c);
    
    //	button = new JButton("6");
    	c.fill = GridBagConstraints.HORIZONTAL;
    	c.weightx = 0.5;
    	c.insets = new Insets(0,0,0,5);
    	c.gridx = 2;
    	c.gridy = 2;
    	pane.add(button("6"), c);
    
    //	button = new JButton("7");
    	c.fill = GridBagConstraints.HORIZONTAL;
    	c.weightx = 0.5;
    	c.insets = new Insets(0,5,0,0);
    	c.gridx = 0;
    	c.gridy = 3;
    	pane.add(button("7"), c);
    
    //	button = new JButton("8");
    	c.fill = GridBagConstraints.HORIZONTAL;
    	c.weightx = 0.5;
    	c.insets = new Insets(0,0,0,0);
    	c.gridx = 1;
    	c.gridy = 3;
    	pane.add(button("8"), c);
    
    //	button = new JButton("9");
    	c.fill = GridBagConstraints.HORIZONTAL;
    	c.weightx = 0.5;
    	c.insets = new Insets(0,0,0,5);
    	c.gridx = 2;	//Colonne
    	c.gridy = 3;	//Righe
    	pane.add(button("9"), c);
    
    //	button = new JButton("+");
    	c.fill = GridBagConstraints.HORIZONTAL;
    	c.weightx = 0.5;
    	c.insets = new Insets(0,5,0,0);
    	c.gridx = 0;
    	c.gridy = 4;
    	pane.add(button("+"), c);
    
    //	button = new JButton("0");
    	c.fill = GridBagConstraints.HORIZONTAL;
    	c.weightx = 0.5;
    	c.insets = new Insets(0,0,0,0);
    	c.gridx = 1;
    	c.gridy = 4;
    	pane.add(button("0"), c);
    
    //	button = new JButton("-");
    	c.fill = GridBagConstraints.HORIZONTAL;
    	c.weightx = 0.5;
    	c.insets = new Insets(0,0,0,5);
    	c.gridx = 2;	//Colonne
    	c.gridy = 4;	//Righe
    	pane.add(button("-"), c);
    
    //	button = new JButton("*");
    	c.fill = GridBagConstraints.HORIZONTAL;
    	c.weightx = 0.5;
    	c.insets = new Insets(0,5,0,0);
    	c.gridx = 0;
    	c.gridy = 5;
    	pane.add(button("*"), c);
    
    //	button = new JButton("/");
    	c.fill = GridBagConstraints.HORIZONTAL;
    	c.weightx = 0.5;
    	c.insets = new Insets(0,0,0,0);
    	c.gridx = 1;
    	c.gridy = 5;
    	pane.add(button("/"), c);
    
    //	button = new JButton(".");
    	c.fill = GridBagConstraints.HORIZONTAL;
    	c.weightx = 0.5;
    	c.insets = new Insets(0,0,0,5);
    	c.gridx = 2;	//Colonne
    	c.gridy = 5;	//Righe
    	pane.add(button("."), c);
    
    //	Display della calcolatrice:
    	JTextField finestrino = new JTextField(10);
    	c.fill = GridBagConstraints.HORIZONTAL;
    	c.ipady = 40;      //Altezza del componente
    	c.insets = new Insets(5,5,0,5);
    	c.weightx = 0.0;
    	c.gridwidth = 3;//lungo 3 colonne
    	c.gridx = 0;
    	c.gridy = 0;
    	pane.add(finestrino, c);
    
    //	button = new JButton("=");
    	c.fill = GridBagConstraints.VERTICAL;
    	c.ipadx = 20;      //larghezza del componente
    	c.gridheight = 5;
    	c.weightx = 0.5;
    	c.insets = new Insets(5,0,0,5);
    	c.gridx = 3;
    	c.gridy = 1;
    	pane.add(button("="), c);
    	}
    
        private static void createAndShowGUI() {
            //Crea e mostra la window.
            JFrame frame = new JFrame("Calcolatrice");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            //Seta il content pane.
            addComponentsToPane(frame.getContentPane());
    
            //Mostro la window.
            frame.pack();
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
        }
    }
    Grazie!!
    Gato

  2. #2
    Utente di HTML.it
    Registrato dal
    Aug 2002
    Messaggi
    8,013
    C'è un po' tutto da rivedere, a partire dalla gestione degli array.
    <´¯)(¯`¤._)(¯`»ANDREA«´¯)(_.¤´¯)(¯`>
    "The answer to your question is: welcome to tomorrow"

  3. #3
    Ciao, grazie per la risposta!!
    Ok,so di aver sbagliato qualcosa anche nella dichiarazione dei JButton,ma non capisco cosa, di conseguenza l'Array, l'assegnazione dei nomi e quindi i posizionamenti...quindi,probabilmente se riesco a capire cosa sbaglio nella dichiarazione dei JButton riesco a risolvere anche il resto...
    Gato

  4. #4
    Utente di HTML.it
    Registrato dal
    Aug 2002
    Messaggi
    8,013
    non dichiari button come array, quindi già lì non dovrebbe compilare (non l'ho nemmeno provato a dire il vero)

    codice:
    JButton[] button = new JButton[15];
    GridBagConstraints non mi risulta avere un metodo add e comunque nel ciclo for provi a fare
    c.add(bott[i]), ma bott[i] non esiste, semmai dovrebbe essere add(button[i])

    Poi più sotto, improvvisamente, button da array di JButton diventa un JButton!

    Vado ad intuito: hai copiato un pezzo di codice da qualche parte ed hai provato a modificarlo senza minimamente intendere che cosa facesse.

    Consiglio: butta tutto e ricomincia da zero. Tutto quello che ti serve è nella documentazione di GridBagLayout nel tutorial su swing che trovi sul sito ufficiale (se cerchi con "The Swing Tutorial" salta fuori immediatamente)
    <´¯)(¯`¤._)(¯`»ANDREA«´¯)(_.¤´¯)(¯`>
    "The answer to your question is: welcome to tomorrow"

  5. #5
    Più che altro ho usato un layout che avevo già tentando di cambiare alcune cose, ma a questo punto credo di aver fatto più casino che altro..
    Grazie del consiglio, vado a leggermi il tutorial!!
    Gato

  6. #6
    Originariamente inviato da fpertegato
    Più che altro ho usato un layout che avevo già tentando di cambiare alcune cose...
    Layout copiato pari pari dal tutorial del GridBagLayout QUI

    Prova così:

    codice:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.JFrame;
    
    public class Calcola {
    
    	private static GridBagConstraints setConstraints(GridBagConstraints c, int fill, int ipadx, 
    double weightx, int gridx, int gridy, Insets insets) {
    		c.fill = fill;
    		c.ipadx = ipadx;
    		c.weightx = weightx;
    		c.insets = insets;
    		c.gridx = gridx;
    		c.gridy = gridy;
    		return c;
    	}
    	
    	public static void addComponentsToPane(Container pane) {
    		pane.setLayout(new GridBagLayout());
    		GridBagConstraints c = new GridBagConstraints();
    
    		JButton[] buttons = new JButton[16];
    
    		String[] nomeBottone = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "+", "-", "*", "/", ".", "="};
    
    		for (int i = 0; i < buttons.length; i++) {
    			buttons[i] = new JButton(nomeBottone[i]);
    		}
    
    		pane.add(buttons[0], setConstraints(c, GridBagConstraints.HORIZONTAL, 40, 0.5, 0, 1, new Insets(5, 5, 0, 0)));
    		pane.add(buttons[1], setConstraints(c, GridBagConstraints.HORIZONTAL, 40, 0.5, 1, 1, new Insets(5, 0, 0, 0)));
    		pane.add(buttons[2], setConstraints(c, GridBagConstraints.HORIZONTAL, 40, 0.5, 2, 1, new Insets(5, 0, 0, 5)));
    		pane.add(buttons[3], setConstraints(c, GridBagConstraints.HORIZONTAL, 40, 0.5, 0, 2, new Insets(0, 5, 0, 0)));
    		pane.add(buttons[4], setConstraints(c, GridBagConstraints.HORIZONTAL, 40, 0.5, 1, 2, new Insets(0, 0, 0, 0)));
    		pane.add(buttons[5], setConstraints(c, GridBagConstraints.HORIZONTAL, 40, 0.5, 2, 2, new Insets(0, 0, 0, 5)));
    		pane.add(buttons[6], setConstraints(c, GridBagConstraints.HORIZONTAL, 40, 0.5, 0, 3, new Insets(0, 5, 0, 0)));
    		pane.add(buttons[7], setConstraints(c, GridBagConstraints.HORIZONTAL, 40, 0.5, 1, 3, new Insets(0, 0, 0, 0)));
    		pane.add(buttons[8], setConstraints(c, GridBagConstraints.HORIZONTAL, 40, 0.5, 2, 3, new Insets(0, 0, 0, 5)));
    		pane.add(buttons[9], setConstraints(c, GridBagConstraints.HORIZONTAL, 40, 0.5, 0, 4, new Insets(0, 5, 0, 0)));
    		pane.add(buttons[10], setConstraints(c, GridBagConstraints.HORIZONTAL, 40, 0.5, 1, 4, new Insets(0, 0, 0, 0)));
    		pane.add(buttons[11], setConstraints(c, GridBagConstraints.HORIZONTAL, 40, 0.5, 2, 4, new Insets(0, 0, 0, 5)));
    		pane.add(buttons[12], setConstraints(c, GridBagConstraints.HORIZONTAL, 40, 0.5, 0, 5, new Insets(0, 5, 0, 0)));
    		pane.add(buttons[13], setConstraints(c, GridBagConstraints.HORIZONTAL, 40, 0.5, 1, 5, new Insets(0, 0, 0, 0)));
    		pane.add(buttons[14], setConstraints(c, GridBagConstraints.HORIZONTAL, 40, 0.5, 2, 5, new Insets(0, 0, 0, 5)));
    
    		JTextField finestrino = new JTextField(10);
    		c = setConstraints(c, GridBagConstraints.HORIZONTAL, 40, 0.0, 0, 0, new Insets(5, 5, 0, 5));
    		c.ipady = 40;
    		c.gridwidth = 3;
    		pane.add(finestrino, c);
    
    		c = setConstraints(c, GridBagConstraints.VERTICAL, 40, 0.5, 3, 1, new Insets(5, 0, 0, 5));
    		c.ipadx = 20;
    		c.gridheight = 5;
    		pane.add(buttons[15], c);
    }
    
    	private static void createAndShowGUI() {
    		JFrame frame = new JFrame("Calcolatrice");
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    		addComponentsToPane(frame.getContentPane());
    
    		frame.pack();
    		frame.setVisible(true);
    	}
    
    	public static void main(String[] args) {
    		javax.swing.SwingUtilities.invokeLater(new Runnable() {
    			public void run() {
    				createAndShowGUI();
    			}
    		});
    	}
    }
    ma ti consiglio di capire ciò che stai facendo piuttosto che copiare alla cieca codice già fatto. Non è il modo di imparare questo, va bene anche il copia e incolla, che personalmente detesto, ma almeno fatto con cognizione di causa.
    "Mai discutere con un idiota. Ti trascina al suo livello e ti batte con l'esperienza." (Oscar Wilde)

  7. #7
    Ti ringrazio per l'illuminazione satifal!
    Anchio odio il copia-incolla, anche se a volte per capire alcuni codici mi tocca usarlo(essendo un neonato in java a volte per capire certe cose uso una sorta di "metodo scientifico")...anche perchè, e prendo ad esempio il GridBagLayout, alcune cose in internet son spiegate davvero male (a volte perchè sono ostiche da spiegare e capire, a volte perchè alcuni articoli son scritti coi piedi).
    Fatalità, quel codice l'ho trovato all'interno di una cartella nel pc (che non è il mio, uso quello della postazione lavorativa). Ora, può anche essere che sia stato scaricato da qualcuno che voleva capire il GridBagLayout (usarlo mi sembra impossibile ora che l'ho capito), io l'ho usato per quel motivo: CAPIRE.
    Ti faccio un esempio: ieri solo CONFRONTANDO il codice che hai postato con quello che avevo precedentemente ho capito:
    -dove avevo sbagliato
    -parecchie cose dei GridBagConstraints
    -assodate alcune cose dei GridBagLayout
    -ho "ripassato" gli Array
    -e altro...

    In altre parole, ed in tutta cordialità:
    Capisco il tuo odio per il copia incolla (e lo condivido, immaginiamo se qualcuno lo usasse per clonare un programma, cambiare poche cose e "farlo suo"...poco carino!!), ma ti porto a ragionare: questo è un forum fatto perchè non tutti siamo allo stesso livello in java, proprio per questo ci aiutiamo giusto? Personalmente, non vedo l'ora di essere all'altezza di aiutare qualcuno, se poi vorrà copia-incollare un codice che avrò postato io ben venga, chissà che lo aiuti a capire qualcosa, per java e nella vita.
    Scusate questo post, probabilmente sembra che io mi stia arrampicando sugli specchi, ma io la vedo così...
    Gato

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.