actionlistener returning a nullexception on jbutton - jframe

I have an action listener set up on my main jframe menu for the buttons listed on it, and they work fine, bringing up other jframes as needed. The problem is when a person clicks the buttons on the jframes brought up I get a nullexception after a jbutton is clicked on that submenu jframe.
Example code:
public class main extends JFrame implements ActionListener
{
public main
{
private JButton thisButton = new JButton( "this" );
private JButton thatButton = new JButton( "that" );
thisButton.addActionListener( this );
thatButton.addActionListener( this );
thisButton.setActionCommand( "THISBUTTON" );
thatButton.setActionCommand( "THATBUTTON" );
setLayOut( new FlowLayout() );
add(thisButton);
public void actionPerformed( ActionEvent event )
{
String source = event.getActionCommand();
if( source.equals( "THISBUTTON" )
{
JFrame thisFrame = new JFrame();
thisFrame.add( thatButton );
if( source.equals( "THATBUTTON" )
{
System.out.println( "pushed thatbutton" );
}
}
}
}
}
Now I am almost certain that I need to set up another action listener for the inner jbutton but I am at a lost to how to do that.

To set up another action listener for the inner JButtons just write this code for each button
thisButton.addActionListener(this);

Related

Multiple RadioButtons Simulator

I'm trying to make a sort of simple soccer simulator. This is the code I created after watching tutorials and i know its pretty bad. All i want to do is add a value to the team, like 1 for the best team and 10 for the worst, and when i click simulate a pop up would show up telling me which team would win given the teams value. But i cant figure out how to do it.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class sim extends JPanel {
public sim() {
// JFrame constructor
super(true);
JRadioButton chelsea, arsenal, chelsea2, arsenal2;
this.setLayout(new GridLayout(3,0));
ButtonGroup group = new ButtonGroup();
ButtonGroup group2 = new ButtonGroup();
// takes image and saves it the the variable
Icon a = new ImageIcon(getClass().getResource("a.PNG"));
Icon c = new ImageIcon(getClass().getResource("c.JPG"));
chelsea = new JRadioButton("Chelsea",c);
chelsea.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal = new JRadioButton("Arsenal",a);
arsenal.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal.setVerticalTextPosition(AbstractButton.BOTTOM);
group.add(chelsea);
group.add(arsenal);
JLabel label = new JLabel("");
TitledBorder titled = new TitledBorder("Team 1");
label.setBorder(titled);
chelsea.setBorder(titled);
arsenal.setBorder(titled);
JButton button = new JButton("Simulate");
button.setHorizontalAlignment(JButton.CENTER);
add(button, BorderLayout.CENTER);
chelsea2 = new JRadioButton("Chelsea",c);
chelsea2.setHorizontalTextPosition(AbstractButton.CENTER);
chelsea2.setVerticalTextPosition(AbstractButton.BOTTOM);
arsenal2 = new JRadioButton("Arsenal",a);
arsenal2.setHorizontalTextPosition(AbstractButton.CENTER);
arsenal2.setVerticalTextPosition(AbstractButton.BOTTOM);
group2.add(chelsea2);
group2.add(arsenal2);
JLabel label2 = new JLabel("");
TitledBorder titled2 = new TitledBorder("Team 2");
label2.setBorder(titled2);
chelsea2.setBorder(titled);
arsenal2.setBorder(titled);
add(label);
add(chelsea);
add(arsenal);
add(button);
add(chelsea2);
add(arsenal2);
HandlerClass handler = new HandlerClass();
chelsea.addActionListener(handler);
}
private class HandlerClass implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//JOptionPane.showMessageDialog(null, String.format("%s", e.getActionCommand()));
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Final");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1920, 1080);
frame.setContentPane(new sim());
frame.setVisible(true);
}
}
Put the ActionListener into the sim class.
public void actionPerformed(ActionEvent e)
{
JButton clicked = (JButton)e.getSource();
if(clicked == button)
{
JOptionPane.showMessageDialog(null, "this team will win");
}
}
You need to decrees the amount of code to just amount needed you dont need to show us all the raidio

GWT - Finding which button is checked in a Dynamically generated list of Radiobuttons

