Change JButtons Names and use the new Name. in methods - java

I have a swing java application on which I have a 114 button
I have created the buttons by a loop
Container pane = getContentPane();
JPanel panel = new JPanel();
JButton b;
for(int i=1;i<115;i++)
{
b = new JButton(""+i);
panel.add(b);
}
So all buttons will take the name b !!!
that is the problem here
I want to give each button a different name to execute different action for each button.
by ActionListener class
JButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
}
});

No, your buttons don't have the name b. You are using a local variable b inside the for loop. You can for instance create an array of buttons and store your JButton instances there. Later, you can loop through that array to change the buttons text.

Perhaps you could add your buttons to a Map using what you want to call the button as the key. Then you can access the button by calling the get() on the Map with whatever you want to call the button.

Related

Java Swing unable to remove a component

I am trying to build a quiz game that rerender itself after user click on the button with answer.
I have added an action listener to 4 buttons. When the button is clicked, it is suppose to reach the outer class which extend JFrame and remove the QuestionPanel that extends the JPanel. And then create a new QuestionPanel and add it back to the frame.
The hierarchy in goes like this :
MainFrame (JFrame) -> QuestionPanel (JPanel) -> optionPanel (JPanel) -> button (JButton)
MainFrame(outer class)
-> QuestionPanel (inner class)
-> OptionPanel (inner class)
But it just freeze during execution
button.addActionListener(e->{
boolean result = false;
JButton target = (JButton) e.getSource();
result = MainFrame.this.questions[currentQuestion].checkAnswer(target.getText());
System.out.println(questions.length);
if(currentQuestion != (questions.length - 1)){
MainFrame.this.remove(qPanel);
//qPanel is the instance of QuestionPanel
currentQuestion++;
qPanel = new QuestionPanel(questions[currentQuestion]);
MainFrame.this.add(qPanel);
}
});
Like many pointed out, you would be better off changing the text inside a component like a Label rather than removing a Jpanel and replacing it. There is simply no need for that, especially just to display text to a user.

Repaint TextFile in JPanel

I quite new in java and I encounter a problem with repaint a TextFile in my JPanel, this is code:
JPanel paneldol = new JPanel();
paneldol.add(new JButton(new AbstractAction("Oblicz pole i obwód")
{
#Override
public void actionPerformed(ActionEvent e) {
paneldol.repaint();
paneldol.revalidate();
}
}
));
paneldol.add(new TextField(model.getPole(), 10));
paneldol.add(new TextField(model.getObwod(), 10));
this.add(paneldol, BorderLayout.PAGE_END);
As you see TextField have metod that generate string, so when i click in button I want to repain panel to have new value in my Textfield, Is this possibly?
so when i click in button I want to repain panel to have new value in my Textfield, Is this possibly?"`
If all you want to do is to change the text in text field on button push, then you should give your class a JTextField variable (or multiple JTextField variables), assign a JTextField object to the variable, and this to the GUI. Then when within your button's listener, simply set the text of the JTextField via its setText(...) method. There's no need to call repaint() or revalidate() as they will do nothing useful in this situation.
Also don't mix AWT with Swing components. Use JTextFields not TextFields.

Java: Creating multiple (duplicate) buttons that perform the same action but to themselves

