Creating live counter within a JFrame - java

I tried searching for some sort of interactive JLabel. I want it to look like this:
I'm not sure what this is called or where I could find info on displaying this. I want it to print a refreshed number when the +/- is pressed. I have it working to print on the eclipse console but am unsure how to get it to print to the JFrame.
Here is some of the code:
String input = JOptionPane.showInputDialog("Please enter the number of laps.");
numLaps = Integer.parseInt(input);
//frame creation
JFrame f = new JFrame("Number of Laps");
f.setSize(550, 450);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(null);
// label creation
JLabel label = new JLabel("You entered " + numLaps + " laps. Press + to add a lap. Press - to subtract a lap.", SwingConstants.CENTER);
label.setBounds(0,0,500,300);
f.add(label);
//display window
f.setVisible(true);
//button creation add
JButton add = new JButton ("+");
add.setBounds(350,250,50,50);
add.setPreferredSize(new Dimension(50,50));
add.addActionListener( new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e) {
// what happens when button is pressed
//numLaps++;
addToLap();
System.out.println(numLaps);
}
});
f.add(add);
//button creation subtract
JButton sub = new JButton ("-");
sub.setBounds(100,250,50,50);
sub.setPreferredSize(new Dimension(50,50));
sub.addActionListener( new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e) {
// what happens when button is pressed
//numLaps--;
subToLap();
System.out.println(numLaps);
}
});
f.add(sub);
& the add/sub methods:
private static void addToLap() {
// TODO Auto-generated method stub
numLaps++;
}
private static void subToLap() {
// TODO Auto-generated method stub
numLaps--;
}

You could try the following:
private int numLaps = 0 // Or the number you want initialize with
Then in your methods should assing the numLaps value to the JLabel like this:
this.myLabel.setText(String.valueOf(numLaps));
I hope it helps.

Related

nothing happen when i click the button java

I have an app and when you run it you take a panel in order to add 3 values and after you need press the OK button in order to continue.
I put a Click() method but when i push OK nothing happen.
Also to mention when i am deluging is working but when i export it as executable jar is not.
JFrame frame = new JFrame();
JLabel mlabel = new JLabel("Please provide xxxx",JLabel.CENTER);
JLabel uLabel = new JLabel("User ID:",JLabel.LEFT);
JPanel buttonField = new JPanel(new GridLayout (1,3));
JPanel userArea = new JPanel(new GridLayout (0,3));
frame.setLayout(new GridLayout (0,1));
buttonField.setLayout(new FlowLayout());
JButton confirm =new JButton("OK");
confirm.addMouseListener((MouseListener) new mouseClick());
buttonField.add(confirm);
App.insertText = new JTextField(20);
frame.add(mlabel);
userArea.add(uLabel);
userArea.add(insertText);
frame.add(buttonField);
frame.setSize(300,600);
App.credGet = false;
frame.setVisible(true);
and the Click :
public void mouseClicked(MouseEvent e) {
App.un = App.insertText.getText();
App.project = ((JTextComponent) App.insertProject).getText();
//App.pw = char[] App.insertPass.getPassword();
char[] input = App.insertPass.getPassword();
App.pw = "";
for (int i1 = 0; i1 < input.length; i1++){
App.pw = App.pw + input[i1];
}
}
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
Line
confirm.addMouseListener((MouseListener) new mouseClick());
I suppose mouseClick is a class you posted in the example below. Why do you cast it to MouseListener? Does it not implement the MouseListener?
Anyway, you'll be better off replacing it with an ActionListener (anonymous class will work fine for you here), e.g.
confirm.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
...
}
});
Read Pros and cons of using ActionListener vs. MouseListener for capturing clicks on a JButton for more info
You should do something like this:
JButton button = new JButton("ButtonName");
//add button to frame
frame.add(button);
//Add action listener to button
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("You clicked the button");
}
});
You could either use an ActionListener using something like this:
anyBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Your Code Here
}
});
Or you could use a Lambda as shown here:
anyBtn.addActionListener(e ->
{
//Your Code Here
});
You should not be using a MouseListener in that way ever. That is not what it is intended for.

Why isn't this printing? (output of radio button)