I have a for loop that displays a list of text fields and radio buttons.
What is the best way to reference the widgets so that I can read the text fields and aslo find which radio button is checked.
Here is my loop
for(int x = 0; x<getLoopCount(); x++)
{
answerTable.setWidget(x,0, new Label("Answer:"));
answerTable.setWidget(x,1, new TextBox());
answerTable.setWidget(x,2, new RadioButton(""));
}
Is there a way to ID each widget so I can reference it?
I would recommend grouping the three widgets together in a composite widget like this:
class AnswerComposite extends Composite {
private final Label label;
private final TextBox textBox;
private final RadioButton radioButton;
public AnswerComposite() {
label = new Label("Answer:");
textBox = new TextBox();
radioButton = new RadioButton("answerGroup");
HorizontalPanel contentPanel = new HorizontalPanel();
contentPanel.add(label);
contentPanel.add(textBox);
contentPanel.add(radioButton);
initWidget(contentPanel);
}
public String getText() {
return textBox.getValue();
}
public boolean isSelected() {
return radioButton.getValue();
}
}
You can then add them to a panel and/or put them in a list like this:
VerticalPanel answersPanel = new VerticalPanel();
List<AnswerComposite> answerComposites = new ArrayList<AnswerComposite>();
for (int i = 0; i < getLoopCount(); i++) {
AnswerComposite answerComposite = new AnswerComposite();
answersPanel.add(answerComposite);
answerComposites.add(answersComposite);
}
Checking your widgets then becomes very easy:
answerComposites.get(i).getText();
answerComposites.get(i).isSelected();
It will probably also be convenient to add a ValueChangeHandler to your RadioButtons (see enrybo's answer).
You can add a ValueChangeHandler to your RadioButton when you are creating them.
for(int x = 0; x<getLoopCount(); x++){
answerTable.setWidget(x,0, new Label("Answer:"));
answerTable.setWidget(x,1, new TextBox());
RadioButton rb = new RadioButton("");
rb.addValueChangeHandler(new ValueChangeHandler(){
#Override
void onValueChange(ValueChangeEvent<Boolean> event){
// Do something
}
});
answerTable.setWidget(x,2, rb);
}
The ValueChangeEvent will only be fired when the RadioButton is checked. It will not fire if another RadioButton in the same group is checked.
Since you're adding the ValueChangeHandler as you're creating your RadioButton you should know what is to be done with it without having to create an ID for it.
Let me give you an adhoc answer, so don't care about the syntax but the algorithmic idea.
Extend GWT button.
abstract class MyButton
extends Button{
// provide the appropriate constructor in impl class,
// especially if using uibinder
abstract public void helloDolly(... args ...);
}
Instantiate all those buttons using MyButton.
MyButton[] buttons = {
new MyButton(){
public void helloDolly(... args ...){
Window.alert("allo allo #1");
}
},
new MyButton(){
public void helloDolly(... args ...){
Window.alert("allo allo #2");
}
},
// blah blah black sheep ....
}
Use clickEvent.getSource() when defining handler.
buttons[i].addEventHandler(
new ClickHandler(ClickEvent click){
Object src = click.getSource();
if (src !instanceOf MyButton){
throw new MyAngryException("For goodness' sake, pls use MyButton");
// or ignore
return;
}
((MyButton)src).helloDolly(... args ...);
}
)

GWT - Reference to a global variable set by callback method

Please help me, as I will go mad with this soon:
When I run the code, on first occasion loadNewPoint() is executed and displays some data from global variable - allPointsAndPlaces
However when I click a button (from a child class), the same method loadNewPoint() gives me null pointer for allPointsAndPlaces.
I have changed the code structure a lot from an original trying to solve this issue, and moved this method (loadNewPoint()) to a parent class to see, if it would solve the issue.
Parent class:
public class CabbieApp implements EntryPoint {
private GetLocationsServiceAsync getAllLocationsService = GWT.create(GetLocationsService.class);
CabbiePoint[] allPointsAndPlaces;
PointsQuiz quiz;
/**
* Entry point method.
*/
public void onModuleLoad() {
//Get all the required data from DB
getAllPointsAndLocations();
}
private void loadAppPages(){
// Associate the Main panel with the HTML host page.
RootPanel rootPanel = RootPanel.get("pointsList");
quiz = new PointsQuiz();
rootPanel.setStyleName("GWTapp");
rootPanel.add(quiz.getMainPanel());
loadNewPoint();
}
private void getAllPointsAndLocations() {
// Initialize the service proxy.
if (getAllLocationsService == null) {
getAllLocationsService = GWT.create(GetLocationsService.class);
}
// Set up the callback object.
AsyncCallback<CabbiePoint[]> callback = new AsyncCallback<CabbiePoint[]>() {
public void onFailure(Throwable caught) {
System.out.println(caught.getMessage());
}
public void onSuccess(CabbiePoint[] result) {
//allPointsAndPlaces = result;
System.out.println(result.length);
allPointsAndPlaces = result;
loadAppPages();
}
};
// Make the call to the service.
getAllLocationsService.getLocations(callback);
}
void loadNewPoint(){
int r = Random.nextInt(allPointsAndPlaces.length);
quiz.CurrentPlace = allPointsAndPlaces[r].getPlaceName();
quiz.CurrentLocation = allPointsAndPlaces[r].getPlaceLocation();
quiz.point.setText(quiz.CurrentPlace);
quiz.location.setText(quiz.CurrentLocation);
quiz.location.setStyleName("invisibleText");
}
}
Child class:
public class PointsQuiz extends CabbieApp{
VerticalPanel mainPanel = new VerticalPanel();
HorizontalPanel navigation = new HorizontalPanel();
TextBox point = new TextBox();
TextBox location = new TextBox();
Button showLocation = new Button("Show Location");
Button nextPoint = new Button("Next Point");
String CurrentPlace, CurrentLocation;
public PointsQuiz() {
// Assemble Add Stock panel.
navigation.add(showLocation);
navigation.add(nextPoint);
navigation.setCellHorizontalAlignment(nextPoint, HasHorizontalAlignment.ALIGN_RIGHT);
navigation.addStyleName("addPanel");
mainPanel.setSpacing(5);
mainPanel.setStyleName("body");
mainPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
mainPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
// Assemble Main panel.
mainPanel.add(point);
point.setWidth("200px");
mainPanel.add(location);
location.setWidth("200px");
mainPanel.add(navigation);
navigation.setWidth("200px");
// Move cursor focus to the input box.
showLocation.setFocus(true);
// Listen for mouse events on the show location button.
showLocation.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
showCurrentLocation();}
});
// Listen for mouse events on the next point button.
nextPoint.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
loadNewPoint();
}
});
}
private void showCurrentLocation(){
location.setStyleName("visibleText");
}
public VerticalPanel getMainPanel() {
return mainPanel;
}
}
I managed to find a solution to this problem with Bhumika's help.
To make this work I had to change CabbiePoint[] allPointsAndPlaces to static.
This would solve the reference problem one way - from child to parent.
Also I managed to find out trough debugging, that this reference
quiz = new PointsQuiz();
is also null on a second run of loadNewPoint(). So this child reference (PointsQuiz quiz;) and any other references to children were set also to static.
You are getting null pointer error because of allPointsAndPlaces is null. As per your coding The value of allPointsAndPlaces is assigned after completion of RPC call in getAllPointsAndLocations() method. so the allPointsAndPlaces has some assigned values.
Here you try to directly access loadNewPoint() method in child class. At a time, allPointsAndPlaces is not assigned.

