JComboBox actionListener doesn't function - java

I have a class that has 4 private attributes, and through a JComboBox selection, I want to modify them through calling a procedure. However, it seems like even though the JComboBox appears with the selection, the attributes that are shown don't change.
public class PanneauVehicule extends JPanel {
private String[] vehicules;
private int majCarburant;
private int majPassager;
public class PanneauVehicule extends JPanel {
//Main constructor
public PanneauVehicule(){
//Creates a JPanel
super();
//Sets layout as BorderLayout
setLayout(new BorderLayout());
initListeVehicule();
initLabels();
}
public void initListeVehicule(){
vehicules = new String[] {Constantes.CS100 , Constantes.CS300 ,
Constantes.GREYHOUND102D3 , Constantes.GREYHOUNDG4500 ,
Constantes.TGVATLANTIQUE , Constantes.TGVDUPLEX};
final JComboBox<String> vehiculesList = new JComboBox<>(vehicules);
//Keep in mind the comboBox does appear with the right selections
add(vehiculesList,BorderLayout.NORTH);
//Here's where it doesnt work.
vehiculesList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
majInfo(2,4);
}
});
}
public void majInfo(int test1, int test2){
this.majCarburant = test2;
this.majPassager = test1;
}
public void initLabels(){
JPanel panneauBas = new JPanel();
panneauBas.setLayout(new GridLayout(2,1,5,5));
JLabel labelCarburant = new JLabel();
labelCarburant.setText("Type de caburant: " + this.majCarburant);
JLabel labelPassagers = new JLabel();
labelPassagers.setText("Nb de passagers: " + this.majPassager);
panneauBas.add(labelPassagers);
panneauBas.add(labelCarburant);
add(panneauBas, BorderLayout.SOUTH);
panneauBas.setBackground(Color.WHITE);
}
After that, I use another procedure that will make majCarburant and majPassager appear on screen. However their values are shown as default (0). I can make their values change manually without using an ActionListener, but the task at hand requires me to use one.

I've been trying ways to just simply change the values through actionListener directly,
You don't invoke an ActionListener directly. Once an ActionListener has been added to the combo box, you can invoke:
setSelectedItem(...) or
setSelectedIndex(...)
on the combo box and the combo box will invoke the ActionListener.

I found the solution after a few more hours of meddling. I just integrated the procedure that creates labels into initListeVehicule, and from there the ActionListener can access the labels to modify their texts.
public void initListeVehiculeInfos(){
vehicules = new String[] {Constantes.CS100 , Constantes.CS300 ,
Constantes.GREYHOUND102D3 , Constantes.GREYHOUNDG4500 ,
Constantes.TGVATLANTIQUE , Constantes.TGVDUPLEX};
final JComboBox<String> vehiculesList = new JComboBox<>(vehicules);
add(vehiculesList,BorderLayout.NORTH);
JPanel panneauBas = panelGenerator();
//these setTexts serve as default values before doing your first selection
final JLabel carb = labelGenerator();
carb.setText("Carburant: Kérosène");
final JLabel passager = labelGenerator();
passager.setText("Nb Passager: 110");
vehiculesList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
InterfaceVehicules info = FabriqueVehicule.obtenirVehicule(vehiculesList.getSelectedIndex());
carb.setText("Carburant: " + info.tabNomTypeCarburant[info.getTypeCarburant()] );
passager.setText("Nb Passagers: " + info.getNbPassagersMax());
}
});
panneauBas.add(carb);
panneauBas.add(passager);
add(panneauBas, BorderLayout.SOUTH);
}

Related

Java - get JRadioButton cmd with Jbutton listener

