Ok so I'm building to show students how a loop goes through an array, I have added 2 images to help explain and the code, the first is the result I get after I click go then it freezes . The Second image is what I'd like it to do after you put in the values of 1 in start, 15 in stop, 3 in step and click the Go Button. And then to be cleared on the click of Clear button. I think they probably related. Can anyone see the problem? Thanks in advanced!
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import javax.swing.JOptionPane;
public class Checkerboard extends Frame implements ActionListener
{
int[] blocksTextField = new int[15];
Panel blocksPanel = new Panel();
TextArea blocksDisplay[] = new TextArea[16];
TextField start = new TextField (3);
TextField stop = new TextField (3);
TextField step = new TextField (3);
//Colors
Color Red = new Color(255, 90, 90);
Color Green = new Color(140, 215, 40);
Color white = new Color(255,255,255);
//textField ints
int inputStart;
int inputStop;
int inputStep;
//Lables
Label custStartLabel = new Label ("Start : ");
Label custStopLabel = new Label ("Stop : ");
Label custStepLabel = new Label ("Step : ");
//Buttons
Button goButton = new Button("Go");
Button clearButton = new Button("Clear");
//panel for input textFields and lables
Panel textInputPanel = new Panel();
//Panel for buttons
Panel buttonPanel = new Panel();
public Checkerboard()
{//constructor method
//set the 3 input textFields to 0
inputStart = 0;
inputStop = 0;
inputStep = 0;
//set Layouts for frame and three panels
this.setLayout(new BorderLayout());
//grid layout (row,col,horgap,vertgap)
blocksPanel.setLayout(new GridLayout(4,4,10,10));
textInputPanel.setLayout(new GridLayout(2,3,20,10));
buttonPanel.setLayout(new FlowLayout());
//setEditable()
//setText()
//add components to blocks panel
for (int i = 0; i<16; i++)
{
blocksDisplay[i] = new TextArea(null,3,5,3);
if(i<6)
blocksDisplay[i].setText(" " +i);
else
blocksDisplay[i].setText(" " +i);
blocksDisplay[i].setEditable(false);
// blocksDisplay[i].setBackground(Red);
blocksPanel.add(blocksDisplay[i]);
}//end for
//add componets to panels
//add text fields
textInputPanel.add(start);
textInputPanel.add(stop);
textInputPanel.add(step);
//add lables
textInputPanel.add(custStartLabel);
textInputPanel.add(custStopLabel);
textInputPanel.add(custStepLabel);
//add button to panel
buttonPanel.add(goButton);
buttonPanel.add(clearButton);
//ADD ACTION LISTENRS TO BUTTONS (!IMPORTANT)
goButton.addActionListener(this);
clearButton.addActionListener(this);
add(blocksPanel, BorderLayout.NORTH);
add(textInputPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
//overridding the windowcClosing() method will allow the user to clisk the Close button
addWindowListener(
new WindowAdapter()
{
public void windowCloseing(WindowEvent e)
{
System.exit(0);
}
}
);
}//end of constructor method
public void actionPerformed(ActionEvent e)
{
//if & else if to see what button clicked and pull user input
if(e.getSource() == goButton) //if go clicked ...
{
System.out.println("go clicked");
try{
String inputStart = start.getText();
int varStart = Integer.parseInt(inputStart);
if (varStart<=0 || varStart>=15 )throw new NumberFormatException();
System.out.println("start = " + varStart);
// roomDisplay[available].setBackground(lightRed);
String inputStop = stop.getText();
int varStop = Integer.parseInt(inputStop);
if (varStop<=0 || varStart>=15 )throw new NumberFormatException();
System.out.println("stop = " + varStop);
String inputStep = step.getText();
int varStep = Integer.parseInt(inputStep);
if (varStep<=0 || varStep>=15 )throw new NumberFormatException();
System.out.println("step = " + varStep);
for (int i = varStart; i<varStop; varStep++)//ADD WHILE LOOP
{
blocksDisplay[i].setBackground(Red);
blocksDisplay[i].setText(" " +i);
}
}
catch (NumberFormatException ex)
{
JOptionPane.showMessageDialog(null, "You must enter a Start, Stop and Step value greater than 0 and less than 15",
"Error",JOptionPane.ERROR_MESSAGE);
}
}
else if(e.getSource() == clearButton ) //else if clear clicked ...
{
System.out.println("clear clicked");
}
//int available = room.bookRoom(smoking.getState());
//if (available > 0)//Rooms is available
}//end action performed method
public static void main(String[]args)
{
Checkerboard frame = new Checkerboard ();
frame.setBounds(50, 100, 300, 410);//changed size to make text feilds full charater size
frame.setTitle("Checkerboarder Array");
frame.setVisible(true);
}//end of main method
}
The problem is your loop: your loop variable name is i but you change the varStep variable instead of i so basically the loop variable never changes and thus the exit condition will never be true.
I believe you want to step i with varStep, so change your loop to:
for (int i = varStart; i<varStop; i += varStep)
// stuff inside loop
Take a look at this loop.
for (int i = varStart; i<varStop; varStep++)//ADD WHILE LOOP
{
blocksDisplay[i].setBackground(Red);
blocksDisplay[i].setText(" " +i);
}
It ends when i >= varStop, but neither i nor varStop change as a consequence of its execution, so it can never stop. You only increment varStep.
I think you want to increment i by varStep on each iteration instead, i.e. i += varStep
You use varStep++ in your for loop. I think you meant to do i+varStep.
The application freezes because you're never increasing i, resulting in an endless loop.
Related
public class Memory extends JFrame {
private static final long serialVersionUID = -2065145900871059367L;
private JPanel contentPane;
public static void main(String[] args) { //auto generated from WindowBuilder
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Memory frame = new Memory();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
JButton[] cards = new JButton[12];
int [] flippedNum = new int[12];
Icon [] catImg = new Icon[12];
{
catImg[0]= new ImageIcon(getClass().getResource("2faceszd.jpg"));
catImg[1] = new ImageIcon(getClass().getResource("blkctszd.jpg"));
catImg[2]= new ImageIcon(getClass().getResource("ct&mszd.png"));
catImg[3]= new ImageIcon(getClass().getResource("floofctszd.jpg"));
catImg[4]= new ImageIcon(getClass().getResource("orngctszd.jpg"));
catImg[5]= new ImageIcon(getClass().getResource("siamctszd.jpg"));
catImg[6]= new ImageIcon(getClass().getResource("2faceszd.jpg"));
catImg[7] = new ImageIcon(getClass().getResource("blkctszd.jpg"));
catImg[8]= new ImageIcon(getClass().getResource("ct&mszd.png"));
catImg[9]= new ImageIcon(getClass().getResource("floofctszd.jpg"));
catImg[10]= new ImageIcon(getClass().getResource("orngctszd.jpg"));
catImg[11]= new ImageIcon(getClass().getResource("siamctszd.jpg"));
} //6 images added twice
Icon photo = new ImageIcon(getClass().getResource("BG.png"));
static List<Integer> cats = new ArrayList<Integer>();{
cats.add(1); cats.add(1);
cats.add(2); cats.add(2);
cats.add(3); cats.add(3);
cats.add(4); cats.add(4);
cats.add(5); cats.add(5);
cats.add(6); cats.add(6);
}
static Random kitty = new Random();
public static int getCardAssignment(){
int cat = kitty.nextInt(cats.size());
int ucat = cats.get(cat);
cats.remove(cat);
return ucat;
} returns a random number to be assigned to an icon
//building the frame
public Memory() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 650, 500);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel title = new JPanel();
title.setName("");
title.setFont(new Font("Tahoma", Font.PLAIN, 16));
title.setBackground(Color.PINK);
contentPane.add(title, BorderLayout.NORTH);
JLabel gameName = new JLabel("Memory Game");
title.add(gameName);
gameName.setFont(new Font("Arial Black", Font.PLAIN, 16));
gameName.setBackground(Color.PINK);
gameName.setEnabled(false);
JPanel cardDisplay = new JPanel();
cardDisplay.setBackground(Color.PINK);
cardDisplay.setFont(new Font("Arial Black", Font.PLAIN, 16));
cardDisplay.setBorder(new EmptyBorder(10, 10, 10, 10));
contentPane.add(cardDisplay, BorderLayout.CENTER);
cardDisplay.setLayout(new GridLayout(3, 4, 10, 10));
ButtonClickEventHandler clickIt = new ButtonClickEventHandler();
for(int i = 0; i < cards.length; i ++){
cards[i] = new JButton(); // new button
flippedNum[i] = getCardAssignment(); //card# assigned to cat icon
cards[i].setIcon(photo); //set background image
cards[i].addActionListener(clickIt); //when you click it
cardDisplay.add(cards[i]); //show them all
System.out.println("background displayed");
//sysprint statements are for testing the output stream only
}
}
private class ButtonClickEventHandler implements ActionListener{
private int q = 0; //# of clickes, like switch statement w/o userinput
private int l; // = 0; records number location when clicked
#Override
public void actionPerformed(ActionEvent e) {
for(int i = 0; i < 12; i ++){
if (q == 0){ //at zero all enabled cards/buttons are face up
if(cards[i] == e.getSource()){//first card clicked //start state
System.out.println("q is 0");
System.out.println("Selection was number " + i);
l = i; // record the click for the next state.
//sets the icon to a cat image w/num [flipped num]
cards[i].setEnabled(false);
// prevents user from clicking the same card twice for a match
cards[i].setIcon(catImg[flippedNum[i]])
cards[i].setDisabledIcon(catImg[flippedNum[i]]);
//prevents the icon from being grayed out when clicked
//setting the icon and THEN the disabled icon shows
//non gray'd out image when clicked that cannot be clicked again
q = 1;
System.out.println("q is now 1");
}
}
else if(q == 1) { //if one card is already clicked, second click
System.out.println("q was not 0, now is 1");
if(cards[i] == e.getSource()){
cards[i].setIcon(catImg[flippedNum[i]]);
System.out.println("first was " + flippedNum[l] + " Second was " + flippedNum[i]);
cards[i].setIcon(catImg[flippedNum[i]]);
q = 2;
}
if(q == 2){
System.out.println("Timer started");
cards[l].doClick(1500);
//i tried moving this up to before q=2, no luck
if(flippedNum[l] == flippedNum[i]){
System.out.println("They Match!!");
cards[i].setEnabled(false);
// permanenty sets the button as disabled
cards[l].setEnabled(false);
q=0;
System.out.println("end of turn q is zero, find another match");
}else {
System.out.println("Dont Match");
cards[i].setEnabled(true);
cards[l].setEnabled(true);
cards[i].setIcon(photo);
cards[l].setIcon(photo);
q = 0;
System.out.println("end of turn, back to start, q = 0");
}
}
}
}
}
}
}
The code SHOULD let the user click on one image where it is displayed and disabled so you can't click it a second time and match it to itself. the second click SHOULD reveal the second card (it doesn't) and start the timer (it does)
with in the q=2 section, the match check is still preformed on the image the user can't see and the timer still flips the first card back over after 1500mills. and if there is a match both cards should stay image side up (it does) and grayed out (it doesn't unless i remove the cards[i].setEnabled, even the previously unseen card turns gray when the .setEnabled is off in the q=0 statement)
I've had teachers, tutors, and friends look over this without any progress, PLEASE help. ty.
SAMPLE OUTPUT:
background displayed
// this is printed 12 times
//once for each card
Selection was number 1 // selected the 4th card in the first row
q is now 1
q was not 0, now is 1
q was not 0, now is 1
q was not 0, now is 1
q was not 0, now is 1
q was not 0, now is 1
q was not 0, now is 1
q was not 0, now is 1
q was not 0, now is 1
q was not 0, now is 1
q was not 0, now is 1
q was not 0, now is 1
q was not 0, now is 1
//selected the second card in the first row which did not "Show"
q was not 0, now is 1
q was not 0, now is 1
first was 6 Second was 1
Timer started
Don't Match// first card flipped back to background after 1.5 seconds
end of turn, back to start, q = 0
q is 0
Selection was number 2 // selected 3rd card in first row
q is now 1
q was not 0, now is 1
q was not 0, now is 1
q was not 0, now is 1
q was not 0, now is 1
q was not 0, now is 1
q was not 0, now is 1
q was not 0, now is 1
q was not 0, now is 1
q was not 0, now is 1
q was not 0, now is 1
q was not 0, now is 1
first was 6 Second was 6 // second image selected, didn't show
Timer started
They Match!! // both images are revealed! neither is gray'd out
end of turn q is zero, find another match
Basically, based on your code doClick(long) will make the button appear pressed, it will not delay the code and will cause actionPerformed to be called again ... when you really don't want it to be.
The solution you seem to be looking for is a Swing Timer, see How to use Swing Timers for more details
I butchered your code a little to get "something" working, it will at least display the second card 1.5 seconds.
private class ButtonClickEventHandler implements ActionListener {
private int q = 0; //# of clickes, like switch statement w/o userinput
private int l; // = 0; records number location when clicked
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < 12; i++) {
if (q == 0) { //at zero all enabled cards/buttons are face up
if (cards[i] == e.getSource()) {//first card clicked //start state
System.out.println("q is 0");
System.out.println("Selection was number " + i);
l = i; // record the click for the next state.
//sets the icon to a cat image w/num [flipped num]
cards[i].setEnabled(false);
// prevents user from clicking the same card twice for a match
cards[i].setIcon(catImg[flippedNum[i]]);
cards[i].setDisabledIcon(catImg[flippedNum[i]]);
//prevents the icon from being grayed out when clicked
//setting the icon and THEN the disabled icon shows
//non gray'd out image when clicked that cannot be clicked again
q = 1;
System.out.println("q is now 1");
break;
}
} else if (q == 1) { //if one card is already clicked, second click
System.out.println("q was not 0, now is 1");
if (cards[i] == e.getSource()) {
cards[i].setIcon(catImg[flippedNum[i]]);
System.out.println("first was " + flippedNum[l] + " Second was " + flippedNum[i]);
flipFlop(l, i);
q = 0;
break;
}
}
}
}
protected void flipFlop(int l, int i) {
Timer timer = new Timer(1500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Timer started");
//cards[l].doClick(1500);
//i tried moving this up to before q=2, no luck
if (flippedNum[l] == flippedNum[i]) {
System.out.println("They Match!!");
cards[i].setEnabled(false);
// permanenty sets the button as disabled
cards[l].setEnabled(false);
System.out.println("end of turn q is zero, find another match");
} else {
System.out.println("Dont Match");
cards[i].setEnabled(true);
cards[l].setEnabled(true);
cards[i].setIcon(photo);
cards[l].setIcon(photo);
System.out.println("end of turn, back to start, q = 0");
}
}
});
timer.setRepeats(false);
timer.start();
}
}
You actionPerformed method could use a little more optimising, once you have established some action, you should break out of the loop, as no further processing should be done, let's face it, once you know which button was clicked and if it was the first or second button, why should you keep iterating?
I am working on a GUI (that this community has been extremely helpful with so far) and I have reached another important step I need to achieve.
Currently my GUI consists of a JOptionsPane. Inside this pane is a panel that contains two lists and four buttons. Two of the buttons are arrows who's text is ">" and "<". (The buttons are in between both lists.)
Those buttons work correctly. A user can select one of the objects from the first list and then click the > and it will move to the second list and visa versa.
Next I need to add a feature where there is a ">>" button. This will move all the items in the first list to the second. I really have no idea how to handle this part. I am assuming it is some type of while loop although I'm not entirely sure.
First allow me to post the simple snipplet that shows the > button.
buttonin = new JButton(" > ");
buttonin.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
int[] fromindex = outputDetails.getSelectedIndices();
Object[] from = outputDetails.getSelectedValues();
for(int i=0; i< from.length; i++){
output.addElement(from[i]);
System.out.println(output);
}
for(int i = (fromindex.length-1); i>=0; i--){
input.remove(fromindex[i]);
}
}
});
Next I will post the full code in case that is needed to understand what I am trying to achieve. I hope this is enough information for someone to assist me if not I apologize, the actual program is very long and I couldn't think of an easy way to isolate this test case.
public static void displayGUI(){
int result = JOptionPane.showOptionDialog(null, getPanel(),"JOptionPane Example : ", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, new String[]{"Confirm","Create Return"}, "default");
if(result == 1){
initialScreenDecisions="NONE";
MainWriter.finishedCounter=true;
System.out.println(MainWriter.finishedCounter);
while(MainWriter.entryDetails.size()>0){
MainWriter.entryDetails.remove(0);
}
while(output.size()>0){
output.remove(0);
}
}
}
private static JPanel getPanel(){
JPanel panel = new JPanel();
JPanel panelTop = new JPanel();
JPanel topButtons = new JPanel();
JPanel bottomButtons = new JPanel();
String text = "<html>"
+"Batch <font size=6 color=>"+MainWriter.batchHeaderCounter+"</font> of <font size=6>"+BatchCounter.BatchTotal+"</font>"
+"<br>Batch Header: <font size=5><font color=red>"+MainWriter.BatchHeader+"</font>"
+"</html>";
JLabel topLabel = new JLabel(text);
panelTop.add(topLabel);
input = new DefaultListModel();
output = new DefaultListModel();
String[] shoppingItems = new String[MainWriter.entryDetails.size()];
shoppingItems = MainWriter.entryDetails.toArray(shoppingItems);
for(int i = 0; i < shoppingItems.length; i++){
input.addElement(shoppingItems[i]);
}
outputDetails = new JList(input);
outputDetails.setVisibleRowCount(10);
outputDetails.setFixedCellHeight(20);
outputDetails.setFixedCellWidth(400);
outputDetails.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
JScrollPane list1 = new JScrollPane(outputDetails);
inputDetails = new JList(output);
inputDetails.setVisibleRowCount(10);
inputDetails.setFixedCellHeight(20);
inputDetails.setFixedCellWidth(400);
inputDetails.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
JScrollPane list2 = new JScrollPane(inputDetails);
JPanel buttonPanel = new JPanel();
buttonin = new JButton(" > ");
buttonin.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
int[] fromindex = outputDetails.getSelectedIndices();
Object[] from = outputDetails.getSelectedValues();
for(int i=0; i< from.length; i++){
output.addElement(from[i]);
System.out.println(output);
}
for(int i = (fromindex.length-1); i>=0; i--){
input.remove(fromindex[i]);
}
}
});
buttonPanel.add(buttonin);
buttonout = new JButton(" < ");
buttonout.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
Object[] to = inputDetails.getSelectedValues();
int[] toindex = inputDetails.getSelectedIndices();
for(int i = 0; i < to.length; i++){
input.addElement(to[i]);
}
for(int i = (toindex.length-1); i >=0; i--){
output.remove(toindex[i]);
}
}
});
buttonall = new JButton(" >> ");
buttonall.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
if(initialScreenDecisions.equals("DEFAULT")){
JOptionPane.showMessageDialog(null, "You have selected to add all entry details. Please " +
"\nclick okay on the next scren to confirm or click " +
"\n'>>' again to cancel the apply all option.");
initialScreenDecisions="ADDALL";
}else if(initialScreenDecisions.equals("ADDALL")){
JOptionPane.showMessageDialog(null, "You have canceled the apply all option.");
initialScreenDecisions="DEFAULT";
}else{
JOptionPane.showMessageDialog(null, "You must disable the '<<' option before you can use this.");
}
}
});
buttonnone = new JButton(" << ");
buttonnone.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
if(initialScreenDecisions.equals("DEFAULT")){
JOptionPane.showMessageDialog(null, "You have selected to skip the current batch and" +
"\nomit all of it's entries. Click okay on the next" +
"\nscreen to confirm or click '<<' again to" +
"\ncancel the option.");
initialScreenDecisions="NONE";
}else if(initialScreenDecisions.equals("NONE")){
JOptionPane.showMessageDialog(null, "You have canceled the omit all option.");
initialScreenDecisions="DEFAULT";
}else{
JOptionPane.showMessageDialog(null, "You must disable the '>>' option before you can use this.");
}
}
});
buttonhelp = new JButton("HELP");
buttonhelp.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(null, "This screen allows you to determine the entry details from" +
"\nthe current batch that will be included in the final return." +
"\nSelect the details you wish to include and click the > arrow to" +
"\nmove them to the right side. Pressing the >> button will" +
"\ninclude all entry details for the current batch in the final" +
"\nreturn. Clicking the < button will move a detail back."+
"\nClick << to omit the entire batch. Use confirm to continue"+
"\nto the next step or 'create return' to finish the Nacha return"+
"\nwith all past additions.");
}
});
buttonPanel.setLayout(new BorderLayout());
topButtons.add(buttonin);
topButtons.add(buttonall);
topButtons.add(buttonnone);
topButtons.add(buttonout);
bottomButtons.add(buttonhelp);
buttonPanel.add(topButtons,BorderLayout.NORTH);
buttonPanel.add(buttonhelp,BorderLayout.SOUTH);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));
bottomPanel.add(Box.createRigidArea(new Dimension(10,0)));
bottomPanel.add(list1);
bottomPanel.add(Box.createRigidArea(new Dimension(5,0)));
bottomPanel.add(buttonPanel);
bottomPanel.add(Box.createRigidArea(new Dimension(5,0)));
bottomPanel.add(list2);
bottomPanel.add(Box.createRigidArea(new Dimension(10,0)));
panel.setLayout(new BorderLayout());
panel.add(panelTop,BorderLayout.NORTH);
panel.add(bottomPanel,BorderLayout.CENTER);
panel.setOpaque(true);
return panel;
}
You can ignore the above >> button contents. Right now it will allow the user to select all of the items in the list it just doesn't visually show the selection. If I get the >> button to move all the items at once then I won't need the extra steps you can see I have implemented.
I'm not too sure what all your variable types are, but I think this should work in your ActionListener for >>.
for (int i = 0; i < input.getSize(); i++) {
output.addElement(input.get(i));
}
input.clear();
I want to add scroll bar to my text area so that if the user inputs a number greater than 20 the text are should have a scroll bar.
Basically I am trying to make a application where user inputs a number he wants the multiplication table and also he inputs up to what number he wants the table to be displayed.But my application show table up to 20 e.g 12 X 20 = 240. and the rest is hidden.
public class LayoutM extends JFrame implements ActionListener {
private JTextField num1;
private JTextField num2;
private JTextArea answer;
private JButton go;
private int num11;
private int num22;
public LayoutM(){
super("Multiplication");
setLayout(new FlowLayout());
Dimension numDim = new Dimension(60,20);
Dimension ansDim = new Dimension(200,300);
Dimension goDim = new Dimension(60,20);
num1 = new JTextField("Number");
num1.setPreferredSize(numDim);
num2 = new JTextField("Upto");
num2.setPreferredSize(numDim);
go = new JButton("GO");
num2.setPreferredSize(goDim);
answer = new JTextArea(20,20);
answer.setPreferredSize(ansDim);
answer.setEditable(false);
add(num1, BorderLayout.CENTER);
add(num2,BorderLayout.CENTER);
add(go,BorderLayout.CENTER);
add(answer,BorderLayout.SOUTH);
go.addActionListener(this);
}
public static void main(String[] args){
LayoutM ob = new LayoutM();
ob.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ob.setVisible(true);
ob.setSize(300,400);
ob.setResizable(false);
ob.setLocationRelativeTo(null);
}
public void actionPerformed(ActionEvent event){
try{
answer.setText(" ");
num11 = Integer.parseInt(num1.getText());
num22 = Integer.parseInt(num2.getText());
for(int count = 1; count < num22+1;count++){
answer.append(num11+ " X "+ count+" = " + num11*count+" \n");
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, "No decimals allowed");
}
}
}
You should put the answer object into a new JScrollPane object, and add the scroll pane to your LayoutM.
So, in your fields you should add:
private JScrollPane scroll;
Instead of using
add(answer,BorderLayout.SOUTH);
You should use
add(scroll,BorderLayout.SOUTH);
And in your actionPerformed() method, you should change the number of rows according to the number you got from the user. Put this before the for loop:
if ( num22 > 20 ) {
answer.setRows(num22);
} else {
answer.setRows(20);
}
I can't figure out why whenever I cycle through my array using the for-loop it only produces one element (the first) to console? I'm pretty sure it's a rookie-mistake I'm looking over, so any tips and suggestions would help.
I'm making a program for fun that compares two strings typed in a text field and if they don't exist in the array it produces a JOPtionPane message on the contrary. It's for a battle-hack I may produce in the future for vBulletin forum, but I'm messing around with algorithms before I move to that step. Thanks, guys!
package battleoptionspart1;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.lang.*;
import javax.swing.border.*;
public class BattleOptionsPart1 extends JFrame{
JButton newthread, previewpost;
JRadioButton battle1;
JTextField postcount, oppA, oppB;
JLabel battle2, max;
JPanel panel;
String [] array = {"Bill","Tom","Wendy", "Paula"};
public BattleOptionsPart1 () {
panel = new JPanel();
Toolkit tool = Toolkit.getDefaultToolkit();
Dimension dim = tool.getScreenSize();
this.setSize(500, 500);
this.setTitle("Battle Options");
GridLayout grid = new GridLayout(0,1,2,2);
this.setLayout(grid);
newthread = new JButton("Post New Thread");
previewpost = new JButton("Preview Post");
postcount = new JTextField("", 4);
oppA = new JTextField("",10);
oppB = new JTextField("",10);
battle1 = new JRadioButton();
battle2 = new JLabel("Would you like to start a recorded battle?");
max = new JLabel("Enter max post count user must have to vote");
ListenForButton listen = new ListenForButton();
newthread.addActionListener(listen);
previewpost.addActionListener(listen);
JPanel opponents = new JPanel();
Border oppBorder = BorderFactory.createTitledBorder("Battlers");
opponents.setBorder(oppBorder);
opponents.add(oppA);
opponents.add(oppB);
JPanel battle = new JPanel();
Border battleBorder = BorderFactory.createTitledBorder("Start Battle");
battle.setBorder(battleBorder);
battle.add(battle1);
battle.add(battle2);
JPanel buttons = new JPanel();
Border buttonBorder = BorderFactory.createTitledBorder("Create Thread");
buttons.setBorder(buttonBorder);
buttons.add(newthread);
buttons.add(previewpost);
JPanel restriction = new JPanel();
Border resBorder = BorderFactory.createTitledBorder("Restrictions");
restriction.setBorder(buttonBorder);
restriction.add(postcount);
restriction.add(max);
this.add(opponents);
this.add(battle);
this.add(restriction);
this.add(buttons);
this.add(panel);
int xPos = (dim.width / 2) - (this.getWidth() / 2);
int yPos = (dim.height / 2) - (this.getHeight() / 2);
this.setLocation(xPos,yPos); //places form in the middle
this.setVisible(true); // users can see form
this.setResizable(false); //users can't resize the form
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class ListenForButton implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String compareA = oppA.getText();
String compareB = oppB.getText();
if (e.getSource() == newthread)
{
System.out.println(compareA + "\n" + compareB);
for(int j = 0; j < array.length; j++)
{
System.out.println(array[j]);
if(!compareA.equals(array[j]))
{
JOptionPane.showMessageDialog(null, compareA + " doesn't exist!", "Error Message", JOptionPane.ERROR_MESSAGE);
oppA.requestFocus();
break;
}
if (!compareB.equals(array[j]))
{
JOptionPane.showMessageDialog(null, compareB + " doesn't exist!", "Error Message", JOptionPane.ERROR_MESSAGE);
oppB.requestFocus();
break;
}
else
{
JOptionPane.showMessageDialog(null, "New thread created successfully!", "Success", JOptionPane.INFORMATION_MESSAGE);
break;
}
}
}
else if (e.getSource() == previewpost)
{
System.exit(0);
}
}
}
public static void main(String[] args) {
BattleOptionsPart1 battle = new BattleOptionsPart1();
}
}
In each of the possible options in your loop, you use break, which leaves the loop immediately. If you remove those statements, you'll process each object in the array.
If you want to check if there's a match, you need to go through every element and do your processing after going through the whole array. Here is an example for an array of type int:
boolean contains = false;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == searchKey)
{
contains = true;
break;
}
}
You're breaking out of the loop. with the break; command after the first array element
I've made a simple calculator
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener
{
GridLayout layout = new GridLayout(5, 1);
JLabel l1 = new JLabel("Number 1:");
JLabel l2 = new JLabel("Number 2:");
JLabel l3 = new JLabel("Answer:");
JTextField t1 = new JTextField(30);
JTextField t2 = new JTextField(30);
JTextField t3 = new JTextField(30);
JButton add = new JButton("+");
JButton sub = new JButton("-");
JButton mul = new JButton("*");
JButton div= new JButton("/");
Float ans;
public Calculator()
{
super("Calculator");
setSize(250, 200);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(add);
add(sub);
add(mul);
add(div);
setLayout(layout);
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String n1 = t1.getText();
String n2 = t2.getText();
Float num1 = Float.parseFloat(n1);
Float num2 = Float.parseFloat(n2);
Object clicked = e.getSource();
if(add == clicked)
{
t3.setText(String.valueOf(num1+num2));
}
else if(sub == clicked)
{
t3.setText(String.valueOf(num1-num2));
}
else if(mul == clicked)
{
t3.setText(String.valueOf(num1*num2));
}
else
{
if(num2 == 0)
t3.setText("Can't Divide By Zero");
else
t3.setText(String.valueOf(num1/num2));
}
}
}
And a class to read it
public class UseMyFrame
{
public static void main(String[] args)
{
Calculator calc = new Calculator();
calc.setVisible(true);
}
}
My problem is I want to add another feature and put 9 buttons 1-9 that when pressed will place their respective numbers on the textfield, but I don't know how to set them to appear at the textfield, I first wanna do set.text but i realized how will the button know where to put its number because if I do set.text i need to either put it on textfield1 or textfield 2. I wanna make the number appear in textfield1 first then on textfield2 if there is already a number on textfield1
but I don't know how to set them to appear at the textfield
The Action you add to your JButton should extend TextAction. The TextAction has access to the last focused text component (so you don't have to keep track of this information yourself). Your code would be something like:
public class AddDigitAction extends TextAction
{
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
String digit = button.getActionCommand();
JTextComponent target = getTextComponent(e);
target.replaceSelection(digit);
}
You can use the same Action for all your buttons. The replaceSelection() method is an easy way to add text to the textfield. It will insert text at the last location of the caret in the text field.
So you need to create a boolean variable that will help you keep track of which field to put the number in. Then in the action of the button you can use that to decide.
if(first){
textField1.setText("1");
first = false;
}else{
textField2.setText("1");
first = true;
}
Now, this snippet is very simple and does not consider all the possibilities. It simply toggles between the two fields. You can extend it to what you need.
If you only want to have single digits:
if(t1.getText().length() == 0)
t1.setText(...);
else
t2.setText(...);
Better: Find out which textfield has the current focus (see javadocs) and put the digit at the end of that text:
tFocused.setText(tFocused.getText() + digit)
first set global int curs = 0 and global string screen
then at each numeric button put that code (all about concatenation of strings )
if(curs==0){
screen="1"; // change the number for each button
jTextField1.setText(screen);
a=Double.parseDouble(screen);
curs++;
}else{
screen=screen+"1"; // // change the number for each button
jTextField1.setText(screen);
a=Double.parseDouble(screen);
curs++;
}