Mmm quasi, ti faccio vedere come deve essere senza le radiobutton. La parte relativa ai miei tentativi di inserimento
delle radiobutton è commentata.
Codice:
codice:
package Programma10;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
@SuppressWarnings("serial")
public class MyFrame extends JFrame implements ItemListener
{
JCheckBox uno = new JCheckBox("Viaggio A/R");
JCheckBox due = new JCheckBox("Pernottamento per 7 notti");
JCheckBox tre = new JCheckBox("Gita a Versailles");
JLabel etichetta = new JLabel("Totale:");
JTextField testo = new JTextField(10);
JRadioButton scelta1 = new JRadioButton("Aereo");
JRadioButton scelta2 = new JRadioButton("Treno");
Component rigid = Box.createRigidArea(new Dimension(150,0));
private final int COSTOVIAGGIO = 300000;
private final int COSTONOTTI = 840000;
private final int COSTOGITA = 120000;
int totale;
public MyFrame()
{
super("Finestra");
setSize(300,150);
testo.setEditable(false);
scelta1.setSelected(true);
//riferimento al container
Container c = getContentPane();
c.setLayout(new BorderLayout());
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
ButtonGroup gruppo = new ButtonGroup();
gruppo.add(scelta1);
gruppo.add(scelta2);
p1.setLayout(new BoxLayout(p1, BoxLayout.Y_AXIS));
//p2.setLayout(new BoxLayout(p2, BoxLayout.X_AXIS)); //per i bottoni a scelta esclusiva
p3.setLayout(new FlowLayout());
//Component rigid = Box.createRigidArea(new Dimension(140,0));
//Aggiunta dei bottoni
p1.add(uno);
//p1.add(p2);
p1.add(due);
p1.add(tre);
p2.add(rigid);
p2.add(scelta1);
p2.add(scelta2);
p3.add(etichetta);
p3.add(testo);
c.add(p1, BorderLayout.NORTH);
c.add(p3, BorderLayout.SOUTH);
uno.addItemListener(this);
due.addItemListener(this);
tre.addItemListener(this);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[]args)
{
MyFrame finestra = new MyFrame();
finestra.setVisible(true);
}
public void itemStateChanged(ItemEvent i)
{
int cifra = 0;
Object o = i.getSource();
if (o == uno)
{
cifra = COSTOVIAGGIO;
}
else if (o == due)
{
cifra = COSTONOTTI;
}
else if (o == tre)
{
cifra = COSTOGITA;
}
int x = i.getStateChange();
if (x == ItemEvent.SELECTED)
{
totale += cifra;
}
else if (x == ItemEvent.DESELECTED)
{
totale -= cifra;
}
testo.setText("" + totale);
}
}
Le radiobutton dovrebbero essere sotto la prima checkbox spostate un pò verso destra. Se provate a togliere i commenti, si ottengono le radiobutton attaccate a sinistra, e tutto il resto si centra.