Storing JList selections in an array String[] in Java - java

I am creating a GUI, and can't figure out how to store the JList user selections in an array. I tried List<<Sting>>, Object[] etc... JRadioButtons and other GUIs are fine, only JList is not working...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test extends JFrame {
private JTextField num3;
private JLabel label3;
private JButton button;
private JRadioButton radio2;
private JRadioButton radio3;
private ButtonGroup radioGroup;
private JList statesList;
String[] states = {"Alabama", "Alaska", "Wyoming"};
String expression;
String frequency;
// no args constructor
public Test() {
createUI();
}
private void createUI() {
Container contentPane = getContentPane();
contentPane.setLayout(null);
label3 = new JLabel();
label3.setText("Search Expression");
label3.setBounds(16, 120, 200, 21);
contentPane.add(label3);
num3 = new JTextField();
num3.setText("(any expression)");
num3.setBounds(16, 144, 150, 21);
num3.setHorizontalAlignment(JTextField.LEFT);
contentPane.add(num3);
button = new JButton("Start!");
button.setBounds(90,430,126,24);
contentPane.add(button);
button.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event)
{
buttonActionPerformed(event);
}
}
);
// States Selection
statesList = new JList(states);
statesList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
statesList.setVisibleRowCount(5);
statesList.setBounds(400, 16, 100, 50);
JScrollPane statesScroll = new JScrollPane(statesList);
statesScroll.setBounds(180, 16, 135, 400);
contentPane.add(statesScroll);
// Radio Buttons
radio2 = new JRadioButton();
radio3 = new JRadioButton();
radio3.setSelected(true);
radioGroup = new ButtonGroup();
radioGroup.add(radio2);
radioGroup.add(radio3);
radio2.setText("Quarterly");
radio3.setText("Yearly");
radio2.setBounds(16,360,90,23);
radio3.setBounds(16,385,75,23);
contentPane.add(radio2);
contentPane.add(radio3);
// set the content Pane window
setTitle("Search Engine");
setSize(750,500);
setVisible(true);
}
// Getting the user's TextField and JRadioButton input
private void buttonActionPerformed(ActionEvent event) {
expression = num3.getText();
if (radio2.isSelected())
frequency = "quarterly";
else frequency = "yearly";
System.out.println(expression+","+frequency);
// The above "expression" and "frequency" work fine. But JList does not
// work. What am I doing wrong? I tried Object[] instead of List<String>...
List<String> values = statesList.getSelectedValues();
return values==null ? null : values.toArray(new String[values.size()]);
}
// main thread
public static void main(String[] args) {
Test application = new Test();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

This variant iterates the Object[] returned by getSelectedValues() to show expected values in the console. Next thing to fix is the layouts.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//public class Test extends JFrame {
public class Test {
private JTextField num3;
private JLabel label3;
private JButton button;
private JRadioButton radio2;
private JRadioButton radio3;
private ButtonGroup radioGroup;
private JList statesList;
String[] states = {"Alabama", "Alaska", "Wyoming"};
String expression;
String frequency;
// no args constructor
public Test() {
createUI();
}
private void createUI() {
JFrame f = new JFrame("Search Engine");
Container contentPane = f.getContentPane();
// This needs fixing NEXT!
contentPane.setLayout(null);
label3 = new JLabel();
label3.setText("Search Expression");
label3.setBounds(16, 120, 200, 21);
contentPane.add(label3);
num3 = new JTextField();
num3.setText("(any expression)");
num3.setBounds(16, 144, 150, 21);
num3.setHorizontalAlignment(JTextField.LEFT);
contentPane.add(num3);
button = new JButton("Start!");
button.setBounds(90,430,126,24);
contentPane.add(button);
button.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent event) {
buttonActionPerformed(event);
}
});
// States Selection
statesList = new JList(states);
statesList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
statesList.setVisibleRowCount(5);
statesList.setBounds(400, 16, 100, 50);
JScrollPane statesScroll = new JScrollPane(statesList);
statesScroll.setBounds(180, 16, 135, 400);
contentPane.add(statesScroll);
// Radio Buttons
radio2 = new JRadioButton();
radio3 = new JRadioButton();
radio3.setSelected(true);
radioGroup = new ButtonGroup();
radioGroup.add(radio2);
radioGroup.add(radio3);
radio2.setText("Quarterly");
radio3.setText("Yearly");
radio2.setBounds(16,360,90,23);
radio3.setBounds(16,385,75,23);
contentPane.add(radio2);
contentPane.add(radio3);
// set the content Pane window
f.setSize(750,500);
//f.pack();
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setVisible(true);
}
// Getting the user's TextField and JRadioButton input
private void buttonActionPerformed(ActionEvent event) {
expression = num3.getText();
if (radio2.isSelected())
frequency = "quarterly";
else frequency = "yearly";
System.out.println(expression+","+frequency);
Object[] values = statesList.getSelectedValues();
for (Object state : values) {
System.out.println(state);
}
}
// main thread
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
Test application = new Test();
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
Tips
Don't extend frame, just use an instance.
J2SE GUIs (Swing & AWT) should be created and updated on the EDT. See Concurrency in Swing - Initial Threads especially.
contentPane.setLayout(null); This will not work in the real world (read probably the next PC as 'the real world'). Use layout managers for a robust GUI. See Laying Out Components Within a Container for details, and also this nested layout example for grouping layouts according to need.

