Is it possible to store array into object array? - java

I have 30 JToggleButton. If they get pressed, I want to pass the i and the title into another class .
confirm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean buttonClicked = false;
for (i = 0; i < 30; i++) {
if (ButtonList[i].isSelected()) {
buttonClicked = true;
System.out.print(i+1);
System.out.println(title);
pass(title, ButtonList[i]);
}
}
if (!buttonClicked) {
JFrame parent= new JFrame();
JOptionPane.showMessageDialog(parent, "You haven't select a seat");
}
}
});
Before calling past() function, I did a test here. The number of title printed seems following the total number of toggleButton clicked. How to avoid this ?
The above code give me this output (Assume 2 toggle button clicked )
1Marvel's Captain America
2Marvel's Captain America

Are you trying to pass all the selected seats for the specified movie?
Set<Integer> selectedSeats = new LinkedHashSet<>();
for (int i = 0; i < 30; i++)
{
if (ButtonList[i].isSelected())
{
selectedSeats.add(i + 1);
}
}
if (selectedSeats.isEmpty())
{
JFrame parent= new JFrame();
JOptionPane.showMessageDialog(parent, "You haven't select a seat");
}
else
pass(title, selectedSeats);

My question is how can I store the array i into a object so that it
can pass with the title in a new function called pass() ?
so, I understood that you want to inform a method named "pass" with the title and the items that it was selected. If that's the case, you could do something like:
pass(list, title);
using the code below (using ArrayList you dont need to use the "buttonClicked" boolean):
confirm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ArrayList<int> list = new ArrayList<int>();
for (i = 0; i < 30; i++) {
if (ButtonList[i].isSelected()) {
list.add(i);
}
}
if (list.size() == 0) {
JFrame parent= new JFrame();
JOptionPane.showMessageDialog(parent, "You haven't select a seat");
}
}
});
I hope this helps.
EDIT: Andy Turner you're right, I just changed it

The class that wants to receive the data could implement the the ActionListener interface. Then you could use that class instead of a new ActionListener.
Here how that could look like:
public class ClassThatWantsEvents implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) { ...
and how you would use it in your current class:
confirm.addActionListener(ClassThatWantsEvents);

Related

How to make a method in a jbutton?

So, i made a button like this
parameter nomor in LoadPlanet and LoadRR is parameter to show some data to textbox.
my code is like this
the button appear correctly, but if i clicked the buttons, all of them show data from the last data which supposed to be data in last button.
-> a result from tblplanet.JmlPlanet() is 8, so the parameter was like LoadPlanet(8), so that every button show 8th data.
my question is how to make the parameter in sequence, so the button can show data correctly? Any ideas?
public void createButton() {
for (i = 0; i < tblplanet.JmlPlanet(); i++) {
tblplanet.draw(i + 1);
planet_name = tblplanet.getNama_planet();
JButton PlanetJButton = new JButton();
PlanetJButton.setBounds(10, 5 + (i * 35), 95, 26);
PlanetJButton.setText(planet_name);
PanelButton.add(PlanetJButton);
PlanetJButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
for (int i = 0; i < tblplanet.JmlPlanet(); i++) {
nomor = i;
LoadPlanet(nomor);
LoadRR(nomor);
}
}
});
}
}
Create a class which implements ActionListener and takes a parameter (int) of the planet that it represents
public class PlanetActionListener implements ActionListener {
private final int planet;
public PlanetActionListener(int planet) {
this.planet = planet;
}
#Override
public void actionPerformed(ActionEvent e) {
LoadPlanet(planet);
LoadRR(planet);
}
}
Then simply add the ActionListener to your button
PlanetJButton.addActionListener(new PlanetActionListener(i));
Depending on how you code is structured, you may need to make the PlanetActionListener an inner class so it can access the appropriate methods. See Nested Classes for more details

Getting value from JRadioButton

