Count-- incrementing wrong - user-interface

I have made a GUI program in Java that you can start and stop a timer after you have picked 10 seconds, 5mins, or 1min. The numbers will count down but they are incrementing in 2. So it will go 10, 8, 6, 4, 2, 0
Everything else is working fine but i cant seem to figure out what is wrong with the counter. Here is my code.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class countdownPanel extends JPanel
{
private ImageIcon banner;
private JComboBox selectCombo;
private JButton stopButton, startButton;
private JLabel picture, theCount;
private Timer timer;
public countdownPanel()
{
setLayout(new BorderLayout());
setBackground(Color.black);
//Banner Image
banner = new ImageIcon ("banner.jpg");
picture = new JLabel(banner);
//Count Down selecter
JComboBox selectCombo = new JComboBox();
selectCombo.addItem("10 Seconds");
selectCombo.addItem("1 Minute");
selectCombo.addItem("5 Minutes");
//countdown components
theCount = new JLabel(" 0");
theCount.setFont(new Font("Helvetica", Font.BOLD, 200));
timer = new Timer(1000, new TimerListener());
//Stop Start Buttons
startButton = new JButton("Start");
stopButton = new JButton("Stop");
ButtonListener listener = new ButtonListener();
startButton.addActionListener(new ButtonListener());
stopButton.addActionListener(new ButtonListener());
selectCombo.addActionListener(new ComboListener());
timer.addActionListener(new TimerListener());
//GUI set up
add(picture, BorderLayout.NORTH);
add(startButton, BorderLayout.WEST);
add(selectCombo, BorderLayout.CENTER);
add(stopButton, BorderLayout.EAST);
add(theCount, BorderLayout.SOUTH);
}
//combo box listener
private class ComboListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
JComboBox levelCombo = (JComboBox) event.getSource();
Object selected = levelCombo.getSelectedItem();
if(selected.toString().equals("10 Seconds"))
theCount.setText("10");
if(selected.toString().equals("1 Minute"))
theCount.setText("60");
if(selected.toString().equals("5 Minutes"))
theCount.setText("300");
}
}
//Start and stop button listeners
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();
//starts timer
if (event.getSource()== startButton)
timer.start();
//stops timer
if (event.getSource()== stopButton)
timer.stop();
}
}
private class TimerListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
String A = theCount.getText();
int count = Integer.parseInt(A);
while(count < 0)
{
count--;
theCount.setText(""+ count);
}
if(count == 0)
theCount.setText(" GO!");
}
}
}

Related

Listener that runs a certain code only when the ENTER key is pressed while the Mouse is in a JTextField?

here is the code for the ENTER key pressed and the Mouse in the TextField separately. What I need is for the program to only run my code when the mouse is inside of the JTextField while ENTER key is pressed. Thanks for any help!
string is what I named the JTextField
What the program does is take a String, and then display its reverse when a JButton is clicked, or the mouse is in the JField while ENTER is pressed.
string.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String word = string.getText();
String reversed = "";
char[] letters = word.toCharArray();
for (int i = letters.length-1; i>=0; i--) {
reversed = reversed + letters[i];
}
reversed.trim();
reverseStr.setText(reversed);
}
});
string.addMouseListener(new MouseListener() {
public void mouseEntered(MouseEvent arg0) {
String word = string.getText();
String reversed = "";
char[] letters = word.toCharArray();
for (int i = letters.length-1; i>=0; i--) {
reversed = reversed + letters[i];
}
reversed.trim();
reverseStr.setText(reversed);
}
public void mouseClicked(MouseEvent arg0) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent arg0) {
}
#Override
public void mouseReleased(MouseEvent arg0) {
}
});
You can define a field, to check whether the mouse is in textfield. Then let the code run when ENTER is pressed and when this field is true.
Take a look at this code:
package test;
import java.awt.BorderLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Test extends JFrame {
private static final long serialVersionUID = -3677708759387911324L;
private boolean mouseInField = false;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new Test().setVisible(true);
});
}
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
JTextField textField = new JTextField(15);
getContentPane().add(textField, BorderLayout.PAGE_START);
textField.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
mouseInField = true;
System.out.println("mouse entered");
}
#Override
public void mouseExited(MouseEvent e) {
mouseInField = false;
System.out.println("mouse exited");
}
});
textField.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER && mouseInField)
System.out.println("enter is pressed while mouse is in text field.");
}
});
}
}

