Limit the number of selected JToggleButton - java

I'm new on swing java, I maked an array of jtoggle buttons and my problem is that I want to limit the number of selected(toggled) buttons for 4 toggled buttons. Is there any property that allows me to do that ?
Here is my code example.
package adad;
import java.awt.*; import java.awt.event.*;
import javax.swing.*;
public class essayer extends JFrame
{
private JToggleButton jb_essai[] = new JToggleButton[6];
JButton pressme = new JButton("Press Me");
essayer() // the frame constructor
{
super("Toggle boutons");
setBounds(100,100,300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = this.getContentPane();
JPanel pane = getContainer();
con.add(pane);
setVisible(true);
}
class ToggleAction implements ActionListener
{
private JToggleButton jb_essai[];
public ToggleAction(JToggleButton a_jb_essai[])
{
jb_essai = a_jb_essai;
}
public void actionPerformed(ActionEvent e)
{
String etatBoutons = "";
int size = jb_essai.length;
for(int i=0;i<size;i++)
{
String tmp = "Bouton "+(i+1)+" : ";
if(jb_essai[i].isSelected()==true )
{
tmp+="enfonce";
}
else
{
tmp+="relache";
}
tmp+="\n";
etatBoutons +=tmp;
}
System.out.println(etatBoutons+"\n---------");
}
}
private JPanel getContainer()
{
GridLayout thisLayout = new GridLayout(6,2);
JPanel container = new JPanel();
ToggleAction tga = new ToggleAction(jb_essai);
container.setLayout(thisLayout);
int j=6;
for (int i=0;i<j;i++)
{
String s = String.valueOf(i+1);
container.add(jb_essai[i]= new JToggleButton(s)); // actuellement tt s'affiche sur un même colone.
jb_essai[i].addActionListener(tga);
}
return container;
}
public static void main(String[] args) {new essayer();}
}

Is there any property that allows me to do that ?
No. There is a ButtonGroup that allows 'one of many'. But that is 1, not N of many. Anything beyond that you'll need to code yourself.

Is there any property that allows me to do that ?
No, you need to write your own code.
Add a common ItemListener to every toggle button. Then when a button is selected you loop though your toggle button array to count the number of selected toggle buttons.
If the count is greater than 4 then you display a JOptionPane with an error message and your reset the last selected button to be unselected. You can use the getSource() method of the ItemListener to get the toggle button.
Or maybe you can extend the ButtonGroup class to implement similar behaviour.

Related

Static variable and actionePerformed method?

I have a class called Windows. The class extends JFrame and adds GUI components to the JFrame container. One of those components is a JTextfield. I am trying to set the text in the JTextfield through the actionPerformed() when generator JButton is clicked. The actionPerformed() is a class called EvenHandler. This is the eventHandler:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class EventHandler implements ActionListener {
int x = 0;
PassWordGenerator password;
Window Window; // It works only when static Window Window.
public void start() {
Window = new Window();
}
#Override
public void actionPerformed(ActionEvent e) {
password = new PassWordGenerator(3,3,3,3);
Window.setGeneratedPswd(password.getPswd());
x += 1;
System.out.println(x);
}
public static void main(String[] args) {
EventHandler x = new EventHandler();
x.start();
}
}
the window class if you want to know how the GUI looks like. The button is the one calling actionePerfome().
import javax.swing.*;
import java.awt.*;
public class Window extends JFrame {
Label passwordLength;
Label labelGnPswd;
JTextField psdLength;
JCheckBox upperCase_letters;
JCheckBox lowerCase_letters;
JCheckBox numbers;
JCheckBox symbols;
JTextField generatedPswd;
EventHandler event = new EventHandler();
JButton generetor;
public Window() {
setLayout(new FlowLayout());
setTitle("PasswordGenerator");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
//Password Length
passwordLength = new Label("Password Length");
add(passwordLength);
//Input text
psdLength = new JTextField("0", 5);
add(psdLength);
//Create checkBoxes
createcheckbxs();
//Label Generated psw
labelGnPswd = new Label("Generated pswd");
add(labelGnPswd);
//Generated Password;
generatedPswd = new JTextField("****", 5);
generatedPswd.setEditable(false);
add(generatedPswd);
//Button
generetor = new JButton("Generate pswd!");
generetor.addActionListener(event);
add(generetor);
setSize(200, 400);
setVisible(true);
}
public String getpsdLength() {
return psdLength.getText();
}
public void setGeneratedPswd(String pswd) {
generatedPswd.setText(pswd);
}
private void createcheckbxs() {
upperCase_letters = new JCheckBox("Include uppercase");
add(upperCase_letters);
lowerCase_letters = new JCheckBox("Include lowercase");
add(lowerCase_letters);
numbers = new JCheckBox("Include numbers ");
add(numbers);
symbols = new JCheckBox("Include symbols ");
add(symbols);
}
}
My question is that When I clicked on the generator JButton I get an error message along the line, "Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException..." I debugged the actionPerformed() and I found out that the Window Window is null when actionPefromed() is called after clicking genetor Jbutton. Why is Window null? Int x is working fine and it is not null. Isn't var x and window the same varaible scope. The only way I could keep the value of Window not null was to make Window a static variable.I hope my problem is a little more clear. Thanks in advance
Your problem seems in this line in Window.java:
generetor.addActionListener(event);
Variable event is declared in Window.java:
EventHandler event = new EventHandler();
The problem is that on event start() is not called so its instance variable Window Window remains null. The EventHandler you instantiate in main() is not used. What you might do is delete your start method and put its contents in the constructor.

How to randomly select a button in a ButtonGroup of JRadioButtons?

I want to have a random radio button to be selected whenever this panel gets initialized, but I'm not sure how/if I can do that.
Is there a way to get a random button from the group and select it?
import javax.swing.*;
public class RandomPanel extends JPanel
{
private ButtonGroup buttonGroup;
private String[] buttonText =
{
"Red",
"Mashed Potatoes",
"Metal",
"Running",
"Butts",
"Turquoise"
};
public RandomPanel()
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setBorder(BorderFactory.createTitledBorder("Random Selections"));
buttonGroup = new ButtonGroup();
for (String text : buttonText)
{
JRadioButton option = new JRadioButton(text);
add(option);
button.add(option);
}
}
}
What you can do is keep a list/array of all the radio buttons you create, and then set the selected by using the button group's setSelected() method, something like this
buttonGroup.setSelected(buttonsArray[randomButtonNum].getModel(), true);
Try using the Randomclass .
// Library location
import java.util.Random;
//Inside some method
Random r = new Random();
randomIndex = r.nextInt(buttonText.length());
text = buttonText[randomIndex];
This will need arranging to suit your implementation, whats shown is a 'how-to' usage.
Note: the argument to nextInt(args) is exclusive. i.e. will return
0 <= x < args
I believe you are looking for something like the solution below.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.*;
public class RandomPanel extends JPanel
{
private ButtonGroup buttonGroup;
private String[] buttonText =
{
"Red",
"Mashed Potatoes",
"Metal",
"Running",
"Butts",
"Turquoise"
};
private JRadioButton[] radioButton;
Random r = new Random();
public RandomPanel()
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setBorder(BorderFactory.createTitledBorder("Random Selections"));
buttonGroup = new ButtonGroup();
radioButton = new JRadioButton[buttonText.length];
for(int rb=0; rb<buttonText.length; rb++)
{
radioButton[rb] = new JRadioButton(buttonText[rb]);
add(radioButton[rb]);
buttonGroup.add(radioButton[rb]);
}
JButton b = new JButton("Random");
b.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
selectRandomButton();
}
});
add(b);
}
public void selectRandomButton()
{
radioButton[r.nextInt(radioButton.length)].setSelected(true);
}
public static void main(String[] args)
{
JFrame f = new JFrame("Test Random Button");
f.setSize(300, 300);
f.setLocationRelativeTo(null);;
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new RandomPanel());
f.setVisible(true);;
}
}
I created a small method that allow me to set any radio group button. Very convenient if you don't want to use if for any radio button.
public void setButtonGroup(int rdValue, Enumeration elements ){
while (elements.hasMoreElements()){
AbstractButton button = (AbstractButton)elements.nextElement();
if(Integer.parseInt(button.getActionCommand())==rdValue){
button.setSelected(true);
}
}
}
then
setButtonGroup(randomIndex, yourButtonGroup.getElements());

