I'm using a SWT DateTime component. It sets the current date as a default selection, when instanciated. How can i prevent this?
I want that no date is selected at all...
Thanks
Patrick
The SWT DateTime control does not support this at all.
I recommend CalendarCombo from the Eclipse Nebula project.
If this is still of use to anyone - I had the same problem, meaning that a field on the UI had to show a date or an empty value: because a date that was NOT selected was also valid input.
While SWT DateTime has to show some sort of a date, it is not a problem at all introducing another level of indirection by simply making a label and a button - too look like DateTime: The then button calls DateTime in a separate modal window. After the user has made the selection, we write the result to the label back in the application window. You also add another button to the modal window and call it e.g. NONE. If the user clicks NONE, you clear the label field in your application.
You will see that I scrape the current value of the date from the label first, so that I can initialize the DateTime control in the modal dialog. This way it all behaves like a new composite control, though I admit it is a bit awkward if you need to do it many times over. E.g.:
private Button buttonDeadlineDate;
private Label labelDeadlineDate;
// ... then define your "composite" control:
lblNewLabel_5 = new Label(group_2, SWT.NONE);
lblNewLabel_5.setBounds(10, 14, 50, 17);
lblNewLabel_5.setText("Deadline:");
// We make our own composite date control out of a label and a button
// and we call a modal dialog box with the SWT DateTime and
// some buttons.
labelDeadlineDate = new Label(group_2, SWT.BORDER | SWT.CENTER);
labelDeadlineDate.setBounds(62, 10, 76, 20);
// Note that I use the strange font DokChampa because this was the only way to get a margin at the top.
labelDeadlineDate.setFont(SWTResourceManager.getFont("DokChampa", 8, SWT.NORMAL));
labelDeadlineDate.setBackground(SWTResourceManager.getColor(255, 255, 255)); // so it does appear editable
buttonDeadlineDate = new Button (group_2, SWT.NONE);
buttonDeadlineDate.setBounds(136, 11, 20, 20); // x - add 74, y - add 1 with respect to label
// ... And later we have the call-back from the listener on the little button above:
//========================================
// Deadline Date
//========================================
buttonDeadlineDate.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
// Define the dialog shell.
// Note: DIALOG_TRIM = TITLE | CLOSE | BORDER (a typical application dialog shell)
final Shell dialog = new Shell (shlTaskScheduler, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
dialog.setText("Enter deadline date (NONE for none)");
//========================================
// Position and size the dialog (relative to the application).
// could have probably also used a single call to dialog.setBounds()
// instead of calling setLocation() and setSize().
//========================================
Point myPoint = new Point(0,0);
myPoint = shlTaskScheduler.getLocation();
myPoint.x +=80; // myPoint.x +=30;
myPoint.y +=320; // myPoint.y +=350;
dialog.setLocation(myPoint);
dialog.setSize(270, 220);
dialog.setLayout (null);
//========================================
// Define dialog contents
//========================================
// Make controls final they it can be accessed from the listener.
final DateTime DTDeadlineDate;
DTDeadlineDate = new DateTime(dialog, SWT.BORDER | SWT.CALENDAR | SWT.DROP_DOWN);
DTDeadlineDate.setBounds(10, 10, 175, 175);
final Button buttonNone = new Button (dialog, SWT.PUSH);
buttonNone.setText ("NONE");
buttonNone.setBounds(200, 35, 55, 25);
final Button buttonOK = new Button (dialog, SWT.PUSH);
buttonOK.setText ("OK");
buttonOK.setBounds(200, 85, 55, 25);
//========================================
// Initialize the DateTime control to
// the date displayed on the button or today's date.
//========================================
// Get the deadline from the main application window
String newDeadlineDateString = (labelDeadlineDate.getText().toString());
myLogger.i (className, "got deadline from main application window as " + newDeadlineDateString);
// If deadline date found, use it to initialize the DateTime control
// else the DateTime control will initialize itself to the current date automatically.
if ((newDeadlineDateString.length() == 10) // probably unnecessary test
&& (isThisDateValid(newDeadlineDateString, "yyyy-MM-dd"))) {
// parse and extract components
try {
String tmpYearString= newDeadlineDateString.substring(0,4);
String tmpMoString = newDeadlineDateString.substring(5,7);
String tmpDayString = newDeadlineDateString.substring(8,10);
int tmpYearInt = Integer.parseInt(tmpYearString);
int tmpMoInt = Integer.parseInt(tmpMoString);
int tmpDayInt = Integer.parseInt(tmpDayString);
DTDeadlineDate.setYear(tmpYearInt);
DTDeadlineDate.setMonth(tmpMoInt - 1); // the control counts the months beginning with 0! - like the calendar
DTDeadlineDate.setDay(tmpDayInt);
} catch(NumberFormatException f) {
// this should not happen because we have a legal date
myScreenMessage.e(className, "Error extracting deadline date from screen <" + newDeadlineDateString + ">. Ignoring");
}
} else if (newDeadlineDateString.length() > 0) {
myLogger.w (className, "Illegal current deadline date value or format <" + newDeadlineDateString + ">. Ignoring.");
// no need to do anything, as the control will initialize itself to the current date
} else {
// no need to do anything, as the control will initialize itself to the current date
}
//========================================
// Set up the listener and assign it to the OK and None buttons.
// Note that the dialog has not been opened yet, but this seems OK.
//
// Note that we define a generic listener and then associate it with a control.
// Thus we need to check in the listener, which control we happen to be in.
// This is a valid way of doing it, as an alternative to using
// addListener() or
// addSelectionListener()
// for specific controls.
//========================================
Listener listener = new Listener () {
public void handleEvent (Event event) {
if (event.widget == buttonOK) {
int newDeadlineDay = DTDeadlineDate.getDay();
int newDeadlineMonth = DTDeadlineDate.getMonth() + 1; // the returned month will start at 0
int newDeadlineYear = DTDeadlineDate.getYear();
String selectedDeadlineDate = String.format ("%04d-%02d-%02d", newDeadlineYear, newDeadlineMonth, newDeadlineDay);
if (isThisDateValid(selectedDeadlineDate, "yyyy-MM-dd")) {
labelDeadlineDate.setText(selectedDeadlineDate);
} else {
// This is strange as the widget should only return valid dates...
myScreenMessage.e(className, "Illegal deadline date selected: resetting to empty date");
labelDeadlineDate.setText("");
}
} else if (event.widget == buttonNone) {
// an empty date is also an important value
labelDeadlineDate.setText("");
} else {
// this should not happen as there are no other buttons on the dialog
myLogger.e(className, "Unexpected widget state: ignoring");
}
// once a button is pressed, we close the dialog
dialog.close ();
}
};
// Still need to assign the listener to the buttons
buttonOK.addListener (SWT.Selection, listener);
buttonNone.addListener (SWT.Selection, listener);
//========================================
// Display the date dialog.
//========================================
dialog.open ();
//========================================
// If you need to do this - you can wait for user selection before returning from this listener.
// Note that this wait is not necessary so that the above button listeners
// can capture events, but rather so that we do not continue execution and end this
// function call before the user has made a date selection clicked on a button.
// Otherwise we would just go on.
while (!dialog.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
...
}
});
You would have to manually set the fields of the instance to 0 or null whatever is appropriate. You could also implement your own NoDateTime object (using the null object pattern) to accomplish the same thing. I would be tempted to represent no time with just null though, is there a reason why you cannot do that?
One Way is to set a selection listener like in this example on Eclipse-DOC
Here is an adapted version:
private boolean isModified = false;
selectDate = new DateTime(this, SWT.DATE | SWT.DROP_DOWN);
SelectionListener selListener = new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
isModified = true;
}
};
selectDate.addSelectionListener(selListener);
Then you can do an If isModified where needed.
Related
I'm relatively new to programming. Hoping someone can help. I have a button that creates a series of labels and text boxes within a frame once the user enters a number. I'm having trouble access the text boxes once they are created. Can someone point me in the right direction. Code snips below. Thanks.
method to create a label and text box.
public JTextField createPrizePanels(){
JLabel prizePanel = new JLabel("Enter Prize Here", SwingConstants.CENTER);
prizePanel.setVerticalAlignment(SwingConstants.TOP);
prizePanel.setFont(new Font("Arial", Font.BOLD, 14));
prizePanel.setForeground(Color.BLUE);
Border border = BorderFactory.createLineBorder(Color.GRAY, 1);
prizePanel.setBorder(border);
prizePanel.setOpaque(true);
prizePanel.setBackground(Color.LIGHT_GRAY);
prizePanel.setBounds(setBoundsX, setBoundsY, 120, 60);
prizeTextBox = new JTextField(50);
prizeTextBox.setBounds(setBoundsX + 5, setBoundsY + 20, 110, 30);
prizeTextBox.setFont(new Font("Arial", Font.BOLD, 12));
prizeTextBox.setOpaque(true);
prizeTextBox.setBackground(Color.WHITE);
prizeTextBox.setForeground(Color.BLACK);
prizeTextBox.setText("No Prize");
prizeTextBox.setHorizontalAlignment(JTextField.CENTER);
lp.add(prizePanel);
lp.add(prizeTextBox);
return prizeTextBox;
}
code that creates multiple text boxes bases on input from user.
JButton numberOfBallonsButton = new JButton("Set");
numberOfBallonsButton.setBounds(360,160,95, 0x1e);
numberOfBallonsButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
numberOfBallons = Integer.parseInt(numberOfBallonsTextBox.getText());
System.out.println(numberOfBallons);
lp.remove(numberOfBallonsButton);
for(int i = 0; i < numberOfBallons; i++ ){
createPrizePanels();
setBoundsX = setBoundsX +125;
if(setBoundsX > 450){
setBoundsX = 120;
setBoundsY = setBoundsY + 65;
}
}
lp.add(startGameButton);
}
});
Up to this point it works fine. However, the user needs to enter text into each text box and press another button. I'm not sure how to access each text field. Thanks in advance.
You are using local fields.you can create global field and the return value of createPrizePanels() is never used and for your case you don't know number of created textfield so you can use List as global field and when you create textfield add it to the list so you access it later from anywhere
After reloading this effect disappears and labels are in their suitable sizes. This repeats only if the application is reloaded. On English locale, this dialog shows normally.
Example of code containing problem label:
private void createDailyGroup(Composite composite)
{
m_typePanels[DAILY] = new Composite(composite, SWT.NONE);
Composite panel = m_typePanels[DAILY];
panel.setLayout(GridLayoutFactory.fillDefaults().numColumns(3).create());
panel.setLayoutData(GridDataFactory.fillDefaults().create());
addRunTime(panel, DAILY);
}
private void addRunTime(Composite panel, int scheduleType)
{
Label runTimeLabel = new Label(panel, SWT.NONE);
runTimeLabel.setText(QmfResources.getString(IDS_RUNTIME_LABEL));
runTimeLabel.setLayoutData(GridDataFactory.fillDefaults().
align(SWT.BEGINNING, SWT.CENTER).grab(false, false).create());
m_runTimes.put(Integer.valueOf(scheduleType), new DateTime(panel, SWT.TIME | SWT.BORDER | SWT.SHORT));
DateTime runTime = m_runTimes.get(Integer.valueOf(scheduleType));
runTime.addSelectionListener(m_parametersChangeListener);
runTime.setLayoutData(GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).create());
}
Try below code, here I am considering runTimeLabel is label where you want to add Chinese locale string
runTimeLabel.getParent().requestLayout();
runTimeLabel.getParent().redraw();
runTimeLabel.getParent().getParent().update();
I'm doing a project in school and I've a distinction feature to implement but have some issues. What I need to do is that I've to check the number of beds left in my SQL database and if it goes below a critical number a JOptionPane appears.
What I'm trying to do is another scenario which is tougher, 2 Frames opened. Eg, first frame user uses the bed, it'll drop to the critical value 10, on the other frame when the user moves his mouse arrow the JOptionPane will pop up showing a message.
I've looked up in this community but I can't seem to implement the codes to make it work. I've got to a point where there's no errors but I can't seem to close the JOptionPane. Basically I would only want this event to fire only when user of either frames go below the bed count.
I'm brand new to this actionevent. I'm doing this project as 3 tier programming with MySQL database.
I've looked at these sites but to no avail:
Stopping mouseMoved
How to temporarily disable event listeners in Swing?
Code for the Frame to show the JOptionPane
public HomePageForm() {
setTitle("Home");
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setBounds(100, 100, 640, 428);
contentPane = new JPanel();
contentPane.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
String cardioMsg = "Beds are running out for Cardiothoracic Department!";
String oncoMsg = "Beds are running out for Oncology Department!";
String orthoMsg = "Beds are running out for Orthopaedic Department!";
String pediaMsg = "Beds are running out for Pediatric Department!";
if (ignoreMouseMovedEvents) {
return;
}
ArrayList<ChangeBed> bedList = new ArrayList<ChangeBed>();
ChangeBedControl cbc8 = new ChangeBedControl();
bedList = cbc8.processCountBedsAvailableDpt4();
for (int i = 0; i < bedList.size(); i++) {
bedsForPediatric = bedList.get(i).getRowCountAvail();
}
if (bedsForPediatric <= 3) {
int valuePedia = JOptionPane.showConfirmDialog(null, pediaMsg, "URGENT", JOptionPane.WARNING_MESSAGE);
if (valuePedia == 0 || valuePedia == 2) {
ignoreMouseMovedEvents = true;
valuePedia = JOptionPane.CLOSED_OPTION;
}
}
}
});
Codes for Controller Class
public ArrayList<ChangeBed> processCountBedsAvailableDpt4() {
ChangeBed changeBed = new ChangeBed();
ArrayList<ChangeBed> bedList = new ArrayList<ChangeBed>();
bedList = changeBed.countBedsAvailableDpt4();
return bedList;
}
Entity class to retrieve from SQL DB
public ArrayList<ChangeBed> countBedsAvailableDpt4() {
ArrayList<ChangeBed> bedList = new ArrayList<ChangeBed>();
boolean rowBooleanAvail;
int rowCountAvail;
try {
myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ooadp?useSSL=false", "root", "root");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT count(*) FROM bed WHERE bedStatus = 'Available' AND department = 'Pediatric'");
while (myRs.next()) {
rowBooleanAvail = myRs.last();
rowCountAvail = myRs.getRow();
ChangeBed cb = new ChangeBed(myRs.getInt(rowCountAvail), "");
bedList.add(cb);
}
} catch (Exception e) {
e.printStackTrace();
}
return bedList;
}
Basically I also have a Login Frame, upon logging in it opens up the frame I've shown in the above codes. At first showing a JOptionPane upon Mousemoved event showing a warning message. Once I click Ok/Cancel it closes the JOptionPane and stops the mousemoved event.
If I have another login frame whereby I login to the homepage (codes of the frame shown above), the same process will repeat whereby an optionpane will be shown.
So now I'll have 2 homepages opened and both mousemoved event deactivated and it won't fire again.
For frame 2, if I were to hit the critical value of to show the JOptionPane as soon as I move the mouse in the first homepage frame - how can I do that?
Lets answer with a question back to you: why do you want to stop the events?
Meaning: you programmed a listener that reacts to certain events. Now you are saying: at some point; I don't want "reactions"; so how do I prevent those events going into my listener?!
That is one way to look at it.
The other: simply tell your listener(s) that they should ignore incoming events, like:
Class SomeExample {
private boolean ignoreMouseMovedEvents = false;
...
#Override
public void mouseMoved(MouseEvent e) {
if (ignoreMouseMovedEvents) {
return;
}
... handle move events
Now you just need to update that boolean field whenever you want to ignore mouse move events.
But lets be precise here: I am not saying that ignoring events is always the best solution. I am merely expressing: if it is hard for you to prevent events from coming "into your system"; then maybe it is easier to let them coming; but change the way how your system reacts to them.
Finally: there is also a slightly different variation of this: instead of telling your listener to ignore events; you can also de-register your listeners from the event source. In other words: you can simply drop your listener from the frame you attached it to. And you re-add it, when events should be processed again.
I want to use this JXDatePicker component in a application that will work on a touch display. Because the default component is small, all the dates and the buttons are hard to click using a bad touch screen I wanted to make them bigger. So far I successfully made the result text field bigger (the one showing the selected date, by changing the font), make the pop-up bigger (the JXMonthView, also by changing its font), change the picture of the JXDatePicker with a bigger image, set the default date to be the current date, set the date format, etc. This is my code:
private void touch_screen_datepicker(JXDatePicker date_picker) {
Toolkit toolkit = Toolkit.getDefaultToolkit();
JXMonthView monthView = date_picker.getMonthView();
date_picker.setDate(new Date());
date_picker.setFont(new Font(Font.DIALOG, Font.PLAIN, 50));
JButton btn_pick = (JButton) date_picker.getComponent(1);
btn_pick.setBackground(new Color(66, 147, 223));
Image image = toolkit.getImage("/home/adrrian/Image/calendar/" + "calendar image 4.png"); //Земање на сликата за мк знаме
ImageIcon icon = new ImageIcon(image); //Правење на икона
btn_pick.setIcon(icon); //Поставување на иконата
SimpleDateFormat longFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat shortFormat = new SimpleDateFormat("yy-MM-dd");
Date startDate = new Date(0);//01.01.1970
shortFormat.set2DigitYearStart(startDate);
DatePickerFormatter formatter = new DatePickerFormatter(
// invers sequence for parsing to satisfy the year parsing rules
new DateFormat[]{shortFormat, longFormat}) {
#Override
public String valueToString(Object value) throws ParseException {
if (value == null) {
return null;
}
return getFormats()[1].format(value);
}
};
DefaultFormatterFactory factory = new DefaultFormatterFactory(formatter);
date_picker.getEditor().setFormatterFactory(factory);
monthView.setFont(new Font(Font.DIALOG, Font.PLAIN, 50));
monthView.setFirstDayOfWeek(Calendar.MONDAY);
}
and this is an image of my final work:
My main problem is how to make the arrow that are changing the months (for example if I go back from this image to show September). I tried listing all of the components, like I did for the button, but still I didn't found anything. Also for better GUI I like to find that dark blue color (where the month is displayed), to make my button the same.
Hope someone can help me. Thanks in advance.
Toolkit toolkit = Toolkit.getDefaultToolkit();
JXMonthView monthView = date_picker.getMonthView();
/*EDITED*/
//1
date_picker.putClientProperty("JComponent.sizeVariant", "large");
monthView.putClientProperty("JComponent.sizeVariant", "large");
//2
date_picker.putClientProperty("JXComponent.sizeVariant", "large");
monthView.putClientProperty("JXComponent.sizeVariant", "large");
//3
date_picker.putClientProperty("JXDatePicker.sizeVariant", "large");
monthView.putClientProperty("JXMonthView.sizeVariant", "large");
//
date_picker.putClientProperty("JDatePicker.sizeVariant", "large");
monthView.putClientProperty("JMonthView.sizeVariant", "large");
SwingUtilities.updateComponentTreeUI(this);
SwingUtilities.updateComponentTreeUI(date_picker);
SwingUtilities.updateComponentTreeUI(monthView);
date_picker.updateUI();
monthView.updateUI();
/*EDITED*/
As #Vighanesh Gursale suggested I insterdet this lines and also did the frame.pack() before setVisible(true), but nothing changes.
I have made some code using nimbus look and feel, i know it is not exact that you want but it is pretty much helpful. Check this code. To perform same you need to find the key of your next and previous buttons key in my case it is Button.margin. Try to use the same key in your code if you are lucky it would work.
import javax.swing.*;
import java.awt.*;
public class Demo {
JFrame frame = new JFrame("");
JButton btn = new JButton("Example");
public Demo() {
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.add(btn);
frame.setVisible(true);
}
public static void main(String[] args) {
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
Insets insets = new Insets(50, 20, 50, 20); //change the size of button
UIManager.put("Button.margin", insets);
}
catch(Exception e)
{
e.printStackTrace();
}
Demo d = new Demo();
}
}
Also keep in mind to use default look and feel or any other look and feel.
This question is quite old but for everyone who is looking how it can be done
UIManager.put("JXMonthView.monthDownFileName", <PATH_TO_IMAGE>);
UIManager.put("JXMonthView.monthUpFileName", <PATH_TO_IMAGE>);
monthDownFileName refers to previous month
monthUpFileName refers to next month
this will change the image with other of your choice (and size)
I have a dialog, within the dialog there is a tableviewer thats shows the results from user actions. I have created a method that has a print button. The print code include is sample code I have found from examples.
final Text t = new Text(composite, SWT.BORDER | SWT.MULTI);
Button localPrintersButton = new Button(composite, SWT.PUSH);
localPrintersButton.setText("Print Results");
localPrintersButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
PrintDialog printDialog = new PrintDialog(Display.getCurrent().getActiveShell(), SWT.NONE);
printDialog.setText("Print");
PrinterData printerData = printDialog.open( );
if(!(printerData==null))
{
Printer p = new Printer(printerData);
p.startJob("PrintJob");
p.startPage( );
Rectangle trim = p.computeTrim(0, 0, 0, 0);
Point dpi = p.getDPI( );
int leftMargin = dpi.x + trim.x;
int topMargin = dpi.y / 2 + trim.y;
GC gc = new GC(p);
Font font = gc.getFont( );
String printText= t.getText( );
Point extent = gc.stringExtent(printText);
gc.drawString(printText, leftMargin, topMargin +
font.getFontData( )[0].getHeight( ));
p.endPage( );
gc.dispose( );
p.endJob( );
p.dispose( );
}
}
});
When my dialog opens there is a text box next to the print button. I can type something in the text box, select the print button and select my local printer, then it prints the contents of the text box.
I am trying to figure out how to print out the table instead of the textbox
Is this possible?
I think you are looking for
Control.class
public boolean print (GC gc)
Perhaps you can create a GC from the Table widget and use GC#copyArea(Image, int, int) to create an image of the table to print.
If the table has scroll bars and not all data is visible, you might need to do some extra work to create multiple images and stitch them together. Hope this helps.