I'd like to change value of my variable "name" when I select right button and click "ok" on my JRadio Frame.
For example when i select r1 and hit "ok" I'd like to have name=="Fast" in the entire package.
package Snake;
public class Radio extends JFrame {
private int delay = 100;
private String name;
JTextField t1;
JButton b;
JRadioButton r1, r2;
JLabel l;
public void selectSpeed() {
b = new JButton("Ok");
r1 = new JRadioButton("Fast");
r2 = new JRadioButton("Slow");
l = new JLabel("Speed: ");
ButtonGroup bg = new ButtonGroup();
bg.add(r1);
bg.add(r2);
add(b);
add(r1);
add(r2);
add(l);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (r1.isSelected()) {
name = "Fast";
} else {
name = "Slow";
}
l.setText("Speed: " + name); // name=="Fast" when r1 is selected
} // name=="Slow" when r2 is selected
});
if (name == "Fast") { // and now name is empty...
delay = 50;
}
if (name == "Slow") {
delay = 500;
}
setLayout(new FlowLayout());
setSize(400, 400);
setVisible(true);
}
public int setSpeed() {
selectSpeed();
return delay;
}
}
If you want to change the delay on button click, You need to write the logic in the ActionListener itself because the code you have written to change the delay will run only once and that too at the start of the execution of your program and at that time, name will be empty.
Then when ever you click the button, It will only execute the ActionListener So delay will not be changed at any time. And other mistake you are making is that you are comparing Strings in wrong way. For more information take a look at it How do I compare Strings in Java?
To change delay dynamically on button click, you need to change it in the ActionListener.
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (r1.isSelected()) {
name = "Fast";
delay = 50;
} else {
name = "Slow";
delay = 500;
}
l.setText("Speed: " + name); // name=="Fast" when r1 is selected
} // name=="Slow" when r2 is selected
});
You need to do it in your JRadioButton listener. For example, like here, at first you change the variable "name" and later in the current listener you check conditions, but you need remember that to compare the strings you need to use "equals":
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (r1.isSelected()) {
name = "Fast";
} else {
name = "Slow";
}
l.setText("Speed: " + name); // name=="Fast" when r1 is selected
if (name.equals("Fast")) { // and now name is empty...
delay = 50;
}
if (name.equals("Slow")) {
delay = 500;
}
} // name=="Slow" when r2 is selected
});
Well I see my mistake now, Thank you.
But it still does not work the way I like. I'd like to change the "delay" value every time I select right button on JRadio and hit "ok" and with this changed value I'd like to go to the other class.
There is the code of a class where I need value of "delay":
package Snake;
public class Gameplay extends Paint implements KeyListener, ActionListener {
private Timer timer;
private int q = 0;
Radio radio = new Radio();
public Gameplay() {
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
timer = new Timer(radio.selectSpeed(), this); //here i need flexible "delay" value
timer.start();
}

java calculator decimal point

I have fully working calculator using java.Can tell me how to add decimal point.I already have the button and the variables are in type double.I just can't make the button work.
I tried to do it myself,but I ended up with error messages every time.
Here is the code:
package oop;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Kalkulator2 extends Applet {
String arg1= "", arg2="";
double ergebnis;
Button zahl[] =new Button[10];
Button funktion[] = new Button[4];
Button ausfuehren;
Button decimalpoint;
char dec='.';
Panel zahlPanel,funktionPanel,ergebnisPanel;
TextField ergebnisFeld = new TextField(5);
int operationArgument;
char operation;
public void init () {
operationArgument= 1; operation =' ';
setLayout(new BorderLayout());
zahlPanel = new Panel();
zahlPanel.setLayout(new GridLayout (4,3));
for (int i=9; i>=0; i--) {
zahl[i] = new Button(String.valueOf(i));
zahl[i].addActionListener(new ButtonZahlen());
zahlPanel.add(zahl[i]);
}
decimalpoint = new Button(String.valueOf(dec)); //decimal point
//decimalpoint.addActionListener(new Button ());
ausfuehren = new Button("=");
ausfuehren.addActionListener(new ButtonAusfuehren()); //zu dem Listener
zahlPanel.add(decimalpoint);
zahlPanel.add(ausfuehren);
add("Center",zahlPanel);
funktionPanel = new Panel();
funktionPanel.setLayout(new GridLayout(4,1));
funktion[0] = new Button("+");
funktion[0].addActionListener(new ButtonOperation());
funktionPanel.add(funktion[0]);
funktion[1] = new Button("-");
funktion[1].addActionListener(new ButtonOperation());
funktionPanel.add(funktion[1]);
funktion[2] = new Button("*");
funktion[2].addActionListener (new ButtonOperation());
funktionPanel.add(funktion[2]);
funktion[3] = new Button("/");
funktion[3].addActionListener (new ButtonOperation());
funktionPanel.add(funktion[3]);
add("East",funktionPanel);
ergebnisPanel = new Panel();
ergebnisPanel.add(ergebnisFeld);
add("North",ergebnisPanel);
}
class ButtonZahlen implements ActionListener{
public void actionPerformed(ActionEvent e) {
switch (operationArgument) {
case 1 : {
arg1+=e.getActionCommand();
ergebnisFeld.setText(arg1);
break;
}
case 2 : {
arg2 +=e.getActionCommand();
ergebnisFeld.setText(arg2);
break;
}
default: { }
}
}
}
class ButtonAusfuehren implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(operation =='+')
ergebnis = new Double(arg1) + new Double(arg2);
else if (operation == '-')
ergebnis = new Double(arg1) - new Double(arg2);
else if(operation =='*')
ergebnis = new Double(arg1) * new Double(arg2);
else if(operation =='/')
ergebnis = new Double(arg1) / new Double(arg2);
ergebnisFeld.setText(String.valueOf(ergebnis));
}
}
class ButtonOperation implements ActionListener{
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("+")) {
operation = '+'; operationArgument = 2;
}
else if(e.getActionCommand().equals("-")) {
operation = '-'; operationArgument = 2;
}
else if(e.getActionCommand().equals("*")) {
operation = '*' ; operationArgument =2;
}
else if(e.getActionCommand().equals("/")) {
operation = '/' ; operationArgument =2;
}
}
}
}
public void paint(Graphics g){ }
}
When the button got clicked, it is trying to create a new button object which doesn't implement an actionListener. Thus it will throw an error saying " what must i do with a new button while i need an object with 'actionPerformed' method " Here is a possible solution;
// create button object
decimalpoint = new Button(".");
// not good : decimalpoint.addActionListener(new Button ());
// event on click
decimalpoint.addActionListener(new YourClassName());
and YourClassName is an instance to handle the button event
class YourClassName implements ActionListener {
public void actionPerformed(ActionEvent e) {
// add decimal point
}
}
I also agree with Andrew Thompson that AWT is not a preferred way to handle your tasks. If your teacher has suggested you to use AWT, then please use Swing. Swing is far better then AWT and should be educated to people who is writing GUI-based java for the first time.
To answer the question, to add a DECIMAL POINT to java code (my example is for GUI NetBeans IDE 8.0.2) I have stumbled across this code. I must admit I have not come across this code having looked for an answer on the net.
private void PointActionPerformed(java.awt.event.ActionEvent evt) {
txtDisplay.setText(txtDisplay.getText()+Point.getText());
}
you can do that simply
specify the button -
Button Decimal;
caste the button you specified in your xml file to (Button)Decimal -
Decimal = findViewById(R.id.the id you gave to the button);
Now set on click listener
Decimal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edit.setText(edit.getText().toString() + ".");
}
where edit is the field you want the text to be filled.

