press buttons one by one - java

Hello I am new to java language,and I have created a JFrame in NetBeans IDE 8.2 .
The JFrame contains 8 buttons created diretly from swing palette.The case is that I am trying to open another JFrame form after clicking for example 5 buttons.
I know that for appearing another JFrame form it is used setVisible(true) method, in the last btnActionPerformed;
What I am asking is that how to make possible clicking 5 buttons and then appear the other Jframe form??If somebody knows what I am asking please help me to find the solution?

You could have a counter variable that each time you clic on a button it increases by 1 its value and when that value is 5, you call setVisible on your second JFrame.
However I suggest you to read The use of multiple JFrames, Good / Bad practice?. The general consensus says it's a bad practice.
As you provided not code, I can only show you that it's possible with the below image and the ActionListener code, however you must implement this solution on your own:
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (e.getSource().equals(buttons[i][j])) {
clics++;
sequenceLabel.setText("Number of Clics: " + clics);
if (clics == 5) {
clics = 0;
frame2.pack();
frame2.setLocationRelativeTo(frame1);
frame2.setVisible(true);
}
}
}
}
}
};

Related

How to create multiple buttons that do the same on different positions without creating actual new buttons?

Im really new to java and Programming as a whole. In school, I decided to work on a project to raise my grade, and as simple java is currently our topic i decided on trying to recreate battleships in a jframe using swing. I've made some good progress so far but im stuck on a quality of Life Problem.
So basically, in the editor we use (Java Editor ( javaeditor.org )) i use swing to implement buttons etc. in the jframe. As im gonna need a lot of Buttons for the games gui, I want to do it, so i dont have to make several buttons which have to be filled in with the arguments. What im trying to do is have some arguments create several buttons for me so they dont actually all need their own “method“ as all buttons have to basically do the exact same thing.
I tried searching for similar things on google but I couldnt find anything, so i decided to create this account to ask if someone might be able to help me with this Problem. If something isnt understandable feel free to ask (English isnt my mother tongue so some parts might be hard to understand).
Looking forward to any replies! Thanks in advance for helping.
Initially I thought I could use a for-loop to create these multiple buttons but there would always be some kind of error with the ActionPerformed argument.
for (int i = 0;i > 25;i++ ) {
jButton[i].setBounds(48, 48 + i, 113, 73);
jButton[i].setText("jButton1");
jButton[i].setMargin(new Insets(2, 2, 2, 2));
jButton[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jButton[i]_ActionPerformed(evt);
}
});
cp.add(jButton[i]);
}
As already said I expect there to be more than 1 button, whilst keeping the lines of code in the constructor as short as possible.
If you're desiring a grid of buttons, then create them in a for loop, and place them in the JPanel using a GridLayout. Something like this might work:
import java.awt.GridLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class ManyButtons extends JPanel {
private static final int SIDES = 10;
private JButton[][] buttonGrid = new JButton[SIDES][SIDES];
public ManyButtons() {
setLayout(new GridLayout(SIDES, SIDES));
for (int row = 0; row < buttonGrid.length; row++) {
for (int col = 0; col < buttonGrid[row].length; col++) {
String text = String.format("[%d, %d]", col + 1, row + 1);
buttonGrid[row][col] = new JButton(text);
buttonGrid[row][col].addActionListener(event -> {
String command = event.getActionCommand();
System.out.println("Button pressed: " + command);
});
add(buttonGrid[row][col]);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
ManyButtons mainPanel = new ManyButtons();
JFrame frame = new JFrame("Many Buttons");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
Also avoid setBounds and null layouts.
Regarding:
.... without creating new JButtons
This is not technically possible if you want a fully functioning button (as opposed to creating a rendered button in a JTable), however, buttons can share ActionListeners, so all buttons that do the same kind of thing (think -- all the number buttons on a calculator) can use the very same ActionListener. Alternatively, you can set a button's Action using your own class that extends from AbstractAction for even greater flexibility and power, and multiple buttons (and JMenuItems) can share the same action.

Hard coded buttons do not appear in design view, or in the running program

Whenever I choose to hard code an object (so far, I have sampled buttons, text fields and comboboxes), it does not appear on the associated form. Is there a separate piece of code that handles this, or can I use the following? Additionally, are layout bonds strictly necessary?
JButton startButton = new JButton("Start for loop ex");
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0){
int start = 1;
int end = 5;
int answer = 0;
for (int i = start; i < end; i++){
answer = answer + i;
}
};
IDEOne showing the entirety of the code:
http://ideone.com/u7CuoG
I think you only created the button, but forgot to put it in the JFrame.
Assuming that this is a subclass of JFrame, you can do this to add the button to the frame:
this.add(startButton);
Also check if you have called setContentPane. If you have not, the button will fill up the whole frame.
It is only natural that dynamically added buttons don't appear in the design view because it would be very slow to compile and run your code every time you open the design view!
EDIT:
I ran the code you gave me and produced this frame. As you can see, the button is on the frame:

How can I create actions for a variable number of buttons?

I'm creating a user interface for a game that I have to do as a class project, and needless to say I'm not experienced with Swing.
I did learn about actionevents and whatnot for simple button pushes, but in those cases I knew how many buttons would be on screen. Here, I need to create a board with an arbitrary number of tiles, which will be represented as buttons in Swing. I need to push a button and "move" my character from one tile to another, so I need to call a method on one tile object to remove the player from that tile, and then add it to another tile.
So my question is, given that the number of buttons is generated at runtime (and stored in a 2d array) how can I make an actionlistener that is able to distinguish between each unique button?
Set all your buttons to the same handler:
ActionListener a = new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() == buttons[0][0]) {
}
// etc
// common handling
}
};
for (int i = 0; i < height; ++i)
for (int j = 0; j < width; ++j)
buttons[i][j].addActionListener(a);

