Related
I am trying to make a GUI which will take a value from one JPanel, and then when a button is pressed it will move on to the next panel, which uses information that was input from the previous panel. Since one panel is dependent on the value the user has input from the previous panel I don't think CardLayout will work here as it refers to the panels as strings.
As an example of the mechanism that I'm trying to implement, I have attempted to create a JFrame where
the first panel will ask the user to input a number,
the second panel will then display to the user the first number that the user selected and ask them to pick a second number,
the third panel will show the both the first and second number that the user selected and ask for a third number.
Finally, the fourth panel will display the sum of the three numbers that the user input in each JPanel, and allow the user to reset the JFrame.
I first created four separate classes that create the four JPanels I want to be able to move between. As can be seen from the code, I have tested each of these JPanels in a separate JFrame to see if they produce the desired effect.
Here is the code for PanelThree, PanelFour and the overall GUI. Panels one and two are very similar to panel three:
Panel Three:
import javax.swing.*;
import java.awt.*;
public class PanelThree extends JPanel {
JPanel row1 = new JPanel();
JPanel row2 = new JPanel();
JPanel row3 = new JPanel();
JSlider slider = new JSlider(0, 10, 5);
JButton next = new JButton("Find the total of all three numbers");
public PanelThree(int num0, int num1) {
BorderLayout lay = new BorderLayout();
setLayout(lay);
JLabel one = new JLabel("Choose your last number on the slider, the
slider goes from one to ten. Your first number was: " + num0 + ". Your
second number was: " + num1);
row1.add(one);
row2.add(slider);
row3.add(next);
add(row1, BorderLayout.NORTH);
add(row2, BorderLayout.CENTER);
add(row3, BorderLayout.SOUTH);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800,600);
PanelThree panelThree = new PanelThree(7, 2);
frame.setContentPane(panelThree);
frame.setVisible(true);
}
}
Panel Four:
import javax.swing.*;
import java.awt.*;
public class PanelFour extends JPanel {
JPanel row1 = new JPanel();
JPanel row2 = new JPanel();
JButton reset = new JButton("Reset");
public PanelFour(int num0, int num1, int num2) {
BorderLayout lay = new BorderLayout();
setLayout(lay);
int tot = num0 + num1 + num2;
JLabel total = new JLabel("All of your numbers add up to: " + tot);
row1.add(total);
row2.add(reset);
add(row1, BorderLayout.CENTER);
add(row2, BorderLayout.SOUTH);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800,600);
PanelFour panelFour = new PanelFour(7, 2, 9);
frame.setContentPane(panelFour);
frame.setVisible(true);
}
}
Now this is the problem, the class which tries to knit the four JPanels together and to have it react based on what the inputs were to the last JPanel in the JFrame. The issue seems to lie specifically with the actionPerformed method which is unable to access the components in the Frame constructor. Here is the code:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Frame extends JFrame implements ActionListener {
int x, y, z;
public void Frame() {
super("Number Adder");
int i = 1;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PanelOne panelOne = new PanelOne();
panelOne.next.addActionListener(this);
PanelTwo panelTwo = new PanelTwo(x);
panelTwo.next.addActionListener(this);
PanelThree panelThree = new PanelThree(x, y);
panelThree.next.addActionListener(this);
PanelFour panelFour = new PanelFour(x, y, z);
panelFour.reset.addActionListener(this);
if (i == 1) {
add(panelOne);
} else if (i == 2) {
add(panelTwo);
} else if (i == 3) {
add(panelThree);
} else {
add(panelFour);
}
}
public actionPerformed(ActionEvent e) {
if (e.getSource() == panelOne.next) {
return x = int panelOne.slider.getValue();
return i = 2;
} else if (e.getSource() == panelTwo.next) {
return y = int panelTwo.slider.getValue();
return i = 3;
} else if (e.getSource() == panelThree.next) {
return z = int panelThree.slider.getValue();
return i = 4;
} else {
return i = 1;
}
repaint();
}
public static void main(String[] args) {
Frame frame = new Frame();
}
}
What can I do to fix this or improve this?
I don't think CardLayout will work here as it refers to the panels as strings
Why not?
You have a sequence of events.
Enter a number,
Display another panel.
There is no reason the second panel can't access the first number entered. That has nothing to do with a CardLayout.
Your second panel, just needs a way to access the data from the first panel. So maybe when you create the second panel you pass in the reference to the first panel. So when you display the second panel you can know access the number entered on the first panel.
I'm making a hangman game for school and I've run into a problem that I simply can't solve, maybe I'm overthinking, maybe I'm not. Anyways, I need to let the user input a letter, and if that letter is in the word used for the game (pikachu. I know, stupid choice but it's pretty basic and easy so I used that) then the letter is revealed, the problem is that after inputting a letter, the user can't guess any more letters. I need a way to loop through the letter input and revealing so that I can actually play the game.
I'm sorry if the solution is so simple but I just can't figure out what needs to change in my code in order to fix my problem because I'm very new to java.
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.*;
import java.awt.event.KeyListener;
import javax.swing.*;
public class PanDisp extends JPanel {
JLabel lblOutput;
JLabel lblGuess;
JButton btnUpdateLabel;
Image imgPkmn;
FraImg fraImg;
String sSecret;
public PanDisp() {//Constructor
KeyInput keyInput = new KeyInput();
KeyInput.LabelChangeListener labelChange = keyInput.new LabelChangeListener();
sSecret = "*******";
lblGuess = new JLabel("Type will go here");
lblOutput = new JLabel(sSecret);
btnUpdateLabel = new JButton("Enter");
add(lblOutput);
add(btnUpdateLabel);
addKeyListener(new KeyInput());
setFocusable(true);
btnUpdateLabel.addActionListener(labelChange);
fraImg = new FraImg(imgPkmn);
}
public void GameOver() {
}
class KeyInput implements KeyListener {
String sInput;
String sWord = "pikachu";
String sSecret = "*******";
char chInput;
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
chInput = (char) e.getKeyChar();
sInput = String.valueOf(chInput);
lblOutput.setText(sInput);
}
#Override
public void keyReleased(KeyEvent e) {
}
class LabelChangeListener implements ActionListener {
char cWord;
int nCorrect, nIncorrect, nNum;
public void actionPerformed(ActionEvent event) {
if (sWord.contains(sInput)) {
for (int i = 0; i < sWord.length(); i++) {
sSecret.replace(sSecret.charAt(i), sWord.charAt(i));
}
nCorrect += 1;
}
else {
nIncorrect += 1;
if (nIncorrect == 7) {
GameOver();
}
}
}
}
}
}
Your problem is that your mindset is off and has to be changed. Don't think "loop", and in fact get "loop" out of the equation. You're programming in an event-driven programming environment, and the loop you're thinking of belongs in the linear console programming environment. Instead think "state of object" and "behavioral changes to state changes", and you'll move much further in this quest. So change the state of your class -- number of guesses, number of correct guesses, and then change the response to the user's input based on this state
For instance, if you wanted to create a console program that allowed a user to enter 5 Strings, and then displayed those Strings back to the user, it would be pretty straight forward, in that you'd create your String array, and then use a for loop to prompt the user 5 times to enter text, grabbing each entered String within the loop. Here "loops" like the one you're requesting work.
Linear Console Program
import java.util.Scanner;
public class Enter5Numbers1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter 5 sentences:");
String[] sentences = new String[5];
for (int i = 0; i < sentences.length; i++) {
System.out.printf("Enter sentence #%d: ", (i + 1));
sentences[i] = scanner.nextLine();
}
System.out.println("You entered the following sentences:");
for (String sentence : sentences) {
System.out.println(sentence);
}
scanner.close();
}
}
If on the other hand you wanted to create a GUI that did something similar, that prompted the user for 5 Strings and accepted those Strings into an array, you couldn't use the same type of for loop. Instead you would need to give your class an int String counter, perhaps called enteredSentenceCount, and in a JButton's ActionListener (or Action -- which is something very similar), you would accept an entered String (perhaps typed into a JTextField called entryField), only if the enteredSentenceCount is less than 5, less than the maximum number of Strings allowed. You would of course increment the enteredSentenceCount variable each time a String is entered. And this combination of increase a counter variable and checking its value will need to substutite for the concept of a "loop". So here the "state" of the class is held in the enteredSentenceCount, and the behavioral change we want is to alter what the button's Action does depending on the enteredSentenceCount's value -- if less than 5, accept a String, and if it is equal to or greater than 5, display the entered Strings.
Event Driven GUI Program
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class Enter5Numbers2 extends JPanel {
private static final int MAX_SENTENCE_COUNT = 5; // number of Strings to enter
private static final String PROMPT_TEMPLATE = "Please enter sentence number %d:";
private String[] sentences = new String[MAX_SENTENCE_COUNT]; // array to hold entered Strings
private int enteredSentenceCount = 0; // count of number of Strings entered
private JTextField entryField = new JTextField(20); // field to accept text input frm user.
// JLabel to display prompts to user:
private JLabel promptLabel = new JLabel(String.format(PROMPT_TEMPLATE, (enteredSentenceCount + 1)));
public Enter5Numbers2() {
// create GUI
// First create Action / ActionListener for button
EntryAction entryAction = new EntryAction("Enter");
JButton entryButton = new JButton(entryAction); // pass it into the button
entryField.setAction(entryAction); // but give it also to JTextField so that the enter key will trigger it
// JPanel to accept user data entry
JPanel entryPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
entryPanel.add(entryField);
entryPanel.add(entryButton);
// allow main JPanel to display prompt
setBorder(BorderFactory.createTitledBorder("Please Enter 5 Sentences"));
setLayout(new GridLayout(2, 1));
add(promptLabel);
add(entryPanel);
}
// Action class, similar to an ActionListener
private class EntryAction extends AbstractAction {
public EntryAction(String name) {
super(name);
putValue(MNEMONIC_KEY, (int) name.charAt(0));
}
#Override
public void actionPerformed(ActionEvent e) {
// check that we haven't entered more than the max number of sentences
if (enteredSentenceCount < MAX_SENTENCE_COUNT) {
// if OK, get the entered text
String sentence = entryField.getText();
// put it in our array
sentences[enteredSentenceCount] = sentence;
entryField.setText(""); // clear the text field
entryField.requestFocusInWindow(); // set the cursor back into the textfield
enteredSentenceCount++; // increment our entered sentence count variable
promptLabel.setText(String.format(PROMPT_TEMPLATE, (enteredSentenceCount + 1))); // change prompt
}
// if the number of sentences added equals the number we want, display it
if (enteredSentenceCount == MAX_SENTENCE_COUNT) {
JTextArea textArea = new JTextArea(6, 30);
for (String sentence : sentences) {
textArea.append(sentence + "\n");
}
JScrollPane scrollPane = new JScrollPane(textArea);
JOptionPane.showMessageDialog(Enter5Numbers2.this, scrollPane, "Five Sentences Entered",
JOptionPane.PLAIN_MESSAGE);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Enter 5 Numbers");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(new Enter5Numbers2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
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 8 years ago.
Improve this question
So I am making a simple tic tac toe game and ran into a problem at the last minute
I am trying to draw a line at the win location but on the final win location(index), the line gets hidden behind the JButton not entirly sure why it is doing this.
I know alot of people say do not use getGraphics(), and I am wondering if that is the source of my issues they say to override the paintComponent method but that is not working for me either
I have attached a pic of what the result is looking like and code snips of how I am trying to perform these actions
PS I am using a JFrame, if any more code is needed I will be glad to show it
if(win[i] == 264){ // if one of the the combinations equal 'X','X','X' which equals 264, then there is a winner
System.out.println("X is the winner!!!");
System.out.println("Game Over!");
number = i;
draw(); }// call draw method
private void draw(){ // drawing a line at winning location
Graphics2D g1 = (Graphics2D) GUI.getFrame().getGraphics(); // declaring graphics on our Jframe
Stroke stroke3 = new BasicStroke(12f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER); // make our strokes cap off round
if(number == 0){ // statements will determine the win location, so at win0, XXX,
g1.setStroke(stroke3); // we will add stroke to our line
g1.drawLine(0,104,500,104); // draw the line starting at the 0,104 and end it at coordinates 500,104
}
here is a more runnable code, it is alot though
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Stroke;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class tic implements Runnable {
final static int row = 3; // our rows
final static int col = 3; // our col
final static int sizeOfBoard = row * col;
// the size of our board is not going to change so we make it final
static JButton[] clickButton;
char[] templateOfBoard; // our board, TicTacToe field, static
char userTurn; // users turn , only one letter, tracks whether it is a X or O
int count; // keeps track of user moves
static JFrame frame; // our JFrame
int number;
public tic(JFrame frame) {
tic.frame = new JFrame("TicTacToe GAME");
clickButton = new JButton[9];
count = 0; // number of turns starts at 0;
number = 0;
setUserTurn('X'); // first turn will always be X
setTemplateOfBoard(new char[sizeOfBoard]); // size of the board we are going to make it
try{
for(int spaces=0; spaces<sizeOfBoard; spaces++){ // size of Board is in the GUI class
getTemplateOfBoard()[spaces] = ' '; // the board is being created, looping through all rows and col
//every index of the board not has a char value equal to a space
//determine if everything came out correctly
//should equal of a total of 9
// 3x3
}
System.out.println("Board template created"); // means the board now has all spaces
}
catch(Exception e){
System.out.println("Could not initalize the board to empty char");
e.printStackTrace();
}
}
public static void main(String[] args){
try{
SwingUtilities.invokeLater(new tic(frame)); // run
}
catch(Exception e){ // wanted to test to ensure that Runnable could be invoked
System.out.println("Could not excute Runnable application");
e.printStackTrace();
}
}
public void run() {
setup(); // going to run out setup method, what our game is made out of
}
public void setup() {
// setting up the Board
// board is composed of JButton
// and a 3x3 frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // when the user closes the window JFrame will exit
//going to design the board now
//the dimensations of the board = sizeOfBoard
getFrame().setLayout(new GridLayout(row, col)); // this is the outline rows * col
// sizes out row * col based on what we define those numbers as
//i.e 3x3
getFrame().setBounds(0,0,500,500); // location at 0,0, size 500 x 500
Border border = new LineBorder(Color.DARK_GRAY, 2); // color of JButton border
System.out.println("Your board game is being created!");
try{
getFrame().setVisible(true); // shows the board,
// this is going to display everything to the screen
System.out.println("Board is now visable");
}
catch(Exception e){
System.out.println("Board was not displayed");
}
// 9 different buttons, for every index there will be a button
for(int i =0; i<sizeOfBoard;i++){ // going to fill the board with clickableButtons by looping through every index and placing a button there
final int move = i;
clickButton[i] = new JButton(); // at a certain index there is a new button
clickButton[i].setSize(250,250); // size of each button
clickButton[i].setBackground(Color.WHITE); // color of the JButton
getFrame().add(clickButton[i]); // we are going to add the actual the button at that index on the frame
clickButton[i].setFont(new Font("Arial", Font.BOLD, 70)); // size of the text
clickButton[i].setBorder(border); // adding border
clickButton[i].getModel().addChangeListener(new ChangeListener() { //going to overRide what happens when we rollover and press a Butotn
public void stateChanged(ChangeEvent e) {
ButtonModel button = (ButtonModel) e.getSource(); // manages the state of the button, i.e lets me control what happens to the button
if(clickButton[move] != null){ // if we do not include this argument
// the buttons are not made yet on the new game, meaning clickButton[i] = null
//so boolean(!button.isRollover()) will return true, since on the new game you can not have your mouse hovered over
// but when it returns true, it will return a null value, giving a null pointer exception
// so best thing to do, is to only run these cases below when the buttons are not null
if (button.isRollover()) { // when the mouse hovers over the index
clickButton[move].setBackground(Color.BLACK); // color will equal black
}
else if(!button.isRollover()){ // when the button is not hovered over
clickButton[move].setBackground(Color.WHITE); // color will be whte, just like our background
}
}
}
});
clickButton[i].addActionListener(new ActionListener() {
//our click events, going to override to let it know what we want to happen
//once we click on the button
public void actionPerformed(ActionEvent e) {
clickButton[move].setEnabled(false); //going to disable the button after it is clicked
//ORDER: button gets clicked first, then the test is added
mouseListener(e, move); // our mouseListenerEvent in game class
//
}
});
}
}
public static void playAgain() {
try{
System.out.println("NEW GAME");
SwingUtilities.invokeLater(new tic(frame)); // run the run(class) again
}
catch(Exception e){ // wanted to test to ensure that Runnable could be invoked
System.out.println("Could not excute Runnable application");
e.printStackTrace();
}
}
public static JFrame getFrame() {
return frame;
}
public tic userMove(int moveMade){
getTemplateOfBoard()[moveMade] = getUserTurn();
// index of the board, or in simpler terms, where the user
// inserts there turn i.e X or O, 0-8
//System.out.println(userMove);
//boolean statement to determine the turns
// So user X starts first
//if the turn is X, the nextTurn is now O,
if(getUserTurn() == 'X'){
setUserTurn('O');
}
else {
setUserTurn('X');
}
count++;
return this; // going to return the userTurn
// issue actually entering the userTurn is not giving right value, but using 'this' does
}
// for some odd reason the toString is causing some issues, keep getting #hash code
//saw online to override it like this
// will make the board out of emepty strings
// going to return a string representation of an object
public String toString(){
return new String(getTemplateOfBoard());
}
public void mouseListener(ActionEvent e, int moveMade){
// mouse click events
// what happens after a button is clicked
if(getTemplateOfBoard()[moveMade] == ' '){ // the user can only space a click, so an letter on the field if it is empty
((JButton)e.getSource()).setText(Character.toString(getUserTurn())); // when the button is clicked, we want an X placed there
if (getUserTurn() == 'X'){
UIManager.getDefaults().put("Button.disabledText",Color.RED); // when the but gets disabled the test will turn red
}
else{
UIManager.getDefaults().put("Button.disabledText",Color.BLUE);
}
//calling the method userTurn to determine who goes next
//problem is that is expects a String
//going to override the toString method
userMove(moveMade); // calling userMove in moveMade, moveMade is the index at which the user put either an X or a O
winner(); // we want to check each time to ensure there was/was not a winner
}
}
public tic winner() { // determines who is the winner
//list below defines all the possible win combinations
// the index of where a X or O can be place
// placed the locations to a int value
int win1 = templateOfBoard[0] + templateOfBoard[1] + templateOfBoard[2];
int win2 = templateOfBoard[3] + templateOfBoard[4] + templateOfBoard[5];
int win3 = templateOfBoard[6] + templateOfBoard[7] + templateOfBoard[8];
int win4 = templateOfBoard[0] + templateOfBoard[3] + templateOfBoard[6];
int win5 = templateOfBoard[1] + templateOfBoard[4] + templateOfBoard[7];
int win6 = templateOfBoard[2] + templateOfBoard[5] + templateOfBoard[8];
int win7 = templateOfBoard[0] + templateOfBoard[4] + templateOfBoard[8];
int win8 = templateOfBoard[2] + templateOfBoard[4] + templateOfBoard[6];
int[] win = new int[]{win1,win2,win3,win4,win5,win6,win7,win8};
// making a array to go through all the possibile wins
//possible total of wins is 8
for(int i = 0;i<win.length;i++){
// looping through the win possibilities
if(win[i] == 264){ // if one of the the combinations equal 'X','X','X' which equals 264, then there is a winner
System.out.println("X is the winner!!!");
System.out.println("Game Over!");
number = i;
draw(); // call draw method
return this; // if statement is true, it will return this(gameOver)
}
else if(win[i] == 237 ){ // if one of the the combinations equal 'O','O','O' which equals 234, then there is a winner
System.out.println("O is the winner!!!");
System.out.println("Game Over!");
number = i;
//draw(); // call draw method
return this;
}
if (count == 9) {
// if none of the statements above are true, it automatically comes done to here
//so if there is nine moves and no win, it is a draw
}
}
return this;
// going to return this method ;
}
private void draw(){ // drawing a line at winning location
Graphics2D g1 = (Graphics2D) getFrame().getGraphics(); // declaring graphics on our Jframe
Stroke stroke3 = new BasicStroke(12f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER); // make our strokes cap off round
if(number == 0){ // statements will determine the win location, so at win0, XXX,
g1.setStroke(stroke3); // we will add stroke to our line
g1.drawLine(0,104,500,104); // draw the line starting at the 0,104 and end it at coordinates 500,104
}
else if(number == 1){
g1.setStroke(stroke3);
g1.drawLine(0,257,500,257);
}
else if(number == 2){
g1.setStroke(stroke3);
g1.drawLine(0,411,500,411);
}
else if(number == 3){
g1.setStroke(stroke3);
g1.drawLine(88,0,88,500);
}
else if(number == 4){
g1.setStroke(stroke3);
g1.drawLine(250,0,250,500);
}
else if(number == 5){
g1.setStroke(stroke3);
g1.drawLine(411,0,411,500);
}
else if(number == 6){
g1.setStroke(stroke3);
g1.drawLine(-22,0,500,500);
}
else if(number == 7){
g1.setStroke(stroke3);
g1.drawLine(520,0,0,500);
}
}
// want to be able to access the private variables
//so we will make getter and setter methods for the ones that we need
public char getUserTurn() { // getter method for userTurn
return userTurn;
}
public void setUserTurn(char userTurn) { // setter method
this.userTurn = userTurn;
}
public char[] getTemplateOfBoard() { //getter method
return templateOfBoard;
}
public void setTemplateOfBoard(char[] templateOfBoard) { // setter method
this.templateOfBoard = templateOfBoard;
}
}
Painting over the top of components can be troublesome, you can't override the paintComponent method of the container which contains the components, because this paints in the background, you can't override the paint method of the container, as child components can be painted without the parent container been notified...
You could add a transparent component over the whole lot, but this just introduces more complexity, especially when a component already already exists ...
public class ConnectTheDots {
public static void main(String[] args) {
new ConnectTheDots();
}
public ConnectTheDots() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
PaintPane pp = new PaintPane();
JFrame frame = new JFrame("Test");
frame.setGlassPane(pp);
pp.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DotsPane(pp));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PaintPane extends JPanel {
private List<JButton[]> connections;
private JButton lastSelected;
public PaintPane() {
setOpaque(false);
connections = new ArrayList<>(25);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
if (lastSelected != null) {
g2d.setColor(Color.RED);
int x = lastSelected.getX() + ((lastSelected.getWidth() - 8) / 2);
int y = lastSelected.getY() + ((lastSelected.getHeight() - 8) / 2);
g2d.fillOval(x, y, 8, 8);
}
for (JButton[] group : connections) {
g2d.setColor(Color.BLUE);
Point startPoint = group[0].getLocation();
Point endPoint = group[1].getLocation();
startPoint.x += (group[0].getWidth() / 2);
startPoint.y += (group[1].getHeight()/ 2);
endPoint.x += (group[0].getWidth() / 2);
endPoint.y += (group[1].getHeight()/ 2);
g2d.draw(new Line2D.Float(startPoint, endPoint));
}
g2d.dispose();
}
protected void buttonClicked(JButton btn) {
if (lastSelected == null) {
lastSelected = btn;
} else {
connections.add(new JButton[]{lastSelected, btn});
lastSelected = null;
}
revalidate();
repaint();
}
}
public class DotsPane extends JPanel {
private PaintPane paintPane;
public DotsPane(final PaintPane pp) {
paintPane = pp;
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource();
paintPane.buttonClicked(btn);
}
};
setLayout(new GridLayout(6, 6));
for (int index = 0; index < 6 * 6; index++) {
JButton btn = new JButton(".");
add(btn);
btn.addActionListener(al);
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
Take a look at How to Use Root Panes for more details
I have placed my JLabel.setText("__") inside a for loop so it can print the length of a word replacing each letter with a 'space' . It is for a hangman game to display the length of the word using blank spaces. However it is only printing once. Any tips on why? Also, if you have any tips on better organizing my code that would be appreciated. Thanks in advance.
/*PACKAGE DECLARATION*/
package Game;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
/************************
* GAME MECHANICS CLASS *
* **********************/
public class GameStructure {
/* INSTANCE DECLARATIONS */
private String []wordList = {"computer","java","activity","alaska","appearance","article",
"automobile","basket","birthday","canada","central","character","chicken","chosen",
"cutting","daily","darkness","diagram","disappear","driving","effort","establish","exact",
"establishment","fifteen","football","foreign","frequently","frighten","function","gradually",
"hurried","identity","importance","impossible","invented","italian","journey","lincoln",
"london","massage","minerals","outer","paint","particles","personal","physical","progress",
"quarter","recognise","replace","rhythm","situation","slightly","steady","stepped",
"strike","successful","sudden","terrible","traffic","unusual","volume","yesterday"};
private int []length = new int [64];
private JTextField tf;//text field instance variable (used)
private JLabel jl2;//label instance variable (used)
private JLabel jl3;//label instance (working on)
private String letter;
/*****************
* LENGTH METHOD *
* ***************/
public void length(){
jl3 = new JLabel();
int j = 0;
for(j = 0; j<64; j++) {
length[j] = wordList[j].length();//gets length of words in wordList
}//end for
int l = 0;
for(int m = 0; m<length[l]; m++) {//supposed to print length of word with '__' as each letter
jl3.setText("__ ");//instead only printing once
l++;
}//end for
}//end length method
/*****************
* WINDOW METHOD *
* ***************/
public void window() {
LoadImageApp i = new LoadImageApp();//calling image class
JFrame gameFrame = new JFrame();//declaration
JPanel jp = new JPanel();
JPanel jp2 = new JPanel();//jpanel for blanks
JLabel jl = new JLabel("Enter a Letter:");//prompt with label
tf = new JTextField(1);//length of text field by character
jl2 = new JLabel("Letters Used: ");
jp2.add(jl3);
jp.add(jl);//add label to panel
jp.add(tf);//add text field to panel
jp.add(jl2);//add letters used
gameFrame.add(i); //adds background image to window
i.add(jp); // adds panel containing label to background image panel
i.add(jp2);
gameFrame.setTitle("Hangman");//title of frame window
gameFrame.setSize(850, 600);//sets size of frame
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//exit when 'x' button pressed
gameFrame.setIconImage(new ImageIcon("Hangman-Game-grey.png").getImage());//set the frame icon to an image loaded from a file
gameFrame.setLocationRelativeTo(null);//window centered
gameFrame.setResizable(false);//user can not resize window
gameFrame.setVisible(true);//display frame
}//end window method
/*********************
* USER INPUT METHOD *
* *******************/
public void userInput() {
tf.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {//when enter key pressed
JTextField tf = (JTextField)e.getSource();
letter = tf.getText();
jl2.setText(jl2.getText() + letter + " ");//sets jlabel text to users entered letter
}//end actionPerformed method
});
}//end userInput method
}//end GameMechanics class
"However it is only printing once. Any tips on why?"
setText will only set the text once. So all you're doing in the loop is setting the text over and over. Here is a suggestion. Concatenate the Strings in the loop, then set the text. Like this:
String line = "";
for(int m = 0; m<length[l]; m++) {
line += "__ ";
l++;
}
jl3.setText(line);
" Also, if you have any tips on better organizing my code that would be appreciated. "
Try Code Review for this.
I'm new in object-oriented programming and I use Java. I'm stil finding it hard to manipulate through the classes using generics and stuff. As a practice, I looked for codes in the internet and my colleague suggested me a program that came from this site.
This is the first class:
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class quine extends JFrame implements ActionListener, WindowListener{
/**
*
*/
private static final long serialVersionUID = 1L;
static ArrayList<Term>[][] table=new ArrayList[5][5]; // SERVES AS OUR STORAGE FOR ARRANGING TERMS AND TO OUR RESULTING TERMS THAT ARE BEING COMPARED.
static Vector<String> inputTerm= new Vector <String>(); // STORES OUR ORIGINAL INPUT/NUMBERS
static Vector<String> resultingTerms= new Vector <String>(); // STORES RESULTING TERMS FOR EACH SET OF COMPARISON
static int var=0; //NUMBER OF VARIABLE
static int numbers=0; //NUMBER OF INPUTS
final static int maxTerms=1000; //MAXIMUM NUMBER OF TERMS WITH SAME NUMBER OF 1'S
static TextField result = new TextField(" ",50);
static TextField text;
static TextField text1;
static quine qWindow;
static String finalT = "";
public static void main(String[] args){
qWindow = new quine("Quine-McCluskey Simulator"); //creates a window
qWindow.setSize(400,250); //sets the size of the window
qWindow.setVisible(true); //makes the window visible
qWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE ); //CLOSES THE WINDOW WHEN CLOSING OR CLICKING THE X BUTTON
JOptionPane.showMessageDialog(null, "Welcome to my Quine-McCluskey Simulator!"); //DISPLAYS MESSAGE
}//end main
public static int count_one(String temp){ //COUNT 1'S FROM EACH TERM
int count=0;
char[] tempArray=temp.toCharArray();
int i=0;
while(i<temp.length()){
if(tempArray[i]=='1'){
count++;
}
i++;
}//end while
return count;
}//end one
public static void getPrimeImplicants(){ // PAIRS TERMS UNTIL NOTHING TO PAIR, END TERMS ARE OUR PRIME IMPLICANTS
table=createTermTable(inputTerm);
printTermTable();
createPairing();
}
public static ArrayList<Term>[][] createTermTable(Vector <String> input){ // CREATE TABLE, ARRANGES TERMS BASED ON THE NUMBER OF 1'S IN
//EACH TERM USING count_one,therefore, row 1 contains terms with 1 1 bit.
Term temp;
int one=0;
int element=0;
ArrayList[][] arrayLists = new ArrayList[var+1][maxTerms+1]; //CREATES AN ARRAY WITH VAR ROWS CORRESPONDING TO POSSIBLE NUMBER OF
// 1 FOR EACH TERM AND 1000 COLUMNS
ArrayList<Term> [][]tempTable = arrayLists;
for(int x=0;x<=var;x++){ //?
for(int y=0;y<=maxTerms;y++){
tempTable[x][y]= new ArrayList<Term>();
}//end y
}//end for x
for(int i=0;i<input.size();i++){
one=count_one(input.get(i)); //COUNT 1'S FROM EACH TERM
temp=initTerm(input.get(i),false); // INITIALIZE PROPERTIES OF THAT TERM
while(!tempTable[one][element].isEmpty()){
element++;
}//end while
tempTable[one][element].add(temp);
element=0;
} //end for
return tempTable;
}//end createTermTable
public static Term initTerm(String n,boolean u){ //INITIALIZE USED and NUM PROPERTY OF THE TERM
Term term=new Term();
term.used=u; // TO INDICATE IF THE TERM IS ALREADY PAIRED
term.num=n; // THE TERM ITSELF
return term;
}//end initTerm
public static void printTermTable(){ // PRINTS THE COMPUTATION/TABLES
System.out.println("\nCOMPUTING:");
for(int i=0;i<var+1;i++){
System.out.print(i);
System.out.println(" --------------------------------------------");
for(int j=0;!table[i][j].isEmpty();j++){ //PRINTS TERM ON EACH ROW WHILE TERM IS NOT EMPTY
System.out.println(table[i][j].get(0).num);
}//end for j
}//end for i
}
public static void createPairing(){ //PAIRS A TERM TO EACH TERM ON THE NEXT ROW
int finalterms=0;
String term_num="";
int found=0;
Vector<String> preResult= new Vector<String>();
for(int x=0;x<=var-1;x++){ // REPEATS PAIRING OF A TERMS OF THE TABLE VAR TIMES TO MAKE SURE WHAT ARE LEFT ARE PRIME IMPLICANTS
preResult=new Vector<String>(); // STORES THE RESULTING TERMS FOR EACH SET OF PAIRING
for(int i=0;i<=var;i++){ //COMPARES A ROW WITH EACH TERMS ON THE NEXT ROW
//Vector <String> rowResult= new Vector<String>(); //STORES RESULTING TERMS ON THAT PARTICULAR TERM OF THE ROW. THIS IS TO AVOID REPETITIONS
for(int j=0;!table[i][j].isEmpty();j++){ // TERM ON THE ROW BEING COMPARED WITH EACH TERM ON NEXT ROW
if(i+1!=var+1) // MAKES SURE THAT THE PROCESS NOT EXCEEDS THE ARRAYBOUND
for(int k=0;!table[i+1][k].isEmpty();k++){ //TERM ON THE NEXT ROW THAT IS BEING COMPARED WITH TERM ON THE CURRENT ROW.
term_num=pair(table[i][j].get(0).num,table[i+1][k].get(0).num); //ASSIGNS RESULT OF PAIRING TO term_num
if(term_num!=null){ // IF PAIRING IS SUCCESSFUL
table[i+1][k].get(0).used=true; // TERM IS PAIRED/USED
/*if(!rowResult.contains(term_num)){ //MAKES SURE THAT TERM IS NOT REPEATE
rowResult.add(term_num);
found=1;
}
*/
if(!preResult.contains(term_num)){ // MAKES SURE THAT TERM IS NOT REPEATED
preResult.add(term_num);
found=1;
finalterms++; // COUNTS THE FINAL/RESULTING TERMS FOR THIS SET OF PAIRING
}//end if !resultingTerms
found=1;
}//end if term_num!=null
}//end for k
if(found==0){ // IF TERM IS NOT SUCCESSFULLY PAIRED/USED, ADD TO THE RESULTING TERMS FOR THIS SET
if(table[i][j].get(0).used!=true){
preResult.add(table[i][j].get(0).num);
}
}
found=0;
}//end for j
}//end for i
table=createTermTable(preResult); // CREATE ANOTHER TABLE FOR NEXT SET. THE NEW TABLE CONTAINS THE RESULTING TERMS OF THIS SET
if(preResult.size()!=0)
resultingTerms=preResult; //IF THE ARE RESULTING TERMS, THEN PRINT AND ASSIGN TO resultingterms. THE END VALUE OF resultingterms WILL BE SIMPLIFIED
printTermTable();
}//end for x
}//end createPairing
public static String pair(String a,String b){
int difference=-1;
char []array1 = new char[a.length()];
char []array2;
for(int i=0;i<var;i++){
array1=a.toCharArray(); //CONVERTS TERMS OF TYPE STRING TO TERMS OF TYPE CHAR
array2=b.toCharArray();
if(array1[i]!=array2[i]){ // IF NOT EQUAL FOR A PARTICULAR CHARACTER FOR THE FIRST TIME, THEN GET THE INDEX CORRESPONDING TO THAT CHARACTER.
if(difference==-1)
difference=i;
else //IF NOT NOT EQUAL FOR THE FIRST TIME, THEN THE TERMS DIFFER IN MORE THAN 1 PLACE
return null;
}//end if
}//end for
if(difference==-1) //THE TERMS ARE INDENTICAL, RETURN NULL, PAIRING UNSUCCESSFUL
return null;
char[] result= a.toCharArray(); //CHARACTER CORRESPONDING TO THE INDEX WHERE TERMS DIFFER ONLY ONCE WILL BE CHANGED TO '-'
result[difference]='-';
String resulTerm= new String(result);
return resulTerm; //RETURNS THE MODIFIED TERM, PAIRING SUCCESSFUL
}//end pair
public static void simplifymore(){ //SIMPLIFY THE RESULTINGTERMS
int primes=resultingTerms.size(); // RESULTING TERMS CORRESPOND TO OUR PRIME IMPLICANTS
int[][] s_table= new int[primes][numbers]; //CREATES A TABLE WITH ROWS EQUAL TO NUMBER OF PRIME IMPLICANTS AND COLUMNS EQUAL TO THE NUMBER OF THE ORIGINAL INPUT
for(int i=0;i<primes;i++){
for(int j=0;j<numbers;j++){
s_table[i][j]=implies(resultingTerms.get(i),inputTerm.get(j));
}//end for j
}//end for i
Vector <String> finalTerms= new Vector<String>(); // STORES THE FINALTERMS
int finished=0;
int index=0;
while(finished==0){ //UNTIL ALL ELEMENTS ARE NOW TURNED TO 0
index=essentialImplicant(s_table);
if(index!=-1)
finalTerms.add(resultingTerms.get(index)); // IF RESULTING TERM IS THE ONLY ONE IMPLYING THE CURRENT ORIGINAL TERM, THEN ADD TO FINAL TERMS
else{ // THOSE THAT HAVE MORE THAN ONE IMPLICATION FOR A PARTICULAR ORIGINAL TERM
index=largestImplicant(s_table);
if(index!=-1)
finalTerms.add(resultingTerms.get(index)); //ADD TO FINAL TERMS IF LARGEST IMPLICANT(ONE WHICH HAS MORE NUMBER OF 1'S. SEE COMMENTS ON largestImplicant.
else
finished=1; //IF INDEX IS -1 THEN ALL ELEMENTS HAVE ALREADY BEEN DELETED OR HAVE MADE VALUE 0
}//end else
}//end while finished
System.out.println("Final Terms :");
for(int x=0;x<finalTerms.size();x++) //PRINTS THE FINAL TERMS IN BINARY FORMAT
System.out.println(finalTerms.get(x));
printSimplified(finalTerms);
}//end simplifymore
public static void printSimplified(Vector <String> finalTerms){
String temp="";
char[] tempArray;
char variables[]= {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'}; //basis for our variables to printed
int index=0;
int i=0;
int j=0;
System.out.print("F = ");
while(i<finalTerms.size()){ //until all final terms are printed in algebraic form.
temp=finalTerms.get(i); //assigns current final term to temp
tempArray=temp.toCharArray(); //CONVERTS TEMP TO ARRAY
while(j<var){
if(tempArray[j]=='-'){ //IGNORES -
index++;
}
else if (tempArray[j]=='0'){
finalT+=variables[26-var+index]+"'"; // PRINTS THE CORRESPONDING LETTER.IF CHARACTER IS 0 THEN APPEND ' AFTER THE VARIABLE
index++;
}
else if (tempArray[j]=='1'){
finalT+=variables[26-var+index]; // PRINTS CORRESPONDING LETTER
index++;
}
else{};
j++;
}//end while
if(i<finalTerms.size()-1)
finalT+=" + "; // APPENDS +
i++;
temp="";
j=0;
index=0;
}//end while
System.out.println(finalT);
}//print simplified
public static int essentialImplicant(int[][] s_table){ // CHECKS EACH RESULTING TERM IMPLYING A PARTICULAR ORIGINAL TERM
for(int i=0;i<s_table[0].length;i++){ //
int lastImplFound=-1;
for(int impl=0;impl<s_table.length;impl++){
if(s_table[impl][i]==1){ //IF RESULTING TERM IMPLIES ORIGINAL TERM
if(lastImplFound==-1){
lastImplFound=impl;
}else{ // IF MORE THAN ONE IMPLICATION,THEN IT IS NOT AN ESSENTIAL PRIME IMPLICANT.GO TO NEXT ORIGINAL TERM
lastImplFound=-1;
break;
}//end else
}
}
if(lastImplFound!=-1){ // ONE IMPLICATION FOR THE ORIGINAL TERM. THIS IS AN ESSENTIAL PRIME IMPLICANT
implicant(s_table,lastImplFound);
return lastImplFound;
}
}//end for impl
return -1;
}
public static void implicant(int [][] s_table,int impA){ // DELETE OR MAKE VALUE 0 THE ROW WHERE THE ESSENTIAL PRIME IMPLICANT IS AND THE COLUMNS OF ALL THE ORIGINAL TERMS IMPLIED BY IT
for(int i=0;i<s_table[0].length;i++){
if(s_table[impA][i]==1)
for(int impB=0;impB<s_table.length;impB++){
s_table[impB][i]=0;
}
}
}//end implicant
public static int largestImplicant(int[][] s_table){
int maxImp=-1;
int max=0;
for(int imp=0;imp<s_table.length;imp++){ // LOCATES WHICH HAS MORE NUMBER OF 1'C IN EACH PRIME
int num=0;
for(int i=0;i<s_table[0].length;i++){
if(s_table[imp][i]==1)
num++;
}//end for i
if(num>max){ // TERM WITH MORE 1'S AT THE END OF THE LOOP WILL BE ADDED TO THE FINAL TERMS
max=num;
maxImp=imp;
}//end if num>max
}//end for imp
if(maxImp!=-1){ // IF WE HAVE SUCCESSFULLY LOCATED A PRIME IMPLICANT
implicant(s_table,maxImp); // DELETE OR MAKE VALUE 0 THE ROW WHERE THE ESSENTIAL PRIME IMPLICANT IS AND THE COLUMNS OF ALL THE ORIGINAL TERMS IMPLIED BY IT
return maxImp;
}//end if maxImp!=-1
return -1;
}
public static int implies(String term1, String term2){ // RETURNS 1 IF RESULTING TERM IMPLIES THE ORIGINAL TERM, 0 OTHERWISE
char[] term1Array=term1.toCharArray();
char[] term2Array=term2.toCharArray();
//EX. ORG TERM IS 100100, RES TERM IS 1--10- ,RESULTING TERM IMPLIES THE ORIGINAL TERM. SINCE - HERE IS TREATED AS 0 OR 1
for(int i=0;i<var;i++){
if(term1Array[i]!=term2Array[i] && term1Array[i]!='-')
return 0;
}
return 1;
}
//end class
public quine(String name){
super(name); //ASSIGNS LABEL OF THE WINDOW
setLayout(new GridLayout(1, 1)); //SETS THE LAYOUT
setLocation(350,200); //SETS THE LOCATION OF THE WINDOW ON THE SCREEN
GridBagLayout gridbag = new GridBagLayout(); //used to align buttons
GridBagConstraints constraints = new GridBagConstraints();//to specify the size and position for the gridbaglayout
setLayout(gridbag);
constraints.weighty = 1; //distributes spaces among columns
constraints.weightx = 1; //distributes spaces among rows
constraints.gridwidth = GridBagConstraints.REMAINDER; //to specify that the component be the last one in its column
Label label1 = new Label(" How many variables does the function have?"); //CREATES A LABEL
label1.setVisible(true); //MAKES THE LABEL VISIBLE, ASSIGNS NEW FONT AND COLOR THEN ADD TO THE WINDOW
label1.setFont(new Font("Sans Serif", Font.BOLD, 12));
label1.setBackground(Color.CYAN);
add(label1);
text1= new TextField("",10);
gridbag.setConstraints(text1,constraints); //applies constraints to text
text1.setEditable(true); //SO THAT WE COULD STILL HAVE AN UNLIMITED LENGTH OF INPUT
text1.setForeground(Color.black);
text1.setBackground(Color.white);
text1.setVisible(true);
text1.addActionListener(this); //ACTIVATES ACTIONLISTENER FOR THIS FIELD
add(text1);
label1 = new Label(" Please list all the minterms that evaluates to 1:");//CREATES LABEL
gridbag.setConstraints(label1,constraints);
label1.setVisible(true); //MAKES THE LABEL VISIBLE, ASSIGNS NEW FONT AND COLOR THEN ADD TO THE WINDOW
label1.setBackground(Color.green);label1.setFont(new Font("Sans Serif", Font.BOLD, 12));
label1.setBackground(Color.CYAN);
add(label1);
text = new TextField("Enter your numbers here separated by a comma",50);
gridbag.setConstraints(text,constraints); //applies constraints to text
text.setEditable(true); //ENABLES UNLIMITED LENGTH OF INPUT
text.setForeground(Color.black);
text.setBackground(Color.white);
text.setVisible(true);
text.addActionListener(this); //ACTIVATES ACTIONLISTENER FOR THIS FIELD
text.setForeground(Color.blue);
add(text);
JButton enter = new JButton ("Enter"); // CREATES BUTTON NAMED Enter
enter.setVisible(true); //MAKES IT VISIBLE, APPLIES THE CONSTRAINTS, AND ADD TO THE WINDOW
add(enter);
enter.setBackground(Color.green);
enter.addActionListener(this); //ACTIVATES ACTIONLISTENER
gridbag.setConstraints(enter,constraints);
JButton reset = new JButton ("Reset"); // CREATES BUTTON NAMED Reset
reset.setVisible(true); //MAKES IT VISIBLE, APPLIES THE CONSTRAINTS, AND ADD TO THE WINDOW
gridbag.setConstraints(reset,constraints);
reset.setBackground(Color.green);
add(reset);
reset.addActionListener(this);
label1 = new Label(" Result:");
gridbag.setConstraints(label1,constraints);
label1.setVisible(true);
label1.setBackground(Color.cyan);
label1.setFont(new Font("Sans Serif", Font.BOLD, 12));
label1.setBackground(Color.CYAN);
add(label1);
result = new TextField(" ",50);
gridbag.setConstraints(result,constraints); //applies constraints to text
result.setEditable(true);
result.setForeground(Color.black);
result.setBackground(Color.white);
result.setVisible(true);
add(result);
}
public void actionPerformed(ActionEvent e) {
String stringInput="";
String numOfVar="";
String temp="";
String temp1="";
int num=0;
if(e.getActionCommand() == "Enter"){ // IF Enter BUTTON IS CLICKED
stringInput = text.getText(); // GETS STRING INPUT FROM TEXT(MINTERMS)
numOfVar = text1.getText(); //GETS STRING INPUT FROM TEXT1(VARIABLES)
var = Integer.parseInt(numOfVar); //CONVERTS numOfVar TO INTEGER
StringTokenizer token= new StringTokenizer(stringInput," ,"); //TOKENIZE INPUT. ELIMINATE ALL COMMAS AND SPACES
while(token.hasMoreTokens()){ //WHILE THERE ARE MORE TOKENS
temp1=token.nextToken(); //GETS TOKEN
numbers++; //COUNTS THE NUMBER OF INPUTS
num=Integer.parseInt(temp1); //CONVERT INPUT TO INTEGER
temp=Integer.toBinaryString(num); //CONVERTS INTEGER FORM OF INPUT TO BINARY IN ITS PROPER LENGTH BASED ON THE NUMBER OF VARIABLES GIVEN
if(temp.length()!=var){
while(temp.length()!=var){
temp="0"+temp;
}
}
inputTerm.add(temp); //ADDS RESULT(BINARY FORM) TO inputTerm
}//end while
getPrimeImplicants(); //GET PRIMEIMPLICANTS
simplifymore(); // SIMPLIFY MORE
result.setText(finalT); // DISPLAYS THE RESULT (SIMPLIFIED) TO RESULT TEXTFIELD
}//end if
if(e.getActionCommand()== "Reset"){ //RESETS THE VALUES FOR NEXT SET OF INPUTS
var=0;
table=new ArrayList[5][5]; // SERVES AS OUR STORAGE FOR ARRANGING TERMS AND TO OUR RESULTING TERMS THAT ARE BEING COMPARED.
inputTerm= new Vector <String>(); // STORES OUR ORIGINAL INPUT/NUMBERS
resultingTerms= new Vector <String>(); //STORES THE RESULTING TERMS FOR EACH COMPUTATION
finalT=""; //STORES THE FINAL TERMS IN THEIR ALGEBRAIC FORM
numbers=0; //COUNTS THE NUMBER OF INPUTS FROM THE USER
text.setText(""); //ERASE THE TEXTS DISPLAYED ON THE TEXT FIELDS
text1.setText("");
result.setText("");
}
}
public void windowActivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {qWindow.setVisible(false);} //CLOSES THE WINDOW AFTER PROGRAMS STOPS RUNNING
public void windowClosing(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
}//end class
And this is the second class. Funny (it only consists of less than 10 lines unlike the first one)
public class Term {
public String num;
public boolean used;
}
Can you please help me incorporate these two classes into one (if that's possible)? I tried declaring String num and boolean used inside the first class and removed the Term but it shows lot of errors. I tried separating the initTerm method into two: one returns a string and the other boolean. But it adds error. What else can I do? Can you also advise me some techniques in doing this?
You can put the whole class inside quine so that Term becomes an inner class of quine. The class Term is then visible to the code in quine and you don't need a separate file anymore for the class Term.
1) Don't declare variables as public unless they are static. It's standard practise to use getter/setter methods to access member variables.
2) Have you tried creating a super class that extends JFrame then get quine to extend that class. Add getter/setters in the super class. Then the sub class can access them via getVariable() etc etc.
3) Class names should start with an upper case letter. Variables, methods and package names should all be lower case.