How set up the Clickhandler for different Buttons?

i'm using gwt and want to create my own onClickHandler.
at the google docs i found a good example:
public class HandlerExample extends Composite implements ClickHandler {
private FlowPanel fp = new FlowPanel();
private Button b1 = new Button("Button 1");
private Button b2 = new Button("Button 2");
public HandlerExample() {
initWidget(fp);
fp.add(b1);
fp.add(b2);
b1.addClickHandler(this);
b2.addClickHandler(this);
}
public void onClick(ClickEvent event) {
// note that in general, events can have sources that are not Widgets.
Widget sender = (Widget) event.getSource();
if (sender == b1) {
// handle b1 being clicked
} else if (sender == b2) {
// handle b2 being clicked
}
}
}
but in my project the clickhandlermethod is out of the file with the buttons. Is there a way to handle buttons with different function with one handler?
greetz
You can do something like this:
public class HandlerExample extends Composite {
private FlowPanel fp = new FlowPanel();
private Button b1 = new Button("Button 1");
private Button b2 = new Button("Button 2");
public HandlerExample() {
initWidget(fp);
fp.add(b1);
fp.add(b2);
}
public List< HandlerRegistration > addClickHandlerToAllButtons( ClickHandler handler ) {
List< HandlerRegistration > handlerRegistrations = new ArrayList< HandlerRegistration >();
handlerRegistrations.add( b1.addClickHandler( handler ) );
handlerRegistrations.add( b2.addClickHandler( handler ) );
return handlerRegistrations;
}
}
Implement HasClickHandlers instead. Then you can set your implementations of ClickHanlder from outside your widget code.
Do you need to have different ClickHandler's for different buttons? If so, then maybe you could just have public/protected methods to set ClickHandler's for each button.

