i have four JRatioButtons inside a ButtonGroup in Java. The two first are enabled and the other two are disabled. If one specific JRatioButton is selected i need to enable the two disabled JRatioButtons.
Im trying this to find the state of the buttons and enable the disabled ones, apparently i found the ones with the disable state but doesnt change that state.
private void activateButtons() {
Enumeration<AbstractButton> elements = myButtonGroup.getElements();
while (elements.hasMoreElements()) {
AbstractButton button = (AbstractButton)elements.nextElement();
if (button.isEnabled()) {
System.out.println("This button is disabled! The text of the button is: '" + button.getText() + "'");
button.setEnabled(true);
}
}
}
Im getting the text of the disabled buttons, but i cant disable them.
Any help? Thanks!
I don't know if you any problems in finding the reference of the radio buttons in the second group or you just cannot disable the radio buttons.
For the first question, it is simple, you just keep the reference of the radio buttons in the second group.
For the second question, you need to subclass a JRadioButton because I found you can not simply call disable for an object of radio button.
The code sample of the sub class would be like this.
this.editable = editable;
if (editable) {
this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
super.enableEvents(Event.MOUSE_DOWN | Event.MOUSE_UP);
} else {
this.setCursor(CursorFactory.createUnavailableCursor());
super.disableEvents(Event.MOUSE_DOWN | Event.MOUSE_UP);
}
Try this, it works.
AbstractButton button = ...
button.getModel().setEnabled(true/false)
Ya, you setEnabled(true) to an enabled RadioButton.
So here the edited, hope can help someone.
private void activateButtons()
{
Enumeration<AbstractButton> elements = myButtonGroup.getElements();
while (elements.hasMoreElements())
{
AbstractButton button = (AbstractButton)elements.nextElement();
if (button.isEnabled()) // if enabled (true)
{
System.out.println("This button is disabled! The text of the button is: '" + button.getText() + "'");
button.setEnabled(false); // set it disabled (false)
}
}
}
Thanks #Hannibal, your post saved my day.
Related
I need the same JButton to perform a different actions once it's clicked again. Like the first time I click the button, a text will appear in the first row of my JTextField, then the second time I click it, a text will appear in the second row if text field. How should I do it?
Here is my code BTW:
private void addActionPerformed(java.awt.event.ActionEvent evt) {
String items1 =(String)list.getSelectedItem();
String qty1 = qty.getText();
String price1 = price.getText();
int qty2 = Integer.parseInt(qty1);
int price2 = Integer.parseInt(price1);
if(evt.getSource() == add){
order1.setText(Integer.toString(qty2));
order2.setText(Integer.toString(price2));
order3.setText(items1);
}
I literally have no idea what to do next.
Here is the pic for the design GUI: http://prntscr.com/pfh96z
Take a Boolean isClickedOnce and change its state upon clicking on your button
private Boolean isClickedOnce = false;
//..
private void addActionPerformed(java.awt.event.ActionEvent evt) {
if(!isClickedOnce) {
//first click
//..
} else {
//second click
//..
}
isClickedOnce = !isClickedOnce;
}
Note: it'll consider every odd number click as first click and every even number of click as second click. it will toggle through your first and second row.
If your case is different lets say you have n number of rows, above procedure won't work and you might wanna do something similar with a list.
Im creating a GUI program with multiple buttons. I'm only able to use one of the buttons at the moment. Here is my Button Listener class. I want to be able to use the "Test" button and then use the "Yes" or "No" button after. Let me know if you need to see any more of my code.
public class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==TestButton)
{
TestWord = (Text_Input.getText());
StringBuilder RevTestWord = new StringBuilder();
RevTestWord.append(TestWord);
RevTestWord = RevTestWord.reverse();
DisplayText = "Is " + RevTestWord + " a real word?";
Test_Anadrome.setText(DisplayText);
if(e.getSource()==YesButton)
{
DisplayText = "Word added to Anadrome list.";
Test_Anadrome.setText(DisplayText);
}
if(e.getSource()==NoButton)
{
DisplayText = "Type a different word and press the 'Test Word' Button.";
Test_Anadrome.setText(DisplayText);
}
}
}
}
Sorry I'm pretty new to Java.
It looks like your if/else statements for your YesButton and NoButton are inside of your if statement for TestButton, so as a result those statements are only being checked if source==TestButton. Try moving this code outside of the if statement:
if(e.getSource()==YesButton)
{
DisplayText = "Word added to Anadrome list.";
Test_Anadrome.setText(DisplayText);
}
if(e.getSource()==NoButton)
{
DisplayText = "Type a different word and press the 'Test Word' Button.";
Test_Anadrome.setText(DisplayText);
}
You need to have all your testing at the same level. The nested ifs are causing problems. And remember to use if/else. No sense in continuing to do other checks if the previous one succeeds.
You can also set the ActionCommand which is a String. For components that use the actionListener, you can do for example button.setActionCommand("mycommand").
Then in the actionPerformed(ActionEvent e) you can do
String cmd = e.getActionCommand();
That allows you do discern between buttons or other components without having direct access to their instance.
If you don't set the ActionCommand it defaults to the button's text.
I am a bit confused regarding a situation I have. I created a ListModel extending DefaultListModel and ListRenderer implementing ListCellRenderer for displaying a custom cell in a JList. The cells are some objects created from a class extending JPanel, that contain a JLabel and a JButton.
My issue is related to the mouse events: I want to trigger a certain event when clicking on the JButton inside a cell of the JList, yet I can not figure out how to match the mouse source point to that of the JButton from the respective index. More exactly, I added a mouse listener to the list, but I want it to trigger something if the mouse point is located inside the bounds of the JButton, and another action if it's on the data item. I added some prints to find out the cause of this, but before that some code to highlight the structure:
public WifiGuiHandler(JButton reference) {
btnReference = reference;
wifiListener = new WifiListener();
wifiPopupContainer = new JScrollPopupMenu("Connections.");
wifiPopupContainer.setMaximumVisibleRows(7);
connectionsHolder = new ArrayList<>();
listOfConnections = new JList();
listOfConnectionsModel = new ListModel(connectionsHolder);
listOfConnectionsRenderer = new ListRenderer();
listOfConnections.setModel(listOfConnectionsModel);
listOfConnections.setCellRenderer(listOfConnectionsRenderer);
wifiPopupContainer.add(listOfConnections);
wifiPopupContainer.pack();
initializeTestVariables();
initializeListeners();
}
Here, the constructor for the class that takes a JButton and adds a mouse listener to it, that triggers the appearance of a JPopupMenu, which has only one component, the JList that hold the entire data. Also, links the ArrayList with the data items to the ListModel.
public void initializeTestVariables() {
for (int i = 0; i <= 10; i++) {
WifiItem item = new WifiItem("Connection number " + i + ".", i);
connectionsHolder.add(item);
}
}
Setting up the data items.
public void initializeListeners() {
listOfConnections.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
int index = listOfConnections.locationToIndex(e.getPoint());
if (index >= 0) {
WifiItem item = (WifiItem) ((ListModel) listOfConnections.getModel()).getElementAt(index);
System.out.println("Button of " + item.getConnectionName() + " is at location :" + item.getButton().getLocation());
System.out.println("Button has the bounds : " + item.getButton().getBounds());
System.out.println("MouseEvent detected on : " + e.getPoint().getLocation());
if (item.getButton().getBounds().contains(e.getPoint())) {
item.connectHere();
}
if (item.getButton().isVisible()) {
System.out.println("Set expanded on : " + item.getConnectionName());
item.setExpandedState(false);
listOfConnectionsModel.fireContentsChanged(item, index, index);
updateGui(false);
} else {
System.out.println("Set expanded on : " + item.getConnectionName());
listOfConnectionsModel.fireContentsChanged(item, index, index);
item.setExpandedState(true);
updateGui(false);
}
}
}
});
btnReference.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
updateGui(true);
}
});
}
And this is where the confusion arises. I correctly get the data item( WifiItem) from the mouse event location/point, but when I click on the JButton of the WifiItem, it doesn't trigger that method, like it doesn't seem to detect that the JButton actually is there. I also set up the prints, and what is strange, the Point for the JButton is always the same, even though it actually is different, and this seems to be the problem. More exactly, from the output of the program:
Button of Connection number 2. is at location :java.awt.Point[x=137,y=33]
Button has the bounds : java.awt.Rectangle[x=137,y=33,width=90,height=26]
MouseEvent detected on : java.awt.Point[x=172,y=125]
Button of Connection number 3. is at location :java.awt.Point[x=137,y=33]
Button has the bounds : java.awt.Rectangle[x=137,y=33,width=90,height=26]
MouseEvent detected on : java.awt.Point[x=172,y=125]
The above mouse events points were actually located on the JButton itself, only it didn't get that. As another strange fact, only if I click the JButton of the FIRST element of the list does it trigger the required mouse action.
Another print revealed that all the JButtons have the same Point and Rectangle, and I don't get it. There are 10 items in the JList, each displayed properly, how can all their JButtons have the same location? I must be missing some key element here. I looked at other posts and tried other recommendations: converting the point with SwingUtilities, removing all the mouse listeners from the JList and adding them to the data items.
To sum it up,the issue is that the list triggers the events for the correct data item in it(meaning, I do get the correct index for the item located there), but if the mouse event happens on the JButton of any data item inside the list, it doesn't trigger the required effect (the point is not withing the bounds of the button, even though it should be).
More exactly, I added a mouse listener for the list, but I want it to trigger something if the mouse point is located inside the bounds of the JButton, and another action if it's on the data item.
An easier solution would be to use a JTable. The data is separated into columns and the JTable has an API to let you know which row/column was selected.
You can use the Table Button Column as your renderer/editor for the button.
Edit:
only if I click the JButton of the FIRST element of the list does it trigger the required mouse action
Sounds like your conversion of the mouse point is off.
, how can all their JButtons have the same location?
Again, the button location is releative to the renderer panel. The panel itself is relative to the row in the JList. So I would guess you need to need the row index and add the height of each of the previous rows to your calculation.
I want to return selected radio button name from button group in java :
ButtonGroup bg = new ButtonGroup();
bg.add(radiobutton1);
bg.add(radiobutton2);
bg.add(radiobutton3);
I think you can loop through the radio buttons, for each button if isSelected() is true then call button.getText() to get the name.
for (AbstractButton button : bg.getElements())
if (button.isSelected())
return button.getText();
Why do you want the button name? It isn't of much use. You can, however, get the all of the button references using bg.getElements(), and you can get the text of each of those references with button.getText(), both of which are of much more use than the name you gave the button. If you REALLY want the name, you can create the buttons and then call radiobutton1.setName("radiobutton1") and then use getName() on the reference.
Ok, I'm new to listeners (still learning the language), and this is my first full-scale attempt to implement them (ie more than just a practice problem in a textbook).
So far, everything is working fine except one big bug: the checkboxes don't stay checked. The ItemListener I assign them runs perfectly (I have a JOptionPane set up to trigger to let me know if it's working or not), but the box itself doesn't stay checked.
I went even further and added conditional logic for if it's state is checked versus unchecked, and found that when I click the box BOTH states get triggered. So I get both JOptionPane popups, the one with the message for if the box is checked and the one for if the box isn't checked.
I'm including my code here. What am I doing wrong?
PS. You'll notice that the code has conditional logic to either add a radio button or a checkbox. When the program finally runs, this component is generated in multiple locations in both formats. The radio button works fine, it's the checkbox ones that I'm having the above issue with.
CODE THAT CREATES THE CHECKBOXES AND ASSIGNS THE LISTENERS:
public OtherField(int voteFor){
this.voteFor = voteFor;
otherPanel = new JPanel();
otherPanel.setLayout(new GridLayout(1, 3));
otherField = new JTextField(10);
otherField.setHorizontalAlignment(SwingConstants.CENTER);
JLabel otherLabel;
otherLabel = new JLabel("Other", SwingConstants.CENTER);
otherRadio = new JRadioButton("", false);
otherRadio.setHorizontalAlignment(SwingConstants.CENTER);
otherRadio.addActionListener(new OtherFieldRadioListener());
otherCheckBox = new JCheckBox("");
otherCheckBox.setHorizontalAlignment(SwingConstants.CENTER);
otherCheckBox.addItemListener(new OtherFieldCheckBoxListener());
otherPanel.add(otherLabel);
otherPanel.add(otherField);
if(voteFor == 1){
otherPanel.add(otherRadio);
}else{
otherPanel.add(otherCheckBox);
}
}
LISTENER CODE (it's a private class in the same class as the code above):
private class OtherFieldCheckBoxListener implements ItemListener{
public void itemStateChanged(ItemEvent e){
String name = otherField.getText();
if(e.getStateChange() == ItemEvent.SELECTED){
JOptionPane.showMessageDialog(null, name);
}else{
JOptionPane.showMessageDialog(null, "Not Selected");
}
}
}
First thing I would try is to set the checkbox either to true or false when you initialize it, i.e
otherCheckBox.setSelected(false)
If this does not work I would check whether OtherField gets called from somewhere else everytime the checkbox is selected and thus the components are redrawn/ the selection is reset (use the debugger and set a breakpoint at the beginning of OtherFields)