How to make some of jtextfield & jlabel not appear in JPanel - java

I am currently making a GUI that prints a textarea. In this textarea I am required to receive the "weights" for the ID of the variable.
I have created multiple labels showing from ID1: - ID8: & their textfields, and use if statements instead but the with the amount of if and else if.
if (id.size = 1){
id1.setvisible(true);
weight1TField.setvisible(true);
}else if (id.size = 2){
id1.setvisible(true);
weight1TField.setvisible(true);
id2.setvisible(true);
weight2TField.setvisible(true);
}
else if (if.size = 3){
id1.setvisible(true);
weight1TField.setvisible(true);
id2.setvisible(true);
weight2TField.setvisible(true);
id3.setvisible(true);
weight3TField.setvisible(true);
}
So on... untill ID8.
The values are added to the array from a jtable in another Jframe when user has selected the rows(maximum 8 rows).
List<String> ID = new ArrayList<>();
I want to create text fields to allow the user to input their weights and jlabels showing the ID beside the textfield e.g ID: TextField. Image is shown below
ID[i] is replaced with the value in the array if there is one while the rest is hidden if there is no value. How can i create the Jlabels and JTexFields without doing the following below.
ID1.setText(ID[0]);
ID2.setText(ID[1]);
ID3.setText(ID[2]);
ID4.setText(ID[3]);
ID5.setText(ID[4]);
ID6.setText(ID[5]);
ID7.setText(ID[6]);
ID8.setText(ID[7]);

What about instead of using fields (I am not sure you are using fields, but the only thing i can do without more code is guess) to store the components into arrays? I have done an example with JLabels, you can do the same with textfields.
private static int idsCount = 6; //The number of ids. Let's say 6
private JLabel[] labels = new JLabel[8]; // Keep the array as a field. (8 = max capacity)
private void initIDLabels {
for (int i = 0; i < labels.length; i++) {
labels[i] = new JLabel();
// add this font to all labels.
labels[i].setFont(new Font("Tahoma", Font.BOLD, 12));
}
changeLabelsVisibility();
}
private void changeLabelsVisibility() {
// Hide all labels.
for (JLabel label : labels) {
label.setVisible(false);
}
// Show all labels that supposed to be visible
for (int i = 0; i < idsCount; i++) {
labels[i].setVisible(true);
}
}

Related

How to find the ID Name of a JLabel Array in Java with MouseListener

