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