I am new to java and creating a Simple gui App. In this simple app, I am trying to write a e-commerce letter for Firms. So, I planned my app something like this..
First i ask to user if he want to write an letter to British Firm or American. For this i use two radio buttons(one for american firm and second for british) and JButton. When user Trigger jbutton then i want to get radiobutton command(which type of letter user want to write).
The problem is I don't have any idea to get Radiobutton command when i trigger jButton. Please give me an Simple Idea(if possible with exapmle not complicated for begginers) to get RadioButtons value..
Here is my java Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class englet{
static public JFrame f;
static public JPanel p;
static class getTypeOfLetter implements ActionListener{
public void actionPerformed( ActionEvent e){
String btnInput = e.getActionCommand();
System.out.println(btnInput);
}
}
public static void askletter(){
JRadioButton btnRadio1;
JRadioButton btnRadio2;
ButtonGroup btngrp;
JButton btnGo = new JButton("Write");
btnRadio1 = new JRadioButton("Write Letter For American Firm");
btnRadio1.setActionCommand("Amer");
btnRadio2 = new JRadioButton("Write Letter For British Firm");
btnRadio2.setActionCommand("Brit");
btngrp = new ButtonGroup();
btnGo.setActionCommand("WriteTest");
btnGo.addActionListener(new getTypeOfLetter());
btngrp.add(btnRadio1);
btngrp.add(btnRadio2);
p.add(btnRadio1);
p.add(btnRadio2);
p.add(btnGo);
}
englet(){
f = new JFrame("English Letter");
p = new JPanel();
askletter();
f.add(p);
f.setSize(400,200);
f.setVisible(true);
}
public static void main (String[] argv ){
englet i = new englet();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I am using Notepad++ and CMD.. Not any another tools like netbeans initllli ecplisse.
**RE-EDIT ** I want a possible solution and can satisfy me.. this app works but i am not able to get radiobuttons commmand with jubtton..
You've got several issues:
Over-use of static. Most of the fields and methods of your code should be non-static
You're missing key fields that will be necessary to transmit the information needed. To get the selected JRadioButton, you need to make JRadioButton fields and check which is selected, or (and my preference), you need to make the ButtonGroup variable a field and check which JRadioButton has been selected based on the ButtonModel returned by the ButtonGroup.
You're currently using local variables and these won't be visible throughout the class, which is why either the JRadioButtons or the ButtonModel most be fields (declared in the class).
If you go with ButtonModel above, you must give each JRadioButton an appropriate actionCommand String.
For example:
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GetRadio extends JPanel {
private static final String[] FIRMS = {"American Firm", "British Firm"};
// You need this field to access it in your listener
private ButtonGroup buttonGroup = new ButtonGroup();
public GetRadio() {
// create JButton and add ActionListener
JButton button = new JButton("Select");
button.addActionListener(new ButtonListener());
// JPanel with a grid layout with one column and variable number of rows
JPanel radioButtonPanel = new JPanel(new GridLayout(0, 1));
radioButtonPanel.setBorder(BorderFactory.createTitledBorder("Select Firm")); // give it a title
for (String firm : FIRMS) {
// create radiobutton and set actionCommand
JRadioButton radioButton = new JRadioButton(firm);
radioButton.setActionCommand(firm);
// add to button group and JPanel
buttonGroup.add(radioButton);;
radioButtonPanel.add(radioButton);
}
// add stuff to main JPanel
add(radioButtonPanel);
add(button);
}
private class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// get button model of selected radio button from ButtonGroup
ButtonModel model = buttonGroup.getSelection();
// if null, no country selected
if (model == null) {
Component component = GetRadio.this;
String message = "You must first select a country!";
String title = "Error: No Country Selected";
int type = JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(component, message, title, type);
} else {
// valid country selected
String country = model.getActionCommand();
System.out.println("Letter to " + country);
}
}
}
private static void createAndShowGui() {
GetRadio mainPanel = new GetRadio();
JFrame frame = new JFrame("Get Radio Btn");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

How can I pass an ArrayList between two separate JTabbedPanes

I have a program utilizing JTabbedPane. On one pane I have a button that updates an arrayList of objects based on input from the same pane.
What I would like to happen is have the second pane update itself with the object information based on the arrayList in the first pane.
However, I am not sure how to pass the list between the panes. Is there some way to push the array to pane #2 when the update button on the first pane is pressed?
Here is the main file. Instantiating the two tabs
public class Assignment6 extends JApplet
{
private int APPLET_WIDTH = 650, APPLET_HEIGHT = 350;
private JTabbedPane tPane;
private StorePanel storePanel;
private PurchasePanel purchasePanel;
private ArrayList computerList;
public void init()
{
computerList = new ArrayList();
storePanel = new StorePanel(computerList, purchasePanel);
purchasePanel = new PurchasePanel(computerList);
tPane = new JTabbedPane();
tPane.addTab("Store Inventory", storePanel);
tPane.addTab("Customer Purchase", purchasePanel);
getContentPane().add(tPane);
setSize (APPLET_WIDTH, APPLET_HEIGHT); //set Applet size
}
}
The first panel instantiates a button listener that applies all of the logic to the array list "compList"
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
//Add Computer to list
Computer comp = new Computer();
comp.setBrandName(brandField.getText());
comp.setPrice(Double.parseDouble(priceField.getText()));
comp.setMemory(Integer.parseInt(memoryField.getText()));
comp.setCPU(typeField.getText(), Integer.parseInt(speedField.getText()));
compList.add(comp);
}
stringField.setText(listString);
alertLabel.setText("Computer Added");
}
}
Here is the other pane. The for loop at the end is what I need to push the arrayList to. After it receives the list, it populates a box with a checkbox for each object in the list
public PurchasePanel(ArrayList compList)
{
west = new JPanel();
east = new JPanel();
totalField = new JTextField();
this.compList = compList;
setLayout(new GridLayout(0,2));
add(west);
add(east);
east.setLayout(new BorderLayout());
east.add(currentTotalLabel, BorderLayout.NORTH);
east.add(totalField, BorderLayout.CENTER);
west.setLayout( new BoxLayout(west, BoxLayout.Y_AXIS));
for(Object c : compList){
System.out.println("Made it");
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String str = ("BrandName:" + (((Computer) c).getBrandName() +"CPU:" + (((Computer) c).getCPU() +"Memory:" + ((Computer) c).getMemory() + "M" +"Price:" + fmt.format(((Computer) c).getPrice()))));
JCheckBox chk = new JCheckBox(str);
west.add(chk);
}
}
}
You can use the same listener used to update the first ArrayList, to update the second pane. Something like:
jButton1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Update the first ArrayList
// Update the second pane
}

