Java: Constructor not working - java

I am having a problem with a GUI constructor I am working on. It is supposed to be the GUI to a tic tac toe game, but none of my buttons are being created, and my GUI window is blank. I am really confused. I create an instance of the TicTacToePanel and add it to the main JFrame.
class TicTacToePanel extends JPanel implements ActionListener {
public void actionPerformed(ActionEvent e) {
}
//Creates the button array using the TicTacToeCell constructor
private TicTacToeCell[] buttons = new TicTacToeCell[9];
//(6) this constructor sets a 3 by 3 GridLayout manager in the panel
///then creates the 9 buttons in the buttons arrray and adds them to the panel
//As each button is created
///The constructer is passed a row and column position
///The button is placed in both the buttons array and in the panels GridLayout
///THen an actionListener this for the button
public void ButtonConstructor() {
//creates the layout to pass to the panel
GridLayout mainLayout = new GridLayout(3, 3);
//Sets a 3 by 3 GridLayout manager in the panel
this.setLayout(mainLayout);
int q = 1; //provides a counter when creating the buttons
for (int row = 0; row < 3; row++) //adds to the current row
{
for (int col = 0; col < 3; col++) //navigates to the correct columns
{
System.out.println("Button " + q + " created");
buttons[q] = new TicTacToeCell(row, col);
mainLayout.addLayoutComponent("Button " + q, this);
this.add(buttons[q]); //adds the buttons to the ticTacToePanel
buttons[q].addActionListener(this); //this sets the panel's action listener to the button
q++; //increments the counter
}
}
}
}

The function you have, despite being called ButtonConstructor, is not a constructor.
In Java, a constructor must share the name of its parent class (and have no return type). The correct signature would be public TicTacToePanel().
I cannot say for sure without seeing a more complete view of your code (you have surely omitted most of it), but it is likely that you are not calling the function with which you provided us at all, but rather using the implied no-argument constructor. Try renaming the function to the signature I gave above.

Related

Creating JPanels with a titled border in a for loop from user input

I want to create a for loop that creates JPanel containers with titled headers. the number of iterations depends on the user input from previous interfaces.
int noofpara=Integer.parseInt(data[6]);
for(int i=1;i<=noofpara;i++){
jPanel1.add(new JPanel().setBorder(new TitledBorder("Perimeter"+i)));
}
The noofpara is the number of perimeters the user chose according to that the for loop should create panels with the titled border with the number of perimeters. the error appears at the jpanel1.add... where it says void type not allowed.
JPanel#setBorder method has void return type, which mean it doesn't return any value when that method invoked.
But JPanel#add method need a value in order to invoked, it gives compilation error since setBorder is void.
You can simply fix this by this.
JPanel childPanel = new JPanel();
childPanel.setBorder(new TitledBorder("Perimeter" + i));
jPanel1.add(childPanel);
You have to make new panel and add.
for (int i = 1; i <= noofpara; i++) {
JPanel innerPane = new JPanel();
innerPane.setBorder(new TitledBorder("Perimeter" + i));
jPanel1.add(innerPane);
}

Dynamically generated jbuttons

I'm trying to make a GUI for that simulates elevators in a building (really to test threading/c-scan), but when generating the buttons for the elevator control panel and the buttons for each individual floor, I'm kind of stuck. I thinking about trying to generate a new pair of buttons for each floor, and generating a new control panel per elevator. Also there's the difficulty of having a variable amount of floors. Anyway my question what is this best way to go about doing this? Perhaps it's not necessary to generate new buttons for everything and just use one set and change what the actions do per floor/elevator? I'm asking because I'm not very familiar with GUIs. Thanks for the help
If all the elevators, and the control panel are the same, you can use a singular method and pass in the elevator or the control panel. CustomPanel extends JPanel and has a method foo.
public void createElevatorButtons(final CustomPanel panel) {
ArrayList<JButton> buttons = new ArrayList<>(); //arraylist of buttons we can keep track of
JPanel buttonPanel = new JPanel(); //the visible component
for(int i = 1; i <= numberOfFloors;i++) {
JButton button = new JButton(String.valueOf(i)); //creates buttons for floors 1 to max
buttons.add(button);
buttonPanel.add(button);
}
panel.add(buttonPanel);
//add the action listeners
for(JButton button : buttons) {
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton floor = (JButton) e.getSource();
int floorNumber = Integer.parseInt(floor.getText());
panel.foo(floorNumber); //we tell the elevator/panel/whatever to do something, you will have to extend JPanel to do foo
}
});
}
}
In this case that the number of floors is variable you can create an array of buttons:
JButton[] buttons = new JButton[MAX_NUMBER_OF_FLOORS];
Then when you determine the exact of number of floors at runtime, you can go to instantiate and add the buttons:
for(int i=0; i<numberOfFloors; i++) {
buttons[i] = new JButton();
controlPanel.add(buttons[i]);
}
Something like this should work.
Assign MAX_NUMBER_OF_FLOORS a big number like 100, there should be a possible limit given by the problem.