So I have a radio button and after that I have an if/else statement that is based upon the outcome. But the if/else statements are supposed print things to the console, but they don't. Is something wrong with the Radio Buttons?
If you could, please provide thorough answers, as I'm not very good with Java. Thanks a ton :D
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RadioButton extends JPanel {
int xDisplacement = 8;
int xVAvg = 8;
int xTime = 8;
static JFrame frame;
JLabel pic;
RadioListener myListener = null;
protected JRadioButton displacement;
protected JRadioButton vAvg;
protected JRadioButton time;
public RadioButton() {
// Create the radio buttons
displacement = new JRadioButton("Displacement");
displacement.setMnemonic(KeyEvent.VK_N);
displacement.setActionCommand("displacement")
//Displacement Button, set to automatically be clicked
vAvg = new JRadioButton("Average Velocity");
vAvg.setMnemonic(KeyEvent.VK_A);
vAvg.setActionCommand("averagevelocity");
//Acceleration Button
time = new JRadioButton("Change in time");
time.setMnemonic(KeyEvent.VK_S);
time.setActionCommand("deltaT");
//The change in time button
// Creates the group of buttons
ButtonGroup group = new ButtonGroup();
group.add(displacement);
group.add(vAvg);
group.add(time);
myListener = new RadioListener();
displacement.addActionListener(myListener);
vAvg.addActionListener(myListener);
time.addActionListener(myListener);
// Set up the picture label
pic = new JLabel(new ImageIcon(""+"numbers" + ".jpg")); //Set the Default Image
pic.setPreferredSize(new Dimension(177, 122));
// Puts the radio buttons down
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0, 1));
panel.add(displacement);
panel.add(vAvg);
panel.add(time);
setLayout(new BorderLayout());
add(panel, BorderLayout.WEST);
add(pic, BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(40,40,40,40));
}
//Listening to the buttons
class RadioListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
pic.setIcon(new ImageIcon(""+e.getActionCommand() + ".jpg"));
}
}
public static void main(String s[]) {
frame = new JFrame("∆x = Vavg * time");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
frame.getContentPane().add(new RadioButton(), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public void running() {
if ( displacement.isSelected()) {
//Option 1
System.out.println("The distance traveled on the x axis in meters is " + xDisplacement);
System.out.println("You can find the Average Velocity by dividing this number by time or find the time by dividing this number by the Average Velocity");
}
if ( vAvg.isSelected()) {
//Option 2
System.out.println("The average velocity in Meters per Second is " + xVAvg);
System.out.println("You can find the displacement by multiplying the time and this number together or to find the time, just divide the displacement by this number");
}
else {
//Option 3
System.out.println("The time in seconds is " + xTime);
System.out.println("You can find the displacement by multiplying the velocity times this number or you can find the average velocity by dividing the displacement by this number");
}
}
}
you are missing ; at this line of your code
displacement.setActionCommand("displacement")
and as MadProgrammer said call your running method in RadioListner class that implements ActionListner
class RadioListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
pic.setIcon(new ImageIcon(""+e.getActionCommand() + ".jpg"));
running();
}
}
Call running from your RadioListener's actionPerformed method

Java Swing (issue with ActionListener)

