My professor told me to put both of these together to make a running program. I am utilizing Netbeans, and it keeps telling me that there is no main class. Am I supposed to create one or am I missing something? How do I put these together into a working gui java application?
Here is the first file, it is called NumberGame
import java.util.Random;
public class NumberGame {
private Random rand = new Random();
private int min, max;
private int num1, num2;
public NumberGame(int min, int max) {
this.min = min;
this.max = max;
newNums();
}
public int getNum1() {
return num1;
}
public int getNum2() {
return num2;
}
public void newNums() {
num1 = rand.nextInt(max - min + 1) + min;
num2 = rand.nextInt(max - min + 1) + min;
}
public int calcSum() {
return num1 + num2;
}
public boolean checkSum(int num) {
return num == calcSum();
}
}
The second file is called App here it is
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class App extends JFrame implements ActionListener {
/* Canvas ============================================ */
private NumberGame numbers;
private Font mainFont = new Font(Font.SANS_SERIF, Font.PLAIN,16);
/* Components for Canvas ============================= */
private JTextField messageField;
private JLabel lblNum1;
private JLabel lblNum2;
private JTextField sumField;
private JButton btnNext;
private JButton btnCheck;
public App(String title, int width, int height) {
// initialize new number game
numbers = new NumberGame(10, 49);
// initialize components
messageField = new JTextField("", 10);
messageField.setEditable(false);
messageField.setHorizontalAlignment(JTextField.CENTER);
messageField.setFont(mainFont);
// add components to board
add(messageField, BorderLayout.NORTH);
add(createCenter(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.SOUTH);
// add action listeners
btnCheck.addActionListener(this);
btnNext.addActionListener(this);
sumField.addActionListener(this);
// create the window
createWindow(title, width, height);
pack();
}
private void createWindow(String title, int width, int height) {
setVisible(true);
setTitle(title);
setSize(width, height);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private JPanel createCenter() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
JLabel lblNumPrompt1 = new JLabel("Number 1 = ", JLabel.RIGHT);
lblNumPrompt1.setFont(mainFont);
lblNum1 = new JLabel(Integer.toString(numbers.getNum1()), JLabel.CENTER);
lblNum1.setFont(mainFont);
JLabel lblNumPrompt2 = new JLabel("Number 2 = ", JLabel.RIGHT);
lblNumPrompt2.setFont(mainFont);
lblNum2 = new JLabel(Integer.toString(numbers.getNum2()), JLabel.CENTER);
lblNum2.setFont(mainFont);
JLabel lblSumPrompt = new JLabel("Sum = ", JLabel.RIGHT);
lblSumPrompt.setFont(mainFont);
sumField = new JTextField("0", 10);
sumField.setHorizontalAlignment(JTextField.CENTER);
sumField.setFont(mainFont);
// add objects to the panel
panel.add(lblNumPrompt1);
panel.add(lblNum1);
panel.add(lblNumPrompt2);
panel.add(lblNum2);
panel.add(lblSumPrompt);
panel.add(sumField);
return panel;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel();
btnNext = new JButton("Next");
btnCheck = new JButton("Check");
panel.add(btnNext);
panel.add(btnCheck);
return panel;
}
#Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button.equals(btnNext)) {
numbers.newNums();
lblNum1.setText(Integer.toString(numbers.getNum1()));
lblNum2.setText(Integer.toString(numbers.getNum2()));
} else {
int num = Integer.parseInt(sumField.getText());
if (numbers.checkSum(num))
messageField.setText("Correct!");
else
messageField.setText("Try Again!");
}
}
}
Simply create a main class and initialize the app class as below, HTH.
public static void main(String args[])
{
//Put in the title and size of the Panel
App app1 = new App("MY game", 1000, 900);
}
Create a main class .
Put all 3 classes into same package.
Simply create an object of App class in main class.
Run the main class.
Related
I am trying to create a game about war. I am starting off with just creating a single window. I am using swing to create windows. However, when the user tries to resize the JFrame, the elements don't move with the frame. I am resizing the buttons that I use, as well as my JPanel. My code can be seen below:
Main.java:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import Numbers.Numbers;
public class Main implements ActionListener {
static JFrame frame;
static JPanel titlePane;
static JButton playButton;
static JButton explanationButton;
static JPanel explanationPane;
static JButton nextButton;
static JLabel explanationLabel;
static JButton backButton;
static int frameSize = 500;
public Main(boolean run) {
if (run) {
frame = new JFrame("War");
titlePane = new JPanel(null);
playButton = new JButton("PLAY");
explanationButton = new JButton("HOW TO PLAY");
explanationPane = new JPanel(null);
nextButton = new JButton("NEXT");
backButton = new JButton("BACK");
titlePane.setSize(frameSize, frameSize);
titlePane.add(playButton);
playButton.setBounds(Numbers.doubleToInt(frameSize/2.5), Numbers.doubleToInt(frameSize/2.5), Numbers.doubleToInt(frameSize/5), Numbers.doubleToInt(frameSize/(100/3)));
playButton.setBackground(Color.GRAY);
playButton.setForeground(Color.WHITE);
playButton.setVisible(true);
explanationButton.setBounds(Numbers.doubleToInt(frameSize/2.5), Numbers.doubleToInt(frameSize/(25/11)), Numbers.doubleToInt(frameSize/5), Numbers.doubleToInt(frameSize/(100/3)));
explanationButton.setBackground(Color.GRAY);
explanationButton.setForeground(Color.WHITE);
explanationButton.setVisible(true);
explanationPane.setSize(frameSize, frameSize);
explanationPane.add(nextButton);
nextButton.setBounds(225, 50, 50, 15);
nextButton.setBackground(Color.GRAY);
nextButton.setForeground(Color.WHITE);
nextButton.setVisible(true);
backButton.setBounds(225, 450, 50, 15);
backButton.setBackground(Color.GRAY);
backButton.setForeground(Color.WHITE);
backButton.setVisible(true);
frame.setSize(frameSize, frameSize);
frame.add(titlePane);
frame.add(explanationPane);
titlePane.setVisible(false);
explanationPane.setVisible(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public void switchPane(String pane) {
switch (pane) {
case "title":
titlePane.setVisible(true);
explanationPane.setVisible(false);
break;
case "explanation":
titlePane.setVisible(false);
explanationPane.setVisible(true);
break;
}
}
#Override
public void actionPerformed(ActionEvent event) {
}
public static void main(String[] args) {
Main war = new Main(true);
war.switchPane("title");
while (true) {
if (frame.getX() != frameSize) {
frameSize = frame.getX();
}
else if (frame.getY() != frameSize) {
frameSize = frame.getY();
}
frame.setSize(frameSize, frameSize);
titlePane.setSize(frameSize, frameSize);
explanationPane.setSize(frameSize, frameSize);
playButton.setBounds(Numbers.doubleToInt(frameSize/2.5), Numbers.doubleToInt(frameSize/2.5), Numbers.doubleToInt(frameSize/5), Numbers.doubleToInt(frameSize/(100/3)));
explanationButton.setBounds(Numbers.doubleToInt(frameSize/2.5), Numbers.doubleToInt(frameSize/(25/11)), Numbers.doubleToInt(frameSize/5), Numbers.doubleToInt(frameSize/(100/3)));
}
}
}
Numbers.java:
package Numbers;
public class Numbers {
public static int doubleToInt(double toConvert) {
int toReturn = (int) toConvert;
return toReturn;
}
}
Any help would be appreciated! :)
Please note I am not close to finishing so please ignore the empty method.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Stuck on a problem that requires grabbing a boolean variable from another class.
I have the following for-loop, boolean and if-else statements
import java.awt.*;
import javax.swing.*;
import java.awt.Color.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.util.Random;
public class Checkers extends JFrame
{
Random random = new Random();
private final int ROWS = 2;
private final int COLS = 5;
private final int GAP = 2;
private final int NUM = ROWS * COLS;
private int i;
private int score;
private JPanel pane = new JPanel(new GridLayout(ROWS,COLS, GAP,GAP));
private JPanel pane2 = new JPanel();
private JPanel pane3 = new JPanel();
private JButton btn1 = new JButton("Play A Game");
private JButton btn2 = new JButton("Exit");
private JButton btn3 = new JButton("Easy");
private JButton btn4 = new JButton("Intermediate");
private JButton btn5 = new JButton("Difficult");
private JLabel lbl1 = new JLabel ("score: " + score);
private JLabel gameLost = new JLabel("You lose! You got: " + score + " points");
private JButton btnRestart = new JButton("Restart");
private MyPanel [] panel = new MyPanel[NUM];
private Color col1 = Color.RED;
private Color col2 = Color.WHITE;
private Color col3 = Color.GREEN;
private Color tempColor;
private boolean isPanelDisabled;
//Starts the checkers GUI, calling the constructor below this.
public static void main(String[] args){
new Checkers();
}
//Sets the dimensions of the GUI, visibility, background color and
//contents via the setBoard();
public Checkers()
{
super("Checkers");
setSize(600,600);
setVisible(true);
setBackground(Color.BLACK);
setBoard();
}
//Makes the grid, contains a conditional boolean, adds the panels to grid based on i value.
//sets Colours accordingly
public void setBoard()
{
boolean isPanelDisabled = false;
for (int i = 0; i < panel.length; i++) {
panel[i] = new MyPanel(this);
pane.add(panel[i]);
if (i % COLS == 0) {
tempColor = col1;
}
if (i == 9 || i <8) {
panel[i].setBackground(col1);
}
if(i == 8){
isPanelDisabled = true;
panel[i].setBackground(col3);
}
}
//pane background colour and the size of this pane.
pane.setBackground(Color.BLACK);
pane.setPreferredSize(new Dimension(300,300));
//pane background colour and size of this pane.
pane2.setBackground(Color.white);
pane2.setPreferredSize(new Dimension(300,300));
//directions on the board where these panes appear.
add(pane, BorderLayout.WEST);
add(pane2, BorderLayout.EAST);
pane2.add(lbl1);
pane2.add(btnRestart);
btnRestart.addActionListener( e -> restartBoard());
pane2.setLayout(new BoxLayout(pane2, BoxLayout.PAGE_AXIS));
}
//increments the score for the user based on current points.
public void incrementScore(){
if (score != 5){
score++;
lbl1.setText("Score: " + Integer.toString(score));
}
else if(score == 5){
lbl1.setText("Congratulations!, you've won!, your score is:" + score);
}
}
}
and this mouseClicked Event
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;
public class MyPanel extends JPanel implements MouseListener, ActionListener {
private final Checkers checkers;
private boolean isPanelDisabled;
//MyPanel Constructor that initiates a instance of checkers.
public MyPanel(Checkers checkers) {
this.checkers = checkers;
addMouseListener(this);
}
#Override
public void actionPerformed(ActionEvent e){
}
// Sets the panel colours according to their int number and the boolean condiiton.
#Override
public void mouseClicked(MouseEvent e) {
if (isPanelDisabled == true){
setBackground(Color.CYAN);
}
else{
setBackground(Color.BLACK);
checkers.incrementScore();
}
}
My Expected result of this should be that if the user clicks the 8th panel in that grid, then the color of that panel will be cyan when pressed and not black, but it cant access the boolean variable? where am i going wrong here?
Your question involves communication between objects of different classes, and there are several ways to do this, but most basic is to call a method of an object in one class to the other.
First lets set up the problem,... I've created classes called MyPanel2 and Checkers2, to distinguish them from yours.
Say in MyPanel2 we have a Checkers2 field and a boolean field called selected that is set to false:
private Checkers2 checkers;
private boolean selected = false;
along with appropriate boolean getter and setter:
public void setSelected(boolean selected) {
this.selected = selected;
}
public boolean isSelected() {
return selected;
}
And say within the Checkers2 class you have a 10 instances of MyPanel2 held within an array, and you want the user to be able to "select" instances of the class, but only allow 7 of them to be selected, and assume that you want to user the set up that you're currently using, you could give the main class, a method, public boolean isPanelDisabled(), and have the MyPanel2 class call this method to determine if selection is allowed. So within MyPanel2 you could have a MouseListener with something like:
#Override
public void mousePressed(MouseEvent e) {
if (selected) {
return;
}
// call the Checkers2 boolean method to check
if (checkers.isPanelDisabled()) {
setBackground(DISABLED_COLOR);
} else {
setBackground(SELECTED_COLOR);
setSelected(true);
}
}
Within Checkers2 .isPanelDisabled() method you'd iterate through the array of MyPanel2 instances to see how many have been selected, something like this could work:
public boolean isPanelDisabled() {
int count = 0;
for (MyPanel2 panel2 : myPanels) {
if (panel2.isSelected()) {
count++;
}
}
return count >= MAX_COUNT;
}
The whole MCVE testable code could look like:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Checkers2 extends JFrame {
private static final int MAX_COUNT = 7;
private final int ROWS = 2;
private final int COLS = 5;
private final int GAP = 2;
private final int NUM = ROWS * COLS;
private MyPanel2[] myPanels = new MyPanel2[NUM];
public Checkers2() {
super("Checkers");
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel gridPanel = new JPanel(new GridLayout(ROWS, COLS, 1, 1));
gridPanel.setBackground(Color.BLACK);
gridPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
for (int i = 0; i < myPanels.length; i++) {
MyPanel2 myPanel = new MyPanel2(this);
gridPanel.add(myPanel);
myPanels[i] = myPanel;
}
JButton resetButton = new JButton("Reset");
resetButton.setMnemonic(KeyEvent.VK_R);
resetButton.addActionListener(evt -> {
for (MyPanel2 myPanel2 : myPanels) {
myPanel2.reset();
}
});
JButton exitButton = new JButton("Exit");
exitButton.setMnemonic(KeyEvent.VK_X);
exitButton.addActionListener(evt -> System.exit(0));
JPanel buttonPanel = new JPanel();
buttonPanel.add(resetButton);
add(gridPanel);
add(buttonPanel, BorderLayout.PAGE_END);
pack();
setLocationRelativeTo(null);
}
public boolean isPanelDisabled() {
int count = 0;
for (MyPanel2 panel2 : myPanels) {
if (panel2.isSelected()) {
count++;
}
}
return count >= MAX_COUNT;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new Checkers2().setVisible(true);
});
}
}
class MyPanel2 extends JPanel {
private static final int PREF_W = 200;
private static final int PREF_H = PREF_W;
private static final int GR = 240;
public static final Color BASE_COLOR = new Color(GR, GR, GR);
public static final Color DISABLED_COLOR = Color.CYAN;
public static final Color SELECTED_COLOR = Color.BLACK;
private Checkers2 checkers;
private boolean selected = false;
public MyPanel2(Checkers2 checkers) {
setBackground(BASE_COLOR);
this.checkers = checkers;
setPreferredSize(new Dimension(PREF_W, PREF_H));
addMouseListener(new MyMouse());
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public boolean isSelected() {
return selected;
}
public void reset() {
setBackground(BASE_COLOR);
setSelected(false);
}
private class MyMouse extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
if (selected) {
return;
}
if (checkers.isPanelDisabled()) {
setBackground(DISABLED_COLOR);
} else {
setBackground(SELECTED_COLOR);
setSelected(true);
}
}
}
}
Another Option is to take all the logic out of MyPanel and put it into the main program, something like:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class Checkers3 extends JPanel {
private static final int MAX_COUNT = 7;
private final int ROWS = 2;
private final int COLS = 5;
private final int GAP = 2;
private final int NUM = ROWS * COLS;
private MyPanel3[] myPanels = new MyPanel3[NUM];
public Checkers3() {
JPanel gridPanel = new JPanel(new GridLayout(ROWS, COLS, 1, 1));
gridPanel.setBackground(Color.BLACK);
gridPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
MyMouse myMouse = new MyMouse();
for (int i = 0; i < myPanels.length; i++) {
MyPanel3 myPanel = new MyPanel3();
myPanel.addMouseListener(myMouse);
gridPanel.add(myPanel);
myPanels[i] = myPanel;
}
JButton resetButton = new JButton("Reset");
resetButton.setMnemonic(KeyEvent.VK_R);
resetButton.addActionListener(evt -> {
for (MyPanel3 myPanel : myPanels) {
myPanel.reset();
}
});
JButton exitButton = new JButton("Exit");
exitButton.setMnemonic(KeyEvent.VK_X);
exitButton.addActionListener(evt -> System.exit(0));
JPanel buttonPanel = new JPanel();
buttonPanel.add(resetButton);
setLayout(new BorderLayout());
add(gridPanel);
add(buttonPanel, BorderLayout.PAGE_END);
}
public boolean isPanelDisabled() {
int count = 0;
for (MyPanel3 panel : myPanels) {
if (panel.isSelected()) {
count++;
}
}
return count >= MAX_COUNT;
}
private class MyMouse extends MouseAdapter {
#Override
public void mousePressed(MouseEvent e) {
MyPanel3 myPanel = (MyPanel3) e.getSource();
if (myPanel.isSelected()) {
return; // it's already selected
} else if (isPanelDisabled()) {
myPanel.setSelected(false);
} else {
myPanel.setSelected(true);
}
}
}
private static void createAndShowGui() {
Checkers3 mainPanel = new Checkers3();
JFrame frame = new JFrame("Checkers");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
#SuppressWarnings("serial")
class MyPanel3 extends JPanel {
private static final int PREF_W = 200;
private static final int PREF_H = PREF_W;
private static final int GR = 240;
public static final Color BASE_COLOR = new Color(GR, GR, GR);
public static final Color DISABLED_COLOR = Color.CYAN;
public static final Color SELECTED_COLOR = Color.BLACK;
private boolean selected = false;
public MyPanel3() {
setBackground(BASE_COLOR);
setPreferredSize(new Dimension(PREF_W, PREF_H));
}
public void setSelected(boolean selected) {
this.selected = selected;
Color background = selected ? SELECTED_COLOR : DISABLED_COLOR;
setBackground(background);
}
public boolean isSelected() {
return selected;
}
public void reset() {
setSelected(false);
setBackground(BASE_COLOR);
}
}
But the BEST option is to put all logic within a separate model class (or classes) and make the GUI's as dumb as possible.
I am trying to write a GUI temperature converter. It has one JTextField and two JButtons. TextField accepts the temperature which the user wants to convert and the user presses the appropriate button. Whenever I click on anyone of the buttons, I get a "Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String" error. Please Help!
public class tempcon extends JFrame {
private JPanel panel;
private JLabel messageLabel;
public JTextField tempC;
private JButton calcButton, calcButton1;
private final int WINDOW_WIDTH = 300;
private final int WINDOW_HEIGHT = 140;
public tempcon() {
setTitle("Temperature convertion");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
setVisible(true);
}
public double getTempC(){
return Double.parseDouble(tempC.getText());
}
private void buildPanel() {
tempC = new JTextField(10);
messageLabel = new JLabel("Enter tempurture");
calcButton = new JButton("Convert to Fahrenheit");
calcButton1 = new JButton("Convert to Celcius");
calcButton.addActionListener(new CalcButtonListener());
calcButton1.addActionListener(new CalcButtonListener1());
panel = new JPanel();
panel.add(messageLabel);
panel.add(tempC);
panel.add(calcButton);
panel.add(calcButton1);
}
public static void main(String[] args){
new tempcon().buildPanel();
}
}
class CalcButtonListener1 implements ActionListener {
public void actionPerformed(ActionEvent e) {
double input;
double temp;
input = new tempcon().getTempC();
temp = input * 1.8 + 32;
JOptionPane.showMessageDialog(null, "That is " + temp + "
degrees Celsius.");
}
}
class CalcButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
double input;
double temp;
input = new tempcon().getTempC();
temp = (input - 32)*1.8;
JOptionPane.showMessageDialog(null, "That is " + temp + "
degrees Fehrenheit.");
}
public static void main(String[] args) {
tempcon myTempWindowInstance = new tempcon();
}
}
The problem is that you are recreating a new frame in your action listeners : new tempcon().getTempC() .
The textfields in these new frames are obviously empty and you get your error.
Consider referring to the same instance of tempcon everywhere, that is simply replace
new tempcon().getTempC();
with
getTempC();
, which will call the getTempC() method of the outer tempcon instance .
This class reads input from a JPanel GUI. Doesn't SOP anything unless I input 1 for each coefficient. Then it just prints "0.0" Any recommendations on how I can get this to work? I've tried everything I can think of.
public class PolyRoots extends PolyGUI {
private double coefficientToFifthPower;
private double coefficientToFourthPower;
private double coefficientToThirdPower;
private double coefficientToSecondPower;
private double coefficientToFirstPower;
private double constant;
private double x;
public double getCoefficientToFifthPower() {
return coefficientToFifthPower;
}
public void setCoefficientToFifthPower(double coefficientToFifthPower) {
this.coefficientToFifthPower = coefficientToFifthPower;
}
public double getCoefficientToFourthPower() {
return coefficientToFourthPower;
}
public void setCoefficientToFourthPower(double coefficientToFourthPower) {
this.coefficientToFourthPower = coefficientToFourthPower;
}
public double getCoefficientToThirdPower() {
return coefficientToThirdPower;
}
public void setCoefficientToThirdPower(double coefficientToThirdPower) {
this.coefficientToThirdPower = coefficientToThirdPower;
}
public double getCoefficientToSecondPower() {
return coefficientToSecondPower;
}
public void setCoefficientToSecondPower(double coefficientToSecondPower) {
this.coefficientToSecondPower = coefficientToSecondPower;
}
public double getCoefficientToFirstPower() {
return coefficientToFirstPower;
}
public void setCoefficientToFirstPower(double coefficientToFirstPower) {
this.coefficientToFirstPower = coefficientToFirstPower;
}
public double getConstant() {
return constant;
}
public void setConstant(double constant) {
this.constant = constant;
}
private double y;
public void readInputCoefficients() {
/* this.coefficientToFifthPower = Integer.parseInt(inputCoefficientFifthPower);
this.coefficientToFourthPower = Integer.parseInt(inputCoefficientFourthPower);
this.coefficientToThirdPower = Integer.parseInt(inputCoefficientThirdPower);
this.coefficientToSecondPower = Integer.parseInt(inputCoefficientSecondPower);
this.coefficientToFirstPower = Integer.parseInt(inputCoefficientFirstPower);
this.constant = Integer.parseInt(inputConstant);*/
}
public double calculateY(double x) {
this.y = this.coefficientToFifthPower * Math.pow(x, 5) + this.coefficientToFourthPower * Math.pow(x, 4) +
this.coefficientToThirdPower * Math.pow(x, 3) + this.coefficientToSecondPower * Math.pow(x, 2) + (this.coefficientToFirstPower * x) + this.constant;
return this.y;
}
public void getTheBounds() {
for (double x = -10.0001; x <= 10.0001; x += .1) {
double y1 = calculateY(x);
double y2 = calculateY(x + .01);
if ((y1 * y2) < 0) {
System.out.println(bisectionMethod(y1, y2));
}
else if((y1 * y2) > 0){
System.out.println(bisectionMethod(y1,y2));
}
}
}
public double bisectionMethod(double a, double b) {
double average;
double root = 0;
double yOfC;
int leaveloop = 0;
for(int x = 0; x <= 10000000; x++) {
average = (a + b) / 2;
yOfC = calculateY(average);
if (Math.abs(yOfC) < 0.0001) {
root = average;
return root;
} else if (yOfC * calculateY(a) > 0) {
a = average;
} else {
b = average;
}
}
System.out.println(root);
return root;
}
}
GUI
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class PolyGUI extends JPanel
{
// ***Variables are created ***
//*** GUIs are made up of JPanels. Panels are created
//*** here and named appropriately to describe what will
//*** be placed in each of them.
JPanel titlePanel = new JPanel();
JPanel c5Panel = new JPanel();
JPanel c4Panel = new JPanel();
JPanel c3Panel = new JPanel();
JPanel c2Panel = new JPanel();
JPanel c1Panel = new JPanel();
JPanel cPanel = new JPanel();
JPanel calculatePanel = new JPanel();
//*** a JLabel is a text string that is given a String value
//*** and is placed in its corresponding JPanel or JButton
JLabel titleLabel = new JLabel();
JLabel c5Label = new JLabel();
JLabel c4Label = new JLabel();
JLabel c3Label = new JLabel();
JLabel c2Label = new JLabel();
JLabel c1Label = new JLabel();
JLabel cLabel = new JLabel();
JLabel questionLabel = new JLabel();
JLabel calculateLabel = new JLabel();
//*** three JButtons are created. When pushed, each button calls
//*** its corresponding actionPerformed() method from the class created
//*** for each button. This method executes the method code, performing
//*** what the button is to do.
JButton calculateButton = new JButton();
//*** a JTextField creates a location where the client can place
//*** text
JTextField x5Txt = new JTextField(8);
JTextField x4Txt = new JTextField(8);
JTextField x3Txt = new JTextField(8);
JTextField x2Txt = new JTextField(8);
JTextField xTxt = new JTextField(8);
JTextField constantTxt = new JTextField(8);
//*** constructor
//*** Variables are given initial values
public PolyGUI()
{
//*** set panel layouts
//*** panels could be LEFT, or RIGHT justified.
titlePanel.setLayout(new FlowLayout(FlowLayout.CENTER));
c5Panel.setLayout(new FlowLayout(FlowLayout.CENTER));
c4Panel.setLayout(new FlowLayout(FlowLayout.CENTER));
c3Panel.setLayout(new FlowLayout(FlowLayout.CENTER));
c2Panel.setLayout(new FlowLayout(FlowLayout.CENTER));
c1Panel.setLayout(new FlowLayout(FlowLayout.CENTER));
cPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
questionLabel.setLayout(new FlowLayout(FlowLayout.CENTER));
calculateButton.setLayout(new FlowLayout(FlowLayout.CENTER));
//*** set Label fonts. You can use other numbers besides 30,20
//*** or 15 for the font size. There are other fonts.
Font quizBigFont = new Font("Helvetica Bold", Font.BOLD, 30);
Font quizMidFont = new Font("Helvetica Bold", Font.BOLD, 20);
titleLabel.setFont(quizBigFont);
questionLabel.setFont(quizMidFont);
c5Label.setFont(quizMidFont);
c4Label.setFont(quizMidFont);
c3Label.setFont(quizMidFont);
c2Label.setFont(quizMidFont);
c1Label.setFont(quizMidFont);
cLabel.setFont(quizMidFont);
//*** labels are given string values
titleLabel.setText("Polynomial Project");
questionLabel.setText("Please enter the coefficients");
c5Label.setText("5");
c4Label.setText("4");
c3Label.setText("3");
c2Label.setText("2");
c1Label.setText("1");
cLabel.setText("constant");
calculateButton.setText("Calculate");
calculateButton.addActionListener(new calculate());
//*** panels
titlePanel.add(titleLabel);
c5Panel.add(c5Label);
c5Panel.add(x5Txt);
c4Panel.add(c4Label);
c4Panel.add(x4Txt);
c3Panel.add(c3Label);
c3Panel.add(x3Txt);
c2Panel.add(c2Label);
c2Panel.add(x2Txt);
c1Panel.add(c1Label);
c1Panel.add(xTxt);
cPanel.add(cLabel);
cPanel.add(constantTxt);
calculatePanel.add(calculateButton);
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(titlePanel);
add(questionLabel);
add(c5Panel);
add(c4Panel);
add(c3Panel);
add(c2Panel);
add(c1Panel);
add(cPanel);
add(calculatePanel);
//*** The method writeToFile() is called from the constructor.
//*** One could call a read method from the constructor.
// writeToFile();
}// constructor
public void display()
{ //*** A JFrame is where the components of the screen
//*** will be put.
JFrame theFrame = new JFrame("GUI Example");
//*** When the frame is closed it will exit to the
//*** previous window that called it.
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//*** puts the panels in the JFrame
theFrame.setContentPane(this);
//*** sets the dimensions in pixels
theFrame.setPreferredSize(new Dimension(600, 380));
theFrame.pack();
//*** make the window visible
theFrame.setVisible(true);
}
class calculate implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Calculating...");
PolyRoots p1 = new PolyRoots();
double x5 = Integer.parseInt(x5Txt.getText());
double x4 = Integer.parseInt(x4Txt.getText());
double x3 = Integer.parseInt(x3Txt.getText());
double x2 = Integer.parseInt(x2Txt.getText());
double x = Integer.parseInt(xTxt.getText());
double constant = Integer.parseInt(constantTxt.getText());
p1.setCoefficientToFifthPower(x5);
p1.setCoefficientToFourthPower(x4);
p1.setCoefficientToThirdPower(x3);
p1.setCoefficientToSecondPower(x2);
p1.setCoefficientToFirstPower(x);
p1.setConstant(constant);
p1.getTheBounds();
}
}
public static void main(String[] args) throws IOException
{
PolyGUI newGUI = new PolyGUI();
newGUI.display();
}
}
Here is a simple example of a program which has a main and you can see what each line of code does.
public class PolyRoots {
private final double[] coeffs; // any number of coefficients.
public PolyRoots(double... coeffs) {
this.coeffs = coeffs;
}
public double calcY(double x) {
double ret = coeffs[0];
for (int i = 1; i < coeffs.length; i++)
ret = ret * x + coeffs[i];
return ret;
}
public static void main(String[] args) {
PolyRoots roots = new PolyRoots(1e-3, -2e-2, 0.1, -1, 5);
for (int i = -10_000; i <= 10_000; i++) {
double x = i / 1000.0;
double y = roots.calcY(x);
System.out.println(x + "\t" + y);
}
}
}
To a program like this you can add getBounds and bisectionMethod however these method does do what they are supposed (because I can't work out what they are even trying to do, but I have only been developing for thirty years ;)
What I am trying to do is add a JLabel to a JPanel which is inside an applet. However, I cannot seem to get the JLabels to appear. I think my problem is where I am adding my Jlabels and I am not "refreshing the screen" and they are not visible.
Edit picture of what I see:Picture of the panels
Here is the code: Main.java
public class Main extends JApplet{
/**
*
*/
private static final long serialVersionUID = -6568278275823927953L;
public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
createGUI();
}
});
} catch(Exception e) {
System.err.println("createGUI did not complete!");
}
}
private void createGUI() {
this.setLayout(new GridLayout(2,1));
Quiz myQuiz = new Quiz();
Options myOption = new Options();
JLabel[] answers = new JLabel[16];
for(int i = 0; i < 16; i++)
{
answers[i] = new JLabel();
answers[i].setText("HI!");
answers[i].setOpaque(true);
myOption.add(answers[i]);
}
myQuiz.setOpaque(true);
myOption.setOpaque(true);
this.add(myQuiz);
this.add(myOption);
}
}
Options.java
public class Options extends JPanel
implements MouseListener {
/**
*
*/
private static final long serialVersionUID = 3701573579935678995L;
Font myFont = new Font("Serif", Font.BOLD | Font.ITALIC, 20);
GridLayout myLayout = new GridLayout(4,4);
int HALF_WIDTH = getWidth() / 2;
int HALF_HEIGHT = getHeight() / 2;
public void init() {
addMouseListener(this);
this.setLayout(myLayout);
}