Java - get JRadioButton cmd with Jbutton listener

I am new to java and creating a Simple gui App. In this simple app, I am trying to write a e-commerce letter for Firms. So, I planned my app something like this..
First i ask to user if he want to write an letter to British Firm or American. For this i use two radio buttons(one for american firm and second for british) and JButton. When user Trigger jbutton then i want to get radiobutton command(which type of letter user want to write).
The problem is I don't have any idea to get Radiobutton command when i trigger jButton. Please give me an Simple Idea(if possible with exapmle not complicated for begginers) to get RadioButtons value..
Here is my java Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class englet{
static public JFrame f;
static public JPanel p;
static class getTypeOfLetter implements ActionListener{
public void actionPerformed( ActionEvent e){
String btnInput = e.getActionCommand();
System.out.println(btnInput);
}
}
public static void askletter(){
JRadioButton btnRadio1;
JRadioButton btnRadio2;
ButtonGroup btngrp;
JButton btnGo = new JButton("Write");
btnRadio1 = new JRadioButton("Write Letter For American Firm");
btnRadio1.setActionCommand("Amer");
btnRadio2 = new JRadioButton("Write Letter For British Firm");
btnRadio2.setActionCommand("Brit");
btngrp = new ButtonGroup();
btnGo.setActionCommand("WriteTest");
btnGo.addActionListener(new getTypeOfLetter());
btngrp.add(btnRadio1);
btngrp.add(btnRadio2);
p.add(btnRadio1);
p.add(btnRadio2);
p.add(btnGo);
}
englet(){
f = new JFrame("English Letter");
p = new JPanel();
askletter();
f.add(p);
f.setSize(400,200);
f.setVisible(true);
}
public static void main (String[] argv ){
englet i = new englet();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I am using Notepad++ and CMD.. Not any another tools like netbeans initllli ecplisse.
**RE-EDIT ** I want a possible solution and can satisfy me.. this app works but i am not able to get radiobuttons commmand with jubtton..
You've got several issues:
Over-use of static. Most of the fields and methods of your code should be non-static
You're missing key fields that will be necessary to transmit the information needed. To get the selected JRadioButton, you need to make JRadioButton fields and check which is selected, or (and my preference), you need to make the ButtonGroup variable a field and check which JRadioButton has been selected based on the ButtonModel returned by the ButtonGroup.
You're currently using local variables and these won't be visible throughout the class, which is why either the JRadioButtons or the ButtonModel most be fields (declared in the class).
If you go with ButtonModel above, you must give each JRadioButton an appropriate actionCommand String.
For example:
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GetRadio extends JPanel {
private static final String[] FIRMS = {"American Firm", "British Firm"};
// You need this field to access it in your listener
private ButtonGroup buttonGroup = new ButtonGroup();
public GetRadio() {
// create JButton and add ActionListener
JButton button = new JButton("Select");
button.addActionListener(new ButtonListener());
// JPanel with a grid layout with one column and variable number of rows
JPanel radioButtonPanel = new JPanel(new GridLayout(0, 1));
radioButtonPanel.setBorder(BorderFactory.createTitledBorder("Select Firm")); // give it a title
for (String firm : FIRMS) {
// create radiobutton and set actionCommand
JRadioButton radioButton = new JRadioButton(firm);
radioButton.setActionCommand(firm);
// add to button group and JPanel
buttonGroup.add(radioButton);;
radioButtonPanel.add(radioButton);
}
// add stuff to main JPanel
add(radioButtonPanel);
add(button);
}
private class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// get button model of selected radio button from ButtonGroup
ButtonModel model = buttonGroup.getSelection();
// if null, no country selected
if (model == null) {
Component component = GetRadio.this;
String message = "You must first select a country!";
String title = "Error: No Country Selected";
int type = JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(component, message, title, type);
} else {
// valid country selected
String country = model.getActionCommand();
System.out.println("Letter to " + country);
}
}
}
private static void createAndShowGui() {
GetRadio mainPanel = new GetRadio();
JFrame frame = new JFrame("Get Radio Btn");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Change JTextArea texts from JButton's actionPerformed which is in another class

I have a fully functional console-based database which I need to add GUIs to. I have created a tab page (currently only one tab) with a button "Display All Student" which when triggered will display a list of students inside a JTextArea which of course is in its own class and not inside the button's action listener class. Problem is, the JTextArea is not recognised inside button's action listener. If I add parameter into the action listener, more errors arise. Help?
I have searched Stack Overflow for similar problems but when I tried it in my code, doesn't really do the trick? Or maybe I just need a nudge in the head. Anyways.
Here is my code so far:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class StudDatabase extends JFrame
{
private JTabbedPane tabbedPane;
private JPanel studentPanel;
private static Scanner input = new Scanner(System.in);
static int studentCount = 0;
static Student studentArray[] = new Student[500];
public StudDatabase()
{
setTitle("Student Database");
setSize(650, 500);
setBackground(Color.gray);
JPanel topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
getContentPane().add( topPanel );
// Create the tab pages
createStudentPage();
// more tabs later...
// Create a tab pane
tabbedPane = new JTabbedPane();
tabbedPane.addTab( "Student Admin", studentPanel );
topPanel.add( tabbedPane, BorderLayout.CENTER );
}
public void createStudentPage()
{
studentPanel = new JPanel();
studentPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
JButton listButton = new JButton("List All Student(s)");
listButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if(studentCount > 0)
{
for(int i=0; i<studentCount; i++)
{
// print out the details into JTextArea
// ERROR! textDisplay not recognised!!!
textDisplay.append("Student " + i);
}
System.out.printf("\n");
}
else // no record? display warning to user
{
System.out.printf("No data to display!\n\n");
}
}
});
studentPanel.add(listButton);
JTextArea textDisplay = new JTextArea(10,48);
textDisplay.setEditable(true); // set textArea non-editable
JScrollPane scroll = new JScrollPane(textDisplay);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
studentPanel.add(scroll);
}
public static void main(String[] args)
{
StudDatabase mainFrame = new StudDatabase();
mainFrame.setVisible(true);
}
Your code isn't working for the same reason this wouldn't work:
int j = i+5;
int i = 4;
You have to declare variables before using them in Java.
Secondly, in order to use a variable (local or instance) from inside an inner class - which is what your ActionListener is - you need to make it final.
So, the below code will compile and run:
final JTextArea textDisplay = new JTextArea(10,48);
...
listButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
...
textDisplay.append("Student " + i);

