Codename One - Extend CheckBox to create a SpanToggleCheckBox - codenameone

I need toggle buttons that are multi line, because the text of some of them is long. I tried to extend CheckBox to create a SpanToggleCheckBox, but it doesn't work, because no text is shown. What's wrong in the following code? How can I achive my purpose?
public class SpanToggleCheckBox extends CheckBox {
private TextArea textArea;
/**
* Constructs a toggle checkbox with the given text
*
* #param text to display
*/
public SpanToggleCheckBox(String text) {
textArea = new TextArea(getUIManager().localize(text, text));
textArea.setActAsLabel(true);
textArea.setColumns(textArea.getText().length() + 1);
textArea.setUIID("Label");
textArea.setEditable(false);
textArea.setFocusable(false);
this.setUIID("CheckBox");
super.setToggle(true);
}
/**
* {#inheritDoc}
*/
#Override
public void paint(Graphics g) {
getUIManager().getLookAndFeel().drawTextArea(g, textArea);
}
/**
* {#inheritDoc}
*/
#Override
protected Dimension calcPreferredSize() {
return getUIManager().getLookAndFeel().getTextAreaSize(textArea, true);
}
/**
* Shorthand for creating the SpanToggleCheckBox
*
* #param text the text for the button
* #return a check box
*/
public static SpanToggleCheckBox createToggle(String text) {
SpanToggleCheckBox cb = new SpanToggleCheckBox(text);
return cb;
}
}

I solved this issue with a different approch.
In the code, I replaced with line of code:
Component button = CheckBox.createToggle(label);
with these lines:
CheckBox myBtn = CheckBox.createToggle("text");
Container container = new Container(BoxLayout.y());
container.setLeadComponent(myBtn);
SpanLabel multiLineText = new SpanLabel(label);
container.add(multiLineText);
In this way, I got a Container that acts like a Toggle Button and that contains a SpanLabel with the multiline text.

Related

Modify a JLabel inside a void method

Please i need your help, im trying to do that i want 3-4 days now and i cant.
I have 2 Classes MainForm and Class2.
I have a JLablel inside a method at Class1 and i want to modify it by pressing a button from the Class2.
public class MainForm {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainForm window = new MainForm();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainForm() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(400, 200, 488, 322);
frame.setTitle("ShutDown");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame.setResizable(false);
/**
* Time BOX
*/
JComboBox<String> timeBox = new JComboBox<String>();
timeBox.setBounds(73, 142, 90, 20);
timeBox.addItem("Days");
timeBox.addItem("Hours");
timeBox.addItem("Minutes");
timeBox.addItem("Seconds");
timeBox.addItem("Right now");
timeBox.setSelectedItem("Minutes");
frame.getContentPane().add(timeBox);
String getTimeBox = timeBox.getSelectedItem().toString();
/**
* The label info.
*/
JLabel labelInfo = new JLabel("");
labelInfo.setBounds(73, 209, 310, 14);
frame.getContentPane().add(labelInfo);
labelInfo.setText(getTimeBox);
}
and the Class 2
Class2
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
i tried much and allways doesnt work, whats the code i need to write in that button to get the selectedItem from the timeBox (comboBox)
and put it to that label?
First of all you need references of both
JComboBox & JLable objects in class 2.
Simple way to do that is to declare respective private members in MainForm instead of local members of initialize method & pass them in to the constructor or use setter method approach.
Let consider that the reference names are jComboBox & jLable respectively.
Now you can use following syntax to reference them from actionPerformed method of the anonymous class using this syntax Class2.this.jComboBox & Class2.this.jLable (jComboBox & jLable is object reference).

how can I add a row dynamically

