Need help to fix ComboBox programming error - java

I'm a kinda newbie actually and just self-studying. I really want to learn how to use JComboBox properly. I have created a simple program but it took me forever to fix it.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SampleButtonKo {
JComboBox combo;
public void ComboBox1() {
String course[] = {
"PM1", "PM2", "PM3", "PM4"
};
JFrame frame = new JFrame("Mang Inasal Ordering System");
JPanel panel = new JPanel();
combo = new JComboBox(course);
combo.setBackground(Color.gray);
combo.setForeground(Color.red);
panel.add(combo);
frame.add(panel);
combo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ie) {
String str = (String) combo.getSelectedItem();
System.out.print("You have chosen " + str);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
}
public static void main(String[] args) {
JComboBox = new JComboBox();
}
}

You forgot a name for the variable
Instead of
JComboBox = new JComboBox();
try
JComboBox j = new JComboBox();
^
But perhaps, as iTech suggests, you want to create an instance of your class.
new SampleButtonKo();

There are obvious few errors in your code, you need to have the constructor named exactly as your class with no return type. Second, in your main you should create an instance of your class not the JComboBox
public class SampleButtonKo{
JComboBox combo;
public SampleButtonKo(){
// Copy your code from "ComboBox1" here
}
public static void main(String[] args) {
new SampleButtonKo();
}
}

Related

How to save multiple text input in different .txt file

I have made a program, which allows users to have as many text boxes as they want in which they can input a text string. I want to save each user input into different variables. I also want to print all of those variable or access the data stored in them when ever I want.
If you can help me that it would be really nice, thanks in advance. If you have any question please let me know in comment and I will answer them.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI
{
private JFrame frame;
private JButton button;
private JTextField tfield;
private String nameTField;
private int count;
public GUI()
{
nameTField = "tField";
count = 0;
}
private void displayGUI()
{
frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 1, 2, 2));
button = new JButton("Add Another");
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent ae)
{
tfield = new JTextField();
tfield.setName(nameTField + count);
count++;
frame.add(tfield);
frame.revalidate();
frame.repaint();
}
});
frame.add(button);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new GUI().displayGUI();
}
});
}
}
What you're looking for is an ArrayList<String>.
Declare a private ArrayList<String> userStrings; where you have your private fields.
In your constructor, add userStrings = new ArrayList<String>();
And then when you receive a string, just add it into your list with userStrings.add(myNewString). (Use your String instead of myNewString)
ArrayLists are indexed like an array, but using a method get, so you can get the first item in your list by using userStrings.get(0).

When using JPanels in java how can you display user input data in one class to another

I've been having some difficulty with this. Basically I want a user to enter a name in one Java class and have that data displayed in another. I try using gets but I keep getting 'null'. Also how would you do this if I wanted to get an int from my class (exampl) to display in my second class. Would it basically be the same?
Here's an example to show what I mean
1st class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Exampl extends JFrame implements ActionListener {
JLabel intro = new JLabel("Welcome What is your name?");
JTextField answer = new JTextField(10);
JButton button = new JButton("Enter");
final int WIDTH = 330;
final int HEIGHT = 330;
JLabel greeting = new JLabel("");
JButton next =new JButton("Next");
String name = answer.getText();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Exampl() {
super("Welcome");
setSize(WIDTH, HEIGHT);
setLayout(new FlowLayout());
add(intro);
add(answer);
add(button);
add(greeting);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == button) {
String greet = "Hello there" + name;
greeting.setText(greet);
add(next);
next.addActionListener(this);
if(source==next)
dispose();
new Hello();
}
}
public static void main(String[] args) {
Exampl frame= new Exampl();
frame.setVisible(true);
}
}
2nd class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Hello extends JFrame implements ActionListener {
String name;
JLabel hi = new JLabel("Nice to see you "+name);
JButton button = new JButton("Enter");
final int WIDTH = 330;
final int HEIGHT = 330;
JLabel greeting = new JLabel("");
JButton next =new JButton("Next");
public Hello() {
super("Welcome");
setSize(WIDTH, HEIGHT);
setLayout(new FlowLayout());
add(hi);
add(button);
add(greeting);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source == button) {
String greet = "example " + name;
greeting.setText(greet);
add(next);
}
}
public static void main(String[] args) {
Exampl frame= new Exampl();
frame.setVisible(true);
}
}
My recommendations for you:
Don't extend JFrame, instead extend JPanel. See: Extends Frame vs creating it inside the program and Why shouldn't you extend JFrame and other components
Don't use multiple JFrames. See The use of multiple JFrames, good / bad practice? (BAD) instead you might want to try using Card Layout or JDialogs
What do you mean by extend? do you mean "public class Hello extends Exampl"? I'm new to java so I don't know much.
From that comment on another answer, you might want to learn the basics first in console applications before going into a GUI application which adds more complexity to your programs and thus your learning.
I'm planning on doing a project where I add the inputted name and a random int into a file so I can store it. Or would it make more sense to add that code into the same class?
From that comment, you can create a public method which returns the value in a JTextField in the format you need, then call that method from the other class, for example:
public String getUserName() {
return userNameField.getText();
}
public int getDigit() {
try {
return Integer.parseInt(digitField.getText());
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
}
return -1; //In case it's not a number, or return 0, or whatever you need
}
//------In another class------//
int digit = object1.getDigit(); //Where object1 is an instance of the other class where those methods are defined
Make a getter in first class and extends second one class then use super.getter();