Trying to display from arraylist on a JPanel

im new to java swing, and Ive got a little problem.
So I've got a class Flight.java. In there I have a method displaySeat2D().
First I had this done with the scanner. Now Im using swing. So basically I made text fields to take in a number of seats and a number of rows. Now Im trying to display this in JPanel. Guess Id have to use JLabel and display it there. Not realy sure. So instead of 0 and 1, id like to have seats and rows displayed like squares for example. Or if its possible id try to keep it simple and display it like in Eclipse console with 0.
This is the code.
// FLIGHT class:
public void displaySeat2D(){
for (int i = 0; i < arraySeatPassenger.length; i++) {//line
System.out.println("");
for (int j = 0; j < arraySeatPassenger[i].length; j++) {// seat
if (arraySeatPassenger[i][j] == null) {
System.out.print("0");//
} else {
System.out.print("1");
}
}
}
System.out.println("");
}
// UI (display part):
lblDisplay.setForeground(new Color(0, 128, 0));
btnDisplayv.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
// Piece of UI
http://i44.tinypic.com/ajnlo3.jpg
That's basically it. I could use help when I click this button some field would appear with for example 4(seats)x4(rows). Thanks for the help.
Have a look at using a JTable. Each seat can be represented by individual cells with the table managing the alignment of the characters in the ArrayList. For more see How to Use Tables

actionListener on a JButton created from vector

I've been searching the web for an answer to my specific basic problem, but was unable to find one.
I must say I am new to programming and I have to do this for school.
I have created an interface of a 6/49 lottery, where you have to click 6 JButtons, creating your "lucky" numbers. In my interface .java, I've created my buttons this way:
JButton b;
for (i = 1; i <= 49; i ++)
{
String s = String.valueOf(i);
b = new JButton(s);
if (i % 2 == 0)
b.setForeground(new Color(3, 121, 184));
else
b.setForeground(new Color(228, 44, 44));
choixNumero.add(b);
Note: "choixNumero" is a gridLayout ( 7 x 7 )
In another .java , I'm creating an actionListener to my JButton b, but that doesn't seems to work. Here is how I wrote it:
intProjet.b.addActionListener(new EcouteurCombinaison()); // where "intProjet" is my interface.java
and heres the code of my EcouteurCombinaison:
private int [] nums;
private int nbRestant = 6;
private class EcouteurCombinaison implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
if (nbRestant > 0)
{
//nums[nbRestant] = indexOf(e)); //will have to find a way to get index of the button pressed
nbRestant --;
intProjet.valNbRestant.setText("" + nbRestant);
}
else
{
JOptionPane.showMessageDialog(null, "Vous avez choisis vos 6 numéros\n Cliquer sur Soumettre pour valider", "Information", JOptionPane.INFORMATION_MESSAGE);
}
}
}
So basically, I'm trying to add the index or the value of my JButton to the vector everytime a button is pushed. I will then send it to another .java
I've implemented others actionListener to my code and they work fine ( JButton, RadioButton, JComboBox ). I don't understand why nothing happens when I click my buttons.
I tried to make this as clear as possible, without pasting all the code.
Edit: The ActionListener works with the last button only ( 49 ). How can I make it listen to all b Buttons ?
intProjet.b refers to the last button created in your loop, so the result is expected. Instead, you can give each button its own instance of a listener, as shown here.
You are continually reassigning the value of b in that loop. When the loop completes, the last JButton to be created is assigned to it. You then bind an ActionListener to that button, but none of the others. I'm not sure why you expected a single invocation of intProjet.b.addActionListener() to add it to all JButtons.

Categories