According to the documentation, getSelectedValues returns an object array.
Object[] values = statesList.getSelectedValues();
If you're positive they're all strings, you can just type cast them.
String[] values = (String[]) statesList.getSelectedValues();
Edit: Try this:
Object[] values = statesList.getSelectedValues();
String[] strings = new String[values.length];
for(int i = 0; i < values.length; i++) {
if(values[i] instanceof String) {
strings[i] = ((String) values[i]);
}
}

Related

How to use single ActionListener for JCheckBox and JTextField

I am writing an eJuice Calculator. Its nowhere near finished as you will see below. My question is: I have 4 JCheckBoxes, and 5 editable JTextFields; can I use one ActionListener to do have the program execute stuff. Or do I need one listener for the CheckBoxes and one for the TextField?
This is a rough draft of code.
package ejuicecalculatorv2;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EJuiceCalculatorV2 extends JFrame {
//Form Controls
private JCheckBox isPGbasedNic_CB = new JCheckBox("PG Based NIC");
private JCheckBox isPGbasedFlavor_CB = new JCheckBox("PG Based Flavor");
private JCheckBox isVGbasedNic_CB = new JCheckBox("VG Based NIC");
private JCheckBox isVGbasedFlavor_CB = new JCheckBox("VG Based Flavor");
private JTextField batchSize_TF = new JTextField(5);
private JLabel batchSize_LB = new JLabel("Batch Size:");
private JTextField baseNicStrength_TF = new JTextField(5);
private JLabel baseNicStrength_LB = new JLabel("Base NIC Strength:");
private JTextField targetNicStrength_TF = new JTextField(5);
private JLabel targetNicStrength_LB = new JLabel("Target NIC Strength:");
private JTextField totalNic_TF = new JTextField(5);
private JLabel totalNic_LB = new JLabel("Total NIC:");
private JTextField flavorStrength_TF = new JTextField(5);
private JLabel flavorStrength_LB = new JLabel("Flavoring Strength:");
private JTextField totalFlavor_TF = new JTextField(5);
private JLabel totalFlavor_LB = new JLabel("Total Flavoring:");
private JTextField vgRatio_TF = new JTextField(5);
private JLabel vgRatio_LB = new JLabel("VG Ratio:");
private JTextField pgRatio_TF = new JTextField(5);
private JLabel pgRatio_LB = new JLabel("PG Ratio:");
private JTextField additionalVG_TF = new JTextField(5);
private JLabel additionalVG_LB = new JLabel("Additional VG:");
private JTextField additionalPG_TF = new JTextField(5);
private JLabel additionalPG_LB = new JLabel("Additional PG:");
private JTextField totalVG_TF = new JTextField(5);
private JLabel totalVG_LB = new JLabel("Total VG:");
private JTextField totalPG_TF = new JTextField(5);
private JLabel totalPG_LB = new JLabel("Total PG:");
private JTextField vgBasedIng_TF = new JTextField(5);
private JLabel vgBasedIng_LB = new JLabel("Total VG Ingredients:");
private JTextField pgBasedIng_TF = new JTextField(5);
private JLabel pgBasedIng_LB = new JLabel("Total PG Ingredients:");
//Variables
private boolean _PGnicFlag;
private boolean _VGnicFlag;
private boolean _PGflavorFlag;
private boolean _VGflavorFlag;
private double baseNic;
private double targetNic;
private double totalNic;
private double flavorStrength;
private double totalFlavor;
private double batchSize;
private double totalPG;
private double totalVG;
private double additionalVG;
private double additionalPG;
private double pgBasedIng;
private double vgBasedIng;
private double pgRatio;
private double vgRatio;
public EJuiceCalculatorV2() {
super("EJuice Calculator V2");
setLayout(new FlowLayout());
//Add CheckBoxes
add(isPGbasedNic_CB);
add(isPGbasedFlavor_CB);
add(isVGbasedNic_CB);
add(isVGbasedFlavor_CB);
//Add TextFields and Labels
add(batchSize_LB);
add(batchSize_TF);
add(vgRatio_LB);
add(vgRatio_TF);
add(pgRatio_LB);
add(pgRatio_TF);
add(baseNicStrength_LB);
add(baseNicStrength_TF);
add(targetNicStrength_LB);
add(targetNicStrength_TF);
add(flavorStrength_LB);
add(flavorStrength_TF);
//Add ActionListeners
ActionListener actionListener = new ActionHandler();
isPGbasedNic_CB.addActionListener(actionListener);
isPGbasedFlavor_CB.addActionListener(actionListener);
isVGbasedNic_CB.addActionListener(actionListener);
isVGbasedFlavor_CB.addActionListener(actionListener);
batchSize_TF.addActionListener(actionListener);
vgRatio_TF.addActionListener(actionListener);
pgRatio_TF.addActionListener(actionListener);
baseNicStrength_TF.addActionListener(actionListener);
targetNicStrength_TF.addActionListener(actionListener);
flavorStrength_TF.addActionListener(actionListener);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class ActionHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent event){
//if event.getSource() == JCheckBox then execute the following code.
if(checkBox.isSelected()){
if(checkBox == isPGbasedNic_CB){
_PGnicFlag = true;
_VGnicFlag = false;
checkBox = isVGbasedNic_CB;
checkBox.setSelected(false);
}
else if(checkBox == isVGbasedNic_CB){
_VGnicFlag = true;
_PGnicFlag = false;
checkBox = isPGbasedNic_CB;
checkBox.setSelected(false);
}
else if(checkBox == isVGbasedFlavor_CB){
_VGflavorFlag = true;
_PGflavorFlag = false;
checkBox = isPGbasedFlavor_CB;
checkBox.setSelected(false);
}
else if(checkBox == isPGbasedFlavor_CB){
_PGflavorFlag = true;
_VGflavorFlag = false;
checkBox = isVGbasedFlavor_CB;
checkBox.setSelected(false);
}
}
else{
if(checkBox == isPGbasedNic_CB){
_PGnicFlag = false;
_VGnicFlag = true;
}
else if(checkBox == isVGbasedNic_CB){
_VGnicFlag = false;
_PGnicFlag = true;
}
else if(checkBox == isVGbasedFlavor_CB){
_VGflavorFlag = false;
_PGflavorFlag = true;
}
else if(checkBox == isPGbasedFlavor_CB){
_PGflavorFlag = false;
_VGflavorFlag = true;
}
}
}
}
public static void main(String[] args) {
// TODO code application logic here
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run (){
new EJuiceCalculatorV2().setVisible(true);
}
});
}
}
My question is: I have 4 JCheckBoxes, and 5 editable JTextFields; can I use one ActionListener to do have the program execute stuff. Or do I need one listener for the CheckBoxes and one for the TextField?
You have a bunch of control components, but none appear ones that would initiate an action from the GUI. Rather all of them, the JCheckBoxes and the JTextFields are there to get input, and you appear to be missing one final component, such as a JButton. I would add this component to your GUi, and I would add a single ActionListener to it and it alone. And then when pressed, it would check the state of the check boxes and the text components and then based on their state, give the user the appropriate response.
Also some, if not most or all of the JTextFields, I'd change to either JComboBoxes or JSpinners, to limit the input that the user can enter to something that is allowable since you don't want the user entering "yes" into the "Batch Size" JTextField.
For example:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.JSpinner.DefaultEditor;
#SuppressWarnings("serial")
public class JuiceTwo extends JPanel {
private static final String[] FLAVORS = {"Flavor 1", "Flavor 2", "Flavor 3", "Flavor 4"};
private static final Integer[] ALLOWABLE_BATCH_SIZES = {1, 2, 5, 10, 15, 20};
private static final String[] ALLOWABLE_VG_RATIOS = {"1/4", "1/3", "1/2", "1/1", "2/1", "3/1", "4/1", "8/1", "16/1"};
private List<JCheckBox> flavorBoxes = new ArrayList<>();
private JComboBox<Integer> batchSizeCombo;
private JSpinner vgRatioSpinner;
public JuiceTwo() {
// JPanel to hold the flavor JCheckBoxes
JPanel flavorPanel = new JPanel(new GridLayout(0, 1)); // hold them in vertical grid
flavorPanel.setBorder(BorderFactory.createTitledBorder("Flavors"));
for (String flavor : FLAVORS) {
JCheckBox flavorBox = new JCheckBox(flavor);
flavorBox.setActionCommand(flavor);
flavorPanel.add(flavorBox);
flavorBoxes.add(flavorBox);
}
batchSizeCombo = new JComboBox<>(ALLOWABLE_BATCH_SIZES);
SpinnerListModel vgRatioModel = new SpinnerListModel(ALLOWABLE_VG_RATIOS);
vgRatioSpinner = new JSpinner(vgRatioModel);
JComponent editor = vgRatioSpinner.getEditor();
if (editor instanceof DefaultEditor) {
((DefaultEditor)editor).getTextField().setColumns(4);
}
JButton getSelectionButton = new JButton("Get Selection");
getSelectionButton.setMnemonic(KeyEvent.VK_S);
getSelectionButton.addActionListener(new SelectionActionListener());
add(flavorPanel);
add(Box.createHorizontalStrut(20));
add(new JLabel("Batch Size:"));
add(batchSizeCombo);
add(Box.createHorizontalStrut(20));
add(new JLabel("VG Ratio:"));
add(vgRatioSpinner);
add(Box.createHorizontalStrut(20));
add(getSelectionButton);
}
private class SelectionActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
for (JCheckBox flavorBox : flavorBoxes) {
System.out.printf("%s selected: %b%n", flavorBox.getActionCommand(), flavorBox.isSelected());
}
System.out.println("Batch Size: " + batchSizeCombo.getSelectedItem());
System.out.println("VG Ration: " + vgRatioSpinner.getValue());
System.out.println();
}
}
private static void createAndShowGui() {
JuiceTwo mainPanel = new JuiceTwo();
JFrame frame = new JFrame("JuiceTwo");
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(() -> createAndShowGui());
}
}