Change JTextArea texts from JButton's actionPerformed which is in another class

I have a fully functional console-based database which I need to add GUIs to. I have created a tab page (currently only one tab) with a button "Display All Student" which when triggered will display a list of students inside a JTextArea which of course is in its own class and not inside the button's action listener class. Problem is, the JTextArea is not recognised inside button's action listener. If I add parameter into the action listener, more errors arise. Help?
I have searched Stack Overflow for similar problems but when I tried it in my code, doesn't really do the trick? Or maybe I just need a nudge in the head. Anyways.
Here is my code so far:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class StudDatabase extends JFrame
{
private JTabbedPane tabbedPane;
private JPanel studentPanel;
private static Scanner input = new Scanner(System.in);
static int studentCount = 0;
static Student studentArray[] = new Student[500];
public StudDatabase()
{
setTitle("Student Database");
setSize(650, 500);
setBackground(Color.gray);
JPanel topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
getContentPane().add( topPanel );
// Create the tab pages
createStudentPage();
// more tabs later...
// Create a tab pane
tabbedPane = new JTabbedPane();
tabbedPane.addTab( "Student Admin", studentPanel );
topPanel.add( tabbedPane, BorderLayout.CENTER );
}
public void createStudentPage()
{
studentPanel = new JPanel();
studentPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
JButton listButton = new JButton("List All Student(s)");
listButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
if(studentCount > 0)
{
for(int i=0; i<studentCount; i++)
{
// print out the details into JTextArea
// ERROR! textDisplay not recognised!!!
textDisplay.append("Student " + i);
}
System.out.printf("\n");
}
else // no record? display warning to user
{
System.out.printf("No data to display!\n\n");
}
}
});
studentPanel.add(listButton);
JTextArea textDisplay = new JTextArea(10,48);
textDisplay.setEditable(true); // set textArea non-editable
JScrollPane scroll = new JScrollPane(textDisplay);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
studentPanel.add(scroll);
}
public static void main(String[] args)
{
StudDatabase mainFrame = new StudDatabase();
mainFrame.setVisible(true);
}
Your code isn't working for the same reason this wouldn't work:
int j = i+5;
int i = 4;
You have to declare variables before using them in Java.
Secondly, in order to use a variable (local or instance) from inside an inner class - which is what your ActionListener is - you need to make it final.
So, the below code will compile and run:
final JTextArea textDisplay = new JTextArea(10,48);
...
listButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
...
textDisplay.append("Student " + i);

Deleting selected checkboxes using java swing

I am new to java swing. I have a code that generates checkboxes. I want to have a button somewhere in my frame, which on clicking, should delete the selected checkbox entries. Here is what I have so far.
public class Scroll extends JPanel {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame frame = new JFrame("JFrame with ScrollBar");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new ResultButtonBar();
newContentPane.setOpaque(true);
JScrollPane scrollPane = new JScrollPane(newContentPane);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
frame.getContentPane().add(scrollPane);
frame.setSize(800, 800);
frame.setVisible(true);
JButton startButton = new JButton("Start");
frame.add(startButton, BorderLayout.SOUTH);
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
JOptionPane.showMessageDialog(null, "basdsadad");
}
});
}
}
and the new ResultButtonBar().java
public class ResultButtonBar extends JPanel {
private HashMap<JCheckBox, ArrayList<Integer>> map = new HashMap<>();
private JLabel _label;
private static final int MAX_CHECKS = 1000;
public ResultButtonBar() {
super();
JButton btn = new JButton();
btn.setVisible(true);
JCheckBox checkBox;
Random r = new Random();
JPanel checkPanel = new JPanel(new GridLayout(0, 1));
_label = new JLabel("You selected nothing");
checkPanel.add(_label);
for (int i = 0; i < MAX_CHECKS; i++) {
StringBuilder sb = new StringBuilder();
ArrayList<Integer> a = new ArrayList<>();
for (int j = 0; j < 2; j++) {
Integer temp = (r.nextInt()) % 100;
a.add(temp);
sb.append(temp).append(" ");
}
checkBox = new JCheckBox(sb.toString().trim());
checkBox.setName("CheckBox" + i);
map.put(checkBox, a);
checkPanel.add(checkBox);
}
add(checkPanel);
}
}
First of all, keep all your check boxes in an ArrayList so you will have a reference to them when you need it.
Then, add a JButton wherever you need. Then iterate over this ArrayList and call invalidate() on the component which contains your check boxes. Next statement would be to call the remove() method on the container; the checkPanel.
Alternatively, you may call removeAll() if all the components in the container are check boxes and you want to remove them.
The alternative pointed by StanislavL is also a good one if you have a lot of different components along with check boxes
I can think of two approaches:
if You are maintaining one JPanel instance which contains only the instances of JCheckBox, then you can first get all the checkbox's using panel.getComponents() method, check their selection state and depending on the state remove it by calling panel.remove(component). For example:
Component checkBox[] = checkBoxPanel.getComponents();
for(Component c:checkBox)
if(((JCheckBox)c).isSelected())
checkBoxPanel.remove(c);
checkBoxPanel.revalidate();
checkBoxPanel.repaint();
The last call revalidate() and repaint() on the checkBoxPanel is important for reflecting changes on the layout and graphics rendering of the components.
You can use ItemListener with the instances of JCheckBox to do things on selection state change. Use an instance of ArrayList<JCheckBox> to add the selected checkBox to the list. However you should use an implemented ItemListener: MyItemListener implements ItemListener and create one instance and add this instances to all the checkboxes to react on state change. You can use event source e.getSource() to get the JCheckBox instance on which the ItemEvent is performed.
Tutorial resource:
How to Write an Item Listener