Cannot set JLabel to Multiple Text Values

My JLabel isn't being set to all of these text values.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class MultipleLables{
static JFrame framey;
static JLabel lbl;
static JButton btn;
public static void GUIWindow () {
framey = new JFrame("Test");
framey.setSize(100, 100);
framey.setLayout(new FlowLayout());
lbl = new JLabel("Example Text");
btn = new JButton("Change Text");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
lbl.setText("First Text");
Thread.sleep(1000);
lbl.setText("Second Text");
Thread.sleep(1000);
lbl.setText("Third Text");
}catch (Exception e) {
//Don't really care if the program dies
}
}
});
framey.add(lbl);
framey.add(btn);
framey.setVisible(true);
}
public static void main(String[] args) {
GUIWindow();
}
}
The output would waits two seconds, then set the value of the JLabel to "Text Three" instead of displaying the three values one after another. I don't see what I'm doing wrong here.
From the question, It is not clear what is the problem you are facing. Please add an example of the code that others can run and test.
If you are trying to see the value of the variables a, b or 'c' in the JLabel , you will need code like
GUIWindow.text.setText(a.toString());
What you are doing now is setting the text "a" and not the value of variable a.
I am not sure what is the data type of the variables a, b or 'c'. If they do have a proper toString() implementation (they probably do as the System.out.println() is giving you the desired output), the above code should work. Else you might need to call the right method on these variables that will give you the desired text.
I was able to fix this issue by creating and running a swing timer. Here is the code, with the fix inside it.
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.*;
public class MulttipleLables{
static JFrame framey;
static JLabel lbl;
static JButton btn;
static Timer t;
static int i;
public static void GUIWindow () {
framey = new JFrame("Test");
framey.setSize(100, 100);
framey.setLayout(new FlowLayout());
lbl = new JLabel("Example Text");
btn = new JButton("Change Text");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e1) {
t = new Timer (1000,new ActionListener() {
public void actionPerformed(ActionEvent e2) {
;
lbl.setText("First Text");
switch (i) {
case 1:
lbl.setText("Second Text");
i++;
break;
case 2:
lbl.setText("Third Text");
i++;
break;
default:
i++;
}
if (i == 3) {
t.stop();
i = 0;
}
}
});
t.start();
}
});
framey.add(lbl);
framey.add(btn);
framey.setVisible(true);
}
public static void main(String[] args) {
GUIWindow();
}
}
I don't have a compiler on me, but I am sure this code should work for what you need.

Editable JComboBox gives error: <identifier> expected and illegal start of type