I have a take home assignment where I need to make a sudoku board that displays integers from a file on a board and allows someone to click a JButton and input a missing value.
I have gotten the board to show up using JPanel and printed the text file to the individual buttons but I can't figure out how to get the addActionListener to pick up any of the buttons that are missing values. It only works for the last button that is blank. (Blank buttons are given a value of 0).
my question is why is the last blank button only being targeted. There are 6 in total but only the last one brings up the dialogue box after being clicked?
public class MyCustomeFrame extends JFrame {
private int[][] numbers;
private String[] nums;
JButton b1;
JButton b2;
JButton b3;
JButton b4;
private JPanel p2;
public MyCustomeFrame() {
// Create the border layout
setLayout(new BorderLayout(5, 5));
// Create a new panel for the buttons to be placed on
JPanel p1 = new JPanel();
// Create 3 buttons
b1 = new JButton("Load");
b2 = new JButton("Save");
b3 = new JButton("Check");
// Adds the 3 buttons to the panel
p1.add(b1);
p1.add(b2);
p1.add(b3);
// Create the event handlers for when the button is pressed
b1.addActionListener(new MyButtonHandler());
b2.addActionListener(new MyButtonHandler());
b3.addActionListener(new MyButtonHandler());
// Place the panel south in the window
add(p1, BorderLayout.SOUTH);
p2 = new JPanel();
// Define the grid parameters
p2.setLayout(new GridLayout(9, 9, 5, 5));
// Show the grid
add(p2, BorderLayout.CENTER);
int[][] numbers = new int[9][9];
int rowIdx = 0;
//This is where i read the input file located on my computer and place the numbers on the Sudoku board
try {
BufferedReader bReader = new BufferedReader(new FileReader(
"C:\\Users\\Derek\\Desktop\\input.txt"));
String line = bReader.readLine();
while (line != null) {
nums = line.split(",");
for (int i = 0; i < numbers[0].length; i++) {
numbers[rowIdx][i] = Integer.parseInt(nums[i]);
// This creates the individual buttons that are then placed on the board
if (numbers[rowIdx][i] >= 1) {
p2.add(new JButton(nums[i]));
} else {
//this is where I'm having the issue
b4 = new JButton(" ");
p2.add(b4);
b4.addActionListener(new MyButtonHandler());
}
}
rowIdx++;
line = bReader.readLine();
}
bReader.close();
} catch (FileNotFoundException g) {
System.out.println("File Not Found!");
} catch (IOException g) {
System.out.println("Something went wrong...Try Again");
g.printStackTrace();
}
}
class MyButtonHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
System.out.println("Loading File...");
} else if (e.getSource() == b2) {
System.out.println("Saving File...");
try {
BufferedWriter bWriter = new BufferedWriter(new FileWriter(
new File("C:\\SudokuSave.txt"), true));
bWriter.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} else if (e.getSource() == b3) {
System.out.println("Checking Solution...");
} else if (e.getSource() == b4) {
System.out.println("clicked");
JOptionPane.showInputDialog("Input a number between 1 - 9");
}
}
}
}
The reason for the problem was already pointed out by Vyacheslav in https://stackoverflow.com/a/21803753
Some hints:
You should use proper variable names. Calling a JButton b2 is horrible. When it is a "Load" button, then call it loadButton. When it is a "Save" button, call it saveButton. Code is written (at most) once, but read possibly hundreds of times. And Java code should read like prose, in the best case.
Reading a file with a hard-coded name in the constructor, in order to build the GUI components, is a very bad practice. You should consider creating some "Data model" that contains the information that you can create your GUI from, and split the process of
reading the file and store the data in the data model, and
creating the GUI from a data model.
This will also allow you to handle Exceptions better than by printing
System.out.println("Something went wrong...Try Again");
In order to resolve your problem, you might consider using anonymous listeners. Creating a single ActionListener that is responsible for all buttons is not very flexible. Usually, you only want to associate a click on a button with a single call to a (private) method. So for example, you could write
JButton saveButton = new JButton("Save");
saveButton.addActionListener(new ActionListener() {
{
#Override
public void actionPerformed(ActionEvent) {
saveButtonWasPressed();
}
});
Particularly for the case that you have several buttons wit similar functionality, this approach offers an advantage: You can create anonymous listeners for each button, each of them containing the required information about which button was clicked - roughly applied to your code:
if (numbers[rowIdx][i] == 0) {
JButton b = new JButton(" ");
panel.add(b);
b.addActionListener(createActionListener(rowIdx, i));
}
...
private ActionListener createActionListener(
final int row, final int column) {
ActionListener actionListener = new ActionListener() {
{
#Override
public void actionPerformed(ActionEvent) {
System.out.println("Pressed button in row "+row+", column "+column);
}
};
return actionListener;
}
Your mistake is pretty simple - every iteration of for you are assigning a new JButton object reference to b4 variable so finally b4 refers to last JButton you had created.

JCombo Box not updating selected item / Innerclass access

I am making a simple calculator in Java, I'm pretty new to Java but I've done a lot of work with languages like it.
The problem is, I need to have the combo box select an item and have it kept up to date, either in a place holder, or in the box itself.
This is the basic class that sets up the frame and everything.
private void initComponents()
{
//TODO:make controls here
//TODO:DONE
JFrame calculator = new JFrame("Steven Seppälä");
calculator.setLayout(new GridLayout(2, 2, 0, 0));
calculator.setSize(400,300);
//"calculator" is the holder for which all the
//items must attach to
calculator.add(new JLabel("Enter the first fraction('1/2')"));
// calculator.add(new JToolBar.Separator(new Dimension(0,10)));
calculator.add(field1);
// calculator.add(new JToolBar.Separator(new Dimension(0,10)));
//TODO: ADD COMBO BOX HERE
String[] operationList = {"+","-","*","/"};
JComboBox operationBox = new JComboBox(operationList);
calculator.add(operationBox);
/*Tried doing the following as well, but it just gave the index 0 consistantly
without changeing, regaurdless of if it did change or not */
// String thing = operationBox.getSelectedItem().toString();
// System.out.println("Selected Operation is: " + thing);
// operationCall = operationBox.getSelectedItem();
operationBox.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//DEBUGGING
operationBox.getSelectedItem().toString();
}
});
calculator.add(new JLabel("Enter the next fraction('3/4')\n",1));
// calculator.add(new JToolBar.Separator(new Dimension(0,0)));
calculator.add(field2);
// calculator.add(new JToolBar.Separator(new Dimension(0,0)));
JButton Cal = new JButton("Calculate");
calculator.add(Cal);
Cal.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//DEBUGGING
System.out.println("Finalizing Calculations...");
calculations();
}
});
//sets exit conditions and the visibility of the window
calculator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
calculator.setVisible(true);
calculator.add(new JLabel(results));
//TODO: add to(?) frame
//TODO:DONE
}
The action listener for the Calculate button works fine, but when I compile as it is now, I get the error message :
FractionFrame.java:53: error: local variable operationBox is accessed from within inner class; needs to be declared final
System.out.println(operationBox.getSelectedItem().toString());
^
In the ActionListener you can access the combo box by using:
JComboBox comboBox = (JComboBox)e.getSource();
Instead of:
JComboBox operationBox = new JComboBox(operationList);
Make it:
final JComboBox operationBox = new JComboBox(operationList);

