Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to display object's attributes in JLabel? (java)

I’m making a restaurant menu in JFrame and I want to display my objects attributes "name" and "price" on the JLabel insted of printing it in the console.
I have the application frame set up with some labels:

public class App {
  public static void main(String[] args) {

    JFrame frame = new JFrame();
    JLabel labelName = new JLabel();
    JLabel labelPrice = new JLabel();

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(800, 650); 
    frame.setVisible(true);

    frame.add(labelName);
    labelName.setBounds(250, 50, 100, 50);

    frame.add(labelPrice);
    labelPrice.setBounds(250, 100, 100, 50);

my Menu class:

class Menu {
  public String name;
  public double price;

  //constructor
  public Menu(String name, double price) {
     this.name = name;
     this.price = price;
   }
}

and the object of class Menu:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Menu dish1 = new Menu("Whatever", 10.99);

How can I display the name and price attributes of my object dish1 in my labels?

>Solution :

You need to use "setText()" method on label object and create a panel where you can add your label. To display name and price you can format string given by object.

Menu dish1 = new Menu("Whatever", 10.99);
JFrame frame = new JFrame();
JLabel label = new JLabel();
JPanel main = new JPanel();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 650); 
frame.setVisible(true);
frame.add(label);

label.setText(String.format("%s %1$,.2f", dish1.name, dish1.price));
main.add(label);
frame.add(main);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading