Modifying a double list with "move all" button - java

I am working on a GUI (that this community has been extremely helpful with so far) and I have reached another important step I need to achieve.
Currently my GUI consists of a JOptionsPane. Inside this pane is a panel that contains two lists and four buttons. Two of the buttons are arrows who's text is ">" and "<". (The buttons are in between both lists.)
Those buttons work correctly. A user can select one of the objects from the first list and then click the > and it will move to the second list and visa versa.
Next I need to add a feature where there is a ">>" button. This will move all the items in the first list to the second. I really have no idea how to handle this part. I am assuming it is some type of while loop although I'm not entirely sure.
First allow me to post the simple snipplet that shows the > button.
buttonin = new JButton(" > ");
buttonin.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
int[] fromindex = outputDetails.getSelectedIndices();
Object[] from = outputDetails.getSelectedValues();
for(int i=0; i< from.length; i++){
output.addElement(from[i]);
System.out.println(output);
}
for(int i = (fromindex.length-1); i>=0; i--){
input.remove(fromindex[i]);
}
}
});
Next I will post the full code in case that is needed to understand what I am trying to achieve. I hope this is enough information for someone to assist me if not I apologize, the actual program is very long and I couldn't think of an easy way to isolate this test case.
public static void displayGUI(){
int result = JOptionPane.showOptionDialog(null, getPanel(),"JOptionPane Example : ", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, new String[]{"Confirm","Create Return"}, "default");
if(result == 1){
initialScreenDecisions="NONE";
MainWriter.finishedCounter=true;
System.out.println(MainWriter.finishedCounter);
while(MainWriter.entryDetails.size()>0){
MainWriter.entryDetails.remove(0);
}
while(output.size()>0){
output.remove(0);
}
}
}
private static JPanel getPanel(){
JPanel panel = new JPanel();
JPanel panelTop = new JPanel();
JPanel topButtons = new JPanel();
JPanel bottomButtons = new JPanel();
String text = "<html>"
+"Batch <font size=6 color=>"+MainWriter.batchHeaderCounter+"</font> of <font size=6>"+BatchCounter.BatchTotal+"</font>"
+"<br>Batch Header: <font size=5><font color=red>"+MainWriter.BatchHeader+"</font>"
+"</html>";
JLabel topLabel = new JLabel(text);
panelTop.add(topLabel);
input = new DefaultListModel();
output = new DefaultListModel();
String[] shoppingItems = new String[MainWriter.entryDetails.size()];
shoppingItems = MainWriter.entryDetails.toArray(shoppingItems);
for(int i = 0; i < shoppingItems.length; i++){
input.addElement(shoppingItems[i]);
}
outputDetails = new JList(input);
outputDetails.setVisibleRowCount(10);
outputDetails.setFixedCellHeight(20);
outputDetails.setFixedCellWidth(400);
outputDetails.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
JScrollPane list1 = new JScrollPane(outputDetails);
inputDetails = new JList(output);
inputDetails.setVisibleRowCount(10);
inputDetails.setFixedCellHeight(20);
inputDetails.setFixedCellWidth(400);
inputDetails.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
JScrollPane list2 = new JScrollPane(inputDetails);
JPanel buttonPanel = new JPanel();
buttonin = new JButton(" > ");
buttonin.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
int[] fromindex = outputDetails.getSelectedIndices();
Object[] from = outputDetails.getSelectedValues();
for(int i=0; i< from.length; i++){
output.addElement(from[i]);
System.out.println(output);
}
for(int i = (fromindex.length-1); i>=0; i--){
input.remove(fromindex[i]);
}
}
});
buttonPanel.add(buttonin);
buttonout = new JButton(" < ");
buttonout.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
Object[] to = inputDetails.getSelectedValues();
int[] toindex = inputDetails.getSelectedIndices();
for(int i = 0; i < to.length; i++){
input.addElement(to[i]);
}
for(int i = (toindex.length-1); i >=0; i--){
output.remove(toindex[i]);
}
}
});
buttonall = new JButton(" >> ");
buttonall.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
if(initialScreenDecisions.equals("DEFAULT")){
JOptionPane.showMessageDialog(null, "You have selected to add all entry details. Please " +
"\nclick okay on the next scren to confirm or click " +
"\n'>>' again to cancel the apply all option.");
initialScreenDecisions="ADDALL";
}else if(initialScreenDecisions.equals("ADDALL")){
JOptionPane.showMessageDialog(null, "You have canceled the apply all option.");
initialScreenDecisions="DEFAULT";
}else{
JOptionPane.showMessageDialog(null, "You must disable the '<<' option before you can use this.");
}
}
});
buttonnone = new JButton(" << ");
buttonnone.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
if(initialScreenDecisions.equals("DEFAULT")){
JOptionPane.showMessageDialog(null, "You have selected to skip the current batch and" +
"\nomit all of it's entries. Click okay on the next" +
"\nscreen to confirm or click '<<' again to" +
"\ncancel the option.");
initialScreenDecisions="NONE";
}else if(initialScreenDecisions.equals("NONE")){
JOptionPane.showMessageDialog(null, "You have canceled the omit all option.");
initialScreenDecisions="DEFAULT";
}else{
JOptionPane.showMessageDialog(null, "You must disable the '>>' option before you can use this.");
}
}
});
buttonhelp = new JButton("HELP");
buttonhelp.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null, "This screen allows you to determine the entry details from" +
"\nthe current batch that will be included in the final return." +
"\nSelect the details you wish to include and click the > arrow to" +
"\nmove them to the right side. Pressing the >> button will" +
"\ninclude all entry details for the current batch in the final" +
"\nreturn. Clicking the < button will move a detail back."+
"\nClick << to omit the entire batch. Use confirm to continue"+
"\nto the next step or 'create return' to finish the Nacha return"+
"\nwith all past additions.");
}
});
buttonPanel.setLayout(new BorderLayout());
topButtons.add(buttonin);
topButtons.add(buttonall);
topButtons.add(buttonnone);
topButtons.add(buttonout);
bottomButtons.add(buttonhelp);
buttonPanel.add(topButtons,BorderLayout.NORTH);
buttonPanel.add(buttonhelp,BorderLayout.SOUTH);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));
bottomPanel.add(Box.createRigidArea(new Dimension(10,0)));
bottomPanel.add(list1);
bottomPanel.add(Box.createRigidArea(new Dimension(5,0)));
bottomPanel.add(buttonPanel);
bottomPanel.add(Box.createRigidArea(new Dimension(5,0)));
bottomPanel.add(list2);
bottomPanel.add(Box.createRigidArea(new Dimension(10,0)));
panel.setLayout(new BorderLayout());
panel.add(panelTop,BorderLayout.NORTH);
panel.add(bottomPanel,BorderLayout.CENTER);
panel.setOpaque(true);
return panel;
}
You can ignore the above >> button contents. Right now it will allow the user to select all of the items in the list it just doesn't visually show the selection. If I get the >> button to move all the items at once then I won't need the extra steps you can see I have implemented.