Getting JButton To Work

right now I have some buttons on a calculator and they are not setup. I am confused as to how to get them to print something in the JTextField when clicked. I am aware that you need to use ActionListener, but I cannot seem to get it working. Thanks for your help!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JPanel implements ActionListener {
private JTextField tf = null;
private JButton[] arrBtn = null;
private String[] btnNames = { "1", "2", "3", "4", "5", "6", "7", "CE", "-", "+", "/", "%", "*", "=" };
private JPanel jp = new JPanel();
private char op = ' ';
private int num1 = 0;
private int num2 = 0;
private int result = 0;
private boolean isOpPressed = false;
private JPanel btnPl;
public Calculator() {
super();
jp = new JPanel();
jp.setLayout(new GridLayout(3, 3));
btnPl = new JPanel();
btnPl.setLayout(new GridLayout(4, 4));
jp.add(new JTextField());
jp.add(new JTextField());
jp.add(new JTextField());
jp.add(new JTextField());
jp.add(new JTextField());
jp.add(new JTextField());
arrBtn = new JButton[btnNames.length];
for (int i = 0; i < arrBtn.length; i++) {
arrBtn[i] = new JButton(btnNames[i]);
arrBtn[i].addActionListener(this);
btnPl.add(arrBtn[i]);
}
this.setLayout(new BorderLayout());
this.add(jp, BorderLayout.NORTH);
this.add(btnPl, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent e) {
}
public static void main(String args[]) {
new Calculator();
JFrame frame = new JFrame("Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
RomanCalculator cal = new RomanCalculator();
frame.add(cal);
frame.pack();
frame.setSize(500, 500);
frame.setVisible(true);
}
}
I suggest first taking a looking at this, this, and this.
Here is how you should be creating a new TextField
JTextField textField = new JTextField();
You should then create a button and action listener similar to this
JButton someBtn = new JButton("Some Text");
someBtn.addActionListener(this);
Your ActionPerformed
#Override
public void actionPerformed(ActionEvent e) {
textField.setText("New Text");
}
If you would like to stay with the approach of using an Array of JButtons I suggest doing something similar.
String[] btnNames = {"1", "2", "3", etc.};
JButton[] allBtns = new JButton[10];
for(int i = 0; i < 10; i++){
allBtns[i] = new JButton(btnNames[i]);
allBtns[i].addActionListener(this);
//Using the previous actionPerformed
}
If you would like to customize what each button does you can do this
anyBtn.addActionListener(e -> textField.setText("Anything"));
Take a look at lambda's for more info.
the way I usually go about it in java is to have an inner class that handles the button clicks
public x extends JFrame(){
//I like to store my buttons in an array if possible.
JButton [] buttonArray = new JButton [2];
//instantialize each of the arrays buttons
buttonArray[0] = new JButton("hello");
buttonArray[1] = new JButton("world");
//create a listener of type buttonpress (currently undefined)
buttonPress Listener = new buttonPress();
//attach the button action listeners to the listener I created above.
buttonArray[0].addActionListener(Listener);
buttonArray[1].addActionListener(Listener);
//Create a private inner class called "buttonPress" which will handle the clicks for its listeners
private class buttonPress implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == buttonArray[0]){
try
{
..some logic
}
catch (Exception e1)
{
JOptionPane.showMessageDialog(null, e1.getMessage());
}
}
else if( e.getSource() == buttonArray[1])
{
...some other logic
}
}
}//close inner class
}//close outer class