gwt get array button value

My gwt project have flexTable show data of image and button on each row and coll.
But my button won't work properly. this is my current code:
private Button[] b = new Button[]{new Button("a"),...,new Button("j")};
private int z=0;
...
public void UpdateTabelGallery(JsArray str){
for(int i=0; i str.length(); i++){
b[i].setText(str.gettitle());
UpdateTabelGallery(str.get(i));
}
}
public void UpdateTabelGallery(GalleryData str){
Image img = new Image();
img.setUrl(str.getthumburl());
HTML himage= new HTML("a href="+str.geturl()+">"+ img +"/a>" + b[z] );
TabelGaleri.setWidget(y, x, himage);
//is here th right place?
b[z].addClickHandler(new ClickHandler(){
#Override
public void onClick(ClickEvent event) {
Window.alert("I wan to show the clicked button text" + b[z].getText());
}
});
z++;
}
I'm still confuse where I should put my button handler. With this current code seems the clickhandler didn't work inside a looping. And if I put it outside loop its not working because I need to know which button clicked. I need to get my index button.but how? Is there any option than array button?
thanks
I was using this method me too, then I've created a new Button with an additional argument.
When I add the ButtonArg I set also the argument:
Panel.add(new ButtonArg("B1", i));
...
// Create a handler for the A-Z buttons
class MyHandler implements ClickHandler {
public void onClick(ClickEvent e) {
ButtonArg btn=(ButtonArg) e.getSource();
Window.alert("Button Text="+btn.getArgument());
}
}
public class ButtonArg extends Button {
int argument;
public ButtonArg(String html, int arg) {
super(html);
setArgument(arg);
}
public int getArgument() {
return argument;
}
public void setArgument(int argument) {
this.argument = argument;
}
[...]
The problem is that you refer to 'z' in your click handler, but the value of z changes, so that when your click handler is actually called the value of z is wrong.
You need a local final variable in UpdateTabelGallery which you assign the current value of z to to allow it to be captured by the handler you create. Even better, get rid of z entirely and pass i to UpdateTableGallery:
public void updateTableGallery(GalleryData str, final int i){
Image img = new Image();
img.setUrl(str.getthumburl());
HTML himage= new HTML("a href="+str.geturl()+">"+ img +"/a>" + b[i] );
TabelGaleri.setWidget(y, x, himage);
//is here th right place?
b[i].addClickHandler(new ClickHandler(){
#Override
public void onClick(ClickEvent event) {
Window.alert("I wan't to show the clicked button text" + b[i].getText());
}
});
}
But what do you expect:
HTML himage= new HTML("a href="+str.geturl()+">"+ img +"/a>" + b[i] );
to do? Aside from the incorrect HTML syntax, I don't think adding ypur button to the string will work.
I know this is old, but it didn't look answered and I was looking to do the same thing. Here's one solution:
public void onModuleLoad() {
Button[] b=new Button[26];
RootPanel rp=RootPanel.get("body");
// Create a handler for the A-Z buttons
class MyHandler implements ClickHandler {
public void onClick(ClickEvent e) {
Button btn=(Button) e.getSource();
Window.alert("Button Text="+btn.getText());
}
}
MyHandler handler = new MyHandler();
for(int i=0;i<26;i++) {
b[i] = new Button(String.valueOf((char)(65+i)));
b[i].addStyleName("sendButton");
rp.add(b[i]);
b[i].addClickHandler(handler);
}
SimplePanel sPanel = new SimplePanel();
}