What I have done.
I have created an array of JLabel like that:
static JLabel numbers[] = new JLabel[25];
I Have given to each of the numbers[each of this] a random number between 1 and 80.
I have added to each of numbers[] array a MouseListener.
I want to make something like, once I press a specific label to change itself background. But to do that I have to detect the ID of the JLabel has been pressed.
The Question:
How can I get the name or the number of the array on JLabel that has been pressed?
So far I only know how to get the text from it with the following code:
JLabel l = (JLabel) e.getSource();
int strNumber = Integer.parseInt(l.getText());
I want the ID of numbers[THIS], not the text but the number of array.
In Button listener, I know how to do that, but in MouseListener is not working...
(At least with the methods I tried to...(e.getSource().getName(); etc.)
You've got the array, you've got a reference to the pressed JLabel: e.getSource();, so simply iterate through the array to find the one that matches the other. e.g.,
#Override
public void mousePressed(MouseEvent e) {
Object source = e.getSource();
int index = -1;
for (int i = 0; i < numbers.length; numbers++) {
if (numbers[i] == source) {
index = i;
break;
}
}
}
// here index either == the array item of interest or -1 if no match
Side issue: that array should not be static, and that it is static suggests that you have some design issues with your program that need to be fixed.

Multiple clickable JPanels

I've currently got 108 auto generated jPanels, each containting a random number.
Is there a way to easily make each of these clickable?
Here's my code..
Creating JPanels:
for (int row = 0; row < numbers.length; row++)
{
for (int col = 0; col < numbers[row].length; col++)
{
int tempNumber = (int)(Math.random() * 9 + 1);
numbers[row][col] = tempNumber;
np1 = new NumberPanel(tempNumber);
np1.setLocation(row*np1.getWidth(), row*getWidth());
add(np1);
}
}
The number panel class:
public NumberPanel(int randomNumber)
{
String number = Integer.toString(randomNumber);
setPreferredSize(new Dimension(40, 40));
setBackground(Color.red);
JLabel label = new JLabel(number, JLabel.LEFT);
label.setFont(new Font("Serif", Font.BOLD, 35));
add(label);
}
Why are you creating a panel to contain a JLabel? Why not just add the label directly to the parent panel?
Instead of using a JLabel to display the random number use a JButton. Then you can add an ActionListener to each of the buttons.
You can make the button look like a label by using:
button.setBorderPainted( false );
So basically, instead of creating 108 panels that contain a JLabel, you just create 108 JButtons and add the buttons directly to the parent panel.
First of all, I think you should avoid using Absolute Position Layout (null layout). As you already know the number of rows and columns, it would be easier to have a GridLayout and keep adding components accordingly.
On the other hand, just add an ActionListener and use the getSource() from the Event to get whatever was clicked. With the panel (or label) clicked, you can get the Text to know whats its value.
Assuming the ActionListener was added to the JLabel, you can do:
if (evt.getSource() instanceof JLabel) {
Integer value = Integer.valueOf(((JLabel) evt.getSource()).getText());
}
I actually like more the idea to have everything decoupled, so I'll just send a FirePropertyChange and receive it wherever I need to process the value.
If NumberPanel extends from JPanel, inside the constructor you can add Mouse listener.
addMouseListener(new MouseListener() {
....
});
If you want to have clickable JPanel with saved "state" you can use JToggleButton:
public class NumberButton extends JToggleButton {
public NumberButton(int randomNumber) {
setBorder(BorderFactory.createEmptyBorder());
String number = Integer.toString(randomNumber);
setText(number);
setFont(new Font("Serif", Font.BOLD, 35));
setPreferredSize(new Dimension(40, 40));
setBackground(Color.red);
}
}

how to update a container in java that already has data in it

Hi all i need to update a containers data for a sudoku game i am creating but am struggling to get the field to update with the new data.the container uses a grid layout and each cell contains a button with the appropriate number for sudoku in it and i need to know how to update the text in these buttons. any help with what methods i could use or any help in general would be greatly appreciated. please see the code i currently have to try and update below i know its probably messy and completely on the wrong track but ive just been trying to mess with stuff hoping it would work.
public void update(int[][] grid2)throws NullPointerException{
myGrid = new Container();
try{
for(int i = 0; i<9; i++){
for(int j = 0; j<9; j++){
String appropriateNumber = convertSimple(grid2[i][j]);
JButton button = new JButton(appropriateNumber);
button.addActionListener(new sudokuListener());
myGrid.add(button);
}
}
}
catch(NullPointerException e){
}
myGrid.setLayout(new GridLayout(9, 9));
myGrid.setPreferredSize (new Dimension(400, 400));
add(myGrid);
puzzleGUI.update();
}
puzzlGUI.update simply contains puzzle.validate() (puzzle being the GUI)
[edit]
ok i have changed things around a bit and used the JButton arrya as suggested and i have been able to set the text of the buttons in this array (i know through a system.out.print) but this does not update the text which is in the actual GUI. aaaaahhh coding is not fun at the end of a semester please help anyone
To re-iterate, if you have a grid of JButtons, why re-create them every time? Why not simply iterate through the components that are already in the grid and update their state, such as perhaps the text showing on the JButtons?
for(int i = 0; i<9; i++){
for(int j = 0; j<9; j++){
String appropriateNumber = convertSimple(grid2[i][j]);
someButtonArray[i][j].setText(appropriateNumber);
// no longer need this stuff
// JButton button = new JButton(appropriateNumber);
// button.addActionListener(new sudokuListener());
// myGrid.add(button);
}
}
Your update method is creating new Swing components every time it is called which is unnecessary if you just need to update the text. To directly update the text in any JButton you could create a button array like so:
JButton[][] buttons = new JButton[9][9];
and create like this (called only once):
for (int i = 0; i<9; i++) {
for(int j = 0; j < 9; j++){
String appropriateNumber = convertSimple(grid2[i][j]);
button[i][j] = new JButton(appropriateNumber);
button[i][j].addActionListener(new sudokuListener());
myGrid.add(button[i][j]);
}
}
then to update :
buttons[row][column].setText("New Text");

JCombobox and JTextfield

I'm trying to work to display a number of jtextfield according to one of the given values in a combobox.
So, I will have a drop down menu with let's say 1 to 4. If the user selects number 3, 3 textfields will be displayed. I've created the jcombobox with a selection of numbers. But I'm not sure how to implement this. If I'm not mistaken I need to use
ItemEvent.SELECTED
I think I need to create a reference to the JTextField object that will be available to the JComboBox's itemListener object.
Any help would be greatly appreciated.
I've added this to my class :
// aOption is the combobox I declared
aOptionComboBox.setModel(new DefaultComboBoxModel(new String[]{"1","2","3"}));
public void itemStateChanged(ItemEvent event) {
String num = (String)aOptionComboBox.getSelectedItem();
int num1 = Integer.parseInt(num);
JTextField[] textfields = new JTextField[num1];
for (int i = 0; i < num1; i++)
{
textfields[i] = new JTextField("Field");
getContentPane().add(textfields[i]);
textfields[i].setBounds(200, 90, 100, 25);
}
}
am I on a right track?
use the getSelectedItem() on the combobox. This will either yield a string or an integer (depending on how you implemented it). Next use a for-loop to determine the amount of JTextField's and store them in an array.
int amount = myJComboBox.getSelectedItem();
JTextField[] textfields = new JTextField[amount];
for (int i = 0; i < amount; i++) {
textfields[i] = new JTextField("awesome");
this.add(textfields[i]);
}
this way you can easily store the textfields and add them to your panel.
Some added information.
The textfield-array must be accesible outside the eventListener, so you must implement it in your class. that way the whole class can use it.

Java: Constructor not working

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.

Categories