How to change a JLabel dynamically

I have one JLabel and one button, the JLabel displays the number of times the button has been pressed, however, I cant figure how to update the JLabel displaying the number of button presses.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class SimpleGui {
private JFrame f = new JFrame("Basic GUI"); // create Frame
int pressed = 0; // tracks number of button presses.
JLabel label1 = new JLabel("You have pressed button " + pressed + "times.");
private JButton start = new JButton("Click To Start!");
public SimpleGui() {
// Setup Main Frame
f.getContentPane().setLayout(new GridLayout(0, 1));
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
calculate();
}
});
// Add components
f.add(label1);
f.add(start);
// Allows the Swing App to be closed
f.addWindowListener(new ListenCloseWdw());
}
public class ListenMenuQuit implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
public class ListenCloseWdw extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
public void launchFrame() {
// Display Frame
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack(); // Adjusts panel to components for display
f.setVisible(true);
}
public static void main(String args[]) {
PrimeTime gui = new PrimeTime();
gui.launchFrame();
}
public void calculate() {
pressed++;
label1 = new JLabel("You have pressed button " + pressed + "times.");
// update the GUI with new jLabel
f.repaint();
}
}
The issue is that you are creating a new, different JLabel that is not show in the panel.
do
public void calculate(){
pressed++;
this.label1.setText("You have pressed button " + pressed + "times.");
}
Change label1 = new JLabel("You have pressed button " + pressed + "times."); to label1.setText("You have pressed button " + pressed + "times.");
You only call calculate() when the button start is clicked. So you can move that method into the ActionListener for the button. And by calling setText on the JLabel, you don't have to call repaint. Normally you don't have to call repaint in Swing. E.g. change your code to something like this instead:
final JLabel label1 = new JLabel("You have pressed button " + pressed + "times.");
private JButton start = new JButton(new AbstractAction("Click To Start!") {
public void actionPerformed(ActionEvent e) {
pressed++;
label1.setText("You have pressed button " + pressed + "times.");
}
});
Try and understand this code, here i use an icon to set the label's image and the getIcon method of Label's to change the icon of previous label using setIcon method.
Icon picLabelicon new ImageIcon(img); /* setting the icon initially */
JLabel picLabel = new JLabel();
picLabel.setIcon(picLabelicon);
Now you have set the icon initially now lets change it dynamically
JLabel modify = new JLabel(new ImageIcon(newimg)); /* new label you wanted to use */
picLabelicon=modify.getIcon();
picLabel.setIcon(picLabelicon);
revalidate();
repaint();

Categories

Resources