I have a task to create a Fahrenheit to Celsius converter, I've written the program as follows, it's the way that teacher has taught us, so I'm obliged to follow it, I know it's even very rudimentary but I have no other choice to follow his stupid way.
All I need help with is that I want to replace that JOptionPane in the last line with "JLabel", I want the result to be showed in a JLabel. What can I do?
Converter.java
public class Converter extends JFrame implements ActionListener{
JTextField Textbox = new JTextField (20);
JButton button1 = new JButton("Submit");
int x;
public Converter()
{
setLayout(new FlowLayout());
add(button1);
add(Textbox);
button1.addActionListener(this);
setVisible(true);
setSize(800,600);
}
public void actionPerformed(ActionEvent arg0)
{
String s=Textbox.getText();
int res=Integer.parseInt(s);
JOptionPane.showMessageDialog(null,(res-32)*(5)/(9)); ///I need help here
}
}
WindowFrame.java
public class WindowFrame {
public static void main(String[] args) {
Converter x = new Converter();
}
}
Create a new JLabel then add it to your container (JFrame), then in the actionPerformed you can do:
public void actionPerformed(ActionEvent arg0)
{
String s = Textbox.getText();
int res = Integer.parseInt(s);
String result = String.valueOf((res-32)*(5)/(9));
label.setText(result);
}
Do the changes in Converter.java as given in image,
Related
I'm writting a program and the GUi Class (main class) is overloaded.
I want to know if it's possible to split the class in several classes.
for example I made a class of constaints.
The main question is if I can keep all interface code in one class(where I'll addd and initialize JTetxFields,JButtons and other Jobjects) and then use them in another class.
for example:
in interface class there will be:
JTextField field = new JTextField(12);
JButton button = new JButton("Click");
and in main class I do smthng like this:
add(field);
add(button);
button.addActionListener(this);
public void actionPerformed(ActionEvent e) {
if(e.getSource==button){
field.setVisible(false);
}
if it's possible with creating new JFrame,then please tell me how to create new Frame and use it in main class.
Your main question -- can you create a class that is a repository of your GUI components and use them elsewhere, and the answer is yes you can, but I don't think that you should, at least not for simple components. You should keep your JTextFields, JButtons in the GUI classes that use them, but any major subsection of your GUI, such as a JPanel that contains components and that has a unique functionality, that can go in its own class.
More important is to separate out different functional parts of your program, especially you should try to separate out the logical or "model" part of your program from the GUI or "view" part. The details of how you do this will depend on the details of your program and overall problem.
For example:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class SeparateClasses {
private static void createAndShowGui() {
SeparateClassView mainPanel = new SeparateClassView();
new SeparateClassControl(mainPanel);
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
public class SeparateClassView extends JPanel {
private JTextField field1 = new JTextField(12);
private JTextField field2 = new JTextField(12);
private JTextField resultField = new JTextField("false", 5);
private JButton button = new JButton("Click");
public SeparateClassView() {
resultField.setEditable(false);
resultField.setFocusable(false);
add(new JLabel("Field 1:"));
add(field1);
add(new JLabel("Field 2:"));
add(field2);
add(button);
add(new JLabel("Two texts equivalent?:"));
add(resultField);
}
public void addButtonListener(ActionListener listener) {
button.addActionListener(listener);
field1.addActionListener(listener);
field2.addActionListener(listener);
}
public String getField1Text() {
return field1.getText();
}
public String getField2Text() {
return field2.getText();
}
public void setField1Text(String text) {
field1.setText(text);
}
public void setField2Text(String text) {
field2.setText(text);
}
public void setResult(boolean result) {
resultField.setText(String.valueOf(result));
}
}
public class SeparateClassControl implements ActionListener {
private SeparateClassView view;
public SeparateClassControl(SeparateClassView view) {
this.view = view;
view.addButtonListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
String text1 = view.getField1Text();
String text2 = view.getField2Text();
boolean result = SeparateClassModel.stringsEquivalent(text1, text2);
view.setResult(result);
}
}
public class SeparateClassModel {
public static boolean stringsEquivalent(String text1, String text2) {
return text1.equalsIgnoreCase(text2);
}
}
I'm writing an application where I need to get two String objects from the GUI to the nullObject class.
I'm relatively new to programming, and am trying my best to learn. If you have any tips on how to make this better, I'd be really thankful!
My GUI class:
package com.giuly.jsoncreate;
public class GUI {
private JFrame startFrame;
private JFrame chkFrame;
private JFrame osFrame;
private JFrame appVFrame;
private JPanel controlPanel;
private JButton nextPage;
private JButton cancel;
private JButton save;
public GUI() {
generateGUI();
}
public static void main(String[]args) {
GUI gui = new GUI();
}
public void generateGUI() {
//Creation of the First Frame
startFrame = new JFrame("JSCON Creator");
startFrame.setSize(1000, 700);
startFrame.setLayout(new FlowLayout());
startFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
//Panel Creation
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
//Button Creation
cancel = new JButton("Cancel");
cancel.setSize(100, 100);
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
nextPage = new JButton("Next");
nextPage.setSize(100, 100);
nextPage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
startFrame.setVisible(false);
showText();
}
});
startFrame.add(controlPanel);
startFrame.add(cancel);
startFrame.add(nextPage);
startFrame.setVisible(true);
startFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void showText() {
JFrame textFrame = new JFrame();
textFrame.setSize(1000, 700);
textFrame.setTitle("Text");
textFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JPanel textPanel = new JPanel();
JLabel titleLabel = new JLabel("Title");
textPanel.add(titleLabel);
JLabel descrLabel = new JLabel("Description");
JTextField tfTitle = new JTextField("",15);
tfTitle.setForeground(Color.BLACK);
tfTitle.setBackground(Color.WHITE);
JTextField tfDescr = new JTextField("",30);
tfDescr.setForeground(Color.BLACK);
tfDescr.setBackground(Color.WHITE);
textPanel.add(tfTitle);
textPanel.add(descrLabel);
textPanel.add(tfDescr);
JButton buttonOK = new JButton("OK");
textPanel.add(buttonOK);
buttonOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String jsonTitle = tfTitle.getText();
String jsonDescr = tfDescr.getText();
System.exit(0);
}
});
textFrame.add(textPanel);
textFrame.setVisible(true);
}
I want to get the Strings jsonTitle and jsonDescr into another class, so I can store them. In the end I will have some Strings and I need to save them in a JSON file. I need a way to get those two Strings, what advice do you guys have?
Erick is correct with his answer. Just thought I should add additional info. If you declare jstonTitle and jsonDescr like your other fields using private you still will not be able to access these fields from another class. Coding up a getter for the fields along with declaring them at the top of GUI should solve your problem. Then just create an instance of GUI in your other class and call the method.
public String getJsonTitle(){
return this.jsonTitle;
}
You're declaring jstonTitle and jsonDescr inside the actionPerformed() method. That means that as soon as actionPerformed() exits you'll lose those variables. You need to declare them in an enclosing context. For example, you could make them fields on the GUI class. Still assign them in actionPerformed(), but declare them up at the top of GUI where you're declaring startFrame, chkFrame, etc.
That will give you the ability to access those values from anywhere within GUI.
Oh, BTW, get rid of System.exit(0);. (Have you actually tried to run your program?)
Im trying to create a choose your own destiny adventure game. I have created the gui which looks like this:
The JTextField shown is going to be the input box which is entered when the button is pressed. Im trying to write the code so that when the button is pressed, its contents is saved to a variable called UserInput, which i can then call up in the main class to use its contents.
My main class is currently just:
public class Main
{
public static void main(String[] args)
{
int i = 0;
int t = 0;
int st = 0;
int h = 0;
Texts textObject = new Texts();
textObject.TextList();
Commands commandObject = new Commands();
commandObject.commands();
GUImain guiObject = new GUImain();
guiObject.displayGUI();
String User_Input = guiObject.();
}
}
The last line is where i want to call up the String from the GUImain class
This is my GUImain class I've tried to cut out any irrelivent code for this question:
import's (lots of them);
public class GUImain
{
private JFrame frame;
private JTextField textField;
private ImageIcon image1;
public void displayGUI()
{
this.frame.setVisible(true);
}
//Launch the application.
public static void main(String[] args)
{
GUImain window = new GUImain();
}
//Create the application.
public GUImain()
{
frame = new JFrame();
frame.setBounds(100, 100, 611, 471);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
...
Creating the JButton and my attempt at making it link to the Text field and save its contents to the variable UserInput, which i want to call up from the main class:
JButton btnEnter = new JButton("Enter"); //enter button
btnOptions.addActionListener(new ActionListener()
{
public String UserInput = "null";
public void actionPerformed(ActionEvent e)
{
UserInput = textField.getText();
}
public String getUserInput()
{
return UserInput;
}
});
btnEnter.setBounds(518, 404, 85, 39);
frame.getContentPane().add(btnEnter);
...
Creating the Text Field:
textField = new JTextField("");
textField.setBounds(5, 410, 508, 28);
frame.getContentPane().add(textField);
textField.setColumns(10);
I'm just starting to learn java so sorry for asking such a basic question, but I've been stuck on it for quite a while now.
Thanks for your time and help.
Thomas
Just try using 'GUImain' as the inner class in class 'Main' and declare a variable
public String UserInput = "null";
in 'Main' class. This variable can now be used in both your classes.
I have main JFrame in my project. And one main JPanel with Y-AXIS BoxLayout which is used to contain another panels in it. This is the way i use my JFrame to show this JPanel by default (I'm not quite convinced if this is the right way):
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
mainPanel = new MainScreenPanel();
MainFrame mainFrame = new MainFrame();
mainFrame.setContentPane(mainPanel);
mainFrame.invalidate();
mainFrame.validate();
mainFrame.setVisible(true);
}
});
}
Next I add two JPanels into mainPanel like this:
public class MainScreenPanel extends javax.swing.JPanel {
public MainScreenPanel() {
StatusPanel sPanel = new StatusPanel();
LogPanel lPanel = new LogPanel();
add(sPanel);
add(lPanel);
}
}
lPanel has different gui elements on it. One of them is a button which opens another panel (addConnectionPanel), and replaces mainPanel in the jFrame Here is the way i do it:
private void addCnctButtonActionPerformed(java.awt.event.ActionEvent evt) {
JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);
topFrame.setContentPane(new AddConnectionPanel());
topFrame.invalidate();
topFrame.validate();
}
AddConectionPanel has some labels and input text boxes. It has two buttons ok and cancel. Here is the code of cancel button:
private void cancelCnctBtnActionPerformed(java.awt.event.ActionEvent evt) {
JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);
topFrame.setContentPane(new MainScreenPanel());
topFrame.invalidate();
topFrame.validate();
}
sPanel is empty. It must be empty until input boxes on AddConnectionPanel are not filled and 'ok' button is not pressed. When these actions are performed, I want to dynamically create JLabels which take parameters from inputs on sPanel. Labels should be grouped, so when the actions performed second time new group must be created. Can some one give me advice on how to do this? And show me my mistakes? Keep in mind I'm using NetBeans.
This would be my approach:
public interface ConnectionPanelListener{
void onOkButtonClicked(String... options);
void onCancelButtonClicked();
}
public class AddConnectionPanel extends JPanel {
private static final long serialVersionUID = 1L;
private ConnectionPanelListener listener;
public AddConnectionPanel(){
final Map<ConnectionOptions, JTextField> components = new HashMap<>(ConnectionOptions.values().length);
for(ConnectionOptions option:ConnectionOptions.values()){
this.add(new JLabel(option.labelCaption));
JTextField textField = new JTextField();
//setup textField;
this.add(textField);
components.put(option, textField);
}
JButton button = new JButton("OK");
button.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(final MouseEvent pE) {
super.mouseClicked(pE);
//TODO validate TextFields
Collection<String> inputs = new Stack<>();
for(Entry<?,JTextField> e : components.entrySet()){
String text = e.getValue().getText();
if(text==null || text.trim().isEmpty()){
//TODO improve input validation
System.out.println("Input text is empty for: "+e.getKey());
} else {
inputs.add(e.getKey() + ": " + text);
}
}
listener.onOkButtonClicked(inputs.toArray(new String[inputs.size()]));
}
});
this.add(button);
button = new JButton("cancel");
button.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(final MouseEvent pE) {
super.mouseClicked(pE);
listener.onCancelButtonClicked();
}
});
this.add(button);
}
public void setConnectionPanelListener(final ConnectionPanelListener l){
listener = l;
}
private enum ConnectionOptions{
IP_ADDRESS("IP-Address:"), PORT("Port:"), WHATEVER_ATTRIBUTE_YOU_NEED("Extras:");
private String labelCaption;
private ConnectionOptions(final String caption) {
labelCaption = caption;
}
}
}
As you can see, AddConnectionPanel expects a Listener to register for the case, that "OK" or "CANCEL" are clicked. So your adjusted implementation could be like:
private void addCnctButtonActionPerformed(java.awt.event.ActionEvent evt) {
JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);
AddConnectionPanel panel = new AddConnectionPanel();
panel.setConnectionPanelListener(new ConnectionPanelListener(){
#Override
void onOkButtonClicked(String... options){ TODO: fill sPanel using the given Strings }
#Override
void onCancelButtonClicked(){ TODO }
});
topFrame.setContentPane(panel);
topFrame.invalidate();
topFrame.validate();
}
I have problem to use action listener to call function void in same class.
example..
code:
public class Product extends JPanel {
JButton add;
JPanel pAdd;
JLabel test;
JFrame frame;
public Product() {
add = new JButton("Add Product");
add.addActionListener(new ButtonListener());
add(add);
}
public void panelAdd(){
pAdd = new JPanel();
pAdd.add(new JLabel("try"));
add(pAdd);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
panelAdd();
}
}
}
How to make call the panelAdd void method?
When you add components to visible JFrame/JPanel/other components, you neet to call revalidate() andrepaint() methods after adding. Change your panelAdd() like next:
public void panelAdd(){
pAdd = new JPanel();
pAdd.add(new JLabel("try"));
add(pAdd);
revalidate();
repaint();
}
If you put
System.out.println("hi");
to
public void panelAdd(){
System.out.println("hi");
pAdd = new JPanel();
pAdd.add(new JLabel("try"));
add(pAdd);
}
you will see hi printed to your console , your code are working, but you have problem in Layout .