Centering GUI's - java

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.

Related

Trouble displaying dice images in a JApplet

Hello I'm trying to add dice images on the side of my craps program. However I keep running into the issue of all my JLabels, Jtextfeilds and JButtons disappearing.
Dice images:
Craps.java:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Craps extends JApplet implements ActionListener{
private static final long serialVersionUID = 1L;
//constant variables for the status of the game
final int WON = 0,LOST =1, CONTINUE = 2;
//other variables used in the program
boolean firstRoll = true;
int sumOfDice = 0;
int myPoint = 0;
int gameStatus = CONTINUE;
int numberHouseWins = 0;
int numberPlayerWins = 0;
String divider = "*******";
int die1,die2,workSum;
//die faces
Image dieFace1,dieFace2,dieFace3,dieFace4,dieFace5,dieFace6;
//graphical user interface components
JLabel dieLabel1, dieLabel2, sumLabel, rollLabel, pointLabel;
JLabel lblHouseWins, lblPlayerWins;
JLabel leftDivider, rightDivider;
JTextField firstDie, secondDie, sum, point;
JTextField txtHouseWins, txtPlayerWins;
JButton roll;
public void paint(Graphics g){
if(die1 == 1){
repaint();
g.drawImage(dieFace1, 0, 0, this);
}
else if( die1 == 2){
repaint();
g.drawImage(dieFace2, 0, 0, this);
}
else if( die1 == 3){
repaint();
g.drawImage(dieFace3, 0, 0, this);
}
else if( die1 == 4){
repaint();
g.drawImage(dieFace4, 0, 0, this);
}
else if( die1 == 5){
repaint();
g.drawImage(dieFace5, 0, 0, this);
}
else if( die1 == 6){
repaint();
g.drawImage(dieFace6, 0, 0, this);
}
if ( die2==1){
repaint();
g.drawImage(dieFace1, 0, 30, this);
}else if( die2 == 2){
repaint();
g.drawImage(dieFace2, 0, 30, this);
}
else if( die2 == 3){
repaint();
g.drawImage(dieFace3, 0, 30, this);
}
else if( die2 == 4){
repaint();
g.drawImage(dieFace4, 0, 30, this);
}
else if( die2 == 5){
repaint();
g.drawImage(dieFace5, 0, 30, this);
}
else if( die2 == 6){
repaint();
g.drawImage(dieFace6, 0, 30, this);
}
}
public void init()
{
//setup graphical user interface components
JPanel display = new JPanel();
display.setLayout(new GridLayout(8, 2, 10, 10));
//creating JLabel Die1 to the display
dieLabel1 = new JLabel("Die 1:",SwingConstants.RIGHT);
display.add(dieLabel1);
firstDie = new JTextField(3);
firstDie.setEditable(false);
display.add(firstDie);
//creating JLabel Die2 to the Display
dieLabel2 = new JLabel("Die 2:",SwingConstants.RIGHT);
display.add(dieLabel2);
secondDie = new JTextField(3);
secondDie.setEditable(false);
display.add(secondDie);
//creating JLabel sum die to the display
sumLabel = new JLabel("Their sum is:",SwingConstants.RIGHT);
display.add(sumLabel);
sum = new JTextField(4);
sum.setEditable(false);
display.add(sum);
//creating JLabel rollLabel to the display
rollLabel= new JLabel("Roll Again",SwingConstants.RIGHT);
display.add(rollLabel);
roll = new JButton("Roll Dice");
roll.addActionListener(this);
display.add(roll);
//creating JLabel pointLabel to the display
pointLabel = new JLabel("Point is:",SwingConstants.RIGHT);
display.add(pointLabel);
point = new JTextField(3);
point.setEditable(false);
display.add(point);
//creating JLabel leftDivider and rightDivider to the display
leftDivider = new JLabel(divider,SwingConstants.RIGHT);
display.add(leftDivider);
rightDivider = new JLabel(divider,SwingConstants.LEFT);
display.add(rightDivider);
//creating JLabel lblPlayerWins and JTextField txtPlayerWins to the display
lblPlayerWins = new JLabel("Player wins:",SwingConstants.RIGHT);
display.add(lblPlayerWins);
txtPlayerWins = new JTextField(4);
txtPlayerWins.setEnabled(false);
display.add(txtPlayerWins);
//creating JLabel lblHouseWins and JTextField txtHouseWins to the display
lblHouseWins = new JLabel("House wins:",SwingConstants.RIGHT);
display.add(lblHouseWins);
txtHouseWins = new JTextField(4);
txtHouseWins.setEnabled(false);
display.add(txtHouseWins);
setContentPane(display);
dieFace1=getImage(getDocumentBase(),"die1.jpg");
dieFace2=getImage(getDocumentBase(), "die2.jpg");
dieFace3=getImage(getDocumentBase(),"die3.jpg");
dieFace4=getImage(getDocumentBase(), "die4.jpg");
dieFace5=getImage(getDocumentBase(),"die5.jpg");
dieFace6=getImage(getDocumentBase(), "die6.jpg");
}
public void actionPerformed(ActionEvent e){
play();
}
public void play(){
if(firstRoll){
sumOfDice = rollDice();
switch (sumOfDice) {
//player wins on first roll
case 7: case 11:
gameStatus = WON;
point.setText("");
break;
//house wins player loses on first roll
case 2:case 3: case 12:
gameStatus = LOST;
point.setText("");
break;
default:
gameStatus = CONTINUE;
myPoint = sumOfDice;
point.setText(Integer.toString(myPoint));
firstRoll = false;
break;
}
}
else{
sumOfDice = rollDice();
if(sumOfDice==myPoint)
gameStatus = WON;
else
if(sumOfDice == 7)
gameStatus = LOST;
}
if(gameStatus == CONTINUE)
showStatus("Roll again");
else{
if(gameStatus == WON){
showStatus("Player wins."+"Click Roll Dice to play again");
numberPlayerWins++;
txtPlayerWins.setText(Integer.toString(numberPlayerWins));
}
else{
showStatus("House wins."+"Click Roll Dice to play again");
numberHouseWins++;
txtHouseWins.setText(Integer.toString(numberHouseWins));
}
firstRoll = true;
}
}
public int rollDice(){
die1 = 1+ (int)(Math.random()*6);
die2 = 1+ (int)(Math.random()*6);
workSum = die1 +die2;
firstDie.setText(Integer.toString(die1));
secondDie.setText(Integer.toString(die2));
sum.setText(Integer.toString(workSum));
return workSum;
}
}
I've edited your code and included comments to explain what I did and the reasoning for it. It was much easier to explain the code in the code, rather than write up a huge explanation and reference different pieces of the code.
I removed your paint method, as it was not needed and endlessly looped between paint and repaint calls.
Note: Sorry about the spacing between types and variables, my IDE is set up that way.
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class Craps extends JApplet implements ActionListener {
private static final long serialVersionUID = 1L;
// constant variables for the status of the game
final int WON = 0, LOST = 1, CONTINUE = 2;
// other variables used in the program
boolean firstRoll = true;
int sumOfDice = 0;
int myPoint = 0;
int gameStatus = CONTINUE;
int numberHouseWins = 0;
int numberPlayerWins = 0;
String divider = "*******";
int die1, die2, workSum;
// graphical user interface components
JLabel dieLabel1, dieLabel2, sumLabel, rollLabel, pointLabel;
JLabel lblHouseWins, lblPlayerWins;
JLabel leftDivider, rightDivider;
JTextField firstDie, secondDie, sum, point;
JTextField txtHouseWins, txtPlayerWins;
JButton roll;
// added these two JLabels to display dice ImageIcons
JLabel dieImg1, dieImg2;
// die faces, changed to an array of ImageIcons
ImageIcon dieFaces[];
// moved these into their own function, init is pretty stuffed
public void createImageIcons() {
// create an array of ImageIcons, easier to set JLabels image using
// index rather than 6 if-else-if statements
dieFaces = new ImageIcon[6];
dieFaces[0] = new ImageIcon(getImage(getDocumentBase(), "die1.jpg"));
dieFaces[1] = new ImageIcon(getImage(getDocumentBase(), "die2.jpg"));
dieFaces[2] = new ImageIcon(getImage(getDocumentBase(), "die3.jpg"));
dieFaces[3] = new ImageIcon(getImage(getDocumentBase(), "die4.jpg"));
dieFaces[4] = new ImageIcon(getImage(getDocumentBase(), "die5.jpg"));
dieFaces[5] = new ImageIcon(getImage(getDocumentBase(), "die6.jpg"));
}
public JPanel createTxtImgContainer(JTextField txt, JLabel img) {
JPanel container = new JPanel();
container.setLayout(new GridLayout(1, 2, 10, 10));
txt.setEditable(false);
container.add(txt);
container.add(img);
return container;
}
#Override
public void init() {
// don't know if this is necessary, but it can't hurt
super.init();
// let's load the images first, no need to run a bunch of code and then
// error out on image loading also we can use the ImageIcons after this
createImageIcons();
// setup graphical user interface components
JPanel display = new JPanel();
display.setLayout(new GridLayout(8, 2, 10, 20));
// creating JLabel Die1 to the display
dieLabel1 = new JLabel("Die 1:", SwingConstants.RIGHT);
display.add(dieLabel1);
firstDie = new JTextField(3);
// created dieImg1 here also set the initial ImageIcon to "die6.jpg"
dieImg1 = new JLabel(dieFaces[5]);
// create a JPanel to house the JTextField and JLabel, and it to display
display.add(createTxtImgContainer(firstDie, dieImg1));
// creating JLabel Die2 to the Display
dieLabel2 = new JLabel("Die 2:", SwingConstants.RIGHT);
display.add(dieLabel2);
secondDie = new JTextField(3);
// created dieImg2 here also set the initial image to "die6.jpg"
dieImg2 = new JLabel(dieFaces[5]);
// create a JPanel to house the JTextField and JLabel, and it to display
display.add(createTxtImgContainer(secondDie, dieImg2));
// creating JLabel sum die to the display
sumLabel = new JLabel("Their sum is:", SwingConstants.RIGHT);
display.add(sumLabel);
sum = new JTextField(4);
sum.setEditable(false);
display.add(sum);
// creating JLabel rollLabel to the display
rollLabel = new JLabel("Roll Again", SwingConstants.RIGHT);
display.add(rollLabel);
roll = new JButton("Roll Dice");
roll.addActionListener(this);
display.add(roll);
// creating JLabel pointLabel to the display
pointLabel = new JLabel("Point is:", SwingConstants.RIGHT);
display.add(pointLabel);
point = new JTextField(3);
point.setEditable(false);
display.add(point);
// creating JLabel leftDivider and rightDivider to the display
leftDivider = new JLabel(divider, SwingConstants.RIGHT);
display.add(leftDivider);
rightDivider = new JLabel(divider, SwingConstants.LEFT);
display.add(rightDivider);
// creating JLabel lblPlayerWins and JTextField txtPlayerWins to the
// display
lblPlayerWins = new JLabel("Player wins:", SwingConstants.RIGHT);
display.add(lblPlayerWins);
txtPlayerWins = new JTextField(4);
txtPlayerWins.setEnabled(false);
display.add(txtPlayerWins);
// creating JLabel lblHouseWins and JTextField txtHouseWins to the
// display
lblHouseWins = new JLabel("House wins:", SwingConstants.RIGHT);
display.add(lblHouseWins);
txtHouseWins = new JTextField(4);
txtHouseWins.setEnabled(false);
display.add(txtHouseWins);
setContentPane(display);
}
#Override
public void actionPerformed(ActionEvent e) {
play();
}
public void play() {
if (firstRoll) {
sumOfDice = rollDice();
switch(sumOfDice) {
// player wins on first roll
case 7 :
case 11 :
gameStatus = WON;
point.setText("");
break;
// house wins player loses on first roll
case 2 :
case 3 :
case 12 :
gameStatus = LOST;
point.setText("");
break;
default:
gameStatus = CONTINUE;
myPoint = sumOfDice;
point.setText(Integer.toString(myPoint));
firstRoll = false;
break;
}
}
else {
sumOfDice = rollDice();
if (sumOfDice == myPoint) {
gameStatus = WON;
} else if (sumOfDice == 7) {
gameStatus = LOST;
}
}
if (gameStatus == CONTINUE) {
showStatus("Roll again");
} else {
if (gameStatus == WON) {
showStatus("Player wins." + "Click Roll Dice to play again");
numberPlayerWins++;
txtPlayerWins.setText(Integer.toString(numberPlayerWins));
} else {
showStatus("House wins." + "Click Roll Dice to play again");
numberHouseWins++;
txtHouseWins.setText(Integer.toString(numberHouseWins));
}
firstRoll = true;
}
}
public int rollDice() {
die1 = 1 + (int) (Math.random() * 6);
die2 = 1 + (int) (Math.random() * 6);
workSum = die1 + die2;
firstDie.setText(Integer.toString(die1));
secondDie.setText(Integer.toString(die2));
sum.setText(Integer.toString(workSum));
// set dieImgs to die values - 1, because the array starts at 0 not 1
dieImg1.setIcon(dieFaces[die1 - 1]);
dieImg2.setIcon(dieFaces[die2 - 1]);
return workSum;
}
}
Here's a screenshot of the applet running:

Modifying a double list with "move all" button

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

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.

Why is my ItemListener program not allowing me to select an option from two different JComboBoxes in Java?

My program will only do one JcomboBox at a time when I am trying to get both numbers to be added together to display the final number.
It allows me to run the program, but it will not display the final price because it does not want to select two things at once.
Here is the code for my program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CottageRental2 extends JFrame implements ItemListener{
// Declare all instance data (primitives and objects used)
private int WIDTH = 676;
private int HEIGHT = 321;
Container con;
private JLabel label1;
private JLabel label2;
private JLabel label3;
JComboBox cbox1;
JComboBox cbox2;
String [ ] roomChoice = {"1 Bedroom: $600","2 Bedroom: $800","3 Bedroom: $1000"};
String [ ] activityChoice = {"Horse Back Riding: $60","Rafting: $40","Row Boat Rental: $50"};
ImageIcon icon1 = new ImageIcon("C:\\Users\\Coding\\Desktop\\cottage.jpeg");
Font f1 = new Font("Ariel", Font.BOLD, 30);
//constructor
public CottageRental2(){
super("Cottage Rental");
con = getContentPane();
con.setLayout(new BorderLayout());
con.setBackground(Color.GRAY);
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void createGUI(){
label1 = new JLabel("Woodberry Cottage Rental", JLabel.CENTER);
label1.setFont(f1);
label1.setForeground(Color.WHITE);
label2 = new JLabel("Rental Amount Due: $660", JLabel.CENTER);
label2.setFont(f1);
label2.setForeground(Color.WHITE);
label3 = new JLabel(icon1);
cbox1 = new JComboBox();
cbox1.addItem(roomChoice[0]);
cbox1.addItem(roomChoice[1]);
cbox1.addItem(roomChoice[2]);
cbox1.addItemListener(this);
cbox2 = new JComboBox();
cbox2.addItem(activityChoice[0]);
cbox2.addItem(activityChoice[1]);
cbox2.addItem(activityChoice[2]);
cbox2.addItemListener(this);
con.add(label1, BorderLayout.NORTH);
con.add(label2, BorderLayout.SOUTH);
con.add(label3, BorderLayout.CENTER);
con.add(cbox1, BorderLayout.WEST);
con.add(cbox2, BorderLayout.EAST);
}
public void itemStateChanged(ItemEvent event){
Object source = event.getSource();
int price1 = 0;
int price2 = 0;
if(source == cbox1){
int roomIndex = cbox1.getSelectedIndex();
if(roomIndex == 0){
price1 = 600;
}
if(roomIndex == 1){
price1 = 800;
}
if(roomIndex == 2){
price1 = 1000;
}
}
if(source == cbox2){
int activityIndex = cbox2.getSelectedIndex();
if(activityIndex == 0){
price2 = 60;
}
if(activityIndex == 1){
price2 = 40;
}
if(activityIndex == 2){
price2 = 50;
}
}
label2.setText("Rental Amount Due: $" + (price1 + price2));
}
public static void main(String[] args){
CottageRental2 object = new CottageRental2();
object.createGUI();
object.setSize(675, 320);
}
}
Your problem is your if (source == ...) if blocks which prevent the program from getting the selected item from the other JComboBox, the one that isn't being actively selected.
One solution: get rid of the offending if blocks that test for the source of the event in the listener:
public void itemStateChanged(ItemEvent event) {
// Object source = event.getSource();
int price1 = 0;
int price2 = 0;
// if(source == cbox1){
int roomIndex = cbox1.getSelectedIndex();
if (roomIndex == 0) {
price1 = 600;
} else if (roomIndex == 1) {
price1 = 800;
} else if (roomIndex == 2) {
price1 = 1000;
}
// }
// if(source == cbox2){
int activityIndex = cbox2.getSelectedIndex();
if (activityIndex == 0) {
price2 = 60;
} else if (activityIndex == 1) {
price2 = 40;
} else if (activityIndex == 2) {
price2 = 50;
}
// }
label2.setText("Rental Amount Due: $" + (price1 + price2));
}
Also, it would be safer if you use some else if blocks in your item selection statements.

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