basically i am working on a tetris game and i want to implement a 2 player versus mode.
for now i have a working single player and now i want to make a gui for a 2 player multiplayer. (i will make a second keylistener and a endGame condition later)
however, when i add both gamepanels (what displays the state of the game after retreiving the state of the game from the boardhandler (1 or 2 depending on which player)) i dont get a correct display/gui.
this is what it looks like:
https://gyazo.com/58f37beab249c975cd4acdb8ae0e0154
this is what it should look like (but i want 2 boards displayed since this screenshot is from singleplayerwindow):
https://gyazo.com/4aecf061109844504a05387fb3d39e8f
anyone know what i am doing wrong and/or how i could fix it ?
thank you <3
package gui;
import tetris.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
public class MultiPlayerWindow extends JPanel
{
private GameLoop gameLoop1 ;
private GameLoop gameLoop2 ;
private boolean gameLoopHasStarted1 ;
private boolean gameLoopHasStarted2 ;
private BoardHandler bh1 ;
private BoardHandler bh2 ;
private HighScoreList highScoreList;
private HumanInput inputController ;
private HumanInput inputController2 ;
private JPanel scorePanel;
private JPanel rightPanel;
public MultiPlayerWindow( MainMenu mainMenu ){
//create the variables
Board board1 = new Board(10 , 20 ) ;
Board board2 = new Board(10 , 20 ) ;
final HumanInput inputController1 = new HumanInput() ;
final HumanInput inputController2 = new HumanInput() ;
this.bh1 = new BoardHandler(board1 , true) ;
this.bh2 = new BoardHandler(board2 , true) ;
this.highScoreList = new HighScoreList() ;
//behaviour
this.addKeyListener(inputController1);
this.addKeyListener(inputController2);
this.setFocusable(true);
this.requestFocusInWindow() ;
this.setLayout(new GridBagLayout());
//create panels
scorePanel = new JPanel() ;
scorePanel.setLayout(new GridBagLayout());
scorePanel.setSize(Config.LEFTPANEL_SIZE);
rightPanel = new JPanel() ;
rightPanel.setLayout(new GridBagLayout());
rightPanel.setSize(Config.RIGHTPANEL_SIZE);
//create the ScoreBoard
final ScoreBoard scoreBoard = new ScoreBoard() ;
GridBagConstraints d = new GridBagConstraints() ;
d.gridx = 0 ;
d.gridy = 0 ;
scorePanel.add(scoreBoard , d) ;
d.insets = new Insets(30,10,10,0);
//add a timer to update ScoreBoard
new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//System.out.println("Trying to update score");
scoreBoard.setScore(gameLoop1.getScore());
scoreBoard.setScore(gameLoop2.getScore());
}
}).start();
//create the Highscore Board
HighScoreBoard highScoreBoard = new HighScoreBoard(highScoreList);
d = new GridBagConstraints();
d.gridx = 0;
d.gridy = 1;
d.insets = new Insets(30,10,10,0);
scorePanel.add(highScoreBoard, d);
//create the combobox to choose between tetris and pentris
String[] optionStrings = {"Tetris", "Pentris"};
final JComboBox optionList = new JComboBox(optionStrings);
optionList.setSelectedIndex(0);
optionList.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(optionList.getSelectedIndex() == 0)
{
bh1.switchToTetris();
bh2.switchToTetris();
}
else if(optionList.getSelectedIndex() == 1)
{
bh1.switchToPentris();
bh2.switchToPentris();
}
}
});
optionList.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
optionList.requestFocus();
}
#Override
public void focusLost(FocusEvent e) {
}
});
d = new GridBagConstraints();
d.gridx = 0;
d.gridy = 2;
d.weightx = 0.5;
d.insets = new Insets(30,10,10,0);
scorePanel.add(optionList, d);
//add the scorePanel
d = new GridBagConstraints();
d.gridx = 1;
d.gridy = 0;
this.add(scorePanel, d);
final GamePanel gamePanel1 = new GamePanel(board1);
final GamePanel gamePanel2 = new GamePanel(board2);
gamePanel1.setSize(Config.GAMEPANEL_SIZE);
gamePanel2.setSize(Config.GAMEPANEL_SIZE);
d = new GridBagConstraints();
d.gridx = 0;
d.gridy = 0;
this.add(gamePanel1, d);
d = new GridBagConstraints();
d.gridx = 2;
d.gridy = 0;
this.add(gamePanel2, d);
//set the Thread
gameLoop1 = new GameLoop(bh1, inputController1, gamePanel1, highScoreList);
gameLoop2 = new GameLoop(bh2, inputController2, gamePanel2, highScoreList);
gameLoop1.start();
gameLoop2.start();
gameLoopHasStarted1 = false;
gameLoopHasStarted2 = false;
//add the buttons
JPanel buttonPanel = new JPanel();
buttonPanel.setAlignmentX(30);
buttonPanel.setLayout(new GridLayout(3,1,10,10));
d = new GridBagConstraints();
d.gridx = 0;
d.weightx = 0.2;
d.gridy = 0;
d.insets = new Insets(200,20,0,20);
rightPanel.add(buttonPanel, d);
//backbutton
d = new GridBagConstraints();
d.gridx = 0;
d.gridy = 1;
d.anchor = GridBagConstraints.SOUTH;
d.insets = new Insets(20, 20, 0, 20);
rightPanel.add(new BackButton(mainMenu), d);
//add the right panel
d = new GridBagConstraints();
d.gridx = 3;
d.gridy = 0;
this.add(rightPanel, d);
final JButton startButton = new JButton("Start");
startButton.requestFocus(false);
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(!gameLoopHasStarted1 && !gameLoopHasStarted2)
{
try{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run(){
gameLoopHasStarted1 = true;
gameLoopHasStarted2 = true;
gameLoop1.startNewGame();
gameLoop2.startNewGame();
optionList.setEnabled(false);
requestFocusInWindow();
startButton.setEnabled(false);
}
});
}
catch(Exception expenction)
{
expenction.printStackTrace();
}
}
}
});
buttonPanel.add(startButton);
//pause button
final JButton pauseButton = new JButton("Pause ");
buttonPanel.add(pauseButton);
pauseButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(!gameLoop1.isPaused() && !gameLoop2.isPaused()) {
gameLoop1.setPaused(true);
gameLoop2.setPaused(true);
pauseButton.setText("Unpause");
}
else if(gameLoop1.isPaused()&& gameLoop2.isPaused())
{
gameLoop1.setPaused(false);
gameLoop2.setPaused(false);
pauseButton.setText("Pause ");
}
}
});
//reset button
JButton resetButton = new JButton("Reset");
buttonPanel.add(resetButton);
resetButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
bh1.resetBoard();
bh2.resetBoard();
optionList.setEnabled(true);
if(gameLoop1.isRunning() && gameLoop2.isRunning())
{
gameLoop1.apruptGameEnd();
gameLoop2.apruptGameEnd();
}
gameLoopHasStarted1 = false;
gameLoopHasStarted2 = false;
gamePanel1.repaint();
gamePanel2.repaint();
startButton.setEnabled(true);
gameLoop1.setPaused(false);
gameLoop2.setPaused(false);
pauseButton.setText("Pause");
scoreBoard.setScore(0);
}
});
//focuslistener for inputController
this.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
}
#Override
public void focusLost(FocusEvent e) {
requestFocusInWindow();
}
});
}
public Dimension getPreferredSize()
{
return Config.SINGLE_PLAYER_SIZE;
}
}
fixed it.
public Dimension getPreferredSize()
{
return Config.SINGLE_PLAYER_SIZE;
}
this last part was what was messing it up, the rest of the code works fine but was previously then (for some tbh unknown reason) messed up by this. not 100% sure why...
Related
Im making a simon game and i have no idea what to do. I got sound and all that good stuff working but as for everything else I have no idea what im doing. I need some help making the buttons work and flash in the right order. (comments are failed attempts) Any help is very much appreciated.
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.border.*;
import java.util.Random;
import java.applet.*;
import java.util.ArrayList;
public class Game extends JFrame
{
JButton button1, button2, button3, button4, button5;
JLabel label1, label2, label3;
JPanel panel1, panel2;
File wavFile1 = new File("NewRing1.wav");
File wavFile2 = new File("NewRing2.wav");
File wavFile3 = new File("NewRing3.wav");
File wavFile4 = new File("NewRing4.wav");
AudioClip sound1;
AudioClip sound2;
AudioClip sound3;
AudioClip sound4;
int sequence1;
int[] anArray;
public Game()
{
anArray = new int[1000];
GridLayout grid = new GridLayout(3, 2);
this.getContentPane().setLayout(grid);
Container theContainer = this.getContentPane();
EtchedBorder edge = new EtchedBorder(EtchedBorder.RAISED);
button1 = new JButton();
button1.setForeground(Color.BLACK);
button1.setBackground(Color.RED);
button2 = new JButton();
button2.setForeground(Color.BLACK);
button2.setBackground(Color.BLUE);
button3 = new JButton();
button3.setForeground(Color.BLACK);
button3.setBackground(Color.GREEN);
button4 = new JButton();
button4.setForeground(Color.BLACK);
button4.setBackground(Color.YELLOW);
button5 = new JButton("Begin");
label1 = new JLabel("Score");
label2 = new JLabel("High Score");
label3 = new JLabel("Follow The Pattern");
panel1 = new JPanel();
panel1.add(label1);
panel1.add(label2);
panel2 = new JPanel();
panel2.add(label3);
panel2.add(button5);
button1.setBorder(edge);
button2.setBorder(edge);
button3.setBorder(edge);
button4.setBorder(edge);
label1.setBorder(edge);
label2.setBorder(edge);
panel1.setBorder(edge);
panel2.setBorder(edge);
label3.setBorder(edge);
theContainer.add(panel1);
theContainer.add(panel2);
theContainer.add(button1);
theContainer.add(button2);
theContainer.add(button3);
theContainer.add(button4);
Button1Handler handleButton1 = new Button1Handler();
button1.addActionListener(handleButton1);
Button2Handler handleButton2 = new Button2Handler();
button2.addActionListener(handleButton2);
Button3Handler handleButton3 = new Button3Handler();
button3.addActionListener(handleButton3);
Button4Handler handleButton4 = new Button4Handler();
button4.addActionListener(handleButton4);
Button5Handler handleButton5 = new Button5Handler();
button5.addActionListener(handleButton5);
try{sound1 = Applet.newAudioClip(wavFile1.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound2 = Applet.newAudioClip(wavFile2.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound3 = Applet.newAudioClip(wavFile3.toURL());}
catch(Exception e){e.printStackTrace();}
try{sound4 = Applet.newAudioClip(wavFile4.toURL());}
catch(Exception e){e.printStackTrace();}
setVisible(true);
}
public class Button1Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound1.play();
}
}
public class Button2Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound2.play();
}
}
public class Button3Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound3.play();
}
}
public class Button4Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
sound4.play();
}
}
/*
public static int[] buttonClicks(int[] anArray)
{
return anArray;
}
*/
public class Button5Handler implements ActionListener
{
public void actionPerformed(ActionEvent actionEvent)
{
for (int i = 1; i <= 159; i++)
{
Random rand = new Random();
int randomNum = rand.nextInt(40) % 4 + 1;
anArray[i] = randomNum;
System.out.println("Element at index: "+ i + " Is: " + anArray[i]);
}
buttonClicks(anArra[3]);
/*
for (int i = 1; i <= 100; i++)
{
Random rand = new Random();
int randomNum = rand.nextInt((4 - 1) + 1) + 1;
if(randomNum == 1)
{
button1.doClick();
sequence1 = 1;
System.out.println(sequence1);
}
else if(randomNum == 2)
{
button2.doClick();
sequence1 = 2;
System.out.println(sequence1);
}
else if(randomNum == 3)
{
button3.doClick();
sequence1 = 3;
System.out.println(sequence1);
}
else
{
button4.doClick();
sequence1 = 4;
System.out.println(sequence1);
}
}
*/
}
}
}
Below is some code to get you started. The playback of the sequences is executed in a separate thread, as you need to use delays in between. This code is by no means ideal. You should use better names for the variables and refactor to try to create a better and more encapsulated game model. Maybe you could use this opportunity to learn about the MVC design pattern?
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.border.*;
import java.util.Random;
import java.applet.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Game extends JFrame {
JButton button1, button2, button3, button4, button5;
JLabel label1, label2, label3;
JPanel panel1, panel2;
File wavFile1 = new File("NewRing1.wav");
File wavFile2 = new File("NewRing2.wav");
File wavFile3 = new File("NewRing3.wav");
File wavFile4 = new File("NewRing4.wav");
AudioClip sound1;
AudioClip sound2;
AudioClip sound3;
AudioClip sound4;
int level;
int score;
int[] anArray;
int currentArrayPosition;
public Game() {
GridLayout grid = new GridLayout(3, 2);
this.getContentPane().setLayout(grid);
Container theContainer = this.getContentPane();
EtchedBorder edge = new EtchedBorder(EtchedBorder.RAISED);
level = 0;
score = 0;
button1 = new JButton();
button1.setForeground(Color.BLACK);
button1.setBackground(Color.RED);
button2 = new JButton();
button2.setForeground(Color.BLACK);
button2.setBackground(Color.BLUE);
button3 = new JButton();
button3.setForeground(Color.BLACK);
button3.setBackground(Color.GREEN);
button4 = new JButton();
button4.setForeground(Color.BLACK);
button4.setBackground(Color.YELLOW);
button5 = new JButton("Begin");
label1 = new JLabel("Score: " + String.valueOf(score));
label2 = new JLabel("High Score");
label3 = new JLabel("Follow The Pattern");
panel1 = new JPanel();
panel1.add(label1);
panel1.add(label2);
panel2 = new JPanel();
panel2.add(label3);
panel2.add(button5);
button1.setBorder(edge);
button2.setBorder(edge);
button3.setBorder(edge);
button4.setBorder(edge);
label1.setBorder(edge);
label2.setBorder(edge);
panel1.setBorder(edge);
panel2.setBorder(edge);
label3.setBorder(edge);
theContainer.add(panel1);
theContainer.add(panel2);
theContainer.add(button1);
theContainer.add(button2);
theContainer.add(button3);
theContainer.add(button4);
Button1Handler handleButton1 = new Button1Handler();
button1.addActionListener(handleButton1);
Button2Handler handleButton2 = new Button2Handler();
button2.addActionListener(handleButton2);
Button3Handler handleButton3 = new Button3Handler();
button3.addActionListener(handleButton3);
Button4Handler handleButton4 = new Button4Handler();
button4.addActionListener(handleButton4);
Button5Handler handleButton5 = new Button5Handler();
button5.addActionListener(handleButton5);
try {
sound1 = Applet.newAudioClip(wavFile1.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound2 = Applet.newAudioClip(wavFile2.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound3 = Applet.newAudioClip(wavFile3.toURL());
} catch (Exception e) {
e.printStackTrace();
}
try {
sound4 = Applet.newAudioClip(wavFile4.toURL());
} catch (Exception e) {
e.printStackTrace();
}
setVisible(true);
}
public class Button1Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound1.play();
buttonClicked(button1);
}
}
public class Button2Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound2.play();
buttonClicked(button2);
}
}
public class Button3Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound3.play();
buttonClicked(button3);
}
}
public class Button4Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
sound4.play();
buttonClicked(button4);
}
}
private void buttonClicked(JButton clickedButton) {
if (isCorrectButtonClicked(clickedButton)) {
currentArrayPosition++;
addToScore(1);
if (currentArrayPosition == anArray.length) {
playNextSequence();
} else {
}
} else {
JOptionPane.showMessageDialog(this, String.format("Your scored %s points", score));
score = 0;
level = 0;
label1.setText("Score: " + String.valueOf(score));
}
}
private boolean isCorrectButtonClicked(JButton clickedButton) {
int correctValue = anArray[currentArrayPosition];
if (clickedButton.equals(button1)) {
return correctValue == 1;
} else if (clickedButton.equals(button2)) {
return correctValue == 2;
} else if (clickedButton.equals(button3)) {
return correctValue == 3;
} else if (clickedButton.equals(button4)) {
return correctValue == 4;
} else {
return false;
}
}
public class Button5Handler implements ActionListener {
public void actionPerformed(ActionEvent actionEvent) {
playNextSequence();
}
}
private void playNextSequence() {
level++;
currentArrayPosition = 0;
anArray = createSequence(level);
(new Thread(new SequenceButtonClicker())).start();
}
private int[] createSequence(int sequenceLength) {
int[] sequence = new int[sequenceLength];
for (int i = 0; i < sequenceLength; i++) {
Random rand = new Random();
int randomNum = rand.nextInt(40) % 4 + 1;
sequence[i] = randomNum;
}
return sequence;
}
private JButton getButtonFromInt(int sequenceNumber) {
switch (sequenceNumber) {
case 1:
return button1;
case 2:
return button2;
case 3:
return button3;
case 4:
return button4;
default:
return button1;
}
}
private void flashButton(JButton button) throws InterruptedException {
Color originalColor = button.getBackground();
button.setBackground(new Color(255, 255, 255, 200));
Thread.sleep(250);
button.setBackground(originalColor);
}
private void soundButton(JButton button) {
if (button.equals(button1)) {
sound1.play();
} else if (button.equals(button2)) {
sound2.play();
} else if (button.equals(button3)) {
sound3.play();
} else if (button.equals(button4)) {
sound4.play();
}
}
private void addToScore(int newPoints) {
score += newPoints;
label1.setText("Score: " + String.valueOf(score));
}
private class SequenceButtonClicker implements Runnable {
public void run() {
for (int i = 0; i < anArray.length; i++) {
try {
JButton nextButton = getButtonFromInt(anArray[i]);
soundButton(nextButton);
flashButton(nextButton);
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Game.class.getName()).log(Level.SEVERE, "Interrupted", ex);
}
}
}
}
}
ive searched online for the answer for a few hours now, so far i havent found anything helpful, i have a JDialog that is supposed to send an object back to the JPanel that called it, after running the code several times i noticed that the JPanel Constructor Finishes before i can press the Save button inside the JDialog,
my problem is this,
how do i pass the object from the JDialog to the JPanel and in which part of the Jpanel Code do i write it?
Here is the JPanel Code:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class AquaPanel extends JPanel implements ActionListener
{
private JFrame AQF;
private BufferedImage img;
private HashSet<Swimmable> FishSet;
private int FishCount;
private AddAnimalDialog JDA;
public AquaPanel(AquaFrame AQ)
{
super();
FishCount=0;
this.setSize(800, 600);
this.AQF = AQ;
gui();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
// if(!FishSet.isEmpty())
// {
// Iterator ITR = FishSet.iterator();
//
// while(ITR.hasNext())
// {
// ((Swimmable) ITR.next()).drawAnimal(g);
// }
// }
}
private void AddAnim()
{
Swimmable test = null;
JDA = new AddAnimalDialog(test);
JDA.setVisible(true);//shows jdialog box needs to set to false on new animal
}
private void Sleep()
{
}
private void Wake()
{
}
private void Res()
{
}
private void Food()
{
}
private void Info()
{
}
private void gui()
{
JPanel ButtonPanel = new JPanel();
Makebuttons(ButtonPanel);
this.setLayout(new BorderLayout());
this.setBackground(Color.WHITE);
ButtonPanel.setLayout(new GridLayout(1,0));
this.add(ButtonPanel,BorderLayout.SOUTH);
}
private void Makebuttons(JPanel ButtonPanel)
{
JButton Addanim = new JButton("Add Animal");
Addanim.setBackground(Color.LIGHT_GRAY);
Addanim.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
AddAnim();
}
});
JButton Sleep = new JButton("Sleep");
Sleep.setBackground(Color.LIGHT_GRAY);
Sleep.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Sleep();
}
});
JButton Wake = new JButton("Wake Up");
Wake.setBackground(Color.LIGHT_GRAY);
Wake.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Wake();
}
});
JButton Res = new JButton("Reset");
Res.setBackground(Color.LIGHT_GRAY);
Res.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Res();
}
});
JButton Food = new JButton("Food");
Food.setBackground(Color.LIGHT_GRAY);
Food.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Food();
}
});
JButton Info = new JButton("Info");
Info.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Info();
}
});
Info.setBackground(Color.LIGHT_GRAY);
JButton ExitAQP = new JButton("Exit");
ExitAQP.setBackground(Color.LIGHT_GRAY);
ExitAQP.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
ButtonPanel.add(Addanim);
ButtonPanel.add(Sleep);
ButtonPanel.add(Wake);
ButtonPanel.add(Res);
ButtonPanel.add(Food);
ButtonPanel.add(Info);
ButtonPanel.add(ExitAQP);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()=="Confirm Add")
{
if(JDA.GetDone())
{
FishSet.add(JDA.GetAnim()) ;
JOptionPane.showMessageDialog(this, JDA.GetAnim().getAnimalName());
}
}
}
public void setBackgr(int sel)
{
switch (sel)
{
case 0:
img=null;
this.setBackground(Color.WHITE);
break;
case 1:
img=null;
this.setBackground(Color.BLUE);
break;
case 2:
try {
img = ImageIO.read(new File("src/aquarium_background.jpg"));
} catch (IOException e) {
System.out.println("incorrect input image file path!!!!");
e.printStackTrace();
}
}
}
private void ConfirmAnimal()
{
if(JDA.GetAnim()!=null)
{
JOptionPane.showMessageDialog(this, "fish exists");
}
else
{
JOptionPane.showMessageDialog(this, "fish doesn't exists");
}
}
}
and the JDialog Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class AddAnimalDialog extends JDialog
{
private JTextField SizeField;
private JTextField HSpeedField;
private JTextField VSpeedField;
private int SelectedAnimal;
private int SelectedColor;
private Boolean IsDone;
private JButton SaveBTN;
Swimmable Animal;
public AddAnimalDialog(Swimmable Anim)
{
super();
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
IsDone = false;
gui();
Anim = Animal;
}
private void gui()
{
this.setSize(new Dimension(400, 300));
JPanel panel = new JPanel();
this.getContentPane().add(panel);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{151, 62, 63, 0};
gbl_panel.rowHeights = new int[]{20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_panel.columnWeights = new double[]{0.0, 1.0, 1.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
JLabel AnimName = new JLabel("Animal Type:");
GridBagConstraints gbc_AnimName = new GridBagConstraints();
gbc_AnimName.insets = new Insets(0, 0, 5, 5);
gbc_AnimName.gridx = 0;
gbc_AnimName.gridy = 1;
panel.add(AnimName, gbc_AnimName);
JComboBox AnimTypecomboBox = new JComboBox();
AnimTypecomboBox.addItem("Fish");
AnimTypecomboBox.addItem("Jellyfish");
GridBagConstraints gbc_AnimTypecomboBox = new GridBagConstraints();
gbc_AnimTypecomboBox.insets = new Insets(0, 0, 5, 5);
gbc_AnimTypecomboBox.anchor = GridBagConstraints.NORTH;
gbc_AnimTypecomboBox.gridx = 1;
gbc_AnimTypecomboBox.gridy = 1;
panel.add(AnimTypecomboBox, gbc_AnimTypecomboBox);
JLabel AnimSize = new JLabel("Size(between 20 to 320):");
GridBagConstraints gbc_AnimSize = new GridBagConstraints();
gbc_AnimSize.insets = new Insets(0, 0, 5, 5);
gbc_AnimSize.gridx = 0;
gbc_AnimSize.gridy = 2;
panel.add(AnimSize, gbc_AnimSize);
SizeField = new JTextField();
GridBagConstraints gbc_SizeField = new GridBagConstraints();
gbc_SizeField.insets = new Insets(0, 0, 5, 5);
gbc_SizeField.fill = GridBagConstraints.HORIZONTAL;
gbc_SizeField.gridx = 1;
gbc_SizeField.gridy = 2;
panel.add(SizeField, gbc_SizeField);
SizeField.setColumns(10);
JLabel HSpeed = new JLabel("Horizontal Speed(between 1 to 10):");
GridBagConstraints gbc_HSpeed = new GridBagConstraints();
gbc_HSpeed.insets = new Insets(0, 0, 5, 5);
gbc_HSpeed.gridx = 0;
gbc_HSpeed.gridy = 3;
panel.add(HSpeed, gbc_HSpeed);
HSpeedField = new JTextField();
GridBagConstraints gbc_HSpeedField = new GridBagConstraints();
gbc_HSpeedField.insets = new Insets(0, 0, 5, 5);
gbc_HSpeedField.fill = GridBagConstraints.HORIZONTAL;
gbc_HSpeedField.gridx = 1;
gbc_HSpeedField.gridy = 3;
panel.add(HSpeedField, gbc_HSpeedField);
HSpeedField.setColumns(10);
JLabel VSpeed = new JLabel("Vertical Speed(between 1 to 10):");
GridBagConstraints gbc_VSpeed = new GridBagConstraints();
gbc_VSpeed.insets = new Insets(0, 0, 5, 5);
gbc_VSpeed.gridx = 0;
gbc_VSpeed.gridy = 4;
panel.add(VSpeed, gbc_VSpeed);
VSpeedField = new JTextField();
GridBagConstraints gbc_VSpeedField = new GridBagConstraints();
gbc_VSpeedField.insets = new Insets(0, 0, 5, 5);
gbc_VSpeedField.fill = GridBagConstraints.HORIZONTAL;
gbc_VSpeedField.gridx = 1;
gbc_VSpeedField.gridy = 4;
panel.add(VSpeedField, gbc_VSpeedField);
VSpeedField.setColumns(10);
JLabel lblAnimalColor = new JLabel("Animal Color:");
GridBagConstraints gbc_lblAnimalColor = new GridBagConstraints();
gbc_lblAnimalColor.insets = new Insets(0, 0, 5, 5);
gbc_lblAnimalColor.gridx = 0;
gbc_lblAnimalColor.gridy = 5;
panel.add(lblAnimalColor, gbc_lblAnimalColor);
JComboBox ColorComboBox = new JComboBox();
ColorComboBox.setModel(new DefaultComboBoxModel(new String[] {"Red", "Magenta", "Cyan", "Blue", "Green"}));
GridBagConstraints gbc_ColorComboBox = new GridBagConstraints();
gbc_ColorComboBox.insets = new Insets(0, 0, 5, 5);
gbc_ColorComboBox.fill = GridBagConstraints.HORIZONTAL;
gbc_ColorComboBox.gridx = 1;
gbc_ColorComboBox.gridy = 5;
panel.add(ColorComboBox, gbc_ColorComboBox);
JButton btnAddAnimal = new JButton("Confirm Add");
GetInput(btnAddAnimal,AnimTypecomboBox,ColorComboBox);
GridBagConstraints gbc_btnAddAnimal = new GridBagConstraints();
gbc_btnAddAnimal.insets = new Insets(0, 0, 0, 5);
gbc_btnAddAnimal.gridx = 0;
gbc_btnAddAnimal.gridy = 9;
panel.add(btnAddAnimal, gbc_btnAddAnimal);
JButton btnClear = new JButton("Clear");
GridBagConstraints gbc_btnClear = new GridBagConstraints();
gbc_btnClear.gridx = 2;
gbc_btnClear.gridy = 9;
panel.add(btnClear, gbc_btnClear);
}
private Color Getcolor(Object obj)
{
Color clr=Color.RED;
if(obj instanceof String)
{
switch((String)obj)
{
case "Red":
clr = Color.RED;
break;
case "Magenta":
clr = Color.MAGENTA;
break;
case "Cyan":
clr = Color.CYAN;
break;
case "Blue":
clr = Color.BLUE;
break;
case "Green":
clr = Color.GREEN;
break;
}
}
return clr;
}
private Fish MakeFish(int size,Color col,int horSpeed,int verSpeed)
{
return new Fish(size,col,horSpeed,verSpeed);
}
private Jellyfish MakeJellyfish(int size,Color col,int horSpeed,int verSpeed)
{
return new Jellyfish(size,col,horSpeed,verSpeed);
}
public Swimmable GetAnim()
{
return Animal;
}
public Boolean GetDone()
{
return IsDone;
}
private void GetInput(JButton Jbtn,JComboBox type,JComboBox col)
{
Jbtn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
if((type.getSelectedItem() instanceof String)&&
((String)type.getSelectedItem()=="Fish"))
{
Color clr=Color.RED;
Object tmp = col.getSelectedItem();
if(col.getSelectedItem() instanceof String)
{
clr = Getcolor(tmp);
}
int size = Integer.parseInt(SizeField.getText());
int Hspeed = Integer.parseInt(HSpeedField.getText());
int VSpeed = Integer.parseInt(VSpeedField.getText());
Animal = MakeFish(size,clr,Hspeed,VSpeed);
}
else if((type.getSelectedItem() instanceof String)&&
((String)type.getSelectedItem()=="Jellyfish"))
{
Color clr=Color.RED;
Object tmp = type.getSelectedItem();
if(col.getSelectedItem() instanceof String)
{
clr = Getcolor(tmp);
}
int size = Integer.parseInt(SizeField.getText());
int Hspeed = Integer.parseInt(HSpeedField.getText());
int VSpeed = Integer.parseInt(VSpeedField.getText());
Animal = MakeJellyfish(size,clr,Hspeed,VSpeed);
}
IsDone=true;
Hide();
SaveBTN = Jbtn;
}
});
}
private void Hide()
{
this.setVisible(false);
}
public JButton GetBTN()
{
return SaveBTN;
}
}
So in short in the JDialog i need to get information from comboboxes and texfields and send that data to an object constructor, and on the "Save" button click i need to transfer the Object from the JDialog that i created with the constructor to the JPanel, how do i do it?
i realized i can send the JPanel to the JDialog and in the JDialog's code where i create the object, i modify the Jpanel's Hashset accordingly
I am trying to make a sign in program with a time clock display. I am having a hard time trying to get the clock into the already made JPanel. It currently pops up 2 seperate JPanels when I run the program. Please help with any suggestions.
CODE:
private static JLabel lblUserName;
private static JTextField txtUserName;
private static JButton btnSignIn;
private static JLabel lblPassword;
private static JPasswordField txtPassword;
private static JButton btnCancel;
private static JTabbedPane tabbedPane;
public static void main(String[] args)
{
UserSignIn frame = new UserSignIn();
JFrame frm = new JFrame();
SimpleDigitalClock clock1 = new SimpleDigitalClock();
frm.add(clock1);
//Pack
frm.pack();
frame.pack();
// Set origional focus on User Name text field
txtUserName.requestFocusInWindow();
// Make Visible
frame.setVisible(true);
frm.setVisible(true);
}
static class SimpleDigitalClock extends JPanel
{
String stringTime;
int hour, minute, second;
String aHour = "";
String bMinute = "";
String cSecond = "";
public void setStringTime(String abc)
{
this.stringTime = abc;
}
public int Number(int a, int b)
{
return (a <= b) ? a : b;
}
SimpleDigitalClock()
{
Timer t = new Timer(1000, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
repaint();
}
});
t.start();
}
#Override
public void paintComponent(Graphics v)
{
super.paintComponent(v);
Calendar rite = Calendar.getInstance();
hour = rite.get(Calendar.HOUR_OF_DAY);
minute = rite.get(Calendar.MINUTE);
second = rite.get(Calendar.SECOND);
if (hour < 10)
{
this.aHour = "0";
}
if (hour >= 10)
{
this.aHour = "";
}
if (minute < 10)
{
this.bMinute = "0";
}
if (minute >= 10)
{
this.bMinute = "";
}
if (second < 10)
{
this.cSecond = "0";
}
if (second >= 10)
{
this.cSecond = "";
}
setStringTime(aHour + hour + ":" + bMinute+ minute + ":" + cSecond + second);
v.setColor(Color.RED);
int length = Number(this.getWidth(),this.getHeight());
Font Font1 = new Font("Digital", Font.BOLD, length / 5);
v.setFont(Font1);
v.drawString(stringTime, (int) length/6, length/2);
}
#Override
public Dimension getPreferredSize()
{
return new Dimension(200, 200);
}
}
public UserSignIn()
{
initGUI();
}
public void initGUI()
{
setTitle("Login");
JPanel pnlUserSignIn = new JPanel(new GridBagLayout());
this.getContentPane().add(pnlUserSignIn);
//build table for employees signed in
JTable t = new JTable(null);
JLabel label = new JLabel("Employees Currently Signed In");
// ROW 1 BUTTONS
// Username and Sign In buttons
lblUserName = new JLabel("Username: ");
txtUserName = new JTextField("Username");
// Actions
//txtUserName.addMouseListener(this);
// Adding objects to Panel
JPanel pnlLogin = new JPanel();
pnlLogin.add(lblUserName);
pnlLogin.add(txtUserName);
//ROW 2 BUTTONS
//Password and Cancel
btnSignIn = new JButton("Sign In");
btnCancel=new JButton("Cancel");
//Actions
btnSignIn.addActionListener(this);
btnCancel.addActionListener(this);
// Adding objects to Panel
JPanel pnlPassword = new JPanel();
pnlPassword.add(btnSignIn);
pnlPassword.add(btnCancel);
JPanel detailsPanel = new JPanel();
detailsPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints gbc = new GridBagConstraints();
// Putting Objects into the grid
gbc.gridx = 0;
gbc.gridy = 0;
pnlUserSignIn.add(label, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
pnlUserSignIn.add(new JScrollPane(t), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
pnlUserSignIn.add(pnlLogin, gbc);
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 2;
pnlUserSignIn.add(pnlPassword, gbc);
//gbc.gridx = 1;
//gbc.gridy = 1;
//gbc.gridwidth = 1;
//gbc.gridheight = 2;
//panel.add(detailsPanel, gbc);
this.pack();
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent actionEvent)
{
if(actionEvent.getSource()==btnCancel)
{
System.exit(0);
}
//if(actionEvent.getSource()==txtUserName)
//{
// txtUserName.setText("");
// txtUserName.requestFocus();
//}
}
PLEASE IGNORE THE COMMENTED CODE, I am working on many things at once.
You don't need another frame. Just add clock to existing one. For example to the SOUTH:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.Timer;
public class UserSignIn extends JFrame implements ActionListener{
private static JLabel lblUserName;
private static JTextField txtUserName;
private static JButton btnSignIn;
private static JLabel lblPassword;
private static JPasswordField txtPassword;
private static JButton btnCancel;
private static JTabbedPane tabbedPane;
public static void main(String[] args) {
UserSignIn frame = new UserSignIn();
SimpleDigitalClock clock1 = new SimpleDigitalClock();
frame.add(clock1, BorderLayout.SOUTH);
// Pack
frame.pack();
// Set origional focus on User Name text field
txtUserName.requestFocusInWindow();
// Make Visible
frame.setVisible(true);
}
static class SimpleDigitalClock extends JPanel {
String stringTime;
int hour, minute, second;
String aHour = "";
String bMinute = "";
String cSecond = "";
public void setStringTime(String abc) {
this.stringTime = abc;
}
public int Number(int a, int b) {
return (a <= b) ? a : b;
}
SimpleDigitalClock() {
Timer t = new Timer(1000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
repaint();
}
});
t.start();
}
#Override
public void paintComponent(Graphics v) {
super.paintComponent(v);
Calendar rite = Calendar.getInstance();
hour = rite.get(Calendar.HOUR_OF_DAY);
minute = rite.get(Calendar.MINUTE);
second = rite.get(Calendar.SECOND);
if (hour < 10) {
this.aHour = "0";
}
if (hour >= 10) {
this.aHour = "";
}
if (minute < 10) {
this.bMinute = "0";
}
if (minute >= 10) {
this.bMinute = "";
}
if (second < 10) {
this.cSecond = "0";
}
if (second >= 10) {
this.cSecond = "";
}
setStringTime(aHour + hour + ":" + bMinute + minute + ":" + cSecond
+ second);
v.setColor(Color.RED);
int length = Number(this.getWidth(), this.getHeight());
Font Font1 = new Font("Digital", Font.BOLD, length / 5);
v.setFont(Font1);
v.drawString(stringTime, (int) length / 6, length / 2);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
public UserSignIn() {
initGUI();
}
public void initGUI() {
setTitle("Login");
JPanel pnlUserSignIn = new JPanel(new GridBagLayout());
this.getContentPane().add(pnlUserSignIn);
// build table for employees signed in
JTable t = new JTable(null);
JLabel label = new JLabel("Employees Currently Signed In");
// ROW 1 BUTTONS
// Username and Sign In buttons
lblUserName = new JLabel("Username: ");
txtUserName = new JTextField("Username");
// Actions
// txtUserName.addMouseListener(this);
// Adding objects to Panel
JPanel pnlLogin = new JPanel();
pnlLogin.add(lblUserName);
pnlLogin.add(txtUserName);
// ROW 2 BUTTONS
// Password and Cancel
btnSignIn = new JButton("Sign In");
btnCancel = new JButton("Cancel");
// Actions
btnSignIn.addActionListener(this);
btnCancel.addActionListener(this);
// Adding objects to Panel
JPanel pnlPassword = new JPanel();
pnlPassword.add(btnSignIn);
pnlPassword.add(btnCancel);
JPanel detailsPanel = new JPanel();
detailsPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
GridBagConstraints gbc = new GridBagConstraints();
// Putting Objects into the grid
gbc.gridx = 0;
gbc.gridy = 0;
pnlUserSignIn.add(label, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
pnlUserSignIn.add(new JScrollPane(t), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
pnlUserSignIn.add(pnlLogin, gbc);
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 2;
pnlUserSignIn.add(pnlPassword, gbc);
// gbc.gridx = 1;
// gbc.gridy = 1;
// gbc.gridwidth = 1;
// gbc.gridheight = 2;
// panel.add(detailsPanel, gbc);
this.pack();
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent actionEvent) {
if (actionEvent.getSource() == btnCancel) {
System.exit(0);
}
// if(actionEvent.getSource()==txtUserName)
// {
// txtUserName.setText("");
// txtUserName.requestFocus();
// }
}
}
So I've been trying to figure out why my JApplet is starting and giving no errors but nothing is showing up. I have an init() method that calls setup_layout(), but I think I may have done something wrong the layouts. Anyone help?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class Assignment8 extends JApplet implements ActionListener
{
public static final int WIDTH = 500;
public static final int HEIGHT = 500;
public static final int NUMBER_OF_DIGITS = 30;
private JTextArea operand, result;
private double answer = 0.0;
private JButton sevenB, eightB, nineB, divideB, fourB, fiveB, sixB, multiplyB, oneB, twoB, threeB, subtractB,
zeroB, dotB, addB, resetB, clearB, sqrtB, absB, expB;
/** public static void main(String[] args)
{
Assignment8 aCalculator = new Assignment8( );
aCalculator.setVisible(true);
}**/
public void init( )
{
setup_layout();
}
private void setup_layout() {
setSize(WIDTH, HEIGHT);
JPanel MainPanel = new JPanel();
JPanel buttonPanel = new JPanel();
JPanel calcPanel = new JPanel();
JPanel textPanel = new JPanel ();
buttonPanel.setLayout(new GridLayout(3, 4));
calcPanel.setLayout(new GridLayout(3, 3));
textPanel.setLayout(new FlowLayout());
MainPanel.setLayout(new BorderLayout());
MainPanel.setBackground(Color.red);
operand = new JTextArea();
result = new JTextArea();
operand.setEditable(false);
result.setEditable(false);
textPanel.add(operand);
textPanel.add(result);
sevenB = new JButton("7");
eightB = new JButton("8");
nineB = new JButton("9");
divideB = new JButton("/");
fourB = new JButton("4");
fiveB = new JButton("5");
sixB = new JButton("6");
multiplyB = new JButton("*");
oneB = new JButton("1");
twoB = new JButton("2");
threeB = new JButton("3");
subtractB = new JButton("-");
zeroB = new JButton("0");
dotB = new JButton(".");
addB = new JButton("+");
resetB = new JButton("Reset");
clearB = new JButton("Clear");
sqrtB = new JButton("Sqrt");
absB = new JButton("Abs");
expB = new JButton("Exp");
sevenB.addActionListener(this);
eightB.addActionListener(this);
nineB.addActionListener(this);
divideB.addActionListener(this);
fourB.addActionListener(this);
fiveB.addActionListener(this);
sixB.addActionListener(this);
multiplyB.addActionListener(this);
oneB.addActionListener(this);
twoB.addActionListener(this);
threeB.addActionListener(this);
subtractB.addActionListener(this);
zeroB.addActionListener(this);
dotB.addActionListener(this);
addB.addActionListener(this);
resetB.addActionListener(this);
clearB.addActionListener(this);
absB.addActionListener(this);
expB.addActionListener(this);
sqrtB.addActionListener(this);
buttonPanel.add(sevenB);
buttonPanel.add(eightB);
buttonPanel.add(nineB);
buttonPanel.add(fourB);
buttonPanel.add(fiveB);
buttonPanel.add(sixB);
buttonPanel.add(oneB);
buttonPanel.add(twoB);
buttonPanel.add(threeB);
buttonPanel.add(zeroB);
buttonPanel.add(dotB);
calcPanel.add(subtractB);
calcPanel.add(multiplyB);
calcPanel.add(divideB);
calcPanel.add(sqrtB);
calcPanel.add(absB);
calcPanel.add(expB);
calcPanel.add(addB);
calcPanel.add(resetB);
calcPanel.add(clearB);
MainPanel.add(buttonPanel);
MainPanel.add(calcPanel);
MainPanel.add(textPanel);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
try
{
assumingCorrectNumberFormats(e);
}
catch (NumberFormatException e2)
{
result.setText("Error: Reenter Number.");
}
catch (DivideByZeroException e1) {
result.setText("Error: CANNOT Divide By Zero. Reenter Number.");
}
}
//Throws NumberFormatException.
public void assumingCorrectNumberFormats(ActionEvent e) throws DivideByZeroException
{
String actionCommand = e.getActionCommand( );
if (actionCommand.equals("1"))
{
int num = 1;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("2"))
{
int num = 2;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("3"))
{
int num = 3;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("4"))
{
int num = 4;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("5"))
{
int num = 5;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("6"))
{
int num = 6;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("7"))
{
int num = 7;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("8"))
{
int num = 8;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("9"))
{
int num = 9;
operand.append(Integer.toString(num));
}
else if (actionCommand.equals("0"))
{
int num = 0;
String text = operand.getText();
//double check = stringToDouble(text);
if(text.isEmpty()||text.contains(".")) {
operand.append(Integer.toString(num));
}
}
else if (actionCommand.equals("."))
{
String text = operand.getText();
if(!text.contains(".")) {
operand.append(".");
}
}
else if (actionCommand.equals("+"))
{
answer = answer + stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("-"))
{
answer = answer - stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("*"))
{
answer = answer * stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("/"))
{
double check = stringToDouble(operand.getText());
if(check >= -1.0e-10 && check <= 1.0e-10 ) {
throw new DivideByZeroException();
}
else {
answer = answer / stringToDouble(operand.getText( ));
result.setText(Double.toString(answer));
operand.setText("");
}
}
else if (actionCommand.equals("Sqrt"))
{
double check = stringToDouble(result.getText());
if(check < 0 ) {
throw new NumberFormatException();
}
else {
answer = Math.sqrt(stringToDouble(result.getText( )));
result.setText(Double.toString(answer));
operand.setText("");
}
}
else if (actionCommand.equals("Abs"))
{
answer = Math.abs(stringToDouble(result.getText( )));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("Exp"))
{
answer = Math.pow(stringToDouble(result.getText( )),stringToDouble(operand.getText( )));
result.setText(Double.toString(answer));
operand.setText("");
}
else if (actionCommand.equals("Reset"))
{
answer = 0.0;
result.setText("");
operand.setText("");
}
else if (actionCommand.equals("Clear"))
{
operand.setText("");
}
else
result.setText("Unexpected error.");
}
//Throws NumberFormatException.
private static double stringToDouble(String stringObject)
{
return Double.parseDouble(stringObject.trim( ));
}
//Divide by Zero Exception Class
public class DivideByZeroException extends Exception {
DivideByZeroException() {
}
}
}
You never add MainPanel to the applet itself.
i.e.,
add(MainPanel);
Also, since MainPanel uses BorderLayout, you will need to add the subPanels with a BorderLayout.XXX constant. i.e.,
change this:
MainPanel.add(buttonPanel);
MainPanel.add(calcPanel);
MainPanel.add(textPanel);
to:
MainPanel.add(buttonPanel, BorderLayout.CENTER);
MainPanel.add(calcPanel, BorderLayout.PAGE_END); // wherever you want to add this
MainPanel.add(textPanel, BorderLayout.PAGE_START);
Note that your code can be simplified greatly by using arrays or Lists.
Or could simplify it in other ways, for instance:
public void assumingCorrectNumberFormats(ActionEvent e)
throws DivideByZeroException {
String actionCommand = e.getActionCommand();
String numbers = "1234567890";
if (numbers.contains(actionCommand)) {
operand.append(actionCommand);
// if you need to work with it as a number
int num = Integer.parseInt(actionCommand);
}
Myself, I'd use a different ActionListeners for different functionality, for instance one ActionListener for numeric and . entry buttons and another one for the operation buttons.
I have a program here that changes an avatars hat and earrings
the problem is that it only restarts once (the load button only works once)
This is what I have:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.JTextArea;
public class Lab14_Navarro extends JFrame {
private int x,y,z;
private Container game;
private JComboBox Head;
private JComboBox Ear;
private JLabel Avatar;
private JTextArea details;
private String []Hat = {"No Hat", "Captain Hat", "Black Leather Hat"};
private JButton load;
private String []Earrings = {"No Earrings", "Silver Dangling Earrings", "Gold Dangling Earrings"};
private ImageIcon [] Accessories =
{ new ImageIcon("blackleather.PNG"),//0
new ImageIcon("blackleather_goldear.PNG"),//1
new ImageIcon("blackleather_silverear.PNG"),//2
new ImageIcon("captainhat.PNG"),//3
new ImageIcon("captainhat_goldear.PNG"),//4
new ImageIcon("captainhat_silverear.PNG"),//5
new ImageIcon("goldear.PNG"),//6
new ImageIcon("noaccessories.PNG"),//7
new ImageIcon("silverear.PNG")};//8
/**
* Creates a new instance of <code>Lab14_Navarro</code>.
*/
public Lab14_Navarro() {
getContentPane().removeAll();
setTitle("Avatar!");
setSize(250,450);
setLocationRelativeTo(null);
game = getContentPane();
game.setLayout(new FlowLayout());
Head = new JComboBox(Hat);
Ear = new JComboBox(Earrings);
Avatar = new JLabel(Accessories[7]);
load = new JButton("Load Image");
details = new JTextArea("AVATAR DETAILS: "+"\n"+" Hat: "+Hat[Head.getSelectedIndex()]+"\n"+" Earrings: "+Earrings[Ear.getSelectedIndex()]);
game.add(Avatar);
game.add(Head);
game.add(Ear);
game.add(load);
game.add(details, BorderLayout.SOUTH);
setVisible(true);
details.setEditable(false);
Head.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
JComboBox temphead = (JComboBox) e.getSource();
int temphat = (int) temphead.getSelectedIndex();
x = temphat;
}
});
Ear.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
JComboBox tempear = (JComboBox) e.getSource();
int tempearrings = (int) tempear.getSelectedIndex();
y = tempearrings;
}
});
load.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
getContentPane().removeAll();
if(x==0&&y==0){
z = 7;
}
if(x==0&&y==1){
z = 8;
}
if(x==0&&y==2){
z = 6;
}
if(x==1&&y==0){
z = 3;
}
if(x==1&&y==1){
z = 5;
}
if(x==1&&y==2){
z = 4;
}
if(x==2&&y==0){
z = 0;
}
if(x==2&&y==1){
z = 2;
}
if(x==2&&y==2){
z = 1;
}
setTitle("Avatar");
setSize(250,450);
setLocationRelativeTo(null);
game = getContentPane();
game.setLayout(new FlowLayout());
Head = new JComboBox(Hat);
Ear = new JComboBox(Earrings);
Avatar = new JLabel(Accessories[z]);
load = new JButton("Load Image");
details = new JTextArea("AVATAR DETAILS: "+"\n"+" Hat: "+Hat[x]+"\n"+" Earrings: "+Earrings[y]);
game.add(Avatar);
game.add(Head);
game.add(Ear);
game.add(load);
game.add(details, BorderLayout.SOUTH);
setVisible(true);
details.setEditable(false);
}
});
}
public static void main(String[] args) {
Lab14_Navarro fs = new Lab14_Navarro();
fs.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Any help is accepted thanks
I just started Java so I'm not that good... yet
When you write, for the second time:
load = new JButton("Load Image");
you're creating a new button, however, you are not giving it a new ActionListener
On another note, you don't need to create a new Button, your original load button is still there, you need only to add it to the contentPane again.