How can I create a single ActionListener for multiple JButtons

I'm creating a basic calculator using MVC. So far I'm adapting a tutorial which merely sums two user entered values together.
Currently each button I'm adding to the view has it's own listener, which is ok. However, the controller as per the tutorial has a single ActionListener inner class per button. This repeats a huge amount of code.
How can I create a single ActionListener class for all buttons pressed, and use a case statement on the id of the button pressed?
Registering the oneButton in the View
void oneListener(ActionListener listenForOneButton){
oneButton.addActionListener(listenForOneButton);
}
Implementing the ActionListener for the oneButton in the Controller inner class
class oneListener implements ActionListener{
public void actionPerformed(ActionEvent e){
int previousNumber, displayNumber = 0;
try{
previousNumber = theView.getPreviousDisplayNumber();
displayNumber = previousNumber+1;
theView.setDisplayNumber(displayNumber);
}
catch(NumberFormatException ex){
System.out.println(ex);
theView.displayErrorMessage("You Need to Enter Integers");
}
}
}
Start with class which implements ActionListener...
public class CalculatorHandler implements ActionListener{
public static final String ADD_ACTION_COMMAND = "Action.add";
public void actionPerformed(ActionEvent e){
if (ADD_ACTION_COMMAND.equals(e.getActionCommand()) {
// Do your addition...
} else if ...
}
}
It's best to define the action commands that this class can handle is constants, thus removing any ambiguity...
Next, in the class that holds the buttons, create an instance of the ActionListener...
CalculatorHandler handler = new CalculatorHandler();
Then create you buttons as per usual and register the handler...
JButton plus = new JButton("+");
plus.setActionCommand(CalculatorHandler.ADD_ACTION_COMMAND);
plus.addActionListener(handler);
The only problem with this approach, IMHO, is that it can create a monster if-else statement which may become difficult to maintain.
To my mind, I'd create some kind of model/builder that contained a series of helper methods (like add(Number), subtract(Number) etc) and use Actions API for the individual actions for each button...but that's just me...
public class SingleActionListener implements ActionListener {
public void initializeButtons() {
JButton[] buttons = new JButton[4];
String[] buttonNames = new String[] {"button1", "button2", "button3", "button4"};
for (int i = 0; i < 4; i++) {
buttons[i] = new JButton(buttonNames[i]);
}
}
public void addActionListenersToButtons() {
for (int i = 0; i < 4; i++) {
buttons[i].addActionListener(this);
}
}
public void actionPerformedd(ActionEvent actionEvent) {
if (actionEvent.getSource() == buttons[0]) {
//Do required tasks.
}
if (actionEvent.getSource() == buttons[1]) {
//Do required tasks.
}
if (actionEvent.getSource() == buttons[2]) {
//Do required tasks.
}
if (actionEvent.getSource() == buttons[3]) {
//Do required tasks.
}
}
}

Combination Lock (Java)

I have a school assignment that i need to create. Below is the info:
Create a frame with ten buttons, labeled 0 through 9. To exit the program, the user must click on the correct three buttons in order, something like 7-3-5. If the wrong combination is used, the frame turns red.
I already finish the frame and the buttons with online research helps, but i just cant make the functionality to work. Please take a look at my codes and thanks in advance.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ComboNumber extends JFrame implements ActionListener{
//variable declaration
int ans1 = 3;
int ans2 = 7;
int ans3 = 1;
int one, two, three;
String inData1, inData2, inData3;
JButton[] button;
//constructs the combolock object
public ComboNumber()
{
//sets flowlayout
getContentPane().setLayout(new FlowLayout());
Container c = getContentPane();
//creates buttons
button = new JButton[10];
for(int i = 0; i < button.length; ++i) {
button[i] = new JButton("" + i);
//adds buttons to the frame
c.add(button[i]);
//registers listeners with buttons
button[i].addActionListener(this);
}
//sets commands for the buttons (useless)
//sets title for frame
setTitle("ComboLock");
}
//end combolock object
//listener object
public void actionPerformed(ActionEvent evt)
{
Object o = evt.getSource();
for(int i = 0; i < button.length; ++i) {
if(button[i] == o) {
// it is button[i] that was cliked
// act accordingly
return;
}
}
}
//end listener object
//main method
public static void main (String[] args)
{
//calls object to format window
ComboNumber frm = new ComboNumber();
//WindowQuitter class to listen for window closing
WindowQuitter wQuit = new WindowQuitter();
frm.addWindowListener(wQuit);
//sets window size and visibility
frm.setSize(500, 500);
frm.setVisible(true);
}
//end main method
}
//end main class
//window quitter class
class WindowQuitter extends WindowAdapter
{
//method to close the window
public void windowClosing(WindowEvent e)
{
//exits the program when the window is closed
System.exit(0);
}
//end method
}
//end class
The basic idea is simple.
You need two things.
What the combination actually is
What the user has guessed
So. You need to add two variables. One contains the combination/secret, the other contains the guesses.
private String secret = "123";
private String guess = "";
This allows you to make the combination as long as you like ;)
Then in your actionPerformed method, you need to add the most recent button click to the guess, check it against the secret and see if they've made a good guess. If the length of the guess passes the number of characters in the secret, you need to reset the guess.
public void actionPerformed(ActionEvent evt) {
Object o = evt.getSource();
if (o instanceof JButton) {
JButton btn = (JButton) o;
guess += btn.getText();
if (guess.equals(secret)) {
JOptionPane.showMessageDialog(this, "Welcome Overloard Master");
dispose();
} else if (guess.length() >= 3) {
JOptionPane.showMessageDialog(this, "WRONG", "Wrong", JOptionPane.ERROR_MESSAGE);
guess = "";
}
}
}

Categories

Resources