I have an assignment where I have to create a Fahrenheit to Celsius (F2C) converter and vice versa. It is in a jframe where there are 3 buttons and 2 text fields.
The first text field will be the input temperature. The second text field will have the converted temperature.
The first button called F2C will convert the number entered from the first text field to Celsius and place it in the second text field.
The second button called C2F will also take the number entered from the first text field and convert it into Fahrenheit and place it in the second text field.
the third button will exit the jframe.
I have most of the code for the layout of the buttons and text field working. The exit button is also working.
My problem is getting the data from the first text field, pressing the F2C button to convert to Celsius, then placing the converted number back into the second text field. Same thing when pressing the C2F button to convert to Fahrenheit.
here's my code so far:
import javax.swing.*; // for GUI
import java.awt.*; // for GUI
import java.awt.color.*; // for Color
import java.awt.event.*; // for events
public class JButtonDemo extends JFrame implements ActionListener
{
JButton jbC2F;
JButton jbF2C;
JButton jbExit;
TextField tfInput;
TextField tfOutput;
public JButtonDemo()
{
int width = 267;
int height = 400;
setTitle("First Frame"); // set title of JFrame
setSize(width, height);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
setLocation((d.width - width)/2, (d.height - height)/2);
/** ***********************************************
*
* create buttons
* register buttons
*************************************************/
// make jbExample and jbExit
jbC2F = new JButton("C2F");
jbF2C = new JButton("F2C");
jbExit = new JButton("exit");
tfInput = new TextField(" ");
tfOutput = new TextField(" ");
// register buttons
jbExit.addActionListener(this);
jbC2F.addActionListener(this);
jbF2C.addActionListener(this);
// create Panel Buttons default to Flow
JPanel buttons = new JPanel();
buttons.setLayout(new FlowLayout(FlowLayout.CENTER));
buttons.setBackground(Color.BLUE);
// add buttons to panel
buttons.add(jbC2F);
buttons.add(jbF2C);
buttons.add(jbExit);
/** **************************************************
*
* create content Container
***************************************************/
// create container
Container content = getContentPane();
content.setBackground(Color.BLUE);
content.setLayout(new FlowLayout());
content.add(tfInput);
content.add(tfOutput);
// add panels
content.add(buttons, BorderLayout.NORTH);
} // end constructor
public void actionPerformed(ActionEvent ae)
{
Object source = ae.getSource();
//test for exit button
if(source == jbExit)
{
System.exit(0);
}
}
public static void main(String args[])
{
JButtonDemo fl = new JButtonDemo();
fl.setVisible(true);
}
}
Do it as follows:
public void actionPerformed(ActionEvent ae) {
double t = Double.parseDouble(tfInput.getText().trim());
Object source = ae.getSource();
// test for exit button
if (source == jbExit) {
System.exit(0);
} else if (source == jbC2F) {
tfOutput.setText(String.valueOf(t * 9.0 / 5.0 + 32.0));
} else if (source == jbF2C) {
tfOutput.setText(String.valueOf((t - 32.0) * 5.0 / 9.0));
}
}
For your answer
You can add an ActionListener to your buttons and remove the implementation of the ActionListener in your class.
For example:
jbC2F.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Parse tfInput.getText() to integer
...
//Set tfOutput to the result with tfOutpput.setText(String str)
...
}
});
And then you parse your text to an integer using Integer.parse(String str) which should be the content of the corresponding text field. You might want to add a try - catch block to catch exceptions thrown by the parse method when the string could not be parsed to a valid integer.
Side note
You can replace
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension d = tk.getScreenSize();
setLocation((d.width - width)/2, (d.height - height)/2);
By
setLocationRelativeTo(null)
This will also center your application to the middle of the screen
Here's an example. You will need to check for exceptions in case of non-numeric input. JFormattatedTextField's could help with that. You will also need to determine which button is pressed so you can do the proper conversion.
public void actionPerformed(ActionEvent ae)
{
String temp = tfInput.getText();
if (!temp.isBlank()) {
double v = Double.valueOf(temp);
double celcius = (v-32)*5/9.;
temp = String.format("%4.2f", celcius);
tfOutput.setText(temp);
}
Object source = ae.getSource();
//test for exit button
if(source == jbExit)
{
System.exit(0);
}
}
Related
I've got the problem that I've got the regex check on an input field and if the input is not as it should be and i press tab to check and normally to move to the next element, it should stay at that current field. But because of the normal tab policy it moves to the next element and even if i request focus on the current element it still moves to the next one.
Thanks for the help beforehand :)
This is my Code snippet:
}else if(comp.getName().equals("input_dauer")){
System.out.println("Test3");
final Pattern pattern = Pattern.compile("^[\\d]{0,}[,.]+[\\d]{1,3}$");
if (!pattern.matcher(input_dauer.getText()).matches()) {
lblDauer.setForeground(Color.red);
MandatoryDauer = 0;
comboBox_aktivitaet.requestFocus();
input_dauer.requestFocus();
}
else{
lblDauer.setForeground(Color.decode("#1E2F3F"));
MandatoryDauer = 1;
textArea_beschreibung.requestFocus();
}
You may disable the focus traversal keys of the JTextField (or whatever your Componentis) with setFocusTraversalKeysEnabled(false), and manually transfer the focus when needed.
In the following example, if the text's length is less than 5 characters, it is deemed invalid so we don't transfer the focus.
If it is valid (length>=5), we transfer the focus with transferFocus() if we want to stick with the logical focus order, or requestFocus() to transfer to a particular component .
A dummy button has been added so that you can watch the focus behaviour.
JPanel contentPane = new JPanel();
JFrame fr = new JFrame();
JButton someButton = new JButton("Button");
JTextField textField = new JTextField(10);
textField.setFocusTraversalKeysEnabled(false);
textField.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(final KeyEvent ke) {
JTextField source = (JTextField) ke.getSource();
if (ke.getKeyCode() == KeyEvent.VK_TAB) {
if (source.getText().length() >= 5) {
System.out.println("Tab with valid text, transferring focus");
source.transferFocus();// or someButton.requestFocus()
} else {
System.out.println("Tab with invalid text");
}
}
}
});
contentPane.add(textField);
contentPane.add(someButton);
fr.setContentPane(contentPane);
fr.pack();
fr.setVisible(true);
I wanted to know how I can make the text of my labels bigger and put breaks in between of the labels. So basically for the code I want it to be:
(Big) Ohms Law
(A bit smaller) Voltage (textbox + button here)
(Same size as Voltage) Resistance (textbox + button here)
So far I have this:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class OhmsLawApplet extends Applet implements ActionListener
{
// declare variables
int RESISTANCE;
int VOLTAGE;
int OHMS;
int V = 0;
int R = 0;
int I = 0;
//construct components
Label OhmsLabel = new Label("Ohms Law"); // Label at the top
Label VOLTAGELabel = new Label("Voltage:"); // Label for Voltage
TextField VOLTAGEField = new TextField(); //Textfield to input Voltage
Label RESISTANCELabel = new Label("Resistance:"); // Label for Resistance
TextField RESISTANCEField = new TextField(); //Textfield to input Resistance
Button CALCULATEButton = new Button("Calculate");
public void init(){
// Add the components to the Applet
setForeground(Color.black);
add(OhmsLabel);
add(VOLTAGELabel);
add(VOLTAGEField);
add(RESISTANCELabel);
add(RESISTANCEField);
add(CALCULATEButton);
CALCULATEButton.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
// UNFINISHED/ DON'T KNOW HOW TO DO YET
VOLTAGE = Integer.parseInt(VOLTAGEField.getText());
RESISTANCE = Integer.parseInt(RESISTANCEField.getText());
VOLTAGE = I*R;
RESISTANCE = V/I;
}
}
You can use Component#setFont(Font) to set the font and thus update the textsize:
Label label = ...
int newSize = ...
label.setFont(label.getFont().getName() , label.getFont().getStyle() , newSize);
This piece of code will create a new font with the style-attributes but a different fontsize.
As for changing the distance of the labels: that depends upon the used LayoutManager. You can set the size of each component manually using Component#setPreferredSize(Dimension), which will work for most LayoutManagers. But the distance of the components solely depends upon the used LayoutManager. You might want to have a look at the GridBagLayout
Simplified: How to make String value to call specific existed JButton variable name in java?
I'm trying to make a non-ordinary Tic-Tac-Toe game...
Anyway, what I will post here is not really the whole concept of that. I just want to make it simple: I have 9 square jButtons named (3 by 3) (and maybe allow user to make 4x4, 5x5, 10x10 etc. via settings in future):
[markbox_00_00] / [markbox_00_01] / [markbox_00_02]
[markbox_01_00] / [markbox_01_01] / [markbox_01_02]
[markbox_02_00] / [markbox_02_01] / [markbox_02_02]
[btnSave] / [btnUndoActions]
where the first two digit represent the row and the next two is the column; and a save button (btnSave) and undo button(btnUndoActions).
Each markbox have default spring value of "0", when I click it turns "1"; and when I click "1" it turns "0". When you press undo button it will reset to last save.
Here is some of my simplified line of codes:
private byte markboxColLimit = 3, markboxRowLimit = 3, row, col;
private byte[][] saveNumber = new byte[markboxRowLimit][markboxColLimit];
private String buttonName;
public Astral_TicTacToe() {
initComponents();
/* I want something like this, but using a for loop based on markboxColLimit and
markboxRowLimit as limits */
markbox_00_00.setText("0");
markbox_00_01.setText("0");
markbox_00_02.setText("0");
markbox_01_00.setText("0");
markbox_01_01.setText("0");
markbox_01_02.setText("0");
markbox_02_00.setText("0");
markbox_02_01.setText("0");
markbox_02_02.setText("0");
/* I know the line below is wrong... what I'm trying is to avoid
* repetitiveness by looping and dynamically calling the variable
* name of JButtons, or in other ways...
*/
/* Attempting to make an alternative code from above (trying to make a loop instead) */
for(row = 0; row < markboxRowLimit; row++){
for(col = 0; col < markboxColLimit; col++){
buttonName = "markbox_0" + Byte.toString(row) + "_0" + Byte.toString(col);
buttonName.setText("0");
}
}
}
private void btnUndoActionsActionPerformed(java.awt.event.ActionEvent evt) {
markbox_00_00.setText(Byte.toString(saveNumber[0][0]));
markbox_00_01.setText(Byte.toString(saveNumber[0][1]));
markbox_00_02.setText(Byte.toString(saveNumber[0][2]));
markbox_01_00.setText(Byte.toString(saveNumber[1][0]));
markbox_01_01.setText(Byte.toString(saveNumber[1][1]));
markbox_01_02.setText(Byte.toString(saveNumber[1][2]));
markbox_02_00.setText(Byte.toString(saveNumber[2][0]));
markbox_02_01.setText(Byte.toString(saveNumber[2][1]));
markbox_02_02.setText(Byte.toString(saveNumber[2][2]));
}
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {
saveNumber[0][0] = Byte.parseByte(markbox_00_00.getText());
saveNumber[0][1] = Byte.parseByte(markbox_00_01.getText());
saveNumber[0][2] = Byte.parseByte(markbox_00_02.getText());
saveNumber[1][0] = Byte.parseByte(markbox_01_00.getText());
saveNumber[1][1] = Byte.parseByte(markbox_01_01.getText());
saveNumber[1][2] = Byte.parseByte(markbox_01_00.getText());
saveNumber[2][0] = Byte.parseByte(markbox_02_00.getText());
saveNumber[2][1] = Byte.parseByte(markbox_02_01.getText());
saveNumber[2][2] = Byte.parseByte(markbox_02_02.getText());
}
private void markbox_00_00ActionPerformed(java.awt.event.ActionEvent evt) {
if("0".equals(markbox_00_00.getText()))
markbox_00_00.setText("1");
else
markbox_00_00.setText("0");
}
private void markbox_00_01ActionPerformed(java.awt.event.ActionEvent evt) {
if("0".equals(markbox_00_01.getText()))
markbox_00_00.setText("1");
else
markbox_00_00.setText("0");
}
....
private void markbox_02_02ActionPerformed(java.awt.event.ActionEvent evt) {
if("0".equals(markbox_00_00.getText()))
markbox_02_02.setText("1");
else
markbox_02_02.setText("0");
}
In short: how can I make String a specific variable name of JButton for calling/accessing/editing for their properties?
Example:
buttonName = markbox_01_02;
buttonName.setText("2");
is equavalent to markbox_01_02.getText("2");
I really appreciate the help, thank you...
P.S. I use to make JFrame in NetBeans Design (just click and drag the objects in palette window like JPanel, JButton, etc., so I don't type the code manually except making my own logical Method).
You probably need to redo your program and rephrase your question because it's kind of unclear where you're stuck that's why I wrote this answer as a Community Wiki.
The following program creates a GridLayout for the board and add 2 JButtons below it which contain "Save" and "Undo" buttons.
Whenever you press a button it will change it's text to 0 or 1 depending on the previous state of the button, and "Undo" button will undo last clic the same way, if it was 0 it will become 1 and viceversa.
I guess you should read How to write an ActionListener before copy-pasting this example, understand what it says and try to understand how this program works.
The logic to "Save" button is up to you 'cause I'm not sure what you wanna do there and I'm not gonna write all the code for you. This is made only for you to get an idea on how to handle events.
Also, the logic to end the game is left to you for the same reasons as the "Save" button.
I wish I knew how to record my screen in Ubuntu and save as GIF but here's a screenshot on how this program looks like:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TicTacToe implements ActionListener {
JFrame frame;
JButton buttons[];
JPanel pane, buttonPane;
boolean pressed[];
JButton save, undo;
int n = -1;
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < buttons.length; i++) {
if(e.getSource() == buttons[i]) {
pressed[i] = !pressed[i];
buttons[i].setText(pressed[i] ? "1" : "0");
n = i;
break;
}
}
}
public TicTacToe () {
frame = new JFrame("Tic Tac Toe Game");
buttons = new JButton[9];
pane = new JPanel(new GridLayout(3, 3));
pressed = new boolean[9];
buttonPane = new JPanel(new FlowLayout());
save = new JButton("Save");
undo = new JButton("Undo");
for (int i = 0; i < buttons.length; i++) {
buttons[i] = new JButton("0");
pressed[i] = false;
}
for (JButton b : buttons) {
b.addActionListener(this);
pane.add(b);
}
undo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (n == -1) {
return;
}
pressed[n] = !pressed[n];
buttons[n].setText(pressed[n] ? "1" : "0");
}
});
buttonPane.add(save);
buttonPane.add(undo);
frame.add(pane, BorderLayout.PAGE_START);
frame.add(buttonPane, BorderLayout.CENTER);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static void main (String args[]) {
new TicTacToe();
}
}
In my Java GUI there are 4 JTextFields. The goal is to enter default values for 3 textfields (example .8 in code below) and calculate the value and display the calculation into the 4th textfield. The user should then be able to change the values of the numbers within the JTextField and then press the calculate button again to get the new values to recalculate and display them.
Problem: when the JTextfields are edited and the calculate button is pressed it does not calculate with the new numbers but instead with the old initial values.
JTextField S = new JTextField();
S.setText(".8");
String Stext = S.getText();
final double Snumber = Double.parseDouble(Stext);
.... *same setup for Rnumber*
.... *same setup for Anumber*
....
JButton btnCalculate_1 = new JButton("Calculate");
btnCalculate_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
int valuec = (int) Math.ceil(((Snumber*Rnumber)/Anumber)/8);
String stringValuec = String.valueOf(valuec);
NewTextField.setText(stringCalc);
}
I have checked several posts and tried:
How Do I Get User Input from a TextField and Convert it to a Double?
Using JTextField for user input
for the basics. However whenever trying to adapt it to my code eclipse returns various errors.
use S.getText() inside the actionPerformed() method.
The code inside actionperformed block is invoked on the button press and the code outside it remains unaffected.
So once you run your code and insert values to text fields, it assigns the a value but it does not change the same when you change the value and press calculate button
try using This code.
class a extends JFrame implements ActionListener
{
JTextField t1,t2,t3;
a()
{
setLayout(null);
t1 = new JTextField();
t2 = new JTextField();
t3 = new JTextField();
JButton B1 = new JButton("Calculate");
t3.setEditable(false);
t1.setBounds(10,10,100,30);
t2.setBounds(10,40,100,30);
t3.setBounds(10,70,100,30);
B1.setBounds(50, 110, 80, 50);
add(t1);
add(t2);
add(t3);
add(B1);
B1.addActionListener(this);
setSize(200,200);
setVisible(true);
}
public static void main(String args[])
{
new a();
}
#Override
public void actionPerformed(ActionEvent e)
{
double Snumber = Double.parseDouble(t1.getText());
double Rnumber = Double.parseDouble(t2.getText());
double Anumber = Snumber+Rnumber;
t3.setText(String.valueOf(Anumber));
}
}
I'm trying to create a Java AWT program with these codes:
import javax.swing.*;
import java.awt.*;
public class Exer1 extends JFrame {
public Exer1(){
super ("Addition");
JLabel add1 = new JLabel("Enter 1st Integer: ");
JTextField jtf1 = new JTextField(10);
JLabel add2 = new JLabel("Enter 2nd Integer: ");
JTextField jtf2 = new JTextField(10);
JButton calculate = new JButton("Calculate");
FlowLayout flo = new FlowLayout();
setLayout(flo);
add(add1);
add(jtf1);
add(add2);
add(jtf2);
add(calculate);
setSize(200,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] a){
Exer1 ex1 = new Exer1();
}
}
My problem is HOW to add these 2 integers using JTextField. Can someone help me? Thank you so much. :)
You need to use ActionListener on your JButton.
Then you need to get int's from JTextField's and sum them like next:
calculate.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
int i1 = Integer.valueOf(jtf1.getText());
int i2 = Integer.valueOf(jtf2.getText());
System.out.println("sum=" + (i1 + i2));
} catch (Exception e1){
e1.printStackTrace();
}
}
});
Generally, you should create an event listener for click events on your button: Lesson: Writing Event Listeners. In that handler, you would take contents of your two text fields, convert them to integers:
Integer i1 = Integer.valueOf(jtf1.getText());
Then you can add those two integers and display them in another control or do anything else with them.
Start with How to Use Buttons, Check Boxes, and Radio Buttons and
How to Write an Action Listeners
This will provide you with the information you need to be able to tell when the user presses the button.
JTextField#getText then return's String. The problem then becomes a problem of converting a String to a int, which if you take the time, there are thousands of examples demonstrating how to achieve that
Once you've played around with oddities of converting String to a int, you could take a look at How to Use Spinners and How to Use Formatted Text Fields which perform there own validation on the values been entered