Java tabs in GUI

I am hoping someone can spoon feed me this solution. It is part of my major lab for the class, and it really isn't giving me too much since I just don understand how to make a GUI with tabs. I can make a regular program with some sort of GUI, but I've been searching and reading and can't put 2 and 2 because of the whole class part and declaring the private variables. So what I am asking is if someone can make me a main GUI with 5 tabs and put my code into 1 tab so I can learn and put the rest of my codes into the other 4 tabs. So I hope you don't think I want you to give me code when I have the code, I just don't really get the tabs, and we haven't gone over it in class. Here is the code with its own gui, I hope what I type makes sense. I learn code by seeing, and this will help me a bunch.
package landscape;
import javax.swing.*;
import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.*;
import java.text.DecimalFormat;
public class Landscape extends JFrame {
private JFrame mainFrame;
private JButton calculateButton;
private JButton exitButton;
private JTextField lengthField;
private JLabel lengthLabel;
private JTextField widthField;
private JLabel widthLabel;
private JTextField depthField;
private JLabel depthLabel;
private JTextField volumeField;
private JLabel volumeLabel;
private JRadioButton builtIn;
private JRadioButton above;
private JTabbedPane panel;
public Landscape()
{
JTabbedPane tabs=new JTabbedPane();
tabs.addTab("Pool", panel);//add a tab for the panel with the title "title"
//you can add more tabs in the same fashion - obviously you can change the title
//tabs.addTab("another tab", comp);//where comp is a Component that will occupy the tab
mainFrame.setContentPane(tabs);//the JFrame will now display the tabbed pane
mainFrame.setSize(265,200);
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
mainFrame.setResizable(false);
JPanel panel = new JPanel();//FlowLayout is default
//Pool
panel.setOpaque(false);//this tells the panel not to draw its background; looks nicer under LAFs where the background inside a tab is different from that of JPanel
panel.add(builtIn);
panel.add(above);
panel.add(lengthLabel);
panel.add(lengthField);
panel.add(widthLabel);
panel.add(widthField);
panel.add(depthLabel);
panel.add(depthField);
panel.add(volumeLabel);
panel.add(volumeField);
panel.add(calculateButton);
panel.add(exitButton);
//creating components
calculateButton = new JButton ("Calculate");
exitButton = new JButton ("Exit");
lengthField = new JTextField (5);
lengthLabel = new JLabel ("Enter the length of your pool: ");
widthField = new JTextField (5);
widthLabel = new JLabel ("Enter the width of your pool: ");
depthField = new JTextField (5);
depthLabel = new JLabel ("Enter the depth of your pool: ");
volumeField = new JTextField (5);
volumeLabel = new JLabel ("Volume of the pool: ");
//radio button
ButtonGroup buttonGroup = new ButtonGroup();
builtIn = new JRadioButton ("Built in");
buttonGroup.add(builtIn);
above = new JRadioButton ("Above");
buttonGroup.add(above);
exitButton.setMnemonic('x');
calculateButton.setMnemonic('C');
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{ System.exit(0); }
});
// create the handlers
calculateButtonHandler chandler = new calculateButtonHandler(); //instantiate new object
calculateButton.addActionListener(chandler); // add event listener
ExitButtonHandler ehandler = new ExitButtonHandler();
exitButton.addActionListener(ehandler);
FocusHandler fhandler = new FocusHandler();
lengthField.addFocusListener(fhandler);
widthField.addFocusListener(fhandler);
depthField.addFocusListener(fhandler);
}
class calculateButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
DecimalFormat num = new DecimalFormat(", ###.##");
double width;
double length;
double depth;
double volume;
double volume2;
double height;
String instring;
instring = lengthField.getText();
if (instring.equals(""))
{
instring = "0";
lengthField.setText("0");
}
length = Double.parseDouble(instring);
instring = widthField.getText();
if (instring.equals(""))
{
instring = "0";
widthField.setText("0");
}
width = Double.parseDouble(instring);
instring = depthField.getText();
if (instring.equals(""))
{
instring = "0";
depthField.setText("0");
}
depth = Double.parseDouble(instring);
volume = width * length * depth;
volumeField.setText(num.format(volume));
volume2 = width * length * depth;
}
}
class ExitButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
class FocusHandler implements FocusListener
{
public void focusGained(FocusEvent e)
{
if(e.getSource() == lengthField || e.getSource() == widthField || e.getSource() == depthField)
{
volumeField.setText("");
}
else if (e.getSource() == volumeField)
{
volumeField.setNextFocusableComponent(calculateButton);
calculateButton.grabFocus();
}
}
public void focusLost1(FocusEvent e)
{
if(e.getSource() == widthField)
{
widthField.setNextFocusableComponent(calculateButton);
}
}
public void focusLost(FocusEvent e)
{
if(e.getSource() == depthField)
{
depthField.setNextFocusableComponent(calculateButton);
}
}
}
public static void main(String args[])
{
Landscape app = new Landscape();
}
}
Instead of getting the content pane and adding to it, just create a new JPanel and add your stuff to that. Then, add the panel to a new JTabbedPane with whatever title you want, and set the content pane of the JFrame to be the tabbed pane.
Here is a simple example of what you would do:
JPanel panel=new JPanel();//FlowLayout is default
panel.setOpaque(false);//this tells the panel not to draw its background; looks nicer under LAFs where the background inside a tab is different from that of JPanel
panel.add(builtIn);
panel.add(above);
//...you get the picture; add all the stuff you already do, just use panel instead of c
JTabbedPane tabs=new JTabbedPane();
tabs.addTab("title", panel);//add a tab for the panel with the title "title"
//you can add more tabs in the same fashion - obviously you can change the title
tabs.addTab("another tab", comp);//where comp is a Component that will occupy the tab
mainFrame.setContentPane(tabs);//the JFrame will now display the tabbed pane
You can leave the rest of your code how it is and it should work fine.
The tutorial and its demo are pretty straight forward examples.

Categories

Resources