Eventhandling and how to use itemListener for multiple items

So I have 2 questions, the following classes regarding the questions I will ask are supplemented below:
1) If I have multiple JCheckBoxes, how can I use an itemListener to know when a specific JCheckBox is selected.
(In the example below, I have 3 JCheckBoxes named petrol, Electric & diesel, if petrol is chosen how can I be aware of this, I want to do something like, if petrol is selected then remove some items from the JComboBox)
2) How can I make the progress bar increase or decrease when a JButton is clicked. In the code below I have a JProgressBar, when the user clicks drive I want the JProgressBar to decrease and when they select refuel I want the JProgressBar to increase. I sort of want the JProgressBar to represent the fuel Level of the car. How would I go about doing this?
Class 1
import javax.swing.*;
import java.awt.*;
import javax.swing.border.*;
public class CarViewer extends JFrame{
//row1
JPanel row1 = new JPanel();
JButton drv = new JButton("Drive");
JButton park = new JButton("Park");
JButton refuel = new JButton("Refuel");
//row2
JPanel row2 = new JPanel();
JLabel carTypeTag = new JLabel("Car Model:", JLabel.RIGHT);
JComboBox<String> options = new JComboBox<String>();
JCheckBox petrol = new JCheckBox("Petrol");
JCheckBox Electric = new JCheckBox("Electric");
JCheckBox diesel = new JCheckBox("Diesel");
JLabel fuelTypeTag = new JLabel("Fuel Type: ", JLabel.RIGHT);
ButtonGroup groupFuelType = new ButtonGroup();
//row3
JPanel row3 = new JPanel();
JLabel costTag = new JLabel("Cost:", JLabel.RIGHT);
JTextField costField = new JTextField(10);
JLabel engTag = new JLabel("Engine Size: ", JLabel.RIGHT);
JTextField engField = new JTextField(5);
JLabel mileageTag = new JLabel("Mileage: ", JLabel.RIGHT);
JTextField mField = new JTextField(10);
JLabel tankSizeTag = new JLabel("Tank size: ", JLabel.RIGHT);
JTextField tSField = new JTextField(5);
//row4
JPanel row4 = new JPanel();
JProgressBar petTank = new JProgressBar();
//row5
JPanel row5 = new JPanel();
JButton reset = new JButton("Reset");
public CarViewer(){
super("Analyse A Car - AAC");
setSize(400,800);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout layoutMaster = new GridLayout(6, 1, 10, 20);
setLayout(layoutMaster);
////Initial Errands
groupFuelType.add(petrol);
groupFuelType.add(diesel);
groupFuelType.add(Electric);
Dimension buttonDimension = new Dimension(80,30);
Dimension resetButtonX = new Dimension(150,100);
drv.setPreferredSize(buttonDimension);
park.setPreferredSize(buttonDimension);
refuel.setPreferredSize(buttonDimension);
petTank.setMinimum(0);
petTank.setMaximum(100);
///Adding Car Models to Dropdown (JComboBox)
options.addItem("Mercedes C63 AMG");
options.addItem("BMW i7");
options.addItem("Jaguar XFR");
options.addItem("Nissan Skyline R35 GTR 4");
EmptyBorder empty0 = new EmptyBorder(60, 0, 440, 0); //empty Border;
EmptyBorder empty2 = new EmptyBorder(50,40,0,120); //empty Border row 3;
EmptyBorder empty4 = new EmptyBorder(80,0,0,0);
//Errands Complete
CarEvent handler = new CarEvent();
//Adding Listeners
drv.addActionListener(handler);
park.addActionListener(handler);
refuel.addActionListener(handler);
reset.addActionListener(handler);
options.addItemListener(handler);
petrol.addItemListener(handler);
Electric.addItemListener(handler);
diesel.addItemListener(handler);
//Listeners Added.
FlowLayout layout0 = new FlowLayout();
row1.setLayout(layout0);
row1.add(drv);
row1.add(park);
row1.add(refuel);
row1.setBorder(empty0);
add(row1);
GridLayout layout1 = new GridLayout(1, 3, 40, 50);
row2.setLayout(layout1);
row2.add(carTypeTag);
row2.add(options);
row2.add(fuelTypeTag);
row2.add(petrol);
row2.add(diesel);
row2.add(Electric);
add(row2);
GridLayout layout2 = new GridLayout(1, 4, 20, 0);
row3.setLayout(layout2);
costField.setEditable(false);
engField.setEditable(false);
tSField.setEditable(false);
mField.setEditable(false);
row3.add(costTag);
row3.add(costField);
row3.add(engTag);
row3.add(engField);
row3.add(tankSizeTag);
row3.add(tSField);
row3.add(mileageTag);
row3.add(mField);
row3.setBorder(empty2);
add(row3);
FlowLayout layout3 = new FlowLayout(FlowLayout.CENTER);
row4.setLayout(layout3);
row4.setBorder(empty4);
row4.add(petTank);
add(row4);
FlowLayout layout4 = new FlowLayout(FlowLayout.CENTER);
row5.setLayout(layout4);
reset.setPreferredSize(resetButtonX);
row5.add(reset);
add(row5);
setVisible(true);
}
public static void main(String[] args){
CarViewer gui = new CarViewer();
}
}
Event handling class (2):
import java.awt.event.*;
public class CarEvent implements ActionListener, ItemListener {
public void actionPerformed(ActionEvent event){
String cmd = event.getActionCommand();
if(cmd.equals("Drive"));{
}
else if(cmd.equals("Park")){
}
else if(cmd.equals("Refuel")){
}
else if(cmd.equals("Reset")){
}
}
public void itemStateChanged(ItemEvent event){
Object identifier = event.getItem();
String item = identifier.toString();
if())
}
}
For the check box question the below code may help you.
Use the CarEvent class as a inner class to CarViewer.
In the CarViewer add the event to each control
public class CarViewer extends JFrame {
petrol.addItemListener (new CarEvent());
Electric.addItemListener (new CarEvent());
diesel.addItemListener (new CarEvent());
class CarEvent implements ActionListener, ItemListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.toString());
}
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getItem().equals(petrol)) {
System.out.println("Petrol");
}
else if (e.getItem().equals(Electric)) {
System.out.println("Electric");
}
else if (e.getItem().equals(diesel)) {
System.out.println("Diesel");
}
}
} //CarEvent class
} //CarViewer class
If you want to use the CarEvent as a separate class then you need to pass the CarViewer class instance to this CarEvent class and access the check boxes (when the check boxes as public)
public class CarViewer extends JFrame {
petrol.addItemListener (new CarEvent(this));
//and so on ,,,,
}//CarViewer class
class CarEvent implements ActionListener, ItemListener {
CarViewer cv:
public CarEvent(CarViewer _object){
cv=_object;
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.toString());
}
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getItem().equals(cv.petrol)) {
System.out.println("Petrol");
}
else if (e.getItem().equals(cv.Electric)) {
System.out.println("Electric");
}
else if (e.getItem().equals(cv.diesel)) {
System.out.println("Diesel");
}
}
}//CarEvent class

