Ok my code has to pick route combo box (check) display in label(check) have a return and single ticket combobox(check) need it to display text(check) my problem is it only prints text related to one of my statments hope someone can tell me how to fix my if statments. The lable changes on a button .It reads code by lable.So far it only prints 15 and wont print 20 unless i had another label but this wouldnt make sense for the program
package learning;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList.*;
import java.util.Arrays.*;
import java.util.List.*;
#SuppressWarnings("unused")
public class test {
String[] items = {"Tipperary_to_cork","Cork_to_Dublin","Limerick_to_Tipperary","Dublin_to_Cork"};
JComboBox c = new JComboBox(items);
JButton b = new JButton("From");
JLabel l = new JLabel();
String[] items2 = {"window","aisle"};
JComboBox m = new JComboBox(items2);
JButton n = new JButton("Seat");
JLabel o = new JLabel();
String[] items3 = {"Single","return"};
JComboBox x = new JComboBox(items3);
JButton y= new JButton("Ticket");
JLabel z = new JLabel("choose Ticket");
String[] items4 = {"1","2","3","4","5","6","7","8","9","10"};
JComboBox<?> xx = new JComboBox(items4);
JButton yy = new JButton("seat");
JLabel zz = new JLabel("Choose a seat");
JLabel hh = new JLabel("cost");
JButton ccc = new JButton("comfirm");
JLabel hhh = new JLabel("");{
}
public test(){
frame();
}
public void frame(){
JFrame wolf = new JFrame();//frame
wolf.setVisible(true);
wolf.setSize(350,350);
wolf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
JPanel p = new JPanel();
p.add(hh);
p.add(c);//
p.add(b);//
p.add(l);//lable1
p.add(m);//
p.add(n);//
p.add(o);//lable 2
p.add(x);//
p.add(y);//
p.add(z);//lable 2
p.add(xx);//
p.add(yy);//
p.add(zz);//lable 2
p.add(ccc);
p.add(hhh);
wolf.add(p);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = c.getSelectedItem().toString();
l.setText(s);
}
});
n.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = m.getSelectedItem().toString();
o.setText(s);
}
});
y.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = x.getSelectedItem().toString();
z.setText(s);
}
});
yy.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = xx.getSelectedItem().toString();
zz.setText(s);
}
});
}
{
if(l.getText().equals("Tipperary_to_cork")&&(z.getText().equals("single"))){
ccc.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
hh.setText("15"); //***
}});
if(l.getText().equals("Tipperary_to_cork")&&(z.getText().equals("return"))){
ccc.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
hh.setText("20"); //****
}
});
}}}
public static void main(String[]args){
new test();
}
}
You want to check "if some condition" when you click the button. So, start with one simple if statement inside one of the actionPerformed methods. You shouldn't add an action listener inside an if statement, you should always perform an action, and determine the event inside that action.
For example
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String s = c.getSelectedItem().toString();
if (s.equals("Tipperary to cork")) {
// TODO: do something
}
}
});
Original answer
These line just happen to work because you have if(false==false)
if(l.equals("Tipperary to cork")==(z.equals("single"))) { ... }
if(l.equals("Tipperary to cork")==(z.equals("return"))) { ... }
The reason they evaluate to false is because you are comparing a JLabel.equals(String). You should use l.getText().equals("text here"), but...
The problem is that you have those if statements inside the constructor for your class, meaning that they are the first thing that is evaluated in your code. You should move the corrected if statements into the ActionListeners for the respective buttons.
Additional note: You seem to want "Tipperary to cork" AND "single". In that case, use && in place of ==. Alternatively, you could do this (psuedocode intentional)
if "Tipperary to cork" {
if "single" { ... }
else if "return" { ... }
}
In reality, though, you should compare c.getSelectedItem().toString() instead of the text of the label, but that's your decision.
Related
this is my first question on this website.
I have this problem, in this class I have two buttons with two different functions, one to exit and another to put the first and last name in a text field.
I can't get the second ActionEvent to work, please help me, thanks.
import javax.swing.*;
import java.awt.event.*;
public class Prueba1 extends JFrame implements ActionListener{
private JLabel nombre, apellidos,respondo;
private JTextField textfield, textfield1;
private JButton boton,botonoff;
public Prueba1() {
setLayout(null);
nombre = new JLabel("Nombre:");
nombre.setBounds(10, 10, 300, 30);
add(nombre);
apellidos = new JLabel("Apellidos");
apellidos.setBounds(10, 40, 300, 30);
add(apellidos);
textfield = new JTextField();
textfield.setBounds(100,10,150,20);
add(textfield);
textfield1 = new JTextField();
textfield1.setBounds(100,40,150,20);
add(textfield1);
boton = new JButton("¿Que saldrá?");
boton.setBounds(10,80,120,30);
boton.addActionListener(this);
add(boton);
botonoff = new JButton("Salir");
botonoff.setBounds(10,120,120,30);
botonoff.addActionListener(this);
add(botonoff);
respondo = new JLabel("UwU");
respondo.setBounds(160,80,300,30);
add(respondo);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == boton) {
String nombreyapellidos, nombre1, apellidos1;
nombre1 = textfield.getText();
apellidos1 = textfield1.getText();
nombreyapellidos = nombre1 + apellidos1;
respondo.setText(nombreyapellidos);
}
}
public void actionPerformed1(ActionEvent e) {
if(e.getSource() == botonoff) {
System.exit(0);
}
}
public static void main(String args[]) {
Prueba1 clase = new Prueba1();
clase.setVisible(true);
clase.setBounds(0, 0, 500, 500);
clase.setResizable(true);
clase.setLocationRelativeTo(null);
}
}
Remove public void actionPerformed1(ActionEvent e) method and add the body of that method in the else branch in the body of public void actionPerformed(ActionEvent e).
public void actionPerformed(ActionEvent e) {
if (e.getSource() == boton) {
String nombreyapellidos, nombre1, apellidos1;
nombre1 = textfield.getText();
apellidos1 = textfield1.getText();
nombreyapellidos = nombre1 + apellidos1;
respondo.setText(nombreyapellidos);
} else if (e.getSource() == botonoff) {
System.exit(0);
}
}
When you provide an ActionListener object to a buttons button.addActionListener(listener)
You have several ways to accomplish this.
button.addActionListener(this);
Is only one way. This way says the the class implements ActionListener.
In effect it implements the
public void actionPerformed(ActionEvent e)
method.
Your
public void actionPerformed1(ActionEvent e)
can't be used by the button at all.
Fortunately there are many other ways to describe the code that should be executed when an action event is produced.
An inner class, static or not. Other class/object.
A lambda expression.
You can find how to express a lambda here.
new to programming and Java is the first language I'm learning.
I'm having difficulty thinking through the logic on this application I'm building. The application is really simple: it has say five checkboxes and a sync button. You select a checkbox and click sync and it runs a cmd command associated with the specific checkbox.
However, I would like to be able to check multiple checkboxes and hit sync and have them all go instead of doing it one at a time. I currently have an if statement (if the checkbox is selected and sync button is pressed) run "xyz" command (that corresponds to that checkbox). But it only runs for the first checkbox (if) and then quits.
Thanks!
Edit. Code below:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.util.Scanner;
class RcSync extends JFrame implements ActionListener{
Container contentPane = getContentPane();
JPanel top = new JPanel();
JPanel center = new JPanel();
JPanel bottom = new JPanel();
JScrollPane mainScrollFrame = new JScrollPane(center);
JLabel displayMessage = new JLabel("Please select a item, and click sync:");
Font customFontHeader = new Font("", Font.BOLD,15);
JButton syncButton = new JButton("Sync");
JButton cancelButton = new JButton("Cancel");
String[] database = {"Apple","Pineapple","Orange","Pear","Fig"};
JCheckBox chk1 = new JCheckBox(database[0]);
JCheckBox chk2 = new JCheckBox(database[1]);
JCheckBox chk3 = new JCheckBox(database[2]);
JCheckBox chk4 = new JCheckBox(database[3]);
JCheckBox chk5 = new JCheckBox(database[4]);
JCheckBox chk6 = new JCheckBox(database[5]);
public RcSync() {
super ("Sync Application");
setSize (400,450);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(top);
setVisible(true);
top.add(displayMessage);
displayMessage.setFont(customFontHeader);
center.add(chk1);
center.add(chk2);
center.add(chk3);
center.add(chk4);
center.add(chk5);
bottom.add(syncButton);
syncButton.addActionListener(this);
cancelButton.addActionListener(new CloseListener());
bottom.add(cancelButton);
bottom.add(emailButton);
emailButton.addActionListener(this);
contentPane.add("North", top);
contentPane.add("South", bottom);
this.getContentPane().add(mainScrollFrame, BorderLayout.CENTER);
center.setLayout(new BoxLayout(center, BoxLayout.Y_AXIS));
}
public void actionPerformed(ActionEvent event){
if ((event.getSource() == syncButton) && (chk1.isSelected())) {
try {
Runtime.getRuntime().exec("cmd /c start \"\" C:\\File\\script.bat " + chk1.getText());
} catch (IOException e) {
e.printStackTrace();}
}
if ((event.getSource() == syncButton) && (chk2.isSelected())) {
try {
Runtime.getRuntime().exec("cmd /c start \"\" C:\\File\\script.bat " + chk2.getText());
} catch (IOException e) {
e.printStackTrace();}
}
if ((event.getSource() == syncButton) && (chk3.isSelected())) {
try {
Runtime.getRuntime().exec("cmd /c start \"\" C:\\File\\script.bat " + chk3.getText());
} catch (IOException e) {
e.printStackTrace();}
}
if ((event.getSource() == syncButton) && (chk4.isSelected())) {
try {
Runtime.getRuntime().exec("cmd /c start \"\" C:\\File\\script.bat " + chk4.getText());
} catch (IOException e) {
e.printStackTrace();}
}
if ((event.getSource() == syncButton) && (chk5.isSelected())) {
try {
Runtime.getRuntime().exec("cmd /c start \"\" C:\\File\\script.bat " + chk5.getText());
} catch (IOException e) {
e.printStackTrace();}
}
}
private class CloseListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
public static void main (String[]args){
RsSync gui = new RcSsync();
}
}
}
I have edited my response since you provided more context to your question. Pasted below: is my approach to solving your problem, working code with explanation, and errors I had to resolve with your associated code:
Approach: Associate a boolean value for each checkbox corresponding to whether or not that option has been 'selected by the end user'. When the sync button is clicked, find which checkboxes have been selected. These checkboxes will return a true value from their isSelected() method. For each checkbox selected add the associated command into a List containing all the commands to be ran on the end user's machine. Iterate through this list until there are no commands left to be ran.
Code:
import javax.swing.*;
import java.util.ArrayList;
import java.awt.*;
import java.awt.event.*;
import java.util.List;
class RcSync extends JFrame implements ActionListener{
Container contentPane = getContentPane();
JPanel top = new JPanel();
JPanel center = new JPanel();
JPanel bottom = new JPanel();
JScrollPane mainScrollFrame = new JScrollPane(center);
JLabel displayMessage = new JLabel("Please select a item, and click sync:");
Font customFontHeader = new Font("", Font.BOLD,15);
JButton syncButton = new JButton("Sync");
JButton cancelButton = new JButton("Cancel");
// Encapsulate your checkboxes to commands, since there is one
// to one relationship and makes future changes easier since there is a single point of change
String[] database = {"Apple","Pineapple","Orange","Pear","Fig"};
CheckboxCommand chk1 = new CheckboxCommand("Checkbox 1 cmd", new JCheckBox(database[0]));
CheckboxCommand chk2 = new CheckboxCommand("Checkbox 2 cmd", new JCheckBox(database[1]));
CheckboxCommand chk3 = new CheckboxCommand("Checkbox 3 cmd", new JCheckBox(database[2]));
CheckboxCommand chk4 = new CheckboxCommand("Checkbox 4 cmd", new JCheckBox(database[3]));
CheckboxCommand chk5 = new CheckboxCommand("Checkbox 5 cmd", new JCheckBox(database[4]));
public RcSync() {
super ("Sync Application");
setSize (400,450);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(top);
setVisible(true);
top.add(displayMessage);
displayMessage.setFont(customFontHeader);
center.add(chk1.checkbox);
center.add(chk2.checkbox);
center.add(chk3.checkbox);
center.add(chk4.checkbox);
center.add(chk5.checkbox);
bottom.add(syncButton);
syncButton.addActionListener(this);
cancelButton.addActionListener(new CloseListener());
bottom.add(cancelButton);
// TODO email button doesn't exist, assuming copy/paste error?
// bottom.add(emailButton);
// emailButton.addActionListener(this);
contentPane.add("North", top);
contentPane.add("South", bottom);
this.getContentPane().add(mainScrollFrame, BorderLayout.CENTER);
center.setLayout(new BoxLayout(center, BoxLayout.Y_AXIS));
}
public void actionPerformed(ActionEvent event){
// Implements the approach I described initially
if (event.getSource() == syncButton){
List<String> cmdsToRun = new ArrayList<>();
if (chk1.isSelected()){
cmdsToRun.add(chk1.getCmdToRun());
}
if (chk2.isSelected()){
cmdsToRun.add(chk2.getCmdToRun());
}
if (chk3.isSelected()){
cmdsToRun.add(chk3.getCmdToRun());
}
if (chk4.isSelected()){
cmdsToRun.add(chk4.getCmdToRun());
}
if (chk5.isSelected()){
cmdsToRun.add(chk5.getCmdToRun());
}
// Note: for verification purposes I just print out your commands
// since they're hard coded to your particular environment
System.out.println(cmdsToRun);
// This is where you would loop through your command list i.e.
// for (int x=0; x<cmdsToRun; x++){ //run command at cmdToRun.get(x); }
}
}
private class CloseListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
// encapsulating your checkboxes to commands
private class CheckboxCommand {
private String cmdToRun;
private boolean isSelected;
private JCheckBox checkbox;
public CheckboxCommand(String cmdToRun, JCheckBox checkbox) {
this.cmdToRun = cmdToRun;
this.checkbox = checkbox;
}
public String getCmdToRun() {
return cmdToRun;
}
public void setCmdToRun(String cmdToRun) {
this.cmdToRun = cmdToRun;
}
public boolean isSelected() {
return this.checkbox.isSelected();
}
public void setSelected(boolean selected) {
isSelected = selected;
}
}
public static void main (String[]args){
// Fixed your typo error to run the swing interface
RcSync gui = new RcSync();
}
}
Verification of correct code:
Key Insight:
I encapsulated your commands to checkboxes into a private class since there is a one to one relationship and this will allow your code to have a single point of change, which in general is a best practice :)
Side Note:
I don't actually run your commands on my end since they're tied to your particular machine. I.e. associated to local scripts, so I printed out dummy commands to prove the code functions appropriately. I added a comment block in the code to show where you can add your environment specific code i.e. Runtime.getRuntime().exec("<CMD>");
Errors to be fixed:
I removed this line: JCheckBox chk6 = new JCheckBox(database[5]); since this will throw an indexOutOfBounds exception since there are only 5 elements in your in-memory database variable not 6.
emailButton doesn't exist so I commented it out:
// bottom.add(emailButton);
// emailButton.addActionListener(this);
This is a typo and won't run the gui: RsSync gui = new RcSsync(); so I changed it appropriately: RcSync gui = new RcSync();
Hopefully that helps! :)
I have a program which uses 3 radiobuttons to switch between 3 incrementing values for a counter, here time.
I want to change status when a radiobutton is pressed, and it does so, but only for a fraction. When launching the program will keep printing
0
Normal
2
Normal
4
Normal
6
etc. When I press the button slow it prints CHANGE Slow once but keeps incrementing with 2 and still prints Normal every time.
How can I have this permenently switch to a different value for status, and a different increment, until I choose another radiobutton again?
package daynightcycle;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
/**
* Day/night cycle with visuals. Adjustable speed and time inserts.
* Optional date or daycounter later
* #author rogie
*/
public class DayNightCycle extends JFrame implements Runnable{
//JFrame entities
private JPanel animationPanel;
public JRadioButton button;
public JRadioButton button2;
public JRadioButton button3;
public int time = 0;
public String status = "Normal";
public static void main(String[] args) {
DayNightCycle frame = new DayNightCycle();
frame.setSize(2000, 1300);
frame.setLocation(1000,350);
frame.createGUI();
frame.setVisible(true);
frame.setTitle("Day/Night Cycle, Rogier");
(new Thread(new DayNightCycle())).start();
}
private void createGUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new FlowLayout() );
animationPanel = new JPanel();
animationPanel.setPreferredSize(new Dimension(2000, 900));
animationPanel.setBackground(Color.black);
window.add(animationPanel);
JRadioButton option1 = new JRadioButton("Slow");
JRadioButton option2 = new JRadioButton("Normal", true);
JRadioButton option3 = new JRadioButton("Fast");
option1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("CHANGE");
status = "Slow";
System.out.println(status);
}
});
option2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
status = "Normal";
}
});
option2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
status = "Fast";
}
});
//option2.setFont(new java.awt.Font("Tahoma", Font.BOLD, 30));
//option2.putClientProperty("JComponent.sizeVariant", "huge"); //doesn't work
ButtonGroup group = new ButtonGroup();
group.add(option1);
group.add(option2);
group.add(option3);
add(option1);
add(option2);
add(option3);
pack();
}
public void run() {
while(true){
System.out.println(time);
System.out.println(status);
try
{
Thread.sleep(500);
if (status.equals("Slow")) {
time += 1;
}
else if (status.equals("Normal")){
time += 2;
}
else {
time += 3;
}
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
}
}
You are creating to DayNightCycle-Objects, the first shows the GUI and the second prints on the console.
Change the line
(new Thread(new DayNightCycle())).start();
to
(new Thread(frame)).start();
public static void main(String[] args) {
final DayNightCycle frame = new DayNightCycle();
frame.setSize(2000, 1300);
frame.setLocation(1000,350);
frame.createGUI();
frame.setTitle("Day/Night Cycle, Rogier");
And then
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
frame.setVisible(true);
}
});
Or in java 8:
EventQueue.invokeLater(() -> frame.setVisible(true));
}
You in effect created a second DayNightCycle.
In our code that is linked by a JButton in a previous frame, part of it that is inside of braces does not run.
I can tell because the JFrame.EXIT_ON_CLOSE is not working because the program does not terminate. If the braces are taken away, other errors appear.
How do we make it so that this code will run?
public class PeopleCreator extends PeopleMove {
public static final JFrame PeopleFrame = new JFrame("The Lovely Couple");
ImageIcon girl = new ImageIcon();// pic of girl
ImageIcon boy = new ImageIcon();// pic of boy
String name = JOptionPane.showInputDialog("What is your name?");
JButton girlDialogue1 = new JButton("Hey " + name
+ "! Hey can you get something to drink");
// This code below does not run.
{
PeopleMove.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
PeopleMove.add(girlDialogue1, BorderLayout.SOUTH);
girlDialogue1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent z) {
JButton boyDialogue1 = new JButton("");// girls first text
{
PeopleMove.add(boyDialogue1);
boyDialogue1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent y) {
JButton girlDialogue2 = new JButton("");// boys
// first
// text
PeopleMove.add(girlDialogue2);
girlDialogue2
.addActionListener(new ActionListener() {
public void actionPerformed(
ActionEvent x) {
JButton boyDialogue2 = new JButton(
"");
PeopleMove.add(boyDialogue2);
boyDialogue2
.addActionListener(new ActionListener() {
public void actionPerformed(
ActionEvent v) {
PeopleMove.pack();
PeopleMove
.setVisible(true);
}
});
}
});
}
});
}
}
});
}
}
Code in your braces will be executed every time you create new instance of PeopleCreator with the new keyword (it is appended to every constructor of current class). I am guessing that you are not creating new peopleCreator anywhere but you are refering to static field holding JFrame.
I want to make an event which will be triggered after i make the selection to the JComboBox.
the problem I'm now facing is that when i added an ActionListener, it was triggered when the user clicked on the box but BEFORE he actually chose the new item, thus the action listener was activated all the time on the previous value which was selected in the box. what i want to do is simply changing the title of an JTextArea according to the selection.
I tried doing something like this:
jBox.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
String alt = GetAlgoAreaTitleByChoice();
panel.remove(jArea);
currentBest = setArea("",alt);
currentBest.setBounds(50, 350, 1000, 290);
panel.add(jArea);
}
});
and the method inside:
private String GetArgsAreaTitleByChoice(){
String chi = jBox.getSelectedItem().toString();
if(chi.equals(generalChoice)){
return "Hello";
}
else if(chi.equals(algoChoice)){
return "World";
}
else if(chi.equals(argsChoice)){
return "Hello";
}
return null;
}
I've tried using the SELECTED events now like this:
public void itemStateChanged(ItemEvent e) {
JComboBox cb = (JComboBox)e.getSource();
// Get the affected item
String item = cb.getSelectedItem().toString();
if (e.getStateChange() == ItemEvent.SELECTED) {
panel.remove(jBox);
textArea = setArea("", item);
panel.add(jBox);
}
but it seems to remove the area from the panel without adding it back... why is this happening?
Here is a simple demonstration with a sample code :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Tester {
public Tester(){
JComboBox box = new JComboBox();
box.addItem("One");
box.addItem("Two");
box.addItem("Three");
box.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent e){
if(e.getStateChange()==ItemEvent.SELECTED){
e.getItem(); //Do what ever you want :))
}
}
});
JFrame frame = new JFrame();
frame.getContentPane().add(box);
frame.pack();
frame.setVisible(true);
}
public static void main(String [] args) {
Tester tester = new Tester();
}
}
For listening of events from JComboBox is better implements ItemListener, returns two events SELECTED/DESELECTED
EDIT
if you remove/add JComponent(s) on Runtime and in already visible container, then you have to call (as least code lines)
revalidate();
repaint();