I am trying to create and Editable JComboBox to allow the user to type the name of the song to purchase. However when I set tunes.setEditable(true); I get an error... any help will be appreciated!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JTextArea;
public class JTunes2 extends JFrame implements ItemListener
{
int songNum,songPrice;
int[] songAmount = {2,5,8,1,4,7,12,10,11,3,6,9};
String result;
JComboBox tunes = new JComboBox();
// set as editable
tunes.setEditable(true);
JLabel labelTunes = new JLabel("Song List");
JLabel outputs = new JLabel();
FlowLayout layout = new FlowLayout();
public JTunes2()
{
super("Song Selector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(layout);
// add song names to combo box and register an item listener.
tunes.addItem("Song1");
tunes.addItem("Song2");
tunes.addItem("Song3");
tunes.addItem("Song4");
tunes.addItem("Song5");
tunes.addItem("Song6");
tunes.addItem("Song7");
tunes.addItem("Song8");
tunes.addItem("Song9");
tunes.addItem("Song10");
tunes.addItem("Song11");
tunes.addItem("Song12");
tunes.addItemListener(this);
panel.add(labelTunes);
panel.add(tunes);
panel.add(outputs);
//add panel to the frame
setContentPane(panel);
}
public void itemStateChanged(ItemEvent e)
{
//create source object
Object source = e.getSource();
//check the type size
if(source == tunes)
{
songNum = tunes.getSelectedIndex();
songPrice = songAmount[songNum];
result = "Total Price $" + songPrice;
//Display result
outputs.setText(result);
}
}
public static void main(String[] args)
{
// create class object
JTunes frame = new JTunes();
frame.setSize(250, 180);
frame.setVisible(true);
}
}
Thank you!
Actually, Java requires that you setup JComponents in the constructor. In order for your code to work, you need to call on setEditable(true) in the constructor, which means that you just need to move tunes.setEditable(true); to the constructor.
Tip: always allocate memory for JComponents in the constructor (you want to draw the components as soon as you create the Jframe). You can have a reference to the JComboBox at the class level.
Here is another version of your code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JTextArea;
public class JTunes2 extends JFrame implements ItemListener
{
int songNum,songPrice;
int[] songAmount = {2,5,8,1,4,7,12,10,11,3,6,9};
String result;
JComboBox tunes;
JLabel labelTunes = new JLabel("Song List");
JLabel outputs = new JLabel();
FlowLayout layout = new FlowLayout();
public JTunes2()
{
super("Song Selector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(layout);
tunes = new JComboBox();
// set as editable
tunes.setEditable(true);
// add song names to combo box and register an item listener.
tunes.addItem("Song1");
tunes.addItem("Song2");
tunes.addItem("Song3");
tunes.addItem("Song4");
tunes.addItem("Song5");
tunes.addItem("Song6");
tunes.addItem("Song7");
tunes.addItem("Song8");
tunes.addItem("Song9");
tunes.addItem("Song10");
tunes.addItem("Song11");
tunes.addItem("Song12");
tunes.addItemListener(this);
panel.add(labelTunes);
panel.add(tunes);
panel.add(outputs);
//add panel to the frame
setContentPane(panel);
}
public void itemStateChanged(ItemEvent e)
{
//create source object
Object source = e.getSource();
//check the type size
if(source == tunes)
{
songNum = tunes.getSelectedIndex();
songPrice = songAmount[songNum];
result = "Total Price $" + songPrice;
//Display result
outputs.setText(result);
}
}
public static void main(String[] args)
{
// create class object
JTunes2 frame = new JTunes2();
frame.setSize(250, 180);
frame.setVisible(true);
}
}
You added the tunes.setEditable(true) at the class level, instead of at the method level. No statements allowed at the class level!
Here's a fixed version: I renamed JTunes2 to JTunes to fix the compilation errors, and moved the setEditable to the constructor. Also I fixed the indentation - this makes it harder to make this mistake:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JTextArea;
public class JTunes extends JFrame implements ItemListener
{
int songNum,songPrice;
int[] songAmount = {2,5,8,1,4,7,12,10,11,3,6,9};
String result;
JComboBox tunes = new JComboBox();
JLabel labelTunes = new JLabel("Song List");
JLabel outputs = new JLabel();
FlowLayout layout = new FlowLayout();
public JTunes()
{
super("Song Selector");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(layout);
tunes.setEditable(true);
// add song names to combo box and register an item listener.
tunes.addItem("Song1");
tunes.addItem("Song2");
tunes.addItem("Song3");
tunes.addItem("Song4");
tunes.addItem("Song5");
tunes.addItem("Song6");
tunes.addItem("Song7");
tunes.addItem("Song8");
tunes.addItem("Song9");
tunes.addItem("Song10");
tunes.addItem("Song11");
tunes.addItem("Song12");
tunes.addItemListener(this);
panel.add(labelTunes);
panel.add(tunes);
panel.add(outputs);
//add panel to the frame
setContentPane(panel);
}
public void itemStateChanged(ItemEvent e)
{
//create source object
Object source = e.getSource();
//check the type size
if(source == tunes)
{
songNum = tunes.getSelectedIndex();
songPrice = songAmount[songNum];
result = "Total Price $" + songPrice;
//Display result
outputs.setText(result);
}
}
public static void main(String[] args)
{
// create class object
JTunes frame = new JTunes();
frame.setSize(250, 180);
frame.setVisible(true);
}
}

about ItemEvent in java GUI

I'm doing a small program with Java GUI
here is mu code:
// DebugFourteen3
// User selects pizza topping and sees price
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//use correct spelling of class name
public class DebugFourteen3 extends JFrame
{
FlowLayout flow = new FlowLayout();
JComboBox pizzaBox = new JComboBox();
JLabel toppingList = new JLabel("Topping List");
JLabel aLabel = new JLabel("Paulos's American Pie");
JTextField totPrice = new JTextField(10);
int[] pizzaPrice = {7,10,10,8,8,8,8};
int totalPrice = 0;
String output;
int pizzaNum;
public DebugFourteen3()
{
super("Pizza List");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(flow);
add(toppingList);
pizzaBox.addItem("cheese");
pizzaBox.addItem("sausage");
pizzaBox.addItem("pepperoni");
pizzaBox.addItem("onion");
pizzaBox.addItem("green pepper");
pizzaBox.addItem("green olive");
pizzaBox.addItem("black olive");
add(pizzaBox);
add(aLabel);
add(totPrice);
itemStateChanged(this);
}
public static void main(String[] arguments)
{
JFrame frame = new DebugFourteen3();
frame.setSize(200, 150);
frame.setVisible(true);
}
public void itemStateChanged(ItemEvent[] list)
{
Object source = list.getSource();
if(source == pizzaBox)
{
int pizzaNum = pizzaBox.getSelectedIndex();
totalPrice = pizzaPrice[pizzaNum];
output = "Pizza Price $" + totalPrice;
totPrice.setText(output);
}
}
}
the compiler gets me error on line 35, it says itemStateChanged() should receive a argument which type is ItemEvent[] but I'm passing "this"(the class it self)
can anyone explain how the itemStateChanged works with the JComboBox?
thanks
You have to add the listener on the combo box instead of calling the itemStateChanged method directly. Adding the listener will enable the callbacks when the click event happens, and jvm will call the itemStateChanged method automatically as combo box is registered for the event. Replace this line
itemStateChanged(this);
with
pizzaBox.addItemListener(this);
At first, you need to implements ItemListener with JFrame. Than add following line with pizzaBox, this will notify overrided public void itemStateChanged(ItemEvent ev) method ItemListener.
pizzaBox.addItemListener(this);
For details, see this tutorial.
Problem :
1.you are not registering itemListener for JComboBox
2.itemStateChanged event takes ItemEvent as argument not ItemEvent[] array
1.Replace this :
itemStateChanged(this);
with this:
pizzaBox.addItemListener(this);
2.Replace This:
public void itemStateChanged(ItemEvent[] list)
With this:
public void itemStateChanged(ItemEvent list)
Complete Code:
// DebugFourteen3
// User selects pizza topping and sees price
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//use correct spelling of class name
public class DebugFourteen3 extends JFrame
{
FlowLayout flow = new FlowLayout();
JComboBox pizzaBox = new JComboBox();
JLabel toppingList = new JLabel("Topping List");
JLabel aLabel = new JLabel("Paulos's American Pie");
JTextField totPrice = new JTextField(10);
int[] pizzaPrice = {7,10,10,8,8,8,8};
int totalPrice = 0;
String output;
int pizzaNum;
public DebugFourteen3()
{
super("Pizza List");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(flow);
add(toppingList);
pizzaBox.addItem("cheese");
pizzaBox.addItem("sausage");
pizzaBox.addItem("pepperoni");
pizzaBox.addItem("onion");
pizzaBox.addItem("green pepper");
pizzaBox.addItem("green olive");
pizzaBox.addItem("black olive");
add(pizzaBox);
add(aLabel);
add(totPrice);
pizzaBox.addItemListener(this);
}
public static void main(String[] arguments)
{
JFrame frame = new DebugFourteen3();
frame.setSize(200, 150);
frame.setVisible(true);
}
public void itemStateChanged(ItemEvent list)
{
Object source = list.getSource();
if(source == pizzaBox)
{
int pizzaNum = pizzaBox.getSelectedIndex();
totalPrice = pizzaPrice[pizzaNum];
output = "Pizza Price $" + totalPrice;
totPrice.setText(output);
}
}
}
Here this i.e DebugFourteen3 is not a type ItemEvent. Thats why
itemStateChanged(ItemEvent[] list)
gives error.
If you want to handle itemStateChanged then you need to implement ItemLisntener and add actionListner to it as
pizzaBox.addItemListener(this);
also add Handler method of ItemLisntener as
public void itemStateChanged(....)
{
//Handling Code goes here
}
Or you can implement ActionListner also
For more information on how to use combobox you can visit here

Categories

Resources