Getting textfile in a combobox

I haven't used comboBox much in java before and I'm having a bit of trouble getting my textfile to appear. I believe I have the files load correctly but it seems like I'm finding difficult to implement it in the code. I do have multiple movie names in the textfile. and when selecting a different movie in the combo box it changes the price,rating etc...
I did this correctly once using an initialize array.
example of the textfile[Taken,PG-13,8:00Am, 7,50
import java.awt.event.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.*;
import javax.swing.*;
public class MovieSelection extends JFrame {
private JPanel ratingPanel;
private JPanel panel;
private JLabel priceLabel;
private JLabel label;
private JButton addCart;
private JButton backButton;
private JButton resetButton;
private JTextField selectedRatingPanel;
private JTextField amountTextField;
private JComboBox movieBox;
private ArrayList<String> movieName;
private ArrayList<String> movieRating;
private ArrayList<String> movieTime;
private ArrayList<String> moviePrice;
public MovieSelection() {
super("Please select your movie");
setSize(575,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
buildMoviePanel();
buildRatingPanel();
add(panel);
setVisible(true);
movieName = new ArrayList<>();
movieRating = new ArrayList<>();
movieTime = new ArrayList<>();
moviePrice = new ArrayList<>();
}
private void readMovies() {
Scanner input=null;
try{
input = new Scanner(new File("TheMovies.txt"));
while(input.hasNext()){
String str = input.nextLine();
StringTokenizer strT = new StringTokenizer(str, ",");
movieName.add(strT.nextToken());
movieRating.add(strT.nextToken());
moviePrice.add(strT.nextToken());
movieTime.add(strT.nextToken());
}
}
catch(Exception element){
input.close();
JOptionPane.showMessageDialog(null, "Error");
}
}
private void buildMoviePanel() {
panel = new JPanel();
priceLabel = new JLabel("Cost:");
backButton = new JButton("Back");
resetButton = new JButton("Rest");
backButton.addActionListener(new BackButton());
resetButton.addActionListener(new ResetButton());
addCart = new JButton("Add to cart");
JTextField totalTextField = new JTextField(10);
JTextField priceTextField = new JTextField(5);
JTextField amountTextField = new JTextField(4);
priceTextField.setEditable(false);
priceTextField.setText(moviePrice);
totalTextField.setEditable(false);
JComboBox movieLists = new JComboBox(movieName);
movieLists.setSelectedIndex(0);
movieLists.addActionListener(new MovieLists());
panel.add(movieLists).setBounds(20,52,80,40);
panel.add(priceLabel).setBounds(375,0,80,40);
panel.add(priceTextField).setBounds(375,52,75,40);
panel.add(backButton).setBounds(20,310,80,40);
panel.add(addCart).setBounds(380,310,100,40);
panel.add(resetButton).setBounds(200, 310, 80, 40);
panel.add(amountTextField);
panel.setLayout(null);
}//buildPanel
private void buildRatingPanel(){
ratingPanel = new JPanel();
label = new JLabel("Rating:");
selectedRatingPanel = new JTextField(9);
selectedRatingPanel.setEditable(false);
selectedRatingPanel.setText("R");
panel.add(label).setBounds(245, 0, 100,40);
panel.add(selectedRatingPanel).setBounds(245,52,100,40);
}
private class MovieLists implements ActionListener {
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
String theMovie = (String) cb.getSelectedItem();
System.out.println(cb.getSelectedIndex());
}
}
private class BackButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
// return back to home page
if (e.getSource() == backButton)
new SelectUserWindow();
setVisible(false);
}
}
private class ResetButton implements ActionListener {
public void actionPerformed(ActionEvent e) {
// return back to home page
if (e.getSource() == resetButton);
}
}
}
Learn to use layout managers
JComboBox does not take an ArrayList (or Collection) as a viable parameter (it can take Object[] or Vector)
movieName, movieRating, movieTime, moviePrice are all uninitialised when you create the UI because you initialise them AFTER the creation of the UI.
JTextField#setText does not take an ArrayList as a viable parameter
Learn to read the output of your application from the console or IDE
Learn to use a debugger - it will save you many hours of frustration and annoyance ;)