I want to add rows dynamically without disturbing other data in a the table ( data is hardcoded in a Object[][] dataForTable. Don't want to persist data in database). I didn't find any method from TableModel or Table itself to do so. Is there any method to achieve this without replacing Object[][] dataForTable or any other way that ?
I have other situation. At any time I want one extra row in the Table that will be empty. And when putting values to this row another empty row will be created dynamically.
Update: I re-evaluated this answer and it includes some bugs and conceptual problems. We decided to add the option to add/remove rows from the Table into the DefaultTableModel. So you can just use ((DefaultTableModel)table).addRow("Col1", "Col2", "Col3"); Just make sure the number of columns is the exact match to the table column count.
Original answer below:
The default table model isn't mutable which is probably an omission on our part. Something like this should probably work (haven't tested):
public class MyTableModel implements TableModel {
private ArrayList<Object[]) data;
private String[] columnNames;
private EventDispatcher dispatcher = new EventDispatcher();
private boolean editable;
public MyTableModel(String[] columnNames, Object[][] data) {
this(columnNames, data, false);
}
public MyTableModel(String[] columnNames, Object[][] data, boolean editable) {
this.data = new ArrayList<Object[]>();
for(Object[] o : data) {
this.data.add(o);
}
this.columnNames = columnNames;
this.editable = editable;
}
/**
* #inheritDoc
*/
public int getRowCount() {
return data.length;
}
/**
* #inheritDoc
*/
public int getColumnCount() {
return columnNames.length;
}
/**
* #inheritDoc
*/
public String getColumnName(int i) {
return columnNames[i];
}
/**
* #inheritDoc
*/
public boolean isCellEditable(int row, int column) {
return editable;
}
/**
* #inheritDoc
*/
public Object getValueAt(int row, int column) {
try {
return data.get(row)[column];
} catch(ArrayIndexOutOfBoundsException err) {
// not the best situation but quite useful for the resource editor
//err.printStackTrace();
return "";
}
}
/**
* #inheritDoc
*/
public void setValueAt(int row, int column, Object o) {
data.get(row)[column] = o;
dispatcher.fireDataChangeEvent(column, row);
}
/**
* #inheritDoc
*/
public void addDataChangeListener(DataChangedListener d) {
dispatcher.addListener(d);
}
/**
* #inheritDoc
*/
public void removeDataChangeListener(DataChangedListener d) {
dispatcher.removeListener(d);
}
public void addRow(Object[] row) {
data.add(row);
dispatcher.fireDataChangeEvent(-1, row);
}
}

How to print JTable?

I have a whole database shown in a JTable and I added a print button but what it does, is to convert the data in the JTable into a .csv file, commands excel to open it and the user can print it, but it looks pretty ugly. Is there a way to send a JTable component to printer?
There is a method under JTable called print(). Will save you alot. See below :-
package com.tanyasis.librarymanager;
import java.awt.HeadlessException;
import java.awt.print.PrinterException;
import java.text.MessageFormat;
import javax.swing.JTable;
/**
* Used to provide printing information and adding information that might be
* important in a page such as page header, contents and footer. This class
* makes sure that all contents of a table fit in the given page.
*
* #author Tanyasis Mwanik
*
*/
public class PrintTable {
private JTable table;
private MessageFormat headerFormat, footerFormat;
/**
* Prints the table and provide post printing information to the user if it
* was succesful
*
* #param table
* <code>JTable</code> to be printed
* #param tableTitle
* <code>String</code> to be used as the table header/title
*/
public PrintTable(JTable table, String tableTitle) {
// TODO Auto-generated constructor stub
this.setTable(table);
// Sets the table header
headerFormat = new MessageFormat(tableTitle);
// Sets the table footer
footerFormat = new MessageFormat("Page {0}");
try {
boolean complete = table.print(JTable.PrintMode.FIT_WIDTH,
headerFormat, footerFormat, true, null, true, null);
if (complete) {
new ConfirmationClass(
"<html><h2>Records Printed Successfully</h2></html>");
}
} catch (HeadlessException | PrinterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* #return the table
*/
public JTable getTable() {
return table;
}
/**
* #param table
* the table to set
*/
public void setTable(JTable table) {
this.table = table;
}
}
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//TODO Auto-generated method stub
MessageFormat header=new MessageFormat("Your Invoice");
MessageFormat footer=new MessageFormat("Page");
try
{
table.print(JTable.PrintMode.FIT_WIDTH, header, footer);
}
catch(Exception ae)
{
System.err.println("Error printing: " + ae.getMessage());
}
}
});
It might help :)

Using GWT-Editor in a UiBinder

