when I execute this segment of code it displays a grid of buttons out of which only the one at the bottom corner of the grid works while others do not. When you click on a button it will turn green meaning it's selected and if you click on it again it will become white meaning deselected. I want to make a cinema theater seat booking system in which the user will select their own seat. I cant figure out why the others aren't working.
Can anyone help me out?
import javax.swing.*;
import java.io.IOException;
import java.awt.image.BufferedImage;
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import javax.swing.border.LineBorder;
import javax.swing.border.Border;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import java.io.File;
class cinemaSeats extends JFrame implements ActionListener {
private JButton[] bt = new JButton[1];
static int c=4;
static int k=5;
public cinemaSeats() throws IOException{
this.setSize(100, 100);
this.setLayout(null);
for(int s=0;s<=10;s++,k+=30)
{
c=4;
for(int j=1;j<=10;j++,c+=30)
{
for (int i = 0; i < bt.length; i++) {
bt[i] = new JButton("");
this.add(bt[i]);
bt[i].setBackground(Color.WHITE);
bt[i].addActionListener(this);
bt[i].setBounds(c,k,30,30);
}
}
}
this.setVisible(true);
this.pack();
this.setSize(new Dimension(3400,735));
}
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < bt.length; i++) {
if (e.getSource() == bt[i]) {
if(bt[i].getBackground() == Color.GREEN){
bt[i].setBackground(Color.WHITE);
}else if(bt[i].getBackground() == Color.WHITE){
bt[i].setBackground(Color.GREEN);
}else{
bt[i].setBackground(Color.WHITE);
}
}
}
}
}
public class cinemaSeat1 {
public static void main()throws IOException {
cinemaSeats bcts = new cinemaSeats();
}
}
Your bt array has length 1. Even though you're creating multiple JButton you keep a reference only to one of them (the last one created).
Because of that, when you get to actionPerformed the if (e.getSource() == bt[i]) condition will be true only when the last button created is pressed.
You will have to keep references to all the buttons or you could do something like this:
public void actionPerformed(ActionEvent e) {
JButton pressedButton = (JButton)e.getSource();
if(pressedButton.getBackground() == Color.GREEN){
pressedButton.setBackground(Color.WHITE);
}else if(pressedButton.getBackground() == Color.WHITE){
pressedButton.setBackground(Color.GREEN);
}else{
pressedButton.setBackground(Color.WHITE);
}
}
Related
I'm trying to move a Robot represented by a JLabel into a GridLayout.
The move is made but the display of the JLabel is only done for the final finishing square.
I would like to see the move from box to box. How can I do ?
import java.awt.Color;
import java.awt.Component;
import java.awt.LayoutManager;
import java.io.Serializable;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.LayoutStyle;
// Robot
public class Robot extends Case implements Serializable {
private ImageIcon imageRobot;
private Color couleur;
public Robot () {
imageRobot = new ImageIcon("./assets/balle.png");
setIcon(imageRobot);
}
public void seDeplacer (JPanel panel, Vector<Case> listeDeCases) {
for (int i=0; i<5; i++) {
LayoutManager layout = panel.getLayout();
try { Thread.sleep(1000);
panel.remove(panel.getComponent(i));
panel.add(this, i);
panel.doLayout();
}
catch (InterruptedException e) {}
}
}
public void detruire () {
}
public void setCouleur (Color couleur) {
this.couleur=couleur;
}
public Color getCouleur () {
return this.couleur;
}
}
try { Thread.sleep(1000);
Don't do this on the AWT Event Dispatch Thread (EDT). Your GUI can't be repainted because this code is blocking it.
Use javax.swing.Timer (not to be confused with any other Timer) to set an event for the next time robot needs to be moved. You will need to keep track of state outside of local variables.
import java.awt.Color;
import java.awt.Component;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Serializable;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.LayoutStyle;
import javax.swing.Timer;
// Robot
public class Robot extends Case implements Serializable {
private ImageIcon imageRobot;
private Color couleur;
public Robot () {
imageRobot = new ImageIcon("./assets/balle.png");
setIcon(imageRobot);
}
public void seDeplacer (JPanel panel) {
Robot currentRoot = this;
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
for (int i=0; i<5; i++) {
panel.remove(panel.getComponent(i));
panel.add(currentRoot, i);
panel.doLayout();
}
}
};
new Timer(delay, taskPerformer).start();
}
public void detruire () {
}
public void setCouleur (Color couleur) {
this.couleur=couleur;
}
public Color getCouleur () {
return this.couleur;
}
}
My program compiles fine, but my console spits out the following:
----jGRASP exec: javac -g CreditGraphics.java
Note: CreditGraphics.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
----jGRASP: operation complete.
First, what makes an operation unsafe? And how can a process be "unchecked"? What does "Recompile with -Xlint" mean? I'm using jGrasp and I'm not sure if that's a button or some sort of command? I want to see the details. It doesn't specify what is unsafe or unchecked, but here's my code anyway:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import java.util.Scanner;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.event.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.util.Properties;
import javax.mail.Header;
import java.util.Enumeration;
import java.util.Properties;
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.JApplet;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Header;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.URLName;
import java.beans.*;
import java.util.ArrayList;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.*;
import java.util.Scanner;
import java.awt.image.*;
import java.io.*;
import java.net.URL;
import javax.imageio.*;
import javax.swing.Timer;
public class CreditGraphics {
//first screen variables
public String cardNum;
public JFrame frame;
public JPanel panel;
public JLabel label;
public JTextField text;
public String cardType = "";
public String carddigits;
public boolean cardValid;
public int length;
public String[] cardTypes;
public JComboBox cardTypesDD;
public static ArrayList<Integer> holdDigits = new ArrayList<Integer>();
public static ArrayList<String> holdDigitsChar = new ArrayList<String>();
public static int[] checkDigits;
public static int checkSum = 0;
//second screen variables in verifyScreen;
public JFrame vframe;
public JPanel vpanel;
public JLabel titlelabel;
public GridBagConstraints grid;
public JLabel namelabel;
public JTextField namefield;
public CreditGraphics() {
frame = new JFrame("MES Banking App");
panel = new JPanel();
label = new JLabel();
cardTypes = new String[4];
cardTypes[0] = "Visa";
cardTypes[1] = "American Express";
cardTypes[2] = "Master Card";
cardTypes[3] = "";
cardTypesDD = new JComboBox(cardTypes);
cardTypesDD.setSelectedIndex(3);
text = new JTextField(16);
panel.add(label);
panel.add(cardTypesDD);
panel.add(text);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setPreferredSize(new Dimension(500, 500));
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
label.setText("<html>Please enter your credit card <br> 'Master Card' 'Visa' or 'American Express'</html>");
text.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//after CC type is entered, prompt user to enter digits
carddigits = text.getText();//gets credit card number from jtextfield
length = carddigits.length();//sets length of card
validateCard(); //uses credit card number and length to determine if it matches up to brand
//below returns if card is valid
if (cardValid == true) {
label.setText("Card brand is valid");
}
waits(1);
text.setText("");
waits(1);
checkDigits();
}
});
cardTypesDD.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
//where program really starts
while (cardTypesDD.getSelectedIndex() == 3) {
label.setText("First, please select a card type from DD list");
}
cardType = (String) cardTypesDD.getSelectedItem();
System.out.println(cardType);
if (!cardType.equals("")) {
label.setText("Thank you, now please enter your card #");
}
//now go to the jtextfield actionlistener
}});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
new CreditGraphics();
}});
}
public void verifyScreen() {
//destroy old frame
frame.dispose();
//create new frame essentially same as last frame
vframe = new JFrame("MES Banking App");
vpanel = new JPanel();
titlelabel = new JLabel("Verification Page");
namelabel = new JLabel("Name: ");
namefield = new JTextField(20);
//title section
vpanel.setLayout(new GridBagLayout());
grid = new GridBagConstraints();
grid.fill = GridBagConstraints.PAGE_START;
grid.weightx = 0;
grid.gridx = 0;
grid.gridy = 0;
vpanel.add(titlelabel, grid);
//name section
grid.gridy = 1;
grid.insets = new Insets(10, 0, 0, 0);
vpanel.add(namelabel, grid);
grid.gridx = 1;
grid.insets = new Insets(10, 10, 0, 0);
vpanel.add(namefield, grid);
vframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
vframe.getContentPane().add(vpanel);
vframe.pack();
vframe.setVisible(true);
}
public static void waits(int k) {
long time0, time1;
time0 = System.currentTimeMillis();
do {
time1 = System.currentTimeMillis();
} while ((time1 - time0) < k * 1000);
}
public void validateCard() {
//check brand
cardValid = false;
if ((cardType.equals("Visa") && carddigits.substring(0, 1).equals("4")) && (length == 13 || length == 16)) {
label.setText("Thank you, next step");
cardValid = true;
}
if ((cardType.equals("Master Card")) && (carddigits.substring(0, 2).equals("51") || carddigits.substring(0, 2).equals("52") || carddigits.substring(0, 2).equals("53") || carddigits.substring(0, 2).equals("54") || carddigits.substring(0, 2).equals("55")) && (length == 16)) {
label.setText("Thank you, next step");
cardValid = true;
}
if ((cardType.equals("American Express") && carddigits.substring(0, 2).equals("37") && length == 15)) {
label.setText("Thank you, next step");
cardValid = true;
}
if (cardValid != true) {
System.out.println("ERROR");
label.setText("ERROR");
waits(2);
System.exit(0);
}
//end check
}
public void checkDigits() {
label.setText("Checking digits using Luhn's algorithm...");
waits(2);
//check digits
checkDigits = new int[length];
for (int i = 0; i < length; i++) {
checkDigits[i] = Integer.parseInt(carddigits.substring(i, i + 1));
//successfully puts digits into array
}
for (int e = length - 2; e >= 0; e -= 2) {
checkDigits[e] = 2 * checkDigits[e];
}
for (int d = 0; d < length; d++) {
holdDigitsChar.add(String.valueOf(checkDigits[d]));
}
for (int v = 0; v < length; v++) {
if (holdDigitsChar.get(v).length() == 2) {
holdDigits.add(Integer.parseInt(holdDigitsChar.get(v).substring(0, 1)));
holdDigits.add(Integer.parseInt(holdDigitsChar.get(v).substring(1, 2)));
} else {
holdDigits.add(Integer.parseInt(holdDigitsChar.get(v)));
}
}
for (int c = 0; c < holdDigits.size(); c++) {
checkSum += holdDigits.get(c);
}
System.out.println("Check sum:" + checkSum);
if (checkSum % 10 == 0) {
label.setText("Numbers check out, thank you");
waits(2);
verifyScreen();
} else {
System.out.println("ERROR");
System.exit(0);
}
}
}
This usually comes up if you're using collections or some other genericized object without generic parameters. For example:
List l = new ArrayList();
vs.
List<String> l = new ArrayList<>(); //or new ArrayList<String>(); in Java < 7
What this means is that the Java compiler cannot guarantee that you are using those collections in a type-safe way. For example, you should shove a String and an Integer into the ArrayList in the first scenario. At some point when you pull it out, there is a distinct possibility that you may attempt to cast the Integer instance into a String, which would result in a ClassCastException. You could, of course, be really, really, careful and not do this, but the compiler is simply alerting you to the fact that there is no way to guarantee what is inside that list.
To get rid of this warning, use the second method of instantiation. If you are sure that you can get away with this (in some instances it is possible because you can be sure what the collection will contain) you can use the #SuppressWarnings("unchecked") annotation.
I already checked this duplicate question and other similar ones and it didn't help. I am trying to add an png to a button when it is clicked. The program is a variable sized tic-tac-toe game for school.
Right now I have:
private ImageIcon X_MARK = new ImageIcon("x.png");
private ImageIcon O_MARK = new ImageIcon("o.gif");
private JButton[][] cells;
...
cells = new JButton[size][size];
JPanel board = new JPanel(new GridLayout(size, size));
board.setBorder(new LineBorder(Color.BLACK, 1));
ButtonListener listener = new ButtonListener();
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++) {
cells[i][j] = new JButton();
cells[i][j].addActionListener(listener);
board.add(cells[i][j]);
}
JFrame ttt = new JFrame();
ttt.add(board);
ttt.setTitle("Show GUI Components");
ttt.setSize(60*size, 60*size);
ttt.setLocation(0, 0);
ttt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ttt.setVisible(true);
...
class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
int i, j;
for (i = 0; i < size; i++)
for (j = 0; j < size; j++)
if (e.getSource() == cells[i][j]) {
if ((i + j) % 2 == 0) {
cells[i][j].setBackground(Color.GREEN);
cells[i][j].setIcon(X_MARK);
} else {
cells[i][j].setBackground(Color.CYAN);
cells[i][j].setIcon(O_MARK);
}
}
}
}
That is all the relevant code I think. I am using Eclipse and I have x.png and o.png in the src folder and the bin folder of the the project. I have also tried a couple of variants I have seen on SO and google searches like, new ImageIcon("C:/Users/BigBoy/workspace_1/EventDriven/src/x.png");, new ImageIcon("src/x.png");, and some other ones involving getClass().getResource among other things. I don't know what else to try. I know I've done this in the past and didn't have this much trouble.
I added .setBackground(Color.GREEN); just to make sure my clicks were registering properly and they are, the problem to me seems to be with the declaring/initializing of the ImageIcon.
NOTE: Right now my button listener just makes the checker board pattern, I will get to actually putting each player's mark after I figure out this icon problem.
You need to understand resources which is what you will want to use. They are located relative to the class files. If the images are with the class files, then
get your image as a resource
Create an ImageIcon from the Image.
i.e., something like:
package whateverpackeyouareusing;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class DefaultFoo {
public static void main(String[] args) throws IOException {
String resource = "x.png";
URL url = Class.class.getResource(resource);
BufferedImage img = ImageIO.read(url);
Icon icon = new ImageIcon(img);
JOptionPane.showMessageDialog(null, icon);
}
}
Edit: A better example per Andrew Thompson:
package some.package;
import java.awt.Image;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class PlayWithImages {
public static final String X_RESOURCE = "x.png";
private Icon xIcon;
public PlayWithImages() throws IOException {
URL xImgUrl = getClass().getResource(X_RESOURCE);
Image xImg = ImageIO.read(xImgUrl);
xIcon = new ImageIcon(xImg);
}
public Icon getXIcon() {
return xIcon;
}
public static void main(String[] args) {
try {
PlayWithImages playWithImages = new PlayWithImages();
Icon xIcon = playWithImages.getXIcon();
JOptionPane.showMessageDialog(null, xIcon);
} catch (IOException e) {
e.printStackTrace();
}
}
}
only problem is that whenever i set initial value for the x and y to be greater than 10,it gives bad result.Please help.It works fine for the values less than 10 for x and y.
i have also debugged it and find out whenever the button is pressed after the 10th index it behaves like setting the variable i to 1.i am unable to fix this issue as i am new in java.so i really need help in this.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.JFrame;
class butMaddFrame extends JFrame implements ActionListener
{
int x=12;
int y=12;
JButton[][] buttons = new JButton[x][y];
JPanel mPanel = new JPanel();
JPanel bPanel = new JPanel();
JPanel cPanel = new JPanel();
JTextArea scoreKeeper = new JTextArea();
Container c = getContentPane();
int[][] intArray = new int[x][y];
public butMaddFrame()
{
butGen();
score2();
//cPanel.add(scoreKeeper);
bPanel.setLayout(new GridLayout(x,y));
mPanel.setLayout(new BorderLayout());
mPanel.add(bPanel, BorderLayout.CENTER);
// mPanel.add(cPanel, BorderLayout.LINE_END);
c.add(mPanel);
setTitle("ButtonMaddness");
setSize(1000,400);
setLocation(200,200);
setVisible(true);
}
private void butGen()
{
for(int i=0;i<x;i++)
for(int j=0;j<y;j++)
{
buttons[i][j] = new JButton(String.valueOf(i)+"x"+String.valueOf(j));
buttons[i][j].setActionCommand("button" +i +"_" +j);
buttons[i][j].addActionListener(this);
bPanel.add(buttons[i][j]);
}
}
private void score()
{
// String string = "";
// for(int i=0;i<x;i++)
// {
// for(int j=0;j<y;j++)
// string += i+"x"+j+" => " +String.valueOf(intArray[i][j]) +"\t";
// string+= "\n";
// }
// scoreKeeper.setText(string);
}
private void score2()
{
for(int i=0;i<x;i++)
for(int j=0;j<y;j++)
buttons[i][j].setText(String.valueOf(intArray[i][j]));
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().contains("button"))
{
int i = Integer.parseInt(Character.toString(e.getActionCommand().replaceAll("button","").replaceAll ("_", "").charAt(0)));
int j = Integer.parseInt(Character.toString(e.getActionCommand().replaceAll("button","").replaceAll ("_", "").charAt(1)));
intArray[i][j]++;
// buttons[i][j].setVisible(false);
buttons[i][j].setBackground(Color.black);
System.out.println(e.getActionCommand() +" " +i +" " +j);
}
// score2();
}
}
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
public class buttonMaddness {
public static void main(String[] args)
{
butMaddFrame myFrame = new butMaddFrame();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Your problem is here:
replaceAll("_", "").charAt(0)
because some of your buttons have things like 11_9 for
example. So you get just the first 1 of the number 11.
Just change your actionPerformed method
to this and your bug will be fixed.
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().contains("button")) {
String str = e.getActionCommand().replaceAll("button", "");
System.out.println(str);
String[] v = str.split("_");
int i = Integer.parseInt(v[0]);
int j = Integer.parseInt(v[1]);
/*
int i = Integer.parseInt(Character.toString(e.getActionCommand()
.replaceAll("button", "").replaceAll("_", "").charAt(0)));
int j = Integer.parseInt(Character.toString(e.getActionCommand()
.replaceAll("button", "").replaceAll("_", "").charAt(1)));
*/
intArray[i][j]++;
// buttons[i][j].setVisible(false);
buttons[i][j].setBackground(Color.black);
System.out.println(e.getActionCommand() + " " + i + " " + j);
}
// score2();
}
i only want one of the above button to be selected by default
but setSelected(true) is not working .
when i run the below program none of the JRadoiButton is selected
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RadioDemo implements ActionListener {
String buttonName;
JPanel radioPanel=new JPanel();
ButtonGroup group = new ButtonGroup();
Enumeration enl;
int result;
ActionEvent e;
JRadioButton birdButton[];
int i;
Vector<JComponent> list;
Vector<String> listName;
public RadioDemo(Vector<JComponent> list,Vector<String> listName,Enumeration en,Enumeration enl)
{
birdButton=new JRadioButton[list.size()];
this.enl=enl;
this.list=list;
this.listName=listName;
for(i=0;i<list.size()-1;i++)
{
buttonName=(String)enl.nextElement();
birdButton[i] = new JRadioButton(buttonName);
birdButton[i].setSelected(false);
birdButton[i].setActionCommand(buttonName);
group.add(birdButton[i]);
birdButton[i].addActionListener(this);
radioPanel.add(birdButton[i]);
}
buttonName=(String)enl.nextElement();
birdButton[i] = new JRadioButton(buttonName);
birdButton[i].setSelected(true);
birdButton[i].setActionCommand(buttonName);
group.add(birdButton[i]);
birdButton[i].addActionListener(this);
radioPanel.add(birdButton[i]);
radioPanel.setLayout(new BoxLayout(radioPanel,BoxLayout.Y_AXIS));
//birdButton.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
result = JOptionPane.showConfirmDialog(null, radioPanel,
"Please choose", JOptionPane.OK_CANCEL_OPTION);
show();
}
/** Listens to the radio buttons. */
public void actionPerformed(ActionEvent e)
{
this.e=e;
}
public void show()
{
if (result == JOptionPane.OK_OPTION)
{ i=0;
while(!birdButton[i].isSelected())
{
i++;
System.out.println(i);
}
//list.removeElementAt(i);
//listName.removeElementAt(i);
System.out.println(i);
System.out.println(e.getActionCommand());
}
}
i also try birdButton[0].setSelected(true);
out of loop
You haven't posted how you call your constructor, so maybe there is something there. I slightly modified your code, added a main method and it seems to work ok. Take a look at it:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
public class RadioDemo implements ActionListener {
String buttonName;
JPanel radioPanel = new JPanel();
ButtonGroup group = new ButtonGroup();
int result;
JRadioButton birdButton[];
Vector<String> listName;
private JRadioButton selectedButton;
public RadioDemo(Vector<String> listName) {
birdButton = new JRadioButton[listName.size()];
this.listName = listName;
int i = 0;
for (String buttonName : listName) {
birdButton[i] = new JRadioButton(buttonName);
if (i == 0) {
birdButton[i].setSelected(true);
selectedButton = birdButton[i];
}
birdButton[i].setActionCommand(buttonName);
group.add(birdButton[i]);
birdButton[i].addActionListener(this);
radioPanel.add(birdButton[i]);
i++;
}
radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.Y_AXIS));
// birdButton.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
result = JOptionPane.showConfirmDialog(null, radioPanel, "Please choose", JOptionPane.OK_CANCEL_OPTION);
show();
}
/** Listens to the radio buttons. */
#Override
public void actionPerformed(ActionEvent e) {
JRadioButton rb = (JRadioButton) e.getSource();
System.err.println(rb.getText() + " is selected");
selectedButton = rb;
}
public void show() {
if (result == JOptionPane.OK_OPTION) {
System.err.println(selectedButton.getText() + " is selected and approved");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Vector<String> buttonNames = new Vector<String>();
buttonNames.add("Show");
buttonNames.add("Something");
buttonNames.add("Else");
buttonNames.add("Beep");
new RadioDemo(buttonNames);
}
});
}
}