Changing text of JLabel in ActionEvent - java

OK, so I'm creating a Tic Tac Toe GUI. I currently having a working frame of 3x3 buttons that will change to either an X or O. My issue is implementing a JLabel on the top of the buttons. The label keeps track of who's turn it is and will change from either "O's turn" or "X's turn" however I can't seem to get the JLabel to update (only spouts errors). Here's a portion of my code showing how Trying to implement this. The program runs fine but as soon as I add the (turn.setText("O's turn");) I get errors.
Any feedback as to why this may not be working would be appreciated.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TicTacToe extends JFrame {
XOButton[] xob = new XOButton[9];
private JLabel turn;
public static int state;
public TicTacToe() {
super("TicTacToe");
//add XOButtons to panel
JPanel center = new JPanel();
state = 0;
JLabel turn = new JLabel("X's turn");
center.setLayout(new GridLayout(3, 3, 2, 2));
//action listener
ButtonListener bl = new ButtonListener();
for (int i = 0; i < 9; i++) {
xob[i] = new XOButton();
xob[i].addActionListener(bl);
center.add(xob[i]);
}
//add panel to frame
setLayout(new BorderLayout());
add(center, BorderLayout.CENTER);
add(turn, BorderLayout.NORTH);
}
//inner action listener class
private class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent ae) {
for (int i = 0; i < 9; i++) {
if(ae.getSource() == xob[i] && xob[i].getState() == XOButton.NONE && state == 0) {
xob[i].setState(XOButton.X);
state = 1;
//turn.setText("O's turn");
} else if(ae.getSource() == xob[i] && xob[i].getState() == XOButton.NONE && state == 1) {
xob[i].setState(XOButton.O);
state = 0;
}
}
}
}
}

