I need a bit of help. I'm just after coming back to programming after being made unemployed.
I'm trying to learn Java and I have run into a difficulty.
The problem is that I want to call a method that should ask the user for an input by pressing a button. This will return the chouce back to the class that called the method.
public class ButtonMain {
private static CreateButton cButton;
public static void main(String[] args) {
cButton = new CreateButton();
cButton.launchButton();
switch(cButton.getSelect()) {
case 'a' : System.out.println("German Car");
break;
case 'b' : System.out.println("Japanese Car");
break;
default : System.out.println("Incorrect Car Selected");
break;
}
}
}
The rest of the code is as follows
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CreateButton implements ActionListener {
private JFrame mainFrame;
private JLabel label1;
private JButton button1;
private JButton button2;
private char select = ' ';
public CreateButton() {
}
public void launchButton() {
createFrame();
createLabel();
createButton1();
createButton2();
}
private void createFrame() {
mainFrame = new JFrame("Cars");
mainFrame.setSize(200, 200);
mainFrame.setLocation(300, 300);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
mainFrame.setPreferredSize(null);
mainFrame.setLayout(new java.awt.GridLayout(3, 1));
}
private void createLabel() {
label1 = new JLabel("Cars", SwingConstants.CENTER);
label1.setSize(200, 100);
mainFrame.getContentPane().add(label1, BorderLayout.CENTER);
}
public void createButton1() {
button1 = new JButton("Mercedes");
button1.setSize(200, 50);
button1.addActionListener(this);
mainFrame.getContentPane().add(button1, BorderLayout.CENTER);
}
private void createButton2() {
button2 = new JButton("Lexus");
button2.setSize(200, 50);
button2.addActionListener(this);
mainFrame.getContentPane().add(button2, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1) {
select = 'a';
System.out.println(select);
}
else if (e.getSource() == button2) {
select = 'b';
System.out.println(select);
}
}
public char getSelect() {
return select;
}
}
What is happening is that the output should read a or b and then whether German or Japanese cars was selected but i'm getting the incorrect car selected.