Java getter not working?

Ok so i have a comboBox, and a JTextField, whenever i chose the quantity, it would be displayed on the textfield. I have another class, which will retrieve the whatever inside the textfield, but the order class doesn't retrieve the information from catalogue class.
class Catalogue extends JPanel {
String[] h1Quantity = {"0","1","2","3","4","5","6","7","8","9","10"};
h1CBox = new JComboBox <String> (h1Quantity);
h1CBox.setSelectedIndex(0);
h1CBox.addActionListener (new Listener());
h1CBox.setPreferredSize ( new Dimension (50,30));
JLabel noBooks = new JLabel ("Quantity");
booksF = new JTextField(8);
public class Listener implements ActionListener {
public void actionPerformed (ActionEvent event) {
int total = h1CBox.getSelectedIndex();
booksF.setText(Integer.toString(total));
}
}
public String booksFText() {
return booksF.getText();
}
}
class Order extends JPanel {
Catalogue catalogue ;
public Order (Catalogue catalogue)
{
this.catalogue = catalogue;
JPanel panel = new JPanel ();
String text2= catalogue.booksFText();
textArea1 = new JTextArea (text2, 20, 35);
add(textArea1);
add(panel);
}
}
I'm new to java so please keep it simple. thanks alot.
You have 2 constructors in the Order class and catalogue is only set in the first one. Set this in the second contructor as well and the NPE should go away (although hard to know for sure without the stacktrace!)
Always try to post complete code. and stack trace too.
See your order class.
class Order extends JPanel {
public Order (Catalogue catalogue)
{
add(textArea);
}
}
If you use the second constructor , then the class variable catalogue will not be given memory. Thus NULL POINTER EXCEPTION . The code inside the second constructor has been moved to the first one.
The other reason may be that the variable being passed in order constructor is not defined properly. Should be done something like this.
Catalogue catalogue = new Catalogue();
Order order = new Order(catalogue);
See Updated Catalogue class.
class Catalogue extends JPanel {
String[] h1Quantity = {"0","1","2","3","4","5","6","7","8","9","10"};
JComboBox<String> h1CBox ; //Assuming you forgot to define it.
JLabel noBooks ;
JTextField booksF ;
//Define a new constructor
public Catalogue () {
//set jlabel
noBooks = new JLabel ("Quantity");
//set combobox
h1CBox = new JComboBox <String> (h1Quantity);
h1CBox.setSelectedIndex(0);
h1CBox.addActionListener (new Listener());
h1CBox.setPreferredSize ( new Dimension (50,30));
//set textfield
booksF = new JTextField(8);
//add UI items to your panel class
add(h1CBox); //combobox
add(noBooks); // label
add(booksF); // textfield
}
public class Listener implements ActionListener {
public void actionPerformed (ActionEvent event) {
int total = h1CBox.getSelectedIndex();
booksF.setText(Integer.toString(total));
}
}
public String booksFText() {
return booksF.getText();
}
}
Always define your UI like this . Of course , there are better ways . Thus code looks clean and you understand things. Learn to put comments to remind you what you tried to do somewhere.
The MAIN Class
public class Main {
static JTextArea textArea = new JTextArea(40,40);
static class Order extends JPanel{
public Order(){
add(textArea);
}
}
static class Catalogue extends JPanel{
....
private ActionListener listener = new ActionListener(){
public void actionPerformed(ActionEvent event){
textArea.setText(h1CBox.getSelectedIndex()+"");
}
};
}
public static void main(String args[]){
//Construct a frame and add panels and you are good to go.
}
}
One last suggestion, if you plan on NOT changing the data of textarea yourself , use textfield or label instead of textarea. Sometimes the text inside textarea is set , but user is unable to see because of improper bounds . So , to be sure just replace the textarea with label or textfield. Cheers :)

Categories

Resources