Guess: your error is a NullPointerException because turn is null. Solution: don't shadow the variable. In other words you're re-declaring the turn variable in the constructor leaving the field null.
e.g.,
public class TicTacToe extends JFrame{
XOButton[] xob = new XOButton[9];
private JLabel turn;
public static int state;
public TicTacToe() {
super("TicTacToe");
//add XOButtons to panel
JPanel center = new JPanel();
state = 0;
JLabel turn = new JLabel("X's turn"); // **** you're re-declaring turn here!
Better:
public class TicTacToe extends JFrame{
XOButton[] xob = new XOButton[9];
private JLabel turn;
public static int state;
public TicTacToe() {
super("TicTacToe");
//add XOButtons to panel
JPanel center = new JPanel();
state = 0;
turn = new JLabel("X's turn"); // **** Note the difference?
In the future, if you have similar problems, please post the entire error message and indicate which line throws the exception as it will help us immensely!

Related

Adding a Button array to a JPanel

I have another problem with my project. I have created this GameBoard made out of JButtons (it works as it's supposed to now) but I would need to add it to a JPanel. I need to display other things (in other panels) in the window. But when I tried to add the Button Array to a panel, and add that panel to the window, crazy things started happening (the buttons were very small, the grid was completely broken etc.). How could I add this Button Array to a JPanel and put that in the center of the window?
Here is my code:
package city;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GameBoard extends JFrame implements ActionListener {
// The overall box count in chess board
public static final int squareCount = 64;
// The Array of buttons (the GameBoard itself)
public Button[][] button = new Button[8][8];
// Colors for all the buttons
public Color defaultColor = Color.WHITE;
public Color darkRedColor = Color.RED;
public Color darkBlueColor = Color.BLUE;
public Color lightBlueColor = Color.CYAN;
public Color lightRedColor = Color.PINK;
public GameBoard(String title) {
// Creates the buttons in the array
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
button[i][j] = new Button();
add(button[i][j]);
button[i][j].setBackground(defaultColor);
}
}
// Build the window
this.setTitle(title); // Setting the title of board
this.setLayout(new GridLayout(8, 18)); // GridLayout will arrange elements in Grid Manager 8 X 8
this.setSize(650, 650); // Size of the chess board
this.setVisible(true); // Sets the board visible
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // If you close the window, the program will terminate
this.setResizable(false); //The window is not resizable anymore ;)
// Sets some text on the buttons
button[0][3].setText("Red's");
button[0][4].setText("Gate");
button[7][3].setText("Blue's");
button[7][4].setText("Gate");
// Colors the buttons
newGame();
}
// Colors the buttons
public void newGame() {
button[0][0].setBackground(lightRedColor);
button[0][1].setBackground(lightRedColor);
button[0][2].setBackground(lightRedColor);
button[0][3].setBackground(darkRedColor);
button[0][4].setBackground(lightRedColor);
button[0][5].setBackground(lightRedColor);
button[0][6].setBackground(lightRedColor);
button[0][7].setBackground(lightRedColor);
button[1][3].setBackground(darkRedColor);
button[7][0].setBackground(lightBlueColor);
button[7][1].setBackground(lightBlueColor);
button[7][2].setBackground(lightBlueColor);
button[7][3].setBackground(lightBlueColor);
button[7][4].setBackground(darkBlueColor);
button[7][5].setBackground(lightBlueColor);
button[7][6].setBackground(lightBlueColor);
button[7][7].setBackground(lightBlueColor);
button[6][4].setBackground(darkBlueColor);
}
// The ActionListener is not yet used
public void actionPerformed(ActionEvent ae) {
String action = ae.getActionCommand();
}
public static void main(String[] args) {
String title = "City - A Two-Player Strategic Game";
GameBoard gameBoard = new GameBoard(title); // Creating the instance of gameBoard
}
}
And here is a screenshot of the bad GUI that generated:
Bad GUI
Thanks for any help, and good luck everyone with a similar problem!
Is this what you are looking for? I am not very sure what´s the problem.
This adds the buttons to a new JPanel and adds this panel to the frame.
JPanel panel = new JPanel(new GridLayout(8, 8));
panel.setSize(650,650);
getContentPane().add(panel, BorderLayout.CENTER);
// Creates the buttons in the array
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
button[i][j] = new JButton();
panel.add(button[i][j]);
button[i][j].setBackground(defaultColor);
}
}
// Build the window
this.setTitle(title); // Setting the title of board
getContentPane().setLayout(new BorderLayout());
this.setSize(650, 650); // Size of the chess board
this.setVisible(true); // Sets the board visible
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // If you close the window, the program will terminate
this.setResizable(false); //The window is not resizable anymore ;)

JApplet will not initialize when Listener is added to jcheckBox

Alright, since it didn't work out last time. I'm going to post my full code here and i hope i can get some replies as to why it's not working. I'm not getting any compiling errors, the applet runs and then nothing shows up and at the bottom it says "applet not initialized." I'm using blueJ. I apologize for the length of this post, I could not figure out how to make this same error with a shorter code.
I have a JApplet program with multiple classes. RegPanel,WorkshopPanel, ConferenceGUI, ConferenceHandler and ConferenceClient. Basically RegPanel and WorkShop panel are added to the ConferenceGUI, which also creates and adds a couple small panels. The ConferenceClient class is just used to initaite the class to run the applet. The ConferenceHandler is used to handle the action events for the JButtons, JTextArea, JCheckBox, etc... Normally this whole program works fine. Except when i add a listener for the JCheckBox, it stops working. The problem area is in the ConferenceGUI class, it is commented with stars to be clear what's causing the problem.
I've been stuck on this error for about a day now and the frustration i'm feeling is overwhelming. So, to get to the point, here's the complete code:
(please, i don't need tips on any other part of the code, I just need help with that error). You may want to skip over the code and just read the ConferenceGUI class where the error is located. If you could also explain to me why this isn't working, it would be very helpful to me. Thank you in advance!
RegPanel Class:
import java.awt.*; import java.awt.event.*; import javax.swing.*;
public class RegPanel extends JPanel
{
protected JTextField regNameTextBox;
protected JCheckBox keynoteCheckBox;
protected final String[] REGTYPES = {"Please select a type","Business","Student","Complimentary"};
protected JPanel registrationPanel, keynotePanel;
protected final double BUSINESSFEE = 895,STUDENTFEE = 495,COMPLIMENTARYFEE = 0;
protected JComboBox regTypeComboBox;
public RegPanel()
{
//Set the layout for the RegPanel to be 2 rows and 1 column.
setLayout(new GridLayout(2, 1));
//initiate the registration panel and add a border
registrationPanel = new JPanel();
registrationPanel.setLayout(new FlowLayout());
registrationPanel.setBorder(BorderFactory.createTitledBorder("Registrant's Name & Type"));
//initiate the comboBox and add the registration types
regTypeComboBox = new JComboBox(REGTYPES);
//Initiate the textfield with a size of 20
regNameTextBox = new JTextField(20);
//Add the registration name textbox and type combobox to the registration panel
registrationPanel.add(regNameTextBox);
registrationPanel.add(regTypeComboBox);
//initiate the second panel for the checkbox
keynotePanel = new JPanel();
keynotePanel.setLayout(new FlowLayout());
//initiate the checkbox and add it to the keynote panel
JCheckBox keynoteCheckBox = new JCheckBox("Dinner and Keynote Speach");
keynotePanel.add(keynoteCheckBox);
//Add the two panels to the main panel
add(registrationPanel);
add(keynotePanel);
}
public double getRegistrationCost()
{
double regFee = 0;
String comboBoxAnswer = (String)regTypeComboBox.getSelectedItem();
switch (comboBoxAnswer)
{
case "Business": regFee = BUSINESSFEE;
break;
case "Student": regFee = STUDENTFEE;
break;
}
return regFee;
}
public double getKeynoteCost()
{
double keynoteCost = 0;
if(keynoteCheckBox.isSelected())
{
keynoteCost = 30;
}
return keynoteCost;
}
public String getRegType()
{
String regType = (String)regTypeComboBox.getSelectedItem();
return regType;
}
}
WorkshopPanel Class:
import java.awt.*; import java.awt.event.*; import javax.swing.*;
public class WorkshopPanel extends JPanel
{
protected final double ITFEE = 295, DREAMFEE = 295, JAVAFEE = 395, ETHICSFEE = 395;
protected final String[] WORKSHOPS = {"IT Trends in Manitoba","Creating a Dream Career","Advanced Java Programming","Ethics: The Challenge Continues"};
protected JList workshopList;
public WorkshopPanel()
{
setLayout(new FlowLayout());
workshopList = new JList(WORKSHOPS);
workshopList.setSelectionMode(2);
BorderFactory.createTitledBorder("Workshops");
add(workshopList);
}
public double getWorkshopCost()
{
Object[] workshops = workshopList.getSelectedValues();
double cost = 0;
String workshopString;
for (int i = 0; i < workshops.length; i++)
{
workshopString = (String)workshops[i];
switch(workshopString)
{
case "IT Trends in Manitoba":
cost += ITFEE;
break;
case "Creating a Dream Career":
cost += DREAMFEE;
break;
case "Advanced Java Programming":
cost += JAVAFEE;
break;
case "Ethics: The Challenge Continues":
cost += ETHICSFEE;
break;
}
}
return cost;
}
public Object[] getWorkshopList()
{
Object[] workshopListArray = workshopList.getSelectedValues();
return workshopListArray;
}
}
ConferenceGUI class (THIS CONTAINS THE ERROR):
import java.awt.*; import java.awt.event.*; import javax.swing.*;
public class ConferenceGUI extends JPanel
{
protected JPanel titlePanel, buttonPanel;
protected RegPanel regPanel;
protected WorkshopPanel workshopPanel;
protected JLabel titleLabel;
protected JButton calculateButton, clearButton;
protected JTextArea resultArea;
protected JScrollPane textScroll;
public ConferenceGUI()
{
setLayout(new BorderLayout());
titlePanel = new JPanel();
titleLabel = new JLabel("Select Registration Options",JLabel.CENTER);
Font titleFont = new Font("SansSerif", Font.BOLD, 18);
titleLabel.setFont(titleFont);
titlePanel.add(titleLabel);
add(titlePanel, BorderLayout.NORTH);
regPanel = new RegPanel();
add(regPanel, BorderLayout.WEST);
workshopPanel = new WorkshopPanel();
add(workshopPanel, BorderLayout.EAST);
buildButtonPanel();
add(buttonPanel, BorderLayout.SOUTH);
ConferenceHandler handler = new ConferenceHandler(this);
regPanel.regTypeComboBox.addItemListener(handler);
regPanel.regNameTextBox.addFocusListener(handler);
//****************************************************************
//The line below is what causes the error. Without it the code
//Works, with it it doesn't and i get the aforementioned error.
//regPanel.keynoteCheckBox.addItemListener(handler);
}
private void buildButtonPanel()
{
buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
calculateButton = new JButton("Calculate Charges");
buttonPanel.add(calculateButton);
clearButton = new JButton("Clear");
buttonPanel.add(clearButton);
resultArea = new JTextArea(5,30);
textScroll = new JScrollPane(resultArea);
buttonPanel.add(textScroll);
ConferenceHandler handler = new ConferenceHandler(this);
calculateButton.addActionListener(handler);
clearButton.addActionListener(handler);
}
}
ConferenceHandler class( this class is unfinished until i get that error straightened out) :
import java.awt.*; import java.awt.event.*; import javax.swing.*;
public class ConferenceHandler implements ActionListener, ItemListener, FocusListener
{
protected ConferenceGUI gui;
public ConferenceHandler(ConferenceGUI gui)
{
this.gui = gui;
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == gui.calculateButton)
{
String regType = gui.regPanel.getRegType();
Object[] workshopList = gui.workshopPanel.getWorkshopList();
String workshopString;
if (regType == "Please select a type")
{
JOptionPane.showMessageDialog(null,"Please select a registration type","Type Error",JOptionPane.ERROR_MESSAGE );
}
else
{
if(gui.regPanel.keynoteCheckBox.isSelected())
{
gui.resultArea.append("Keynote address will be attended/n");
}
else
{
gui.resultArea.append("Keynot address will not be attended/n");
}
}
}
if (e.getSource() == gui.clearButton)
{
gui.resultArea.append("CLEAR");
}
}
private double getTotalCharges()
{
double charges = 0;
return charges;
}
public void itemStateChanged(ItemEvent e)
{
}
public void focusLost(FocusEvent e)
{
}
public void focusGained(FocusEvent e)
{
}
}
ConferenceClient Class:
import java.awt.*; import java.awt.event.*; import javax.swing.*;
public class ConferenceClient extends JApplet
{
private final int WINDOW_HEIGHT = 700, WINDOW_WIDTH = 250;
private ConferenceGUI gui;
private Container c;
public ConferenceClient()
{
gui = new ConferenceGUI();
c = getContentPane();
c.setLayout(new BorderLayout());
c.add(gui, BorderLayout.CENTER);
setSize(WINDOW_HEIGHT, WINDOW_WIDTH);
}
}
You're shadowing your keynoteCheckBox variable. First you create a instance field in RegPanel, but in the constructor, you redeclare it...
public class RegPanel extends JPanel {
protected JCheckBox keynoteCheckBox;
//...
public RegPanel() {
//...
//initiate the checkbox and add it to the keynote panel
JCheckBox keynoteCheckBox = new JCheckBox("Dinner and Keynote Speach");
keynotePanel.add(keynoteCheckBox);
This leaves the instance field as null which will cause a NullPointerException
Also, this: regType == "Please select a type" is not how to compare Strings in Java, you want to use something more like "Please select a type".equals(regType)

JLabel.setText() relocates all labels in mousewheelevent

EDIT: leaving short code which shows issue:
Then label.setText("") is called and it has to change the text, i.e. scaler overcame 50 barrier the label dissapears for the mousewheelevent -> re-emerges on next event. Also a problem of the label not being present on the Load-up.
In actual program labels stack together in 1 spot if any of them has .setText() changing value or .setVisible changing (These two methods I need to be able to use without affecting labels positioning)
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.OverlayLayout;
public class brokenLabel extends JFrame
{
private JLayeredPane layerPane;
private JPanel breakingLabelPanel = new JPanel();
private JLabel label;
private int scaler = 50;
private int xstart = 200;
private int ystart = 200;
public static void main(String[] args)
{
#SuppressWarnings("unused")
brokenLabel program = new brokenLabel();
}
public brokenLabel()
{
// Frame setup used on the program
final JFrame frame = new JFrame("This is a slideshow");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
layerPane = new JLayeredPane();
frame.setContentPane(layerPane);
// Panel used (it's similar to what's added on the actual program)
breakingLabelPanel.setOpaque(true);
breakingLabelPanel.setLayout(new OverlayLayout(breakingLabelPanel));
breakingLabelPanel.setVisible(true);
breakingLabelPanel.setSize(getMaximumSize());
breakingLabelPanel.addMouseWheelListener(new MouseWheelListener(){
#Override
public void mouseWheelMoved(MouseWheelEvent arg0)
{
if (scaler > 5 || arg0.getWheelRotation() < 0)
scaler = scaler - 5*arg0.getWheelRotation();
setTexts();
}
});
//The testing label
label = new JLabel(new String("1"));
label.setLocation(xstart , ystart);
breakingLabelPanel.add(label);
frame.add(breakingLabelPanel,layerPane);
frame.setVisible(true);
//revalidate and repaint don't help make label visible on load-up
frame.revalidate();
frame.repaint();
}
public void setTexts(){
label.setLocation(xstart + scaler,ystart + 25);
if(scaler < 50)
{
label.setText("1");
}
else
{
label.setText("2");
}
}
}

Can't get the next JFrame to pop up

I'm making the game of battleship and I can't get the JFrame with the win panel nor the JFrame with the lose panel to pop up when the player wins or loses. Any ideas why? I'm thinking it just never gets to the other two loops in the main program, but I'm not sure. I did check to make sure that the global variables correct and incorrect were incrementing correctly, and they are.
//Battleship.java
import javax.swing.*;
import java.awt.*;
import java.util.Scanner;
import java.io.*;
import javax.swing.JOptionPane;
public class Battleship
{
public static String name;
public static void main (String[] args) throws IOException
{
Battleship.name = JOptionPane.showInputDialog("What is your name?");
String answer = JOptionPane.showInputDialog("Welcome to Battleship, "+name+". Would you like instructions?"); //(GUI1) Dialog Box
if(answer.equals ("yes") || answer.equals ("Yes"))
{
JOptionPane.showMessageDialog(null,"In this variant of Battleship, you will try to bomb two randomly-placed ships"
+"\nby clicking on the buttons that represent the field of play. There are two ships:"
+"\nOne 1x2 ship and one 1x3 ship. Green is a hit and red is a miss. Good luck!");
}
//Creates a JFrame and adds the Buttons panel to it
JFrame frame = new JFrame("Battleship");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Buttons b = new Buttons(); //(GUI2) 1-D Array of Buttons
Check c = new Check();
NamePanel n = new NamePanel();
JPanel panel = new JPanel(); //Instantiating a panel
panel.add(c);
panel.add(b); //Adds the 1-D Array of buttons to the panel
panel.setBackground(Color.blue);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
frame.getContentPane().add (panel);
frame.pack();
frame.setVisible(true);
frame.getContentPane().validate();
frame.getContentPane().repaint();
if(Buttons.correct == 5 && (Buttons.incorrect+Buttons.correct)<=15)
{
//Creats a new frame and adds the winner's panel to the frame
JFrame frame1 = new JFrame("Winner!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
WinPanel panel2 = new WinPanel();
frame1.getContentPane().add(panel2);
frame1.pack();
frame1.setVisible(true);
}
else if(Buttons.correct<5 && (Buttons.incorrect+Buttons.correct) >= 15)
{
//Creates a new frame and adds the loser's panel to the frame
JFrame frame1 = new JFrame("You lost");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
LosePanel panel2 = new LosePanel();
frame1.getContentPane().add(panel2);
frame1.pack();
frame1.setVisible(true);
}
}
}
//Buttons.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Scanner;
import java.io.*;
import java.util.Random;
import java.util.*;
public class Buttons extends JPanel
{
JButton[] btn;
static int[] numbers = new int[5];
public static int correct = 0;
public static int incorrect = 0;
public Buttons() throws IOException
{
String[] numberLine = choose(new File("Coords.txt")).split(",");
for(int i = 0; i < 5; i++)
{
numbers[i] = Integer.parseInt(numberLine[i]);
}
btn = new JButton[25];
setLayout(new GridLayout(5,5));
setBackground(Color.blue);
setPreferredSize(new Dimension(300,300));
ButtonListener blisten = new ButtonListener(); //LI
for(int i=0;i<25;i++)
{
btn[i] = new JButton();
btn[i].addActionListener(blisten);
add (btn[i]);
}
} //Ends Constructor
private class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
Object source = event.getSource();
while((Buttons.correct+Buttons.incorrect)<15 && (Buttons.correct<5))
{
for(int i=0;i<25;i++)
if(source==btn[i])
if(i==numbers[0] || i==numbers[1] || i==numbers[2] || i==numbers[3] || i==numbers[4])
{
btn[i].setBackground(Color.green);
btn[i].setEnabled(false);
Buttons.correct++;
System.out.println(Buttons.correct);
}
else
{
btn[i].setBackground(Color.red);
btn[i].setEnabled(false);
Buttons.incorrect++;
System.out.println(Buttons.incorrect);
}
break;
}
}
}
//Choose method to choose a random line of the imported text file
public static String choose(File f) throws FileNotFoundException
{
String result = null; //String is set to null
Random rand = new Random(); //Instantiating a random number generator
int n = 0;
for(Scanner sc = new Scanner(f); sc.hasNext(); ) //for loop-as long as the file has more to read
{
++n; //Incrementing temp variable
String line = sc.nextLine(); //Reading from the file
if(rand.nextInt(n) == 0)
result = line; //String result is now equal to the text imported from the file
}
return result; //Returning the string
}
} //Ends Program
// LosePanel.java
import javax.swing.*;
import java.awt.*;
public class LosePanel extends JPanel
{
public LosePanel()
{
setPreferredSize(new Dimension(500,500));
setBackground(Color.white);
}
public void paintComponent(Graphics page) //DR
{
super.paintComponent(page);
page.drawOval(165,165,150,150);
page.fillOval(165+47,165+25,10,10);
page.fillOval(165+92,165+25,10,10);
page.drawArc(165+45,165+80,60,30,0,180);
page.drawString("Better luck next time", 182,90);
}
}
// WinPanel.java
import javax.swing.*;
import java.awt.*;
public class WinPanel extends JPanel
{
public WinPanel()
{
setPreferredSize(new Dimension(500,500));
setBackground(Color.white);
}
public void paintComponent(Graphics page) //(DR)
{
super.paintComponent(page);
page.drawOval(165,165,150,150);
page.fillOval(165+47,165+25,10,10);
page.fillOval(165+92,165+25,10,10);
page.drawArc(165+46,165+70,60,30,0,-180);
page.drawString("You've won the game! Congratulations!", 150,90);
}
}
Guis are event driven frame works. That is, the user does something and you respond to it
Basically, what's happening, is you're checking the state of Buttons before anythings actually being done.
Take a look at Creating a GUI in Swing, How to use buttons and How to write an Action Listener for some ideas, examples and suggestions on writing GUI's

Event for JComboBox array and show information at the JLabel Array

I have the JComboBox Array and the JLabel Array like this
What i will do here to make the JLabel return corresponding when I select the values in each JComboBo
Example when comboBox[0].setSelectItem(4); the label[0] will get the text is 4
when the comboBox[4].setSelectedItem(2); the lable[4] will get the text is 2
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JLabel;
public class Example extends javax.swing.JFrame implements ItemListener {
JComboBox[] comboBox = new JComboBox[5];
JLabel[] label = new JLabel[5];
public void test() {
for (int i = 0; i < label.length; i++) {
comboBox[i] = new JComboBox();
label[i] = new JLabel();
add(comboBox[i]);
add(label[i]);
for (int j = 0; j <= 10; j++) {
comboBox[i].addItem(j);
}
comboBox[i].addItemListener(this);
}
}
#Override
public void itemStateChanged(ItemEvent e) {
// What i will do here to make the JLabel return corresponding when I
// select the values in each JComboBox
/*
* Example when comboBox[0].setSelectItem(4); the label[0] will get the
* text is 4 when the comboBox[4].setSelectedItem(2); the lable[4] will
* get the text is 2
*/
}
}
Please anyone help me :(
JComboBox has method
public int getSelectedIndex()
Use it to get index, convert the index to string and set to the JLabel.
1) You adding your components directly to JFrame with help of
add(comboBox[i]); add(label[i]); , but in this case your JFrame use BorderLayout as default, and you always add components to Center position, in this case you will see only one component. Tutorial for LayoutManager.
I recommend you to add your labels and comboBoxes to separate panels and then add them to JFrame.
2)Your Example class implements ItemListener and you add it to your JComboBox, it's right but in this case you must to loop relevat JLabel in itemStateChanged(ItemEvent e). Try to add separate listeners to each comboBox with JLabel as parametr.
3) Instead of adding each value to comboBox you can use constructor of JComboBox with array parametr.
I changed your code examine it:
import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Test extends javax.swing.JFrame {
JComboBox[] comboBox = new JComboBox[5];
JLabel[] label = new JLabel[5];
public void test() {
JPanel labels = new JPanel();
JPanel boxes = new JPanel();
Object[] values = new Object[]{1,2,3,4,5,6,7,8,9,0};
for (int i = 0; i < label.length; i++) {
comboBox[i] = new JComboBox(values);
label[i] = new JLabel(" ");
boxes.add(comboBox[i]);
labels. add(label[i]);
comboBox[i].addItemListener(getListener(label[i]));
}
getContentPane().add(boxes,BorderLayout.SOUTH);
getContentPane().add(labels,BorderLayout.NORTH);
pack();
}
private ItemListener getListener(final JLabel jLabel) {
return new ItemListener() {
#Override
public void itemStateChanged(ItemEvent arg0) {
if(arg0.getStateChange() == ItemEvent.SELECTED){
jLabel.setText(((JComboBox)arg0.getSource()).getSelectedItem().toString());
}
}
};
}
public static void main(String...strings ){
Test test = new Test();
test.test();
test.setVisible(true);
}
}
and output:

Categories

Resources