Java Scroll bar - java

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

Related

Custom java calculator troubleshooting

New programmer here, I have been working for a few days on this bit of code that is meant to create a UI where I input a basement's perimeter length (textfield integer), if a new pump is needed (combobox string), if there is an outlet nearby (combobox string), and how many hours It will take to prepare a site (textfield integer), and I calculate my costs to complete a job. I was able to set up a UI where I can enter the inputs and press a button to calculate but I'm having trouble connecting the button I made to the formula I made to generate a price. Here is my code:
package packagepackage;
import packagepackage.HintTextFieldUI;
import java.awt.*;
import java.awt.BorderLayout;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CP_GUI implements ActionListener {
String[] sumpo = {"New sump pump","Existing sump pump"};
String[] electo = {"There is an outlet within 6 feet of sump pump","There is no outlet nearby, or I do not need a new one"};
Integer estimatex = 0;
String esto = String.valueOf(estimatex);
public volatile String estimatoof = "Estimated Cost: ${}".format(esto);
private JComboBox sump = new JComboBox(sumpo);
private JComboBox elec = new JComboBox(electo);
private JTextField linear = new JTextField();
private JTextField prep = new JTextField();
private JLabel title = new JLabel("Drain Tile Calculator");
private JButton calculate = new JButton("Calculate!");
public JLabel estimate = new JLabel(estimatoof);
private JFrame frame = new JFrame();
private JPanel panel = new JPanel();
public CP_GUI() {
linear.addActionListener(this);
calculate.addActionListener(this);
elec.addActionListener(this);
sump.addActionListener(this);
prep.addActionListener(this);
// the panel with the button and text
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(400, 400, 100, 100));
panel.setLayout(new GridLayout(0, 1));
panel.add(linear);
panel.add(sump);
panel.add(elec);
panel.add(prep);
frame.add(panel, BorderLayout.CENTER);
panel.add(title);
calculate.addActionListener(this);
panel.add(calculate);
// set up the frame and display it
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Drain Tile Calculator");
frame.pack();
frame.setVisible(true);
linear.setUI(new HintTextFieldUI("Perimeter length", true));
prep.setUI(new HintTextFieldUI("Hours of preptime", true));}
// create one Frame
public static void main(String[] args) {
new CP_GUI();
}
#Override
public void actionPerformed(ActionEvent e){
// TODO Auto-generated method stub
if(e.getSource()==linear) {String input = linear.getText();
Integer pars = Integer.parseInt(input);
Integer distVar = pars *= 13;
estimatex += distVar;
} else if (e.getSource()==sump) {String inputa = sump.getToolTipText();
int sumpa = 0;
if(inputa == "New sump pump" | inputa == "yes") {
sumpa += 260;}
estimatex += sumpa;
} else if (e.getSource()==elec) {String inputb =elec.getToolTipText();
int eleca = 0;
if("There is an outlet within 6 feet of the sump pump".equals(inputb)) {
eleca += 1;
}
eleca *= 280;
estimatex += eleca;
}
else if (e.getSource()==prep) {String inputc = prep.getText();
int parsa = Integer.parseInt(inputc);
int prepCost = parsa += 1;
prepCost *= 110;
estimatex += prepCost;
} else if (e.getSource()==linear) {
String disto = linear.getText();
int di = Integer.parseInt(disto);
di *= 13;
String pumpo = (String)sump.getSelectedItem();
int sumpo = 0;
if ("New sump pump".equals(pumpo)) {
sumpo += 260;
}
String ele = (String)elec.getSelectedItem();
int elc = Integer.parseInt(ele);
elc *= 280;
String clea = prep.getText();
int cla = Integer.parseInt(clea);
cla += 1;
cla *= 110;
int cali = 0;
cali += di;
cali += sumpo;
cali += elc;
cali += cla;
estimatex = cali;
}
}
}
Edit: Made the suggested edits made so far and now the UI opens and works, the only issue is that the estimated price does not show up. Am I connecting the action listener correctly?
Your "primary" problem is right here...
String disto = String.valueOf(linear);
where linear is a JTextField, so the above call will generate something like...
javax.swing.JTextField[,0,0,0x0,invalid,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=com.apple.laf.AquaTextFieldBorder#4e323305,flags=288,maximumSize=,minimumSize=,preferredSize=,caretColor=javax.swing.plaf.ColorUIResource[r=0,g=0,b=0],disabledTextColor=javax.swing.plaf.ColorUIResource[r=128,g=128,b=128],editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=com.apple.laf.AquaImageFactory$SystemColorProxy[r=0,g=0,b=0],selectionColor=com.apple.laf.AquaImageFactory$SystemColorProxy[r=165,g=205,b=255],columns=0,columnWidth=0,command=,horizontalAlignment=LEADING]
which is obviously not what you're looking for.
You should probably be just doing something like...
String disto = linear.getText();
pumpo == "New sump pump" is also not how you compare a String in Java, you should be using "New sump pump".equals(pumpo) ... but I suspect you're going to have the same issues as mentioned above.
I really recommend you take the time to read through Creating a GUI With Swing as well as taking the time to come to grips with the core basics of the language

How to fill JComboBox after user fills necessary text fields?

I want to add a JComboBox to my main panel and fill it with an ArrayList I made in a different method named rectSizeList (which right now prints the ArrayList to the console), this method gets its parameters from another static method named actionPerformed. I cant figure a way to take the filled array after user input to fill my ComboBox. Any help will be appreciated.
All comment is this format are to aid question:
/*
* Like so
*
*/
All other comments are to help whomever my want to compile and run, so that they might understand what is going on.
Main class
import javax.swing.*;
public class ductulatorApp
{
public static void main(String[] args)
{
JFrame frame = new DuctulatorFrame();
frame.setVisible(true);
}
}
Frame class
import javax.swing.*;
import java.awt.*;
public class DuctulatorFrame extends JFrame
{
private static final long serialVersionUID = 1L;
public DuctulatorFrame()
{
setTitle("Test Scores");
setSize(267, 200);
centerWindow(this);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new DuctulatorPanel();
this.add(panel);
}
private void centerWindow(Window w)
{
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
setLocation((d.width-w.getWidth())/2, (d.height-w.getHeight())/2);
}
}
Panel class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.ArrayList;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class DuctulatorPanel extends JPanel implements ActionListener
{
private static final long serialVersionUID = 1L;
private JTextField staticTextField,
cfmTextField,
rductTextField,
sqductTextField;
private JLabel staticLabel,
cfmLabel,
rductLabel,
sqductLabel;
private JButton calculateButton,
exitButton,
clearButton;
private JComboBox ductSizes; //JComboBox instance
private String[] ductList; //Array to fill JComboBox
double staticP; //static pressure entered by user
double cfm; //cfm entered by user
double deSQ;
double de; //round duct diameter
double pi = 3.14;
double ca; //round duct surface area
double radious;
double sqrA; //rectangular duct area
//two sides of rectangular duct
double a = 4;
double b = 4;
String squareduct;
public DuctulatorPanel()
{
// Creates main panel for labels and text fields
JPanel displayPanel = new JPanel();
displayPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
staticLabel = new JLabel("Static pressure:");
displayPanel.add(staticLabel);
staticTextField = new JTextField(10);
displayPanel.add(staticTextField);
cfmLabel = new JLabel(" CFM:");
displayPanel.add(cfmLabel);
cfmTextField = new JTextField(10);
displayPanel.add(cfmTextField);
rductLabel = new JLabel("Round Duct:");
displayPanel.add(rductLabel);
rductTextField = new JTextField(15);
rductTextField.setEditable(false);
rductTextField.setFocusable(false);
displayPanel.add(rductTextField);
sqductLabel = new JLabel("Square Duct:");
displayPanel.add(sqductLabel);
/*
* This is where I want to add my JComboBox problem is I want to populate ductList arr
* with the array inside rectSizeList(int number) BELOW
* right now this method only prints my array to the console
* this method takes its parameters from the value assigned to
* actionperformed(ActionEvent e)
* below is comboBox commented out
*/
//ductList = new String[list.size]; THIS IS ASSUMING I COULD SOME HOW TRANSFER
//ductList = list.toArray(ductList); ARRAYLIST UP HERE AND NAME IT LIST AND USE IT
//ductSizes = new JComboBox(ductList);
//ductSizes.setSelectedIndex(1);
//displayPanel.add(ductSizes);
sqductTextField = new JTextField(10);
sqductTextField.setEditable(false);
sqductTextField.setFocusable(false);
displayPanel.add(sqductTextField);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
calculateButton = new JButton("Calculate");
calculateButton.addActionListener(this);
buttonPanel.add(calculateButton);
clearButton = new JButton("Clear");
clearButton.addActionListener(this);
buttonPanel.add(clearButton);
exitButton = new JButton("Exit");
exitButton.addActionListener(this);
buttonPanel.add(exitButton);
this.setLayout(new BorderLayout());
this.add(displayPanel, BorderLayout.CENTER);
this.add(buttonPanel, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e)
{
NumberFormat number = NumberFormat.getNumberInstance();
number.setMaximumFractionDigits(1);
Object source = e.getSource();
if(source == exitButton)System.exit(0);
else if(source == clearButton)
{
staticTextField.setText("");
cfmTextField.setText("");
rductTextField.setText("");
sqductTextField.setText("");
staticP = 0;
cfm = 0;
deSQ = 0;
}
else if(source == calculateButton)
{
try
{
staticP = Double.parseDouble(staticTextField.getText());
cfm = Double.parseDouble(cfmTextField.getText());
}
catch(NumberFormatException nfe)
{
staticTextField.setText("Invalid input");
staticP = 0;
cfm = 0;
deSQ = 0;
de = 0;
}
deSQ = staticP * (0.109136 * Math.pow(cfm, 1.9)); //Calculate round duct
de = Math.pow(deSQ, 0.199) * 2.5; //diameter
// Calculate round duct surface area
radious = de/2;
ca = (radious * radious) * pi;
ca = (int)ca;
rectSizeList((int)ca);
double i = 0;
for(i=0; i<ca; i++)
{
a = a + 0.5;
b = b + 0.5;
i = a * b; // convert round duct to rectangular duct
}
sqrA = i;
a = (int)a;
b = (int)b;
rductTextField.setText(number.format(de));
squareduct = (a + " x " + b);
sqductTextField.setText(squareduct);
}
}
public ArrayList<String> rectSizeList(int number)
{
if (number <= 0) throw new IllegalArgumentException("The number should be greater than 0.");
int i = 0;
int j = 0;
/*
* This is the array list I am hoping to use in order to fill array for
* comboBox
*/
ArrayList<String> rectangularDucts = new ArrayList<String>(); //Create array for rectangular duct
// Fill array for rectangular duct using nested for loop
/*
* If statement will ensure the result is with in range of surface
* area of duct
*/
for(i=4; i<=50; i++)
{
for(j=4; j<=50; j++)
{
if(number == i*j || (i*j)+1 == number || (i*j)-2 == number)
{
rectangularDucts.add(i + " x " + j);
}
}
if(number == i*j || (i*j)+1 == number || (i*j)-2 == number)
{
rectangularDucts.add(i + " x " + j);
}
}
System.out.println(rectangularDucts);
return rectangularDucts;
}
}
I think that your problem is easily solved with just a DefaultComboBoxModel object, or in your situation (I guess), a DefaultComboBoxModel<String> object. Give your class this field, create your JComboBox with this as its model, by passing it into the constructor, and then fill this model object as the need arises.
For example:
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class ComboModelEg extends JPanel {
private DefaultComboBoxModel<String> comboModel = new DefaultComboBoxModel<>();
private JComboBox<String> comboBox = new JComboBox<>(comboModel);
private JTextField textField = new JTextField(5);
public ComboModelEg() {
// so combo box is wide enough
comboBox.setPrototypeDisplayValue(" ");
add(comboBox);
add(textField);
add(new JButton(new AddToComboAction("Add Text", KeyEvent.VK_A)));
}
// AbstractAction is like a *super* ActionListener
private class AddToComboAction extends AbstractAction {
public AddToComboAction(String name, int mnemonic) {
super(name); // button's text
putValue(MNEMONIC_KEY, mnemonic); // button's mnemonic key
}
#Override
public void actionPerformed(ActionEvent e) {
String text = textField.getText(); //get text from text field
comboModel.addElement(text); // and put it into combo box's model
}
}
private static void createAndShowGui() {
ComboModelEg mainPanel = new ComboModelEg();
JFrame frame = new JFrame("ComboModelEg");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Translated to your code, it could look something like:
for (i = 4; i <= 50; i++) {
for (j = 4; j <= 50; j++) {
if (number == i * j || (i * j) + 1 == number
|| (i * j) - 2 == number) {
// rectangularDucts.add(i + " x " + j); //!!
comboModel.addElement(i + " x " + j); //!!
}
}
if (number == i * j || (i * j) + 1 == number || (i * j) - 2 == number) {
// rectangularDucts.add(i + " x " + j);
comboModel.addElement(i + " x " + j); //!!
}
}
this is how i do it
ArrayList<String> myList = new ArrayList<>();
//some code to populate the list
jComboBox.removeAllItems();
for(int i=0;i<myList.size();i++){
jComboBox.addItem(myList.get(i));
}

Program freezing(not responding) after button click no a Java app

Ok so I'm building to show students how a loop goes through an array, I have added 2 images to help explain and the code, the first is the result I get after I click go then it freezes . The Second image is what I'd like it to do after you put in the values of 1 in start, 15 in stop, 3 in step and click the Go Button. And then to be cleared on the click of Clear button. I think they probably related. Can anyone see the problem? Thanks in advanced!
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import javax.swing.JOptionPane;
public class Checkerboard extends Frame implements ActionListener
{
int[] blocksTextField = new int[15];
Panel blocksPanel = new Panel();
TextArea blocksDisplay[] = new TextArea[16];
TextField start = new TextField (3);
TextField stop = new TextField (3);
TextField step = new TextField (3);
//Colors
Color Red = new Color(255, 90, 90);
Color Green = new Color(140, 215, 40);
Color white = new Color(255,255,255);
//textField ints
int inputStart;
int inputStop;
int inputStep;
//Lables
Label custStartLabel = new Label ("Start : ");
Label custStopLabel = new Label ("Stop : ");
Label custStepLabel = new Label ("Step : ");
//Buttons
Button goButton = new Button("Go");
Button clearButton = new Button("Clear");
//panel for input textFields and lables
Panel textInputPanel = new Panel();
//Panel for buttons
Panel buttonPanel = new Panel();
public Checkerboard()
{//constructor method
//set the 3 input textFields to 0
inputStart = 0;
inputStop = 0;
inputStep = 0;
//set Layouts for frame and three panels
this.setLayout(new BorderLayout());
//grid layout (row,col,horgap,vertgap)
blocksPanel.setLayout(new GridLayout(4,4,10,10));
textInputPanel.setLayout(new GridLayout(2,3,20,10));
buttonPanel.setLayout(new FlowLayout());
//setEditable()
//setText()
//add components to blocks panel
for (int i = 0; i<16; i++)
{
blocksDisplay[i] = new TextArea(null,3,5,3);
if(i<6)
blocksDisplay[i].setText(" " +i);
else
blocksDisplay[i].setText(" " +i);
blocksDisplay[i].setEditable(false);
// blocksDisplay[i].setBackground(Red);
blocksPanel.add(blocksDisplay[i]);
}//end for
//add componets to panels
//add text fields
textInputPanel.add(start);
textInputPanel.add(stop);
textInputPanel.add(step);
//add lables
textInputPanel.add(custStartLabel);
textInputPanel.add(custStopLabel);
textInputPanel.add(custStepLabel);
//add button to panel
buttonPanel.add(goButton);
buttonPanel.add(clearButton);
//ADD ACTION LISTENRS TO BUTTONS (!IMPORTANT)
goButton.addActionListener(this);
clearButton.addActionListener(this);
add(blocksPanel, BorderLayout.NORTH);
add(textInputPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
//overridding the windowcClosing() method will allow the user to clisk the Close button
addWindowListener(
new WindowAdapter()
{
public void windowCloseing(WindowEvent e)
{
System.exit(0);
}
}
);
}//end of constructor method
public void actionPerformed(ActionEvent e)
{
//if & else if to see what button clicked and pull user input
if(e.getSource() == goButton) //if go clicked ...
{
System.out.println("go clicked");
try{
String inputStart = start.getText();
int varStart = Integer.parseInt(inputStart);
if (varStart<=0 || varStart>=15 )throw new NumberFormatException();
System.out.println("start = " + varStart);
// roomDisplay[available].setBackground(lightRed);
String inputStop = stop.getText();
int varStop = Integer.parseInt(inputStop);
if (varStop<=0 || varStart>=15 )throw new NumberFormatException();
System.out.println("stop = " + varStop);
String inputStep = step.getText();
int varStep = Integer.parseInt(inputStep);
if (varStep<=0 || varStep>=15 )throw new NumberFormatException();
System.out.println("step = " + varStep);
for (int i = varStart; i<varStop; varStep++)//ADD WHILE LOOP
{
blocksDisplay[i].setBackground(Red);
blocksDisplay[i].setText(" " +i);
}
}
catch (NumberFormatException ex)
{
JOptionPane.showMessageDialog(null, "You must enter a Start, Stop and Step value greater than 0 and less than 15",
"Error",JOptionPane.ERROR_MESSAGE);
}
}
else if(e.getSource() == clearButton ) //else if clear clicked ...
{
System.out.println("clear clicked");
}
//int available = room.bookRoom(smoking.getState());
//if (available > 0)//Rooms is available
}//end action performed method
public static void main(String[]args)
{
Checkerboard frame = new Checkerboard ();
frame.setBounds(50, 100, 300, 410);//changed size to make text feilds full charater size
frame.setTitle("Checkerboarder Array");
frame.setVisible(true);
}//end of main method
}
The problem is your loop: your loop variable name is i but you change the varStep variable instead of i so basically the loop variable never changes and thus the exit condition will never be true.
I believe you want to step i with varStep, so change your loop to:
for (int i = varStart; i<varStop; i += varStep)
// stuff inside loop
Take a look at this loop.
for (int i = varStart; i<varStop; varStep++)//ADD WHILE LOOP
{
blocksDisplay[i].setBackground(Red);
blocksDisplay[i].setText(" " +i);
}
It ends when i >= varStop, but neither i nor varStop change as a consequence of its execution, so it can never stop. You only increment varStep.
I think you want to increment i by varStep on each iteration instead, i.e. i += varStep
You use varStep++ in your for loop. I think you meant to do i+varStep.
The application freezes because you're never increasing i, resulting in an endless loop.

Inputting numbers in a textfield via button on GUI

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++;
}

Combine Prime Factor Code into JPanel - Java

I have a working JFrame GUI with my JPanel all setup. I am trying to combine two different codes that I've got setup and working. The first code was a text converter toUpperCase in a JPanel, and the second is a Prime Factor (not prime numbers) code. I've been trying to get the JPanel to give an output of Prime Factors for any number that a user inputs. Here is what I have....
JPanel Code
public class Prime extends JPanel {
private JLabel formattedText;
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new Prime());
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
public Prime(){
setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
JPanel panel = new JPanel(); panel.setPreferredSize(new Dimension(640,100));
JLabel label = new JLabel("Enter a number to check for it's prime number(s).");
JTextField field = new JTextField("0");
field.addActionListener(new FieldListener());
add(label);
add(field);
add(panel);
panel = new JPanel(); panel.setPreferredSize(new Dimension(640,380));
formattedText = new JLabel();
panel.add(formattedText);
add(panel);
}
private class FieldListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
JTextField field = (JTextField)event.getSource();
formattedText.setText(field.getText().toUpperCase()); // I know this is wrong... I can't figure out what to change here to get it to pull the code below.
}
}
public class PrimeFactors {
}
}
and here is the Prime Factor code
public class Temp {
static int primeCheck = 1;
public static void main(String[] args) {
System.out.println("Enter a number whose Prime factors are desired: ");
Scanner numS = new Scanner(System.in);
int numPriFac = 0;
if (numS.hasNextInt()) {
numPriFac = numS.nextInt();
}
System.out.println("All the Prime Factors of the entered number are:");
for (int tap = 1; tap <= numPriFac; tap++) {
if (numPriFac % tap == 0) {
for (int primeTest = 2; primeTest < tap; primeTest++) {
if (tap % primeTest == 0) {
primeCheck = 1;
break;
} else {
primeCheck = 0;
}
}
if (primeCheck == 0 || tap == 2) {
System.out.print(tap + " ");
}
}
}
}
}
That last PrimeFactors code in the bottom is just something left over from when I was trying to get it working on my own. Thanks so much for any help!!!
Step 1: Change the line
public static void main(String[] args) {
to something like
public static String primeFactors(int number) {
and make the method use the provided argument number instead of asking for input.
Step 2: Create a StringBuilder inprimeFactors and change all calls to System.out.print to calls to stringBuilder.append()
Step 3: Set stringBuilder.toString() as return value for primeFactors
Step 4: Change the line
formattedText.setText(field.getText().toUpperCase());
to
formattedText.setText(Temp.primeFactors(Integer.parseInt(field.getText())));
I'll leave the error handling and input safe guarding to you.

Categories

Resources