I'm not too sure what all your variable types are, but I think this should work in your ActionListener for >>.
for (int i = 0; i < input.getSize(); i++) {
output.addElement(input.get(i));
}
input.clear();

Related

Adding and removing checkboxes dynamically

I want to make ToDoList App. After successfully adding task to do (which contains checkbox, JLabel and date, all putted in a box) i want to remove them dynamically. With adding it's not problem but when i try to remove (ater clicking checked in checkbox) it works only once. Then it either removes not once which are intended or not removing them at all. I am not sure why it's not working so I paste all code below.
JSpinner dateSpin;
Box eventBox, boxBox;
Box[] taskBox = new Box[1000];
JTextField eventName;
Date date;
Checkbox[] doneCheck = new Checkbox[1000];
JLabel taskLabel;
JPanel panel;
JScrollPane scrollPane;
SimpleDateFormat simpleDate;
int i = 0;
public static void main(String[] args) {
new Main();
}
private Main(){
this.setSize(400, 600);
this.setTitle("To-Do List");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setLocationRelativeTo(null);
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
boxBox = Box.createVerticalBox();
scrollPane = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
eventBox = Box.createHorizontalBox();
eventBox.setBorder(BorderFactory.createEtchedBorder());
JLabel plusSign = new JLabel("+");
plusSign.setFont(new Font("Serafi", PLAIN, 20));
plusSign.setMaximumSize(new Dimension(Integer.MAX_VALUE, plusSign.getMinimumSize().height));
eventBox.add(plusSign);
eventName = new JTextField(20);
eventName.setFont(new Font("Times", Font.ITALIC, 15));
eventName.setMaximumSize(new Dimension(Integer.MAX_VALUE, eventName.getMinimumSize().height));
eventName.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == eventName){
/* to do: saving every task in some file, figure out how to remove
those tasks (checkbox + jlabel) -> whole box from screen or how to send them to "done"
also "done" to do*/
simpleDate = new SimpleDateFormat("E-dd-MM-yyyy");
taskBox[i] = Box.createHorizontalBox();
taskBox[i].setBorder(BorderFactory.createTitledBorder(simpleDate.format(date)));
doneCheck[i] = new Checkbox();
doneCheck[i].addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
int k = 0;
for (int j = 0; j < doneCheck.length; j++) {
if(doneCheck[j].getState()){
//remove(doneCheck[k]);
//System.out.println("?" + i + "?" + k + " " + e.getSource().toString());
System.out.println("xxxxx" + doneCheck[j].getState());
break;
}
System.out.println("oooooo");
k++;
}
System.out.println(doneCheck.length + taskBox[k].toString());
//System.out.println("! " + k + " " + e.getSource().toString());
boxBox.remove(taskBox[k]);
//boxBox.removeAll();
boxBox.revalidate();
boxBox.repaint();
}
});
taskBox[i].add(doneCheck[i]);
String taskName = eventName.getText();
taskLabel = new JLabel(taskName);
taskLabel.setMinimumSize(new Dimension(500,10));
taskLabel.setPreferredSize(new Dimension(300, 10));
taskBox[i].add(taskLabel);
boxBox.add(taskBox[i]);
boxBox.setMaximumSize(new Dimension(Integer.MAX_VALUE, boxBox.getMinimumSize().height + 11));
panel.add(boxBox);
panel.revalidate();
panel.repaint();
i++;
}
}
});
eventBox.add(eventName);
date = new Date();
dateSpin = new JSpinner(new SpinnerDateModel(date, null, null, Calendar.DAY_OF_MONTH));
JSpinner.DateEditor dateEditor = new JSpinner.DateEditor(dateSpin, "dd/MM/yy");
dateSpin.setEditor(dateEditor);
dateSpin.setMaximumSize(new Dimension(Integer.MAX_VALUE, dateSpin.getMinimumSize().height));
dateSpin.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
if(e.getSource() == dateSpin){
date = (Date) dateSpin.getValue();
}
}
});
eventBox.add(dateSpin);
panel.add(eventBox, new FlowLayout());
this.add(scrollPane);
this.setVisible(true);
}
You never remove elements from the taskBox and doneCheck arrays.
Now if you mark the first entry as done, your ItemListener will always find this first entry when looping over the doneCheck array.
Marking the entries as done in reverse order (always the last shown entry) will remove one entry after the other.
As to your software design: it's considered bad practice to manage your data in several parallel arrays.
Please consider creating a custom class for the todo items that manages all the elements of a single todo item.
Unless you are initializing doneCheck items somewhere, this:
Checkbox[] doneCheck = new Checkbox[1000];
And this:
int k = 0;
for (int j = 0; j < doneCheck.length; j++) {
if (doneCheck[j].getState()) {
--------^^^^^^^^^^^^
Is probably one the reason it fails: you probably got a NullPointerException somewhere, eg: when value of j > 0. The NPE will probably be catched by the EventDispatchThread which may or may not be kind enough to show it on stderr...
I fail to see why you are using this array, and you can shorten your code and avoid NPE like this:
Checkbox cb = new Checkbox();
cb.addItemListener(event -> {
if (cb.getState()) { // not null!
boxBox.remove(cb);
boxBox.revalidate();
boxBox.repaint();
}
});
doneCheck[i] = cb; // I still don't know why you need that.
My guess is that you have 2 variables global int i = 0 and local int k = 0 in here
public void itemStateChanged(ItemEvent e) {
// int k = 0;//<-------- LOCAL
for (int j = 0; j < doneCheck.length; j++) {
if(doneCheck[j].getState()){
//Either k = j;
boxBox.remove(taskBox[j]);
//remove(doneCheck[k]);
//System.out.println("?" + i + "?" + k + " " + e.getSource().toString());
System.out.println("xxxxx" + doneCheck[j].getState());
break;
}
System.out.println("oooooo");
//k++;//<-- ALWAYS == last j value before the break;
}
System.out.println(doneCheck.length + taskBox[k].toString());
//System.out.println("! " + k + " " + e.getSource().toString());
//boxBox.remove(taskBox[k]);//
//boxBox.removeAll();
boxBox.revalidate();
boxBox.repaint();
}
Every time you call for itemStateChanged int k = 0; will be initialized to 0 and you will be removing element[j] from array of taskBox. As you k++ statement will be equal to the last j value before the break; because it sits after the if(doneCheck[j].getState()){...
Try moving boxBox.remove(taskBox[j]); inside the for loop and using j instead of k.

Centering GUI's

I've created a simple guessing game with GUI's. The problem is, whenever I maximize my window, the whole GUI is stuck in the top middle. I would like to know how to center it in the middle and how to make it bigger. Here's the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GuessingGameNew implements ActionListener {
private final double VERSION = 2.3;
//Initializing Main Window and Difficulty Window
JFrame window = new JFrame("Guess The Number " + VERSION);
JFrame DiffFrame = new JFrame("Difficulty");
JButton btnNewGame = new JButton("New Game");
JButton btnInstruction = new JButton("Instructions");
JButton btnDifficulty = new JButton("Change Difficulty");
JButton btnAbout = new JButton("About");
JButton btnExit = new JButton("Exit");
JButton btnOK = new JButton("Ok");
JButton btnDiff[] = new JButton[6];
//Making Panel for Main Menu Buttons
JPanel pnlMainMenu = new JPanel();
//Making Panel for Difficulty Buttons
JPanel pnlDifficulty = new JPanel();
int diff = 10;
int tries;
int Secret;
int Guess;
int option = 0;
boolean Cancel = false;
GuessingGameNew() { //constructor
//Setting Main Window properties
window.setSize(400, 300);
window.setLocation(500, 260);
window.setLayout(new FlowLayout(FlowLayout.CENTER));
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DiffFrame.setSize(230, 210);
DiffFrame.setLocation(530, 230);
DiffFrame.setLayout(new BorderLayout());
//MainMenu Panel Layout and adding Main Menu Buttons
// GridLayout(int rows, int columns, int Horizontal_Gap, intVertical_Gap)
pnlMainMenu.setLayout(new GridLayout(5, 1, 2, 8));
pnlMainMenu.add(btnNewGame);
pnlMainMenu.add(btnInstruction);
pnlMainMenu.add(btnDifficulty);
pnlMainMenu.add(btnAbout);
pnlMainMenu.add(btnExit);
pnlMainMenu.setBackground(Color.red);
//Setting Layout for Difficulty Panel
pnlDifficulty.setLayout(new GridLayout(6, 1, 2, 2));
btnDiff[0] = new JButton("Very Easy (0 - 3)");
btnDiff[1] = new JButton("Easy (0 - 50)");
btnDiff[2] = new JButton("Medium (0 - 100)");
btnDiff[3] = new JButton("Hard (0 - 500)");
btnDiff[4] = new JButton("Very Hard (0 - 1000)");
btnDiff[5] = new JButton("Custom (0 - ?)");
btnNewGame.addActionListener(this);
btnInstruction.addActionListener(this);
btnDifficulty.addActionListener(this);
btnAbout.addActionListener(this);
btnExit.addActionListener(this);
btnOK.addActionListener(this);
for(int i=0; i<6; i++) {
btnDiff[i].addActionListener(this);
pnlDifficulty.add(btnDiff[i]);
}
window.add(pnlMainMenu);
window.setVisible(true);
}
public void actionPerformed(ActionEvent click) {
System.out.println("Action Performed");
if(click.getSource() == btnNewGame) {
NewGame();
}
if(click.getSource() == btnExit) {
option = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?", "Exit Game" ,JOptionPane.YES_NO_OPTION);
if(option == JOptionPane.YES_OPTION)
System.exit(0);
}
if(click.getSource() == btnInstruction) {
JOptionPane.showMessageDialog(null,
"Game:" + "\nClick New Game to start a new game.\nGuess a number between 0 and the selected number. Keep Guessing until you get it correct."
+ "\n\nDifficulty:" + "\nYou can change the difficulty of the game\n in the Main Menu to a Custom range or a \npreset range."
, "Instructions", JOptionPane.INFORMATION_MESSAGE);
}
if(click.getSource() == btnAbout) {
JOptionPane.showMessageDialog(null,JOptionPane.INFORMATION_MESSAGE);
}
if(click.getSource() == btnDifficulty) {
Change_Difficulty();
}
for(int i=0; i<6; i++) {
if(click.getSource() == btnDiff[i]) {
if(click.getSource() == btnDiff[0])
diff = 3;
if(click.getSource() == btnDiff[1])
diff = 50;
if(click.getSource() == btnDiff[2])
diff = 100;
if(click.getSource() == btnDiff[3])
diff = 500;
if(click.getSource() == btnDiff[4])
diff = 1000;
if(click.getSource() == btnDiff[5])
diff = Custom();
DiffFrame.setVisible(false);
}
}
}
public void NewGame() {
tries = 1;
Guess = 101;
Secret = (int)((Math.random()) * (diff + 1));
Cancel = false;
while(Guess != Secret) {
try {
if(tries == 1) {
Guess = Integer.parseInt(JOptionPane.showInputDialog(null, "Try: 1" + "\nGuess a number between 0 and " + diff, "Guess?", JOptionPane.PLAIN_MESSAGE));
tries++;
} else {
if(Guess > Secret)
Guess = Integer.parseInt(JOptionPane.showInputDialog(null, "Try: " + tries + "\n" + Guess + "\nGuess Lower..."));
else if(Guess < Secret)
Guess = Integer.parseInt(JOptionPane.showInputDialog(null, "Try: " + tries + "\n" + Guess + "\nGuess Higher..."));
tries++;
}
} catch(NumberFormatException e) {
if(e.getMessage() == "null") {
option = JOptionPane.showConfirmDialog(null, "Are you sure you want to go back to the Main Menu?", "Cancel?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if(option == JOptionPane.YES_OPTION) {
Cancel = true;
break;
}
}
JOptionPane.showMessageDialog(null, "Error: " + e.getMessage() + "\nEnter whole numbers only!");
}
}
if(!Cancel) {
tries--;
JOptionPane.showMessageDialog(null, Guess + " is Correct!!\nYou WON in " + tries + " tries.", "Winner", JOptionPane.INFORMATION_MESSAGE);
option = JOptionPane.showConfirmDialog(null, "Do you want to try again?", "Try Again?", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);
if(option == JOptionPane.YES_OPTION)
NewGame();
}
}
public void Change_Difficulty() {
DiffFrame.add(pnlDifficulty, BorderLayout.CENTER);
DiffFrame.setVisible(true);
}
public int Custom() {
try {
diff = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter a number that you want to be the range (0 to ?)", diff));
} catch(NumberFormatException e) {
}
return diff;
}
public static void main(String[] args) {
new GuessingGameNew();
}
}
You are setting a FlowLayout:
window.setLayout(new FlowLayout(FlowLayout.CENTER));
This layout has no notion of vertical alignment, it will only wrap its contents when out of horizontal space. Setting the alignment applies only to horizontal behavior.
I would like to know how to center it in the middle and how to make it bigger.
If you delete that line then the default CENTER position of BorderLayout will be used, which centers and stretches the component both horizontally and vertically:
The default Layout Manager for a JFrame is the BorderLayout. Calling window.getContentPane().add(component); or if you feel like typing more, then window.getContentPane().add(component, BorderLayout.CENTER); adds your component to the center of the window. Also, as a tip, do study Layout Managers deeply. You can build really cool stuff with the proper understanding of how they work, what they do, and which one is more appropriate for which scenario.

Comparing the text of different JButtons

I am currently coding a game and part of it consist of having different tiles to be put in a board. I plan on simulating this by having different buttons that will be used to represent the tiles with their corresponding coordinates. For example, one button will say "A1", "A2", etc. What I would like to accomplish, is to have the user click on the "A1" tile and then the button on the board that represents "A1" will change colors, is there any way to go through the buttons on the board and compare its text to the selection of the user? The following is what I used to create the board:
JButton[][] buttons = new JButton[9][12];
JPanel panel = new JPanel(new GridLayout(9,12,5,5));
panel.setBounds(10, 11, 800, 600);
frame.getContentPane().add(panel);
//board
for (int r = 0; r < 9; r++)
{
for (int c = 0; c < 12; c++)
{
buttons[r][c] = new JButton("" + (c + 1) + numberList[r]);
buttons[r][c].setBackground(Color.WHITE);
panel.add(buttons[r][c]);
}
}
This is what I wrote on the code of one of the tiles
JButton tile1 = new JButton ("A1");
tile1.setBounds(60,725,60,60);
frame.getContentPane().add(tile1);
tile1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String buttonText = tile1.getText();
// iterating through all buttons:
for(int i=0;i<buttons.length;i++){
for(int j=0;j<buttons[0].length;j++)
{
JButton b = buttons[i][j];
String bText = b.getText();
if(buttonText.equals(bText))
{
[i][j].setBackground(Color.BLACK);
}
}
}
}
} );
However, it is given me an error saying that there is an action expected after "{"
You may add an action listener to each of the JButton you are creating in the loop like below:
buttons[r][c].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// your code here
}
} );
Placing the listener in your code may look like
JButton[][] buttons = new JButton[9][12];
JPanel panel = new JPanel(new GridLayout(9,12,5,5));
panel.setBounds(10, 11, 800, 600);
frame.getContentPane().add(panel);
//board
for (int r = 0; r < 9; r++)
{
for (int c = 0; c < 12; c++)
{
buttons[r][c] = new JButton("" + (c + 1) + numberList[r]);
buttons[r][c].setBackground(Color.WHITE);
buttons[r][c].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
String buttonText = button.getText();
// now iterate over all the jbuttons you have
for(int i=0;i<buttons.length;i++){
for(int j=0;j<buttons[0].length;j++){
JButton b = buttons[i][j];
String bText = b.getText();
if(buttonText.equals(bText)){
// you found a match here
// and you have the positions i, j
//
}
}
}
}
} );
panel.add(buttons[r][c]);
}
}
And you could store the the colors to be changed to in global static array, and use that array in your action listener.
For information on adding listener to the JButton, you may refer this thread How do you add an ActionListener onto a JButton in Java
Hope this helps!
You need listeners.
Implement ActionListener to your class. This will require you to add public void actionPerformed(ActionEvent e) {} to your class.
Every JButton you use should have an action listener.
Apply one like that:
JButton but = new JButton();
but.addActionListener(this);
Finally, in the actionPerformed method we added, you need to add something like that:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == but)
but.setBackground(Color.BLACK);
}
P.S. you can get a button's text value by the means of:
but.getText();