JTextArea - How to set text at a specified offset?

I want to set some text at a specified offset in my JTextArea. Let's say I have already in my edit "aaa bbb" and I want to overwrite "bbb" with "house", how can I do that in Java?
You could use replaceRange()
public void replaceRange(String str,
int start,
int end)
Replaces text from the indicated start to end position with the new text specified. Does nothing if the model is null. Simply does a delete if the new string is null or empty.
This method is thread safe, although most Swing methods are not. Please see Threads and Swing for more information.
You need to take a look at three methods setSelectionStart(...), setSelectionEnd(...) and replaceSelection(...).
Here is a small sample program to help your cause :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextAreaSelection
{
private JTextField replaceTextField;
private JTextField startIndexField;
private JTextField endIndexField;
private void createAndDisplayGUI()
{
final JFrame frame = new JFrame("JTextArea Selection");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationByPlatform(true);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
contentPane.setOpaque(true);
final JTextArea tarea = new JTextArea(10, 10);
tarea.setText("aaa bbb");
final JButton updateButton = new JButton("UPDATE TEXT");
updateButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//tarea.setSelectionStart(4);
//tarea.setSelectionEnd(7);
//tarea.replaceSelection("house");
int selection = JOptionPane.showConfirmDialog(null, getPanel());
if (selection == JOptionPane.OK_OPTION)
{
if (replaceTextField.getDocument().getLength() > 0
&& startIndexField.getDocument().getLength() > 0
&& endIndexField.getDocument().getLength() > 0)
{
String text = replaceTextField.getText().trim();
int start = Integer.parseInt(startIndexField.getText().trim());
int end = Integer.parseInt(endIndexField.getText().trim());
tarea.replaceRange(text, start, end);
}
}
}
});
contentPane.add(tarea, BorderLayout.CENTER);
contentPane.add(updateButton, BorderLayout.PAGE_END);
frame.getContentPane().add(contentPane);
frame.pack();
frame.setVisible(true);
}
private JPanel getPanel()
{
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 2, 2, 2));
JLabel replaceLabel = new JLabel("Enter new String : "
, JLabel.CENTER);
replaceTextField = new JTextField(10);
JLabel startIndexLabel = new JLabel("Enter Start Index : "
, JLabel.CENTER);
startIndexField = new JTextField(10);
JLabel endIndexLabel = new JLabel("Enter End Index : ");
endIndexField = new JTextField(10);
panel.add(replaceLabel);
panel.add(replaceTextField);
panel.add(startIndexLabel);
panel.add(startIndexField);
panel.add(endIndexLabel);
panel.add(endIndexField);
return panel;
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TextAreaSelection().createAndDisplayGUI();
}
});
}
}

Categories

Resources