Replace current JScrollPane to another JScrollPane in JPanel

I would like to change my current JScrollpane to a new one. I would like it to change after I pressed my button and the method actionPerformed is called.
The problem I currently have is that it only paints the Jscroll at the beginning of the application, when i want to change it, it dosent work.(When the application is running).
What I do is:
In the beginning of the application I make a new JscrollPane and this one is empty. If the button is pressed: Show another JscrollPane with content.
if(btnPressed == true){
//set current empty jscroll pane to a filled one.
jscrollpane = View.createScrollPlane();
//View.createScrollPlane = This method fills the JscrollPane with text.
}
else { //show a empty one
jscrollpane = new JscrollPane();
}
I have tried:
- remove
- add
- revalidate
- repaint
And also:
JscrollPane.setViewPortView(JscrollPane);
I've looked to CardLayout but I would rather not and it dosent allow me since only empty containers can be changed to CardLayout. Currently its on GridBagLayout.
Thanks in advance
RE-edit: the Create-UI method dosent change the current empty Jscrollpanel to the new one. It only initialise it once (at the beginning) but dosent update the Jscroll panel. (when i tried to put it on false) it worked, the boolean did change to true but dosent update the jscroll panel.
package readDataPluginPackage;
import com.change_vision.jude.api.inf.AstahAPI;
import com.change_vision.jude.api.inf.project.ProjectAccessor;
import javafx.embed.swing.JFXPanel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeListener;
public class Application {
JPanel mainJPanel;
private JPanel leftJPanel;
private JPanel rightJPanel;
private JButton btnSynchronise;
private JButton btnPreview;
private JScrollPane JScrollPaneReport;
public JScrollPane JScrollPanePreview;
private boolean btnPreviewClicked = false;
public Application() {
$$$setupUI$$$();
btnPreview.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
btnPreviewClicked = true;
JOptionPane.showMessageDialog(null, "Showing..." + btnPreviewClicked);
// ShowXMLFileView showXMLFileView = new ShowXMLFileView();
// JScrollPanePreview = showXMLFileView.createLabelPane();
// if (btnPreview.isEnabled()) {
// ShowXMLFileView showXMLFileView = new ShowXMLFileView();
// JScrollPanePreview = showXMLFileView.createLabelPane();
JOptionPane.showMessageDialog(null, "XML File Preview has been updated.");
createUIComponents();
// JScrollPanePreview.revalidate();
// JScrollPanePreview.repaint();
JOptionPane.showMessageDialog(null, "Components are created again.");
}
// }
});
btnSynchronise.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Synchronising...");
}
});
}
public static void main(String[] args) {
try {
//Save Astah Project as XML File
ProjectAccessor prjAccessor = AstahAPI.getAstahAPI().getProjectAccessor();
prjAccessor.open("C:\\Users\\delina\\generated\\test.asta");
prjAccessor.exportXMI("C:\\Users\\delina\\generatedXMI\\temp.xml");
prjAccessor.close();
//Show the most recent version of the xml file of the Astah Project
ReadXMLFile rd = new ReadXMLFile();
rd.showXMLFileLines();
} catch (Exception e) {
e.printStackTrace();
}
JFrame frame = new JFrame("Application");
frame.setContentPane(new Application().mainJPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private void createUIComponents() {
if (btnPreviewClicked == true) {
// ShowXMLFileView showXMLFileView = new ShowXMLFileView();
// JScrollPanePreview = showXMLFileView.createLabelPane();
// JScrollPanePreview.setViewportView(JScrollPanePreview);
leftJPanel.remove(JScrollPanePreview);
ShowXMLFileView showXMLFileView = new ShowXMLFileView();
JScrollPane JScrollPanePreview = showXMLFileView.createLabelPane();
leftJPanel.add(JScrollPanePreview);
JScrollPanePreview.revalidate();
JScrollPanePreview.repaint();
JOptionPane.showMessageDialog(null, "JScrollPanel changed");
} else {
JScrollPanePreview = new JScrollPane();
}
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* #noinspection ALL
*/
private void $$$setupUI$$$() {
createUIComponents();
mainJPanel = new JPanel();
mainJPanel.setLayout(new GridBagLayout());
leftJPanel = new JPanel();
leftJPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc;
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
mainJPanel.add(leftJPanel, gbc);
btnSynchronise = new JButton();
btnSynchronise.setText("Synchronise");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 2;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
leftJPanel.add(btnSynchronise, gbc);
btnPreview = new JButton();
btnPreview.setText("Preview");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
leftJPanel.add(btnPreview, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
leftJPanel.add(JScrollPanePreview, gbc);
JScrollPanePreview.setBorder(BorderFactory.createTitledBorder("XML File Preview"));
rightJPanel = new JPanel();
rightJPanel.setLayout(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
mainJPanel.add(rightJPanel, gbc);
JScrollPaneReport = new JScrollPane();
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
rightJPanel.add(JScrollPaneReport, gbc);
JScrollPaneReport.setBorder(BorderFactory.createTitledBorder("Synchronise report"));
}
/**
* #noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return mainJPanel;
}
}
package readDataPluginPackage;
import com.change_vision.jude.api.inf.project.ProjectAccessor;
import com.change_vision.jude.api.inf.project.ProjectAccessorFactory;
import com.change_vision.jude.api.inf.project.ProjectEvent;
import com.change_vision.jude.api.inf.project.ProjectEventListener;
import com.change_vision.jude.api.inf.ui.IPluginExtraTabView;
import com.change_vision.jude.api.inf.ui.ISelectionListener;
import javax.swing.*;
import java.awt.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ShowUserInterface extends JPanel implements IPluginExtraTabView, ProjectEventListener {
public ShowUserInterface() {
initComponents();
}
private void initComponents() {
setLayout(new BorderLayout());
add(createLabelPane());
addProjectEventListener();
}
private void addProjectEventListener() {
try {
ProjectAccessor projectAccessor = ProjectAccessorFactory.getProjectAccessor();
projectAccessor.addProjectEventListener(this);
} catch (ClassNotFoundException e) {
e.getMessage();
}
}
private Container createLabelPane() {
JLabel label = new JLabel("AuguSoft Synchronise");
JScrollPane pane = new JScrollPane(label);
Method privateMethod = null;
Application app = null;
Object o = null;
JComponent jComponent = null;
try {
app = new Application();
privateMethod = Application.class.getDeclaredMethod("$$$setupUI$$$");
privateMethod.setAccessible(true);
o = privateMethod.invoke(app);
jComponent = app.$$$getRootComponent$$$();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return jComponent;
}
#Override
public void projectChanged(ProjectEvent e) {
}
#Override
public void projectClosed(ProjectEvent e) {
}
#Override
public void projectOpened(ProjectEvent e) {
}
#Override
public void addSelectionListener(ISelectionListener listener) {
}
#Override
public Component getComponent() {
return this;
}
#Override
public String getDescription() {
return "Show AuguSoft Synchronise here";
}
#Override
public String getTitle() {
return "AuguSoft View";
}
public void activated() {
}
public void deactivated() {
}
}
So, with doing nothing else but looking at you code, I noticed that in your createUIComponents method, you are shadowing the JScrollPanePreview property...
public class Application {
//...
public JScrollPane JScrollPanePreview;
//...
public Application() {..}
private void createUIComponents() {
if (btnPreviewClicked == true) {
//...
leftJPanel.remove(JScrollPanePreview);
ShowXMLFileView showXMLFileView = new ShowXMLFileView();
JScrollPane JScrollPanePreview = showXMLFileView.createLabelPane();
//...
} else {
JScrollPanePreview = new JScrollPane();
}
}
This means that the next time you come to replace the JScrollPanePreview, you won't have the correct reference to remove it.
To my mind (and I don't have you full code base or intention), I'd simply replace the JScrollPanePreview view port (besides, I'm not sure how you can assign a Container to a JScrollPane anyway :P)
private void createUIComponents() {
if (btnPreviewClicked == true) {
JScrollPanePreview.setViewportView(showXMLFileView.createLabelPane());
} else {
JScrollPanePreview = new JScrollPane();
}
}
Just as an observation ;)

How do I create an arraylist in and add and view it with buttons?

I'm trying to make a GUI program that enters and removes cars from an arraylist and displays the cars using JButtons. I am unable to get the arraylist to print from clicking on one of the buttons. I'm also unsure if my arraylist is made correctly. Any help would be greatly appreciated.
import java.util.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Window extends JFrame {
public Window() {
super ("Rent-a-Car");
setSize(400, 100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
JPanel p = new JPanel();
JButton b1 = new JButton("Add Car");
JButton b2 = new JButton("Rent Car");
JButton b3 = new JButton("Library");
p.add(b1);
p.add(b2);
p.add(b3);
add(p);
final ArrayList<String> cars = new ArrayList<String>();
cars.add("Audi");
cars.add("VolksWagon");
cars.add("Mercedes");
cars.add("BMW");
cars.add("Ford");
cars.add("Subaru");
cars.add("Lexus");
cars.add("Acura");
cars.add("Nissan");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Scanner sc = new Scanner(System.in);
JOptionPane.showInputDialog("Enter car model");
String model = sc.next();
JOptionPane.showMessageDialog(null, "Car added");
cars.add(model);
}
});
/*b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for(int i=0 < cars.size(); i++) {
System.out.println();
}
}
});*/
}
}
In your ActionListener for b1 you're trying to scan it from the wrong place. If you run this, you've probably noticed that the JOptionPane doesn't do anything when you submit a car with the add button. However, if you enter a string into the terminal, an dialog will pop up saying "Car added". This is because Scanner sc is scanning System.in! This is not meant for GUIs.
Fortunately, it's really simple to get input from a JOptionPane.
EDIT: Added a few things like a JTextArea in a JScrollPane that is easy to append to and changed it to a simple GridLayout.
I also moved the ActionListeners into an inner class so that you don't clutter up your code with anonymous functions everywhere. It's also a bit easier to add stuff with the (e.getSource()) conditionals, too.
Set model equal to the result of showInputDialog as such:
import java.util.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.GridLayout;
import javax.swing.*;
public class Window extends JFrame {
private JPanel p;
private JButton b1, b2, b3;
private JTextArea textArea;
private JScrollPane scrollPane;
private ArrayList<String> cars;
public Window() {
super ("Rent-a-Car");
setLayout(new GridLayout(2, 1));
setSize(400, 100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
p = new JPanel();
b1 = new JButton("Add Car");
b2 = new JButton("Rent Car");
b3 = new JButton("Library");
b1.addActionListener(new ButtonListener());
b2.addActionListener(new ButtonListener());
b3.addActionListener(new ButtonListener());
textArea = new JTextArea("");
textArea.setEditable(false);
scrollPane = new JScrollPane(textArea);
p.add(b1);
p.add(b2);
p.add(b3);
add(p);
//add(textArea);
add(scrollPane);
cars = new ArrayList<String>();
cars.add("Audi");
cars.add("VolksWagon");
cars.add("Mercedes");
cars.add("BMW");
cars.add("Ford");
cars.add("Subaru");
cars.add("Lexus");
cars.add("Acura");
cars.add("Nissan");
}
public void displayText(String s) {
textArea.append(s + "\n");
textArea.setCaretPosition(textArea.getDocument().getLength());
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
String model = JOptionPane.showInputDialog("Enter car model");
cars.add(model);
displayText("Added car: " + model);
}
else if (e.getSource() == b2) {
//add something later
}
else if (e.getSource() == b3) {
for (String car : cars) {
displayText(car);
}
}
}
}
}

Simple animation through use of paintComponent

I'm trying to make a small square move across the top of the panel. I'm not worried about the seamlessness of the animation or flicker or anything like that. It appears that in the while-loop, repaint() isn't repeatedly calling the paintComponent. Thoughts?
public class NodeMove extends JFrame {
boolean running = true;
public NodeMove() {
widgetNode panel = new widgetNode();
add(panel);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
Runnable node = new widgetNode();
Thread thread1 = new Thread(node);
thread1.start();
}
class widgetNode extends JPanel implements Runnable {
private static final long serialVersionUID = 1L;
private int x = 30;
private int y = 30;
public widgetNode() {
}
public void run(){
while(running){
nodeUpdate();
repaint();
try {
Thread.sleep(500);
} catch (InterruptedException e) {}
}
}
public void nodeUpdate(){
x += 4;
}
protected void paintComponent(Graphics g) {
super.paintComponents(g);
g.drawRect(x, y, 30, 30);
}
}
public static void main(String[] args) {
NodeMove frame = new NodeMove();
for(int i = 0; i < 50; i++){
frame.repaint();
}
}
}

JavaFx State change Listener

I am working on an application where I want to implement a menu. I have a GameState and a MainMenu class. Both extends Group. I can't figure out how to write a change listener to the Main.state, so when it changes from .MENU to .GAME the scenes will switch.
Here's is a part of the MainMenu class:
public class MainMenu extends Group {
private final Image background;
private final Rectangle bgRect;
private final int buttonNo = 3;
private MenuButton[] buttons;
private final double xStart = -200;
private final double yStart = 100;
private Group root;
private Scene scene;
public MainMenu () {
background = new Image(getClass().getResource("mainmenuBg.png").toString());
bgRect = new Rectangle(660,660);
bgRect.setFill(new ImagePattern(background));
root = new Group();
scene = new Scene(root, 650, 650);
scene.setCamera(new PerspectiveCamera());
root.getChildren().add(bgRect);
initButtons(root);
//Start game
buttons[0].setOnMouseClicked(new EventHandler<Event>() {
#Override
public void handle(Event t) {
Main.state = STATE.GAME;
}
});
//Options
buttons[1].setOnMouseClicked(new EventHandler<Event>() {
#Override
public void handle(Event t) {
//options menu will come here
}
});
//Exit
buttons[2].setOnMouseClicked(new EventHandler<Event>() {
#Override
public void handle(Event t) {
Platform.exit();
}
});
}
//...
}
The main class:
public class Main extends Application {
public int difficulty = 1;
GameState gameState;
MainMenu mainMenu;
public enum STATE {
MENU,
GAME
}
public static STATE state = STATE.MENU;
#Override
public void start(Stage stage) {
stage.resizableProperty().setValue(false);
stage.setTitle("Main");
Scene scene = new Scene(new StackPane(), 650, 650);
stage.setScene(scene);
stage.show();
if(Main.state == STATE.MENU)
enterMainMenu(stage);
if(Main.state == STATE.GAME)
enterGameState(stage);
}
//...
}
Any help would be appreciated.
I have succeeded to find a good solution.
I have removed the scene field from these classes, and added the super method in the constructors, than added the elements to the class (this.getChildren().addAll(..)).
Finally, here's my main controller:
public class Main extends Application {
public int difficulty = 1;
public GameState gameState = new GameState(difficulty);
public MainMenu mainMenu = new MainMenu();;
StackPane stackPane = new StackPane();
#Override
public void start(final Stage stage) {
stage.resizableProperty().setValue(false);
stage.setTitle("Main");
Scene scene = new Scene(stackPane, 650, 650);
scene.setCamera(new PerspectiveCamera());
stage.setScene(scene);
stage.show();
stackPane.getChildren().add(mainMenu);
mainMenu.getStartButton().setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
changeScene(gameState);
try {
gameState.startGame();
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
public void changeScene(Parent newPage) {
stackPane.getChildren().add(newPage);
EventHandler<ActionEvent> finished = new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
stackPane.getChildren().remove(0);
}
};
final Timeline switchPage = new Timeline(
new KeyFrame(Duration.seconds(0), new KeyValue(stackPane.getChildren().get(1).opacityProperty(), 0.0), new KeyValue(stackPane.getChildren().get(0).opacityProperty(), 1.0)),
new KeyFrame(Duration.seconds(3), finished, new KeyValue(stackPane.getChildren().get(1).opacityProperty(), 1.0), new KeyValue(stackPane.getChildren().get(0).opacityProperty(), 0.0))
);
switchPage.play();
}
}

Resources