Need a layout? How it should be used?

So im writing a small test program for fun replicating a inventory from games like minecraft and runescape. Basically a frame with another one inside it, and pictures of your items in it, and a scroll bar to scroll down through all the stuff you have in your inventory. The "Stuff" i would have in my inventory would be buttons added later on with their own functionality, so you can scroll through vertically and see all the "stuff." Right now i have some test buttons being added to deomsntrate the error. Basically i want the buttons to be 100,100 and for them to be in a row of 4, and go onto the next column. I though GridLayout would be the best choice, but it seems to add more rows after being added into a scrollpane. Well heres the code skimmed down:
public class inventory extends JFrame{
public static void main(String[] args){
new inventory();
}
JPanel mainInv = new JPanel();
JScrollPane sp;
public inventory(){
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Toolkit tk = this.getToolkit();
setLocation(tk.getScreenSize().width/2-getWidth()/2, tk.getScreenSize().height/2-getHeight()/2);
setLayout(null);
mainInv.setSize(getWidth()-10, 1000);
mainInv.setBackground(Color.blue);
mainInv.setLayout(new GridLayout(8,4));
sp = new JScrollPane(mainInv, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
sp.setMaximumSize(new Dimension(400,400));
sp.setBounds(5, 5, 500-10, 500-130);
JButton[] testButs = new JButton[100];
for(int i = 0; i < 50; i++){
testButs[i] = new JButton("Test Button " + i);
testButs[i].setSize(100,100);
mainInv.add(testButs[i]);
}
add(sp);
setVisible(true);
}
}
With GridLayout the number of rows is the dominating factor.
If you have 8 rows and 4 columns that can only fit 48 buttons, if you try to add a 49th button it will create a 5th column not a 9th row.
You can solve your problem by setting up the GridLayout with more rows.

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);

JScrollPane always clears my Panel

Hy.. I have a JPanel, and in this contentPanel I added some other custom panels and give them locations etc. So now I added a JScrollPane to the contentPanel and always when I scroll down it clears my contentPanel, but the panels are still there but not visible...
How can I make them visible again?
That's my code to add the Panel into the contentPanel. The x,y,j are some settingsstuff for the location because I have an fixed window.
private void reloadContentPanel() {
int x = -200, y = 0, j = 1, row = 4;
EventPanel panel = null;
int i;
for(i=0; i < this.images.size();i++)
{
panel = new EventPanel(this.images.get(i).getAbsolutePath(),
this.images.get(i).getName());
panel.setLocation(x+(j*200), y);
j++;
if(i == row) {
x = -200;
y += 205;
j = 1;
row += 5;
}
this.contentPanel.add(panel);
}
this.repaint();
}
Thanks
it sounds like you are not using a LayoutManager correctly.
after creating your JFrame (i'm guessing within your constructor) add the following (for example):
this.setLayout(new FlowLayout());
this will certainly not be the best layout manager for what you are trying to do but will stop the add calls from overriding the displayed component.
you will need to read further about LayoutManagers
besides this, it's not really advisable to extend JFrame. It's better practice to treat JFrame as a member of your class just like all the other components.
I have the answer! :)
I use a GridLayout not a FlowLayout, so it's fine and it automatically refreshes the panels =)

Categories