BACKGROUND INFO: I want to make a 9x9 grid of buttons that act as empty beds. All buttons say "Add bed" and when clicked open up a window to write data about the occupant. Once saved the button will change to an occupied bed image.
QUESTION: Is it possible to create an event listener that does the same thing for each button, but applies it to the button being pressed? Im new to java but I understand that good code should be able to do this in a few lines rather than 100+
CODE:
//button1 (inside the gui function)
addBed1 = new JButton("Add bed"); //button 1 of 9
addBed1.addActionListener(new room1Listener());
class room1Listener implements ActionListener{
public void actionPerformed(ActionEvent event){
addBed1.setText("Adding bed..);
addBedGui(); //Generic window for adding bed info.
}
}
Is it possible to create an event listener that does the same thing for each button, but applies it to the button being pressed? Im new to java but I understand that good code should be able to do this in a few lines rather than 100+
Absolutely. In fact you can create one ActionListener object and add this same listener to each and every button in a for loop. The ActionListener will be able to get a reference to the button that pressed it via the ActionEvent#getSource() method, or you can get the JButton's actionCommand String (usually its text) via the ActionEvent#getActionCommand() method.
e.g.,
// RoomListener, not roomListener
class RoomListener implements ActionListener{
public void actionPerformed(ActionEvent event){
AbstractButton btn = (AbstractButton) event.getSource();
btn.setText("Adding bed..);
addBedGui(); //Generic window for adding bed info.
}
}
and
RoomListener roomListener = new RoomListener();
JButton[] addButtons = new JButton[ADD_BUTTON_COUNT];
for (int i = 0; i < addButtons.length; i++) {
addButtons[i] = new JButton(" Add Bed "); // make text big
addButtons[i].addActionListener(roomListener);
addBedPanel.add(addButtons[i]);
}

Component passed to constructor doesn't display

I've created a class that creates a panel, and in the constructor I'm passing a button with an action listener attached.
This is the code for the button:
JButton back = new JButton("Back");
back.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
menus.show(contentPane, "Main");
}
});
It's then passed to a constructor like so:
lightsPane = new lightsPane(back).contents;
tasksPane = new Tasks(tasksBack).contents;
tvPane = new TV(tvBack).contents;
Inside the classes the button is added to a JPanel and that JPanel is then added to contents. Like so:
public class lightsPane{
JPanel contents;
lightsPane(JButton back){
contents = new JPanel(new BorderLayout);
//add back button to lower right of panel
JPanel backPane = new JPanel();
backPane.setLayout(new BorderLayout());
backPane.add(back, BorderLayout.CENTER);
contents.add(backPane, BorderLayout.SOUTH);
}
}
I know the constructor is working right as when I create a button inside it to add to contents it displays fine. What's going on here? Can I pass this button to the constructor or not? If I can why isn't this displaying?
yes, you can pass a button to a constructor as you are passing a reference which you used in another class it is perfectly fine.
There is nothing wrong with passing the JButton through the constructor if it is used properly. The class either is not using it at all or is using it but in the wonge way.

ActionEvent for jButton given a jRadioButton option

So basically, I'm trying to make a simple program here with GUI that let's you make a choice given two jRadioButtons as choices of which either of the two leads to a corresponding storyline in similar fashion to visual novels. The problem however is that I'm having trouble connecting the idea of a jButton to a choice from a jRadioButton.
The concept is like this: In a frame, there's a jTextArea which displays strings of texts forming a storyline which gives two options to choose from here and there as represented by two jRadioButtons which then must be executed by a jButton.
So far, the only logic I've placed inside the ActionListener for both jRadioButtons is having to disable the other once a jRadioButton is clicked while the jButton is intentionally blank. Anyone got any similar program or module he / she would like to share, at least, the logic on this one programatically speaking?
We usually use RadioButtons to choose between one of a few options and only one button can be selected at a time. To get this functionality, you need to add your buttons to a javax.swing.ButtonGroup . Here is a quick example:
//Fields declared in your main GUI class
JRadioButton option1,option2;
JButton goButton; //executes the "Story"
//Constructor code or place in init() method that constructor calls:
{
//initialize buttons and place them in your frame.
ButtonGroup buttonGroup = new javax.swing.ButtonGroup();
buttonGroup.add(option1);
buttonGroup.add(option2);
buttonGroup1.setSelected(option1.getModel(), true);
goButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
goButtonActionPerformed(evt);
}
});
}
private void goButtonActionPerformed(java.awt.event.ActionEvent evt) {
if(option1.isSelected()) {
//place text in your text area
}
if(option2.isSelected()) {
//place different text in your text area
}
}

Categories