Program freezing(not responding) after button click no a Java app

Ok so I'm building to show students how a loop goes through an array, I have added 2 images to help explain and the code, the first is the result I get after I click go then it freezes . The Second image is what I'd like it to do after you put in the values of 1 in start, 15 in stop, 3 in step and click the Go Button. And then to be cleared on the click of Clear button. I think they probably related. Can anyone see the problem? Thanks in advanced!
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import javax.swing.JOptionPane;
public class Checkerboard extends Frame implements ActionListener
{
int[] blocksTextField = new int[15];
Panel blocksPanel = new Panel();
TextArea blocksDisplay[] = new TextArea[16];
TextField start = new TextField (3);
TextField stop = new TextField (3);
TextField step = new TextField (3);
//Colors
Color Red = new Color(255, 90, 90);
Color Green = new Color(140, 215, 40);
Color white = new Color(255,255,255);
//textField ints
int inputStart;
int inputStop;
int inputStep;
//Lables
Label custStartLabel = new Label ("Start : ");
Label custStopLabel = new Label ("Stop : ");
Label custStepLabel = new Label ("Step : ");
//Buttons
Button goButton = new Button("Go");
Button clearButton = new Button("Clear");
//panel for input textFields and lables
Panel textInputPanel = new Panel();
//Panel for buttons
Panel buttonPanel = new Panel();
public Checkerboard()
{//constructor method
//set the 3 input textFields to 0
inputStart = 0;
inputStop = 0;
inputStep = 0;
//set Layouts for frame and three panels
this.setLayout(new BorderLayout());
//grid layout (row,col,horgap,vertgap)
blocksPanel.setLayout(new GridLayout(4,4,10,10));
textInputPanel.setLayout(new GridLayout(2,3,20,10));
buttonPanel.setLayout(new FlowLayout());
//setEditable()
//setText()
//add components to blocks panel
for (int i = 0; i<16; i++)
{
blocksDisplay[i] = new TextArea(null,3,5,3);
if(i<6)
blocksDisplay[i].setText(" " +i);
else
blocksDisplay[i].setText(" " +i);
blocksDisplay[i].setEditable(false);
// blocksDisplay[i].setBackground(Red);
blocksPanel.add(blocksDisplay[i]);
}//end for
//add componets to panels
//add text fields
textInputPanel.add(start);
textInputPanel.add(stop);
textInputPanel.add(step);
//add lables
textInputPanel.add(custStartLabel);
textInputPanel.add(custStopLabel);
textInputPanel.add(custStepLabel);
//add button to panel
buttonPanel.add(goButton);
buttonPanel.add(clearButton);
//ADD ACTION LISTENRS TO BUTTONS (!IMPORTANT)
goButton.addActionListener(this);
clearButton.addActionListener(this);
add(blocksPanel, BorderLayout.NORTH);
add(textInputPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
//overridding the windowcClosing() method will allow the user to clisk the Close button
addWindowListener(
new WindowAdapter()
{
public void windowCloseing(WindowEvent e)
{
System.exit(0);
}
}
);
}//end of constructor method
public void actionPerformed(ActionEvent e)
{
//if & else if to see what button clicked and pull user input
if(e.getSource() == goButton) //if go clicked ...
{
System.out.println("go clicked");
try{
String inputStart = start.getText();
int varStart = Integer.parseInt(inputStart);
if (varStart<=0 || varStart>=15 )throw new NumberFormatException();
System.out.println("start = " + varStart);
// roomDisplay[available].setBackground(lightRed);
String inputStop = stop.getText();
int varStop = Integer.parseInt(inputStop);
if (varStop<=0 || varStart>=15 )throw new NumberFormatException();
System.out.println("stop = " + varStop);
String inputStep = step.getText();
int varStep = Integer.parseInt(inputStep);
if (varStep<=0 || varStep>=15 )throw new NumberFormatException();
System.out.println("step = " + varStep);
for (int i = varStart; i<varStop; varStep++)//ADD WHILE LOOP
{
blocksDisplay[i].setBackground(Red);
blocksDisplay[i].setText(" " +i);
}
}
catch (NumberFormatException ex)
{
JOptionPane.showMessageDialog(null, "You must enter a Start, Stop and Step value greater than 0 and less than 15",
"Error",JOptionPane.ERROR_MESSAGE);
}
}
else if(e.getSource() == clearButton ) //else if clear clicked ...
{
System.out.println("clear clicked");
}
//int available = room.bookRoom(smoking.getState());
//if (available > 0)//Rooms is available
}//end action performed method
public static void main(String[]args)
{
Checkerboard frame = new Checkerboard ();
frame.setBounds(50, 100, 300, 410);//changed size to make text feilds full charater size
frame.setTitle("Checkerboarder Array");
frame.setVisible(true);
}//end of main method
}
The problem is your loop: your loop variable name is i but you change the varStep variable instead of i so basically the loop variable never changes and thus the exit condition will never be true.
I believe you want to step i with varStep, so change your loop to:
for (int i = varStart; i<varStop; i += varStep)
// stuff inside loop
Take a look at this loop.
for (int i = varStart; i<varStop; varStep++)//ADD WHILE LOOP
{
blocksDisplay[i].setBackground(Red);
blocksDisplay[i].setText(" " +i);
}
It ends when i >= varStop, but neither i nor varStop change as a consequence of its execution, so it can never stop. You only increment varStep.
I think you want to increment i by varStep on each iteration instead, i.e. i += varStep
You use varStep++ in your for loop. I think you meant to do i+varStep.
The application freezes because you're never increasing i, resulting in an endless loop.

for loop for array only processing one element in java?

I can't figure out why whenever I cycle through my array using the for-loop it only produces one element (the first) to console? I'm pretty sure it's a rookie-mistake I'm looking over, so any tips and suggestions would help.
I'm making a program for fun that compares two strings typed in a text field and if they don't exist in the array it produces a JOPtionPane message on the contrary. It's for a battle-hack I may produce in the future for vBulletin forum, but I'm messing around with algorithms before I move to that step. Thanks, guys!
package battleoptionspart1;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.lang.*;
import javax.swing.border.*;
public class BattleOptionsPart1 extends JFrame{
JButton newthread, previewpost;
JRadioButton battle1;
JTextField postcount, oppA, oppB;
JLabel battle2, max;
JPanel panel;
String [] array = {"Bill","Tom","Wendy", "Paula"};
public BattleOptionsPart1 () {
panel = new JPanel();
Toolkit tool = Toolkit.getDefaultToolkit();
Dimension dim = tool.getScreenSize();
this.setSize(500, 500);
this.setTitle("Battle Options");
GridLayout grid = new GridLayout(0,1,2,2);
this.setLayout(grid);
newthread = new JButton("Post New Thread");
previewpost = new JButton("Preview Post");
postcount = new JTextField("", 4);
oppA = new JTextField("",10);
oppB = new JTextField("",10);
battle1 = new JRadioButton();
battle2 = new JLabel("Would you like to start a recorded battle?");
max = new JLabel("Enter max post count user must have to vote");
ListenForButton listen = new ListenForButton();
newthread.addActionListener(listen);
previewpost.addActionListener(listen);
JPanel opponents = new JPanel();
Border oppBorder = BorderFactory.createTitledBorder("Battlers");
opponents.setBorder(oppBorder);
opponents.add(oppA);
opponents.add(oppB);
JPanel battle = new JPanel();
Border battleBorder = BorderFactory.createTitledBorder("Start Battle");
battle.setBorder(battleBorder);
battle.add(battle1);
battle.add(battle2);
JPanel buttons = new JPanel();
Border buttonBorder = BorderFactory.createTitledBorder("Create Thread");
buttons.setBorder(buttonBorder);
buttons.add(newthread);
buttons.add(previewpost);
JPanel restriction = new JPanel();
Border resBorder = BorderFactory.createTitledBorder("Restrictions");
restriction.setBorder(buttonBorder);
restriction.add(postcount);
restriction.add(max);
this.add(opponents);
this.add(battle);
this.add(restriction);
this.add(buttons);
this.add(panel);
int xPos = (dim.width / 2) - (this.getWidth() / 2);
int yPos = (dim.height / 2) - (this.getHeight() / 2);
this.setLocation(xPos,yPos); //places form in the middle
this.setVisible(true); // users can see form
this.setResizable(false); //users can't resize the form
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class ListenForButton implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String compareA = oppA.getText();
String compareB = oppB.getText();
if (e.getSource() == newthread)
{
System.out.println(compareA + "\n" + compareB);
for(int j = 0; j < array.length; j++)
{
System.out.println(array[j]);
if(!compareA.equals(array[j]))
{
JOptionPane.showMessageDialog(null, compareA + " doesn't exist!", "Error Message", JOptionPane.ERROR_MESSAGE);
oppA.requestFocus();
break;
}
if (!compareB.equals(array[j]))
{
JOptionPane.showMessageDialog(null, compareB + " doesn't exist!", "Error Message", JOptionPane.ERROR_MESSAGE);
oppB.requestFocus();
break;
}
else
{
JOptionPane.showMessageDialog(null, "New thread created successfully!", "Success", JOptionPane.INFORMATION_MESSAGE);
break;
}
}
}
else if (e.getSource() == previewpost)
{
System.exit(0);
}
}
}
public static void main(String[] args) {
BattleOptionsPart1 battle = new BattleOptionsPart1();
}
}
In each of the possible options in your loop, you use break, which leaves the loop immediately. If you remove those statements, you'll process each object in the array.
If you want to check if there's a match, you need to go through every element and do your processing after going through the whole array. Here is an example for an array of type int:
boolean contains = false;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == searchKey)
{
contains = true;
break;
}
}
You're breaking out of the loop. with the break; command after the first array element

Categories

Resources