I am trying to make use of Editor in a GWT application, so I have read the official documentation. I have also looked at he question enter link description here and its answers, but I still cannot figure out the ultimate "purpose" of Editors. As an example case, supposing a UiBinder with some fields:
#UiField
TextBox name;
#UiField
TextArea comment;
#UiField
ListBox type;
...
I create additionally a method editCustomer as:
private void editCustomer(CustomerProxy entity) {
MyRequestFactory requestFactory = MyRequest.getRequestFactory();
CustomerRequestContext requestContext = requestFactory.customerRequest();
entity = requestContext.edit(entity);
editorDriver.edit(entity, requestContext);
}
I think the approach with Editor makes for connecting UiBinder fields with the Database. How is this done, based on the common way of sending data in the database through a "Save" Buttton?
#UiHandler("saveButton")
void onSaveButtonClick(ClickEvent event){
????
}
I have been using the MVP pattern for a while and have some more complicated editors. I found that it is good put put your EditorDriver in your view becuase when you initialize it you can bind it to your specific view. My examples require an activity / view interface / view implementation.
This is an abstract activity that can be extended by other activities but I included the relevant content. I have stripped quite a bit of code out but this should give you an idea of a useful way to use editors. My editor is quite complex and has quite a few sub editors. I have only included the name and description. We have found this to be a quite useful design pattern for handling Editors.
public abstract class AbstractTaskBuilderActivity extends <E extends AnalyticsTaskProxy, R extends DaoRequest<E>> implements TaskBuilderView {
/**
* Create a new task. This will initialize any new lists.
* #param context The RequestContext to use to create the task.
* #param clazz The class type to be created.
* #return
*/
protected E create(R context, Class<E> clazz) {
// This is implemented in my inherited classes.
E editableAnalyticsTask = context.create(clazz);
// More initialization code expecially initializing arrays to empty so that
// any ListEditor sub editors will work.
return editableAnalyticsTask;
}
/**
* Call to edit the task and update the dashboards.
* #param context
* #param task
*/
protected void doEdit(R context, E task) {
RequestFactoryEditorDriver<? super AnalyticsTaskProxy, ?> driver = display.getEditorDriver();
E editable = context.edit(task);
context.save(editable).with(driver.getPaths()).to(new Receiver<Long>() {
#Override
public void onFailure(ServerFailure error) {
display.showError(error.getMessage());
super.onFailure(error);
}
public void onConstraintViolation(Set<ConstraintViolation<?>> violations) {
display.getEditorDriver().setConstraintViolations(violations);
}
#Override
public void onSuccess(Long response) {
clientFactory.getPlaceController().goTo(getSavePlace());
}
});
driver.edit(editable, context);
}
/**
* Save the task.
*/
#Override
public void onSaveTask() {
RequestFactoryEditorDriver<? super AnalyticsTaskProxy, ?> driver = display.getEditorDriver();
RequestContext request = driver.flush();
request.fire();
}
}
My view interface
public interface TaskBuilderView extends View {
public interface Presenter {
void onSaveTask();
}
public RequestFactoryEditorDriver<AnalyticsTaskProxy, ?> getFactoryEditorDriver();
public void setPresenter(Presenter presenter);
}
My view implementation
public class AnalyticsTaskBuilderViewImpl extends ViewImpl implements AnalyticsTaskBuilderView, Editor<AnalyticsTaskProxy> {
interface AnalyticsTaskBuilderDriver extends RequestFactoryEditorDriver<AnalyticsTaskProxy, AnalyticsTaskBuilderViewImpl> {
}
/**
* UiBinder implementation.
*
* #author chinshaw
*
*/
#UiTemplate("AnalyticsTaskBuilderView.ui.xml")
interface Binder extends UiBinder<Widget, AnalyticsTaskBuilderViewImpl> {
}
/**
* Name component for the name of the analytics operation.
* This also implements {#link HasEditorErrors so it can show
* constraint violations when an error occurs.
*/
#UiField
ValueBoxEditorDecorator<String> name;
/**
* Description component that edits analytics operation description.
* This also implements {#link HasEditorErrors} so it can show
* constraint violations when an error occurs
*/
#UiField
ValueBoxEditorDecorator<String> description;
public AnalyticsTaskBuilderViewImpl(Resources resources) {
super(resources);
// Must initialize the view before calling driver initialize
initWidget(GWT.<Binder> create(Binder.class).createAndBindUi(this));
driver.initialize(this);
}
#Override
public void setPresenter(Presenter presenter) {
this.presenter = presenter;
bindToPresenter();
}
// Save the task
#UiHandler("saveTask")
void handleClick(ClickEvent clickEvent) {
presenter.onSaveTask();
}
#Override
public RequestFactoryEditorDriver<AnalyticsTaskProxy, ?> getEditorDriver() {
return driver;
}
}

