Reseting Spinner Value in Java Swing - java

I have knowledge about C programming but I'm a newbie Java Programmer, and I want to ask a question to you. I try to set both spinners values null if they are less then "1" but I couldn't do it. I'm waiting for your helps, thank you.
Spinner spinnermin = new JSpinner();
spinnermin.addFocusListener(new FocusAdapter() {
#Override
public void focusLost(FocusEvent e) {
valuemin =(Integer) spinnermin.getValue();
if(valuemin<0){
spinnermin.setValue(null);
}
}
});
spinnermin.setBounds(478, 215, 76, 20);
frame.getContentPane().add(spinnermin);
JSpinner spinnerhour = new JSpinner();
spinnerhour.addFocusListener(new FocusAdapter() {
#Override
public void focusLost(FocusEvent e) {
valuehour = (Integer) spinnerhour.getValue();
if(valuehour<1){
spinnerhour.setValue(null);
}
}
});
spinnerhour.setBounds(362, 215, 86, 20);
frame.getContentPane().add(spinnerhour);

You state:
I try to set both spinners values null if they are less then "1" but I couldn't do it.
Much better to use a SpinnerNumberModel that doesn't allow for negative values. For example,
JSpinner hourSpinner = new JSpinner(new SpinnerNumberModel(1, 1, 24, 1));
This creates a JSpinner that allows int values from 1 to 24, and that starts at 1.
It really doesn't make sense to assign null to a component that expects to hold a numeric value, and rather than try to do this, better to limit the user's ability to input unacceptable values. Also please have a look at the JSpinner Tutorial.
As a side recommendation, while null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.

Related

Problems with updating a JScrollPane

I know there are already 1000 threads out there that deal with this, but I've tried everything and nothing has worked so far. I am making a little app that lets me log work hours, so I have an array of strings that contains all of the hours that I work. I am trying to update the array, then update the JList that has the text, then update the JScrollPane that has the list on it. This way I can see the hours I added directly after I add them on a window off to the side.
I've tried revalidate() and repaint() on every object, I've tried the removeAll() method on the list as well as the scroll pane, and nothing seems to work! The only thing I CAN do is change the color of the border on the scrollpane!! I don't know why the layout is so easy to update but not the text on the pane!
Thanks for any help you can give! If you want to see the code, I can post it but it's a little confusing as this is just a very small part of the whole.
I try to sort you out from it.
As you trying to add time string in Jlist then want to update your Jscroll pane.
I will go through simple
Just create your design view like:
Jpanel1(card layout)
|
----> Jscrollpane1
|
------>Jpanel2
|
--------> Your Jlist will be here on dynamic runtime
and you can manage panels instead of Jlist.
But here I go with list
public void getUpdateOldWorkTimeList()
{
List<String> workTimeList;
SwingWorker<Void, Void> mySwingWorker = new SwingWorker<Void, Void>() {
#Override
protected Void doInBackground() throws Exception {
workTimeList=getMyTimeList(); // here you put your work time array
Thread.sleep(100);
return null;
}
};
mySwingWorker.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("state")) {
if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
jPanel2.removeAll();
jPanel2.revalidate();
jPanel2.repaint();
for (int i = 0; i < workTimeList.size(); i++) {
jPanel2.add(new ModelJList()).setVisible(true);
}
}
}
});
jPanel3.setLayout(new model.WrapLayout(FlowLayout.CENTER, 1, 0));
jPanel1.setBackground(new Color(0, 0, 0, 0));
jScrollPane1.setBackground(new Color(0, 0, 0, 0));
i
jScrollPane1.getVerticalScrollBar().setUnitIncrement(16);
int remainScroll=jScrollPane1.getVerticalScrollBar().getMaximum()- jScrollPane1.getVerticalScrollBar().getModel().getExtent();
jScrollPane1.getVerticalScrollBar().setValue(remainScroll);
jPanel1.removeAll();
jPanel1.add(jScrollPane1);
jPanel1.revalidate();
jPanel1.repaint();
}
2 things must remind:
list model class: You need to implement.(As your look n feel you want).
getMyTimeList() method to array to list conversion.
I already had implement it for chat application to add chat for sender and receiver side.
All the best

How to call `setText` on multiple JTextfields?

I want to figure out a way to set the text for multiple JTextfields in just a few lines (preferable one line) of code rather than a new line for every textfield.
I am looking for a way to invoke the setText method on multiple JTextfield values. My code works correctly, but I do not want to write out someField.setText("0.00"); for each JTextfield.
Here is code with the repeated calls that I want to shorten:
JButton btnNewButton_1 = new JButton("Clear");
btnNewButton_1.setBounds(367, 533, 86, 32);
btnNewButton_1.setFont(new Font("Tahoma", Font.PLAIN, 11));
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textIncome.setText("0.00");
textGrossSalary.setText("0.00");
textGrossSalary.setText("0.00");
textHousehold.setText("0.00");
textFood.setText("0.00");
textChildren.setText("0.00");
textBills.setText("0.00");
textIncidentals.setText("0.00");
textCredit.setText("0.00");
textHome.setText("0.00");
textInvestings.setText("0.00");
textPets.setText("0.00");
textTransport.setText("0.00");
textLifestyle.setText("0.00");
textTax.setText("0.00");
textDisposable.setText("0.00");
textHealthFitness.setText("0.00");
textGiftsDonations.setText("0.00");
}
});
Put them in a List or an array and iterate over them
For example, create an instance field array which contains the fields which you want to set (to the same value)
private JTextField fields[] = new JTextField[]{
textIncome,
textGrossSalary,
textGrossSalary,
textHousehold,
textFood,
textChildren,
textBills,
textIncidentals,
textCredit,
textHome,
textInvestings,
textPets,
textTransport,
textLifestyle,
textTax,
textDisposable,
textHealthFitness,
textGiftsDonations};
Then when the ActionListener is triggered, iterate over it...
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (JTextField field : fields) {
field.setText("0.00");
}
}
});
Based on btnNewButton_1.setBounds(367, 533, 86, 32);, I'd advise avoiding using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify

JSpinner doesn't show

I really doesn't understand what it's going on with my JSpinner.
I instanciated it and then I tried to set it on my JPanel with a setBounds but the only thing I get is this :
The little square on the middle is what should be my JSpinner..
My code is like this :
private JSpinner spinnerDayBirth;
spinnerDayBirth = new JSpinner();
spinnerDayBirth.setBounds(280,351, 25, 25);
add(spinnerDayBirth);
They're few lines betweens each of these instructions but they never touch to this JSpinner.
So I wonder why I can't get a normal JSpinner..
Thank you in advance !
I had same problem. I worked with simply spinnerModel then I tried your program and it works too.
There is one thing to do - re-set your model. If you want the spinner to appear you have to set new spinner model again.
for example i typed this code:
public void method() {
jPanel2.setLocation(0, 96);
jPanel2.setSize(getWidth(), getHeight() - 96);
jPanel2.getHeight() - jButton1.getHeight() - 50);
jSpinner1.setModel(new SpinnerNumberModel(2,1,10,1)); //<- this is line you need to type
jSpinner1.setSize(60, 25);
jSpinner1.setLocation(0,0);
}

How to add a timer to change text of a JTextPane in java?

I am working on a java program, what I want to implement is once the window loads, the set of text in a JTextPane to change. I have the below code that creates the JTextPane;
JTextPane txtpnReady = new JTextPane();
txtpnReady.setText("Ready");
txtpnReady.setEditable(false);
txtpnReady.setBounds(181, 39, 169, 20);
contentPane.add(txtpnReady);
I am unsure of how to add a timer that will change the text of this JTextPane, after 2 seconds, I need it to say Ready once the program loads, then after 2 seconds Steady and then after 2 seconds, Go.
Thanks.
You may want to take a look to How to Use Swing Timers trail. You can do something like this:
Timer timer = new Timer(2000, new ActionListener() {
private String nextText = "Steady";
#Override
public void actionPerformed(ActionEvent e) {
txtpnReady.setText(nextText);
if(!nextText.equals("Go")) {
nextText = "Go";
} else {
((Timer)e.getSource()).stop();
}
}
});
timer.setRepeats(true);
timer.setDelay(2000);
timer.start();
Off-topic
About this:
txtpnReady.setBounds(181, 39, 169, 20);
The use of setBounds() is not a good practice since swing applications must be able to run on different platforms and Look & feels. You should let layout managers do their job and avoid the use of setBounds() and set(Preferred|Maximum|Minimum)Size.
Suggested readings:
Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
Using Layout Managers

How can I make a JSpinner object have its entire contents highlighted so that user input does not require deleting when focus is gained?

Not much to add to the Title question.
Here's what tabbing to the first box looks like, with cursor before the first character in the field, so that the user will have to delete the character if he wishes to enter his own month, day, or year number:
Here's what I'd like, when the field is tabbed to (or otherwise selected), so the user doesn't have to delete the character(s) presented if he wishes to enter his own year, etc.:
I can accomplish this for a JTextField like so, for example:
txtDateFrom.select(0,99);
But .select() isn't a method for JSpinner.
(I realize that this raises the question, "Why use a spinner?" but the obvious answer is that I'd like both methods of selecting to be available, as is common in design.)
(A much less pressing but related matter... I made an integer array of 100 year-dates [e.g., 2014] named years and used SpinnerListModel(years) because when using the SpinnerNumberModel, a year would be displayed as 2,014. I can live with what I've done, but is there a less-brute-force way? There's no method containing "format" that I could find for this method.)
This works in Java 1.7.0_51, in Windows and Linux. I don't have the ability to test it in OS X.
JSpinner.DefaultEditor editor =
(JSpinner.DefaultEditor) spinner.getEditor();
editor.getTextField().addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent event) {
final JTextField textField = (JTextField) event.getComponent();
EventQueue.invokeLater(new Runnable() {
public void run() {
EventQueue.invokeLater(new Runnable() {
public void run() {
textField.selectAll();
}
});
}
});
}
});
Side note: Have you considered replacing your three JSpinners with a single JSpinner like this?
JSpinner spinner = new JSpinner(new SpinnerDateModel());
spinner.setEditor(new JSpinner.DateEditor(spinner, "MM/dd/yyyy"));
The up/down arrow buttons (and arrow keys) will change whichever field contains the text cursor.
It won't solve your focus issue, but you may decide that the issue is less of an issue.

Categories

Resources