I load my jCalendar to Calendar then I used the day for the index but problem every month's days different so I can't select. When I click 21, I'm selecting 10.
Calendar cal = Calendar.getInstance();
cal.setTime(jCalendar1.getDate());
int day = cal.get(Calendar.DAY_OF_MONTH);
JPanel jpanel = jCalendar1.getDayChooser().getDayPanel();
Component compo[] = jpanel.getComponents();
compo[day].setBackground(Color.red);
public class CalendarTest2 extends JFrame {
private static final long serialVersionUID = 1L;
public CalendarTest2() {
Calendar cal = Calendar.getInstance();
JCalendar jCalendar1 = new JCalendar();
cal.setTime(jCalendar1.getDate());
int dayToBeSelected = cal.get(Calendar.DAY_OF_MONTH);
dayToBeSelected = 21;
JPanel jpanel = jCalendar1.getDayChooser().getDayPanel();
Component compo[] = jpanel.getComponents();
for (Component comp : compo) {
if (!(comp instanceof JButton))
continue;
JButton btn = (JButton) comp;
if (btn.getText().equals(String.valueOf(dayToBeSelected)))
comp.setBackground(Color.red);
}
add(jpanel);
}
public static void main(String[] args) {
CalendarTest2 test = new CalendarTest2();
test.setVisible(true);
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.setSize(800, 800);
}
}
Instead of accessing the 'button to be selected' through index,
try to access the button through the text(day number) written on it.
The reason is, calendar of a month is displayed using 49 buttons arranged in 7x7 fashion .
So for ex) index 0 will always point to 'Sunday' button.
Related
using Java and Java Swing for a GUI. The scenario is that I want a user to enter in a desired time (in a JTextbox) in the format of HH:MM:SS and from that given time, countdown by seconds until it hits zero.
Currently I am using a timer and the timer.between function. I create an Instant() from the user input time and also use instant.now().
The instants are being created, however, the countdown clock doesn't count down from the user input time, but rather some random numbers that I can't figure out where they are coming from. Can anyone else see the problem?
javax.swing.Timer countDown = new javax.swing.Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Duration countingDown = Duration.between(Instant.now(), userInputCountDown);
autoShutOffTF.setText(String.format("%02d:%02d:%02d",
countingDown.toHours(),
countingDown.toMinutes() % 60,
countingDown.getSeconds() % 60));
}
});
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Getting user input, parsing String in the form of HH:MM:SS
String countdownInput = autoShutOffTF.getText();
String getHours = countdownInput.substring(0,2);
int hours = Integer.parseInt(getHours);
String getMins = countdownInput.substring(3,5);
int mins = Integer.parseInt(getMins);
String getSecs = countdownInput.substring(6,8);
int seconds = Integer.parseInt(getSecs);
//Creating a date instance, to get the current year, month and date
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
//creating a new calendar with all of the data
Calendar cal = Calendar.getInstance();
cal.set(year, month, day, hours, mins, seconds);
//creating a new instant with the new calendar with all of the data
userInputCountDown = cal.toInstant();
//starting timer
countDown.start();
}
});
Don't use Date or Calendar, the java.time API is more the capable of achieving what you want.
Looking at this...
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
//creating a new calendar with all of the data
Calendar cal = Calendar.getInstance();
cal.set(year, month, day, hours, mins, seconds);
You're creating a new time, based on the hours/mins/seconds, but, what worries me is, is what happens if the time is less than now? This "might" be the issue you're having.
So, some thing you might want to do is verify if the time is before or after the current time and roll the day accordingly - assuming you want to use an absolute time (ie create a timer which counts down from now to 6pm)
This...
Duration countingDown = Duration.between(Instant.now(), userInputCountDown);
also seems off to me, as userInputCountDown should be in the future
The following example takes a slightly different approach, as it creates a "timer" that will create a target in the future (based on the input) from the current time (adding the hours, mins and seconds) and use it as the anchor point for the count down.
So, you might say, "create a 1 hour" timer, for example.
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField targetHours;
private JTextField targetMins;
private JTextField targetSeconds;
private Instant futureTime;
private Timer timer;
private JLabel countDown;
public TestPane() {
setLayout(new GridBagLayout());
targetHours = new JTextField("00", 2);
targetMins = new JTextField("00", 2);
targetSeconds = new JTextField("00", 2);
JPanel targetPane = new JPanel(new GridBagLayout());
targetPane.add(targetHours);
targetPane.add(new JLabel(":"));
targetPane.add(targetMins);
targetPane.add(new JLabel(":"));
targetPane.add(targetSeconds);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(8, 8, 8, 8);
add(targetPane, gbc);
JButton btn = new JButton("Start");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
futureTime = LocalDateTime.now()
.plusHours(Long.parseLong(targetHours.getText()))
.plusMinutes(Long.parseLong(targetMins.getText()))
.plusSeconds(Long.parseLong(targetSeconds.getText()))
.atZone(ZoneId.systemDefault()).toInstant();
if (timer != null) {
timer.stop();
}
countDown.setText("---");
timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Duration duration = Duration.between(Instant.now(), futureTime);
if (duration.isNegative()) {
timer.stop();
timer = null;
countDown.setText("00:00:00");
} else {
String formatted = String.format("%02d:%02d:%02d", duration.toHours(), duration.toMinutesPart(), duration.toSecondsPart());
countDown.setText(formatted);
}
}
});
timer.start();
}
});
add(btn, gbc);
countDown = new JLabel("---");
add(countDown, gbc);
}
}
}
WARNING - I do NO validation on the input, so you will have to be careful.
If, instead, you wanted to count down to a particular point in time (ie count down from now to 6pm), then you would need to use LocalDateTime#withHour(Long)#withMinute(Long)#withSecond(Long) chain instead. But, beware, you'll have to verify if the time is in the future or past and take appropriate action, because if you want to countdown to 6pm, but it's 7pm ... what does that actually mean :/ ?
I am currently having another problem, this time with JSpinners. I want to add dynamically JSpinners on the screen by right click, via the add button. After I add them, I want them to be inserted in an array of JSpinners and then the data from the JSpinners to be stored into a Date ArrayList. So far I am facing this problem:
If I add a new JSpinner the Date Array does not get automatically the Date from the second JSpinner or third or so on. It only gets the data from the first JSpinner.
I am really lost here. Appreciate any help here. Thanks and best regards
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import javax.swing.event.*;
import java.text.SimpleDateFormat;
public class TestingGround
{
Toolkit toolkit;
JFrame frame;
JPopupMenu menu;
Calendar calendar1, calendar2;
Date startDate, saveThisDate;
String stringStoredInitialRequestDate;
ArrayList <Date> dateArray; // array to store the dates from the request date
JSpinner spinner;
ArrayList <JSpinner> spinnerArray;
SpinnerModel model1;
int countAddClicks;
int val1;
public TestingGround()
{
frame = new JFrame("Testing ground area");
centerToScreen();
menu = new JPopupMenu();
JMenuItem addRow = new JMenuItem("Add ComboBox");
JMenuItem removeRow = new JMenuItem("Remove ComboBox");
JPanel panel = new JPanel();
JPanel mainGridPanel = new JPanel();
mainGridPanel.setLayout(new GridLayout(0,2));
mainGridPanel.setBorder(BorderFactory.createLineBorder(Color.red));
panel.add(mainGridPanel);
// -------------------------------------------
dateArray = new <Date> ArrayList(); // array used to store the initial request dates
spinnerArray = new <JSpinner> ArrayList();
JButton saveDataButton = new JButton("save state");
countAddClicks =0;
val1 = -1;
panel.add(saveDataButton);
// ACTION LISTENERS
addRow.addActionListener(new ActionListener(){ // Right click to add JComboBoxes to the screen
public void actionPerformed(ActionEvent event) {
System.out.println("Starting click is: " + countAddClicks);
// JSPINNER 1
calendar1 = Calendar.getInstance();
Date now = calendar1.getTime();
calendar1.add(Calendar.YEAR, -10);
Date startDate = calendar1.getTime();
calendar1.add(Calendar.YEAR, 20);
Date endDate = calendar1.getTime();
model1 = new SpinnerDateModel(now, startDate, endDate, Calendar.YEAR);
spinner = new JSpinner(model1); // creating Visual Spinner
String format = "dd MMM yy"; // formatting Visual Spinner 1
JSpinner.DateEditor editor = new JSpinner.DateEditor(spinner, format);
spinner.setEditor(editor); // applying the formatting to the visual spinner
spinnerArray.add(countAddClicks,spinner); // adds the spinner to the array of spinners
/*
model1.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
changedDate = ((SpinnerDateModel) e.getSource()).getDate();
}
});
*/
saveThisDate = now;
dateArray.add(countAddClicks, saveThisDate); // add to the DATE array the new date (in the correct slot, going side by side with the other array);
countAddClicks++;
System.out.println("After click is: " + countAddClicks);
mainGridPanel.add(spinner); // add the JTextField to the JPanel
mainGridPanel.repaint();
mainGridPanel.revalidate();
}
});
removeRow.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent event) {
countAddClicks--;
if (countAddClicks <0) {
countAddClicks = 0;
}
if (spinnerArray.size() > 0 & dateArray.size() >0 ) {
spinner = spinnerArray.remove(spinnerArray.size()-1);
mainGridPanel.remove(spinner);
}
System.out.println("After removal click is: " + countAddClicks);
mainGridPanel.revalidate();
mainGridPanel.repaint();
}
});
saveDataButton.addActionListener (new ActionListener() {
public void actionPerformed(ActionEvent e) {
dateArray.clear();
for (int i=0; i< spinnerArray.size(); i++) {
JSpinner tempSpinner = spinnerArray.get(i); // creating a temporary spinner
calendar2 = Calendar.getInstance(); // creating a temporary calendar
Date now2 = calendar2.getTime();
calendar1.add(Calendar.YEAR, -50);
Date startDate2 = calendar2.getTime();
calendar2.add(Calendar.YEAR, 50);
Date endDate2 = calendar2.getTime();
SpinnerModel model2 = new SpinnerDateModel(now2, startDate2, endDate2, Calendar.YEAR);
tempSpinner.setModel(model2); // setting up a temporary spinnerModel and adding it to this instance of JSpinner
model2.addChangeListener(new ChangeListener() { // adding a listener to this model2
public void stateChanged(ChangeEvent e) {
saveThisDate = ((SpinnerDateModel) e.getSource()).getDate(); // checking for user input
System.out.println(saveThisDate); // for testing purpose it is showing that it detects the change
}
});
dateArray.add(saveThisDate); // add to the DATE array the new date (in the correct slot, going side by side with the other array);
}
// Only for checking purpose if the arrays are the correct sizes
System.out.println();
System.out.println("The size of the JSpinner Array is: " + spinnerArray.size() ); // showing correct
System.out.println("The content of the Date Array is: " + dateArray ); // checking the Date array. This is where data is not added, it is not working!
System.out.println("The size of the Date Array is: " + dateArray.size()); // showing correct
System.out.println();
}
});
// Cand dau click din butonul cel mai din dreapta (3) se deschide menium popup
frame.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent event) {
if (event.getButton() == event.BUTTON3) {
menu.show(event.getComponent(), event.getX(),event.getY());
}
}
});
menu.add(addRow);
menu.add(removeRow);
frame.add(panel);
frame.setVisible(true);
}
public void centerToScreen()
{
frame.setSize(700,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("A Popup Menu");
toolkit = frame.getToolkit();
Dimension size = toolkit.getScreenSize();
frame.setLocation((size.width-frame.getWidth())/2, (size.height-frame.getHeight())/2);
}
public static void main(String[]args){
new TestingGround();
}
}
The source of the nulls in one of the ArrayLists: You're adding null values to the dateArray ArrayList
Date changedDate; // null
addRow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
// .....
dateArray.add(countAddClicks, changedDate); // changedDate is null
and you never change these values. Yes you assign a new Date instance to the changedDate variable, but the ArrayList is not holding variables, it's holding objects.
Note that here:
saveDataButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dateArray.clear();
for (int i = 0; i < spinnerArray.size(); i++) {
//.....
model2.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
changedDate = ((SpinnerDateModel) e.getSource()).getDate(); // **** (A) ****
System.out.println(changedDate);
}
});
// ...
}
}
});
again you change the Date instance held by the dateArray variable, but again, this has no effect on the nulls held by the ArrayList.
I suggest that you get rid of the dateArray ArrayList and instead extract the data from the JSpinners when needed (in a listener).
#Hovercraft Full Of Eels I have solved this problem!! I am so proud, now everything works. So it adds dynamically JSpinners and stores the dates in individual Array Slots. I will paste the code if anyone will search for something similar so they can use it as a reference. Thanks again
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import javax.swing.event.*;
import java.text.SimpleDateFormat;
public class TestingGround {
Toolkit toolkit;
JFrame frame;
JPopupMenu menu;
Calendar calendar1, calendar2;
Date startDate, saveThisDate;
ArrayList<Date> dateArray; // array to store the dates from the request date
JSpinner spinner;
ArrayList<JSpinner> spinnerArray;
SpinnerModel model1;
JPanel mainGridPanel;
int countAddClicks;
public TestingGround() {
frame = new JFrame("Testing ground area");
centerToScreen();
menu = new JPopupMenu();
JMenuItem addRow = new JMenuItem("Add ComboBox");
JMenuItem removeRow = new JMenuItem("Remove ComboBox");
JPanel panel = new JPanel();
mainGridPanel = new JPanel();
mainGridPanel.setLayout(new GridLayout(0, 2));
mainGridPanel.setBorder(BorderFactory.createLineBorder(Color.red));
panel.add(mainGridPanel);
// -------------------------------------------
dateArray = new <Date>ArrayList(); // array used to store the initial
// request dates
spinnerArray = new <JSpinner>ArrayList();
JButton saveDataButton = new JButton("save state");
countAddClicks = 0;
panel.add(saveDataButton);
// ACTION LISTENERS
addRow.addActionListener(new ActionListener() { // Right click to add
// JComboBoxes to the
// screen
public void actionPerformed(ActionEvent event) {
System.out.println("Starting click is: " + countAddClicks);
// JSPINNER 1
calendar1 = Calendar.getInstance();
Date now = calendar1.getTime();
calendar1.add(Calendar.YEAR, -10);
Date startDate = calendar1.getTime();
calendar1.add(Calendar.YEAR, 20);
Date endDate = calendar1.getTime();
model1 = new SpinnerDateModel(now, startDate, endDate, Calendar.YEAR);
spinner = new JSpinner(model1); // creating Visual Spinner
String format = "dd MMM yy"; // formatting Visual Spinner 1
JSpinner.DateEditor editor = new JSpinner.DateEditor(spinner, format);
spinner.setEditor(editor); // applying the formatting to the
// visual spinner
spinnerArray.add(countAddClicks, spinner); // adds the spinner
// to the array of
// spinners
saveThisDate = now;
dateArray.add(countAddClicks, saveThisDate); // add to the DATE
// array the new
// date (in the
// correct slot,
// going side by
// side with the
// other array);
countAddClicks++;
System.out.println("After click is: " + countAddClicks);
mainGridPanel.add(spinner); // add the JTextField to the JPanel
mainGridPanel.repaint();
mainGridPanel.revalidate();
}
});
removeRow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
countAddClicks--;
if (countAddClicks < 0) {
countAddClicks = 0;
}
if (spinnerArray.size() > 0 & dateArray.size() > 0) {
spinner = spinnerArray.remove(spinnerArray.size() - 1);
dateArray.remove(dateArray.size() - 1);
mainGridPanel.remove(spinner);
}
System.out.println("After removal click is: " + countAddClicks);
mainGridPanel.revalidate();
mainGridPanel.repaint();
}
});
saveDataButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dateArray.clear();
for (int i = 0; i < spinnerArray.size(); i++) {
JSpinner tempSpinner = new JSpinner(); // creating a
// temporary spinner
calendar2 = Calendar.getInstance(); // creating a temporary
// calendar
Date now2 = calendar2.getTime();
calendar2.add(Calendar.YEAR, -50);
Date startDate2 = calendar2.getTime();
calendar2.add(Calendar.YEAR, 50);
Date endDate2 = calendar2.getTime();
SpinnerModel model2 = new SpinnerDateModel(now2, startDate2, endDate2, Calendar.YEAR);
tempSpinner.setModel(model2); // setting up a temporary
// spinnerModel and adding
// it to this instance of
// JSpinner
model2.addChangeListener(new ChangeListener() { // adding a
// listener
// to this
// model2
public void stateChanged(ChangeEvent e) {
saveThisDate = ((SpinnerDateModel) e.getSource()).getDate(); // checking
// for
// user
// input
System.out.println(saveThisDate); // for testing
// purpose it is
// showing that
// it detects
// the change
}
});
saveThisDate = (Date) spinnerArray.get(i).getValue();
System.out.println("Content of the Spinner Array is: " + spinnerArray.get(i).getValue());
dateArray.add(saveThisDate); // add to the DATE array the
// new date (in the correct
// slot, going side by side
// with the other array);
}
// Only for checking purpose if the arrays are the correct sizes
System.out.println();
System.out.println("The size of the JSpinner Array is: " + spinnerArray.size()); // showing
// correct
System.out.println("The content of the Date Array is: " + dateArray); // checking
// the
// Date
// array.
// This
// is
// where
// data
// is
// not
// added,
// it
// is
// not
// working!
System.out.println("The size of the Date Array is: " + dateArray.size()); // showing
// correct
System.out.println();
}
});
// Cand dau click din butonul cel mai din dreapta (3) se deschide menium
// popup
frame.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent event) {
if (event.getButton() == event.BUTTON3) {
menu.show(event.getComponent(), event.getX(), event.getY());
}
}
});
menu.add(addRow);
menu.add(removeRow);
frame.add(panel);
frame.setVisible(true);
}
public void centerToScreen() {
frame.setSize(700, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("A Popup Menu");
toolkit = frame.getToolkit();
Dimension size = toolkit.getScreenSize();
frame.setLocation((size.width - frame.getWidth()) / 2, (size.height - frame.getHeight()) / 2);
}
public static void main(String[] args) {
new TestingGround();
}
}
I am creating a dumb phone (like old traditional phone) and I'm using GUI programming. I need help with dialing the numbers. I don't know how to get the numbers to pop up on the display and stay there, and also use the delete button to delete the numbers that is up on the display too. I will post a youtube link so you can see a sample run.
I am currently stuck on passing the text from the button of each number that should display the number, however it's displaying the text of the button. I also, don't know how to keep the number there when other buttons are pressed without it being reset.
Here is my code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.*;
public class DumbPhone extends JFrame
{
private static final long serialVersionUID = 1L;
private static final int WIDTH = 300;
private static final int HEIGHT = 500;
private static final String CALL_BUTTON_TEXT = "Call";
private static final String TEXT_BUTTON_TEXT = "Text";
private static final String DELETE_BUTTON_TEXT = "Delete";
private static final String CANCEL_BUTTON_TEXT = "Cancel";
private static final String SEND_BUTTON_TEXT = "Send";
private static final String END_BUTTON_TEXT = "End";
private static final String CALLING_DISPLAY_TEXT = "Calling...";
private static final String TEXT_DISPLAY_TEXT = "Enter text...";
private static final String ENTER_NUMBER_TEXT = "Enter a number...";
private JTextArea display;
private JButton topMiddleButton;
private JButton topLeftButton;
private JButton topRightButton;
private JButton[] numberButtons;
private JButton starButton;
private JButton poundButton;
private boolean isNumberMode = true;
private String lastPressed = "";
private int lastCharacterIndex = 0;
private Date lastPressTime;
public DumbPhone()
{
setTitle("Dumb Phone");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
createContents();
setVisible(true);
topLeftButton.setEnabled(false);
}
private void createContents()
{
//create JPanel, and JTextArea display
JPanel panel = new JPanel(new GridLayout(5,3));
display = new JTextArea();
display.setPreferredSize(new Dimension(280, 80));
display.setFont(new Font("Helvetica", Font.PLAIN, 32));
display.setLineWrap(true);
display.setEnabled(false);
panel.add(display);
//create JButtons
topLeftButton = new JButton(DELETE_BUTTON_TEXT);
topMiddleButton = new JButton((CALL_BUTTON_TEXT));
topRightButton = new JButton((TEXT_BUTTON_TEXT));
numberButtons = new JButton[10];
numberButtons[1] = new JButton("<html><center>1<br></center></html>");
numberButtons[2] = new JButton("<html><center>2<br>ABC</center></html>");
numberButtons[3] = new JButton("<html><right>3<br>DEF</right></html>");
numberButtons[4] = new JButton("<html><center>4<br>GHI</center></html>");
numberButtons[5] = new JButton("<html><center>5<br>JKL</center></html>");
numberButtons[6] = new JButton("<html><center>6<br>MNO</center></html>");
numberButtons[7] = new JButton("<html><center>7<br>PQRS</center></html>");
numberButtons[8] = new JButton("<html><center>8<br>TUV</center></html>");
numberButtons[9] = new JButton("<html><center>9<br>WXYZ</center></html>");
numberButtons[0] = new JButton("<html><center>0<br>space</center></html>");
poundButton = new JButton("#");
starButton = new JButton("*");
//add JButtons to buttons JPanel
panel.add(topLeftButton);
panel.add(topMiddleButton);
panel.add(topRightButton);
panel.add(numberButtons[1]);
panel.add(numberButtons[2]);
panel.add(numberButtons[3]);
panel.add(numberButtons[4]);
panel.add(numberButtons[5]);
panel.add(numberButtons[6]);
panel.add(numberButtons[7]);
panel.add(numberButtons[8]);
panel.add(numberButtons[9]);
panel.add(starButton);
panel.add(numberButtons[0]);
panel.add(poundButton);
//add Listener instance (inner class) to buttons
topLeftButton.addActionListener(new Listener());
topMiddleButton.addActionListener(new Listener());
topRightButton.addActionListener(new Listener());
//JButton[] array = new JButton[10];
for (int i = 0; i < numberButtons.length; i++)
{
numberButtons[i].addActionListener(new Listener());
numberButtons[i] = new JButton(String.valueOf(i));
}
starButton.addActionListener(new Listener());
poundButton.addActionListener(new Listener());
//add display and buttons to JFrame
setLayout(new BorderLayout());
add(display, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
}
private class Listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == topLeftButton)
{
if(lastPressTime == null)
{
display.setText(ENTER_NUMBER_TEXT);
}
else
{
topLeftButton.setEnabled(true);
lastCharacterIndex--;
lastPressed = lastPressTime.toString();
}
}
else if(e.getSource() == topMiddleButton)
{
if(lastPressTime == null || lastCharacterIndex == 0)
{
display.setText(ENTER_NUMBER_TEXT);
}
else
{
display.setText(CALLING_DISPLAY_TEXT);
}
}
else if(e.getSource() == topRightButton)
{
if(lastPressTime == null || lastCharacterIndex == 0)
{
display.setText(TEXT_DISPLAY_TEXT);
}
else
{
display.setText(CALLING_DISPLAY_TEXT);
}
}
else
{
topLeftButton.setEnabled(true);
if (e.getSource() instanceof JButton)
{
//String text = ((JButton) e.getSource()).getText();
display.setText(lastPressed + " f" + numberButtons[lastCharacterIndex].getText());
}
}
Date currentPress = new Date();
long currentTime = currentPress.getTime();
if(lastPressTime != null)
{
//long lastPressTime = lastPressTime.getTime();
//subtract lastPressTime from currentPress time to find amount of time elapsed since last button pressed.
}
lastPressTime = currentPress;
String buttonLetters = ""; // Parse Letter from button (e.g "abc").
//update lastCharacterIndex.
lastCharacterIndex++;
lastCharacterIndex = lastCharacterIndex % buttonLetters.length();
}
}
for example, if I push the button 2, instead of giving me "2", it will give me < html>< center>2ABC < / center >< / html >
Therefore, I need help with
Having the numberButtons, when pushed to show the numbers that were pushed.
Be able to delete those numbers.
Here is the link to the sample run: https://www.youtube.com/watch?v=evmGWlMSqqg&feature=youtu.be
Try starting the video 20 seconds in.
to delete the number, you can use the labelname.setText("")
At a basic level, you simply want to maintain the "numbers" separately from the UI. This commonly known as a "model". The model lives independently of the UI and allows the model to be represented in any number of possible ways based on the needs of the application.
In your case, you could use a linked list, array or some other simple sequential based list, but the easiest is probably to use a StringBuilder, as it provides the functionality you require (append and remove) and can make a String very simply.
So, the first thing you need to do is create an instance of model as an instance level field;
private StringBuilder numbers = new StringBuilder(10);
this will allow the buffer to be accessed any where within the instance of the class.
Then you need to update the model...
else
{
topLeftButton.setEnabled(true);
if (e.getSource() instanceof JButton)
{
String text = numberButtons[lastCharacterIndex].getText();
numbers.append(text);
}
}
To remove the last character you can simply use something like...
if (numbers.length() > 0) {
numbers.deleteCharAt(numbers.length() - 1);
}
Then, when you need to, you update the UI using something like...
display.setText(numbers.toString());
Now, this is just basic concepts, you will need to take the ideas and apply it to your code base
LINK TO GUI IMAGE HERE -------> http://imgur.com/uPD0K5S
public class MainMenu extends javax.swing.JFrame {
public MainMenu() {
initComponents();
cmbRoomNumber.setEnabled(false);
jPanel1.setVisible(false);
btnBook.setEnabled(false);
//SETTING COMBOBOXES TO NONE
cmbPhotoId.setSelectedIndex(-1);
cmbStayDuration.setSelectedIndex(-1);
//LABELS VALIDATION
jlblNameVer.setVisible(false);
//SETTING DATE TODAY
Date now = new Date();
//Set date format as you want
SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy");
this.ftxtCheckinDate.setText(sf.format(now));
}
As you can see i want to add days to Check-out Date(ftxtCheckOutDate) depending on how many days selected in the combobox(cmbStayDuration)
Im using netbeans JFrame
Thanks :)
private void cmbStayDurationActionPerformed(java.awt.event.ActionEvent evt) {
}
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, combobox number);
Basically Calendar class has a function to add days.
Get the date now, get the combo box day, then add it.
For example:
public static void main(String[] args) {
// TODO code application logic here
Calendar c = Calendar.getInstance();
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
c.setTime(d);
System.out.println(sdf.format(c.getTime()));
c.setTime(d);
c.add(Calendar.DATE, 10);
System.out.println(sdf.format(c.getTime()));
}
Output:
05/11/2015
15/11/2015
As for changing the value of Check-out Date form as the ComboBox changes, you can add either an ActionListener to listen to it change.
Example
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Improve this question
Is there any good and free Date AND Time Picker available for Java Swing?
There are a lot date pickers available but no date AND time picker. This is the closest I came across so far: Looking for a date AND time picker
Anybody?
For a time picker you can use a JSpinner and set a JSpinner.DateEditor that only shows the time value.
JSpinner timeSpinner = new JSpinner( new SpinnerDateModel() );
JSpinner.DateEditor timeEditor = new JSpinner.DateEditor(timeSpinner, "HH:mm:ss");
timeSpinner.setEditor(timeEditor);
timeSpinner.setValue(new Date()); // will only show the current time
You can extend the swingx JXDatePicker component:
"JXDatePicker only handles dates without time. Quite often we need to let the user choose a date and a time. This is an example of how to make use JXDatePicker to handle date and time together."
http://wiki.java.net/twiki/bin/view/Javadesktop/JXDateTimePicker
EDIT: This article disappeared from the web, but as SingleShot discovered, it is still available in an internet archive. Just to be sure, here is the full working example:
import org.jdesktop.swingx.calendar.SingleDaySelectionModel;
import org.jdesktop.swingx.JXDatePicker;
import javax.swing.*;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.DateFormatter;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.*;
import java.awt.*;
/**
* This is licensed under LGPL. License can be found here: http://www.gnu.org/licenses/lgpl-3.0.txt
*
* This is provided as is. If you have questions please direct them to charlie.hubbard at gmail dot you know what.
*/
public class DateTimePicker extends JXDatePicker {
private JSpinner timeSpinner;
private JPanel timePanel;
private DateFormat timeFormat;
public DateTimePicker() {
super();
getMonthView().setSelectionModel(new SingleDaySelectionModel());
}
public DateTimePicker( Date d ) {
this();
setDate(d);
}
public void commitEdit() throws ParseException {
commitTime();
super.commitEdit();
}
public void cancelEdit() {
super.cancelEdit();
setTimeSpinners();
}
#Override
public JPanel getLinkPanel() {
super.getLinkPanel();
if( timePanel == null ) {
timePanel = createTimePanel();
}
setTimeSpinners();
return timePanel;
}
private JPanel createTimePanel() {
JPanel newPanel = new JPanel();
newPanel.setLayout(new FlowLayout());
//newPanel.add(panelOriginal);
SpinnerDateModel dateModel = new SpinnerDateModel();
timeSpinner = new JSpinner(dateModel);
if( timeFormat == null ) timeFormat = DateFormat.getTimeInstance( DateFormat.SHORT );
updateTextFieldFormat();
newPanel.add(new JLabel( "Time:" ) );
newPanel.add(timeSpinner);
newPanel.setBackground(Color.WHITE);
return newPanel;
}
private void updateTextFieldFormat() {
if( timeSpinner == null ) return;
JFormattedTextField tf = ((JSpinner.DefaultEditor) timeSpinner.getEditor()).getTextField();
DefaultFormatterFactory factory = (DefaultFormatterFactory) tf.getFormatterFactory();
DateFormatter formatter = (DateFormatter) factory.getDefaultFormatter();
// Change the date format to only show the hours
formatter.setFormat( timeFormat );
}
private void commitTime() {
Date date = getDate();
if (date != null) {
Date time = (Date) timeSpinner.getValue();
GregorianCalendar timeCalendar = new GregorianCalendar();
timeCalendar.setTime( time );
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, timeCalendar.get( Calendar.HOUR_OF_DAY ) );
calendar.set(Calendar.MINUTE, timeCalendar.get( Calendar.MINUTE ) );
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Date newDate = calendar.getTime();
setDate(newDate);
}
}
private void setTimeSpinners() {
Date date = getDate();
if (date != null) {
timeSpinner.setValue( date );
}
}
public DateFormat getTimeFormat() {
return timeFormat;
}
public void setTimeFormat(DateFormat timeFormat) {
this.timeFormat = timeFormat;
updateTextFieldFormat();
}
public static void main(String[] args) {
Date date = new Date();
JFrame frame = new JFrame();
frame.setTitle("Date Time Picker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DateTimePicker dateTimePicker = new DateTimePicker();
dateTimePicker.setFormats( DateFormat.getDateTimeInstance( DateFormat.SHORT, DateFormat.MEDIUM ) );
dateTimePicker.setTimeFormat( DateFormat.getTimeInstance( DateFormat.MEDIUM ) );
dateTimePicker.setDate(date);
frame.getContentPane().add(dateTimePicker);
frame.pack();
frame.setVisible(true);
}
}
Use the both combined.. that's what i did:
public static JPanel buildDatePanel(String label, Date value) {
JPanel datePanel = new JPanel();
JDateChooser dateChooser = new JDateChooser();
if (value != null) {
dateChooser.setDate(value);
}
for (Component comp : dateChooser.getComponents()) {
if (comp instanceof JTextField) {
((JTextField) comp).setColumns(50);
((JTextField) comp).setEditable(false);
}
}
datePanel.add(dateChooser);
SpinnerModel model = new SpinnerDateModel();
JSpinner timeSpinner = new JSpinner(model);
JComponent editor = new JSpinner.DateEditor(timeSpinner, "HH:mm:ss");
timeSpinner.setEditor(editor);
if(value != null) {
timeSpinner.setValue(value);
}
datePanel.add(timeSpinner);
return datePanel;
}
There is the FLib-JCalendar component with a combined Date and Time Picker.
As you said Date picker is easy, there are many out there.
As for a Time picker, check out how Google Calendar does it when creating a new entry. It allows you to type in anything while at the same time it has a drop down in 30 mins increments. The drop down changes when you change the minutes.
If you need to allow the user to pick seconds, then the best you can do is a typable/drop down combo