AWT repaint issues

I am trying to make some small additions to some old java code that does not support swing. I need to add a small dialog that contains a panel which has a checkbox and a couple text fields. When the user clicks on the checkbox I want to disable or enable the checkboxes. This part seems to work well but the text fields are not properly getting redrawn. When I click the checkbox the fields do not appear to become enabled but if I then click on the panel or the text field you see that they are enabled (the opposite is also true, when I un-check the checkbox the fields still look enabled until you try and click on them and they become ghosted and do not become selected). I use the setEnabled(boolean) to set the status of the fields. I have tried calling repaint and validate on both the fields and the panel after changing the status and this does not seem to work. I have also tried to have the fields request focus and this did not work. Anyone have any other ideas?
//The class that contains all of this is of type Window
//Declaration of the components
private Panel _inputPanel;
private TextField min , max;
//This method adds to two text fields
public void addMinMaxtextFields(String min, String max) {
TextField minField = new TextField(min);
TextField maxField = new TextField(max);
this.min = minField;
this.max = maxField;
this.min.setEnabled(false);
this.max.setEnabled(false);
_inputPanel.add(minField);
_inputPanel.add(maxField);
}
//listener for the checkbox
public void itemStateChanged(ItemEvent e) {
Component[] components = _inputPanel.getComponents();
min.setEnabled(!min.isEnabled());
min.setVisible(true);
min.validate();
min.repaint();
_inputPanel.validate();
_inputPanel.repaint();
this.pack();
this.setSize(this.getWidth(), this.getHeight());
this.validate();
this.repaint();
/* do nothing */
}
You will need to call update(Graphics g) on Panel after setEnabled(boolean) is called.
check :
http://download-llnw.oracle.com/javase/1.4.2/docs/api/java/awt/Container.html#update(java.awt.Graphics)
I tried following code (built from code you provided), Its working fine.
import java.awt.Checkbox;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class CheckUI extends Dialog implements ItemListener {
// The class that contains all of this is of type Window
// Declaration of the components
private Panel _inputPanel;
private TextField min, max;
private Checkbox cb;
public CheckUI(Frame owner, boolean modal) {
super(owner, modal);
_inputPanel = new Panel();
this.add(_inputPanel);
addMinMaxtextFields("min", "max");
}
// This method adds to two text fields
public void addMinMaxtextFields(String min, String max) {
cb = new Checkbox();
cb.addItemListener(this);
TextField minField = new TextField(min);
TextField maxField = new TextField(max);
this.min = minField;
this.max = maxField;
this.min.setEnabled(false);
this.max.setEnabled(false);
_inputPanel.add(minField);
_inputPanel.add(maxField);
_inputPanel.add(cb);
}
// listener for the checkbox
public void itemStateChanged(ItemEvent e) {
Component[] components = _inputPanel.getComponents();
min.setEnabled(!min.isEnabled());
min.setVisible(true);
min.validate();
min.repaint();
_inputPanel.validate();
_inputPanel.repaint();
this.pack();
this.setSize(this.getWidth(), this.getHeight());
this.validate();
this.repaint();
/* do nothing */
}
/**
* #param args
*/
public static void main(String[] args) {
Frame parent = new Frame();
parent.setVisible(true);
parent.setExtendedState(Frame.MAXIMIZED_BOTH);
parent.pack();
CheckUI ui = new CheckUI(parent, true);
ui.pack();
ui.setVisible(true);
}
}

Resources