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 :)
Related
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.
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).
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);
}
}
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;
}
}
ive been trying to figure this out for 2 hours now and i cant seem to understand what went wrong.
I am using Symfony2 and FOSUserBundle.
I created a User entity which extends FOSUserBundle's BaseUser class. Within this User entity, i have 3 variables, id, my_mentors and my_mentees. More details are below:
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToMany(targetEntity="User", mappedBy="my_mentees")
*/
protected $my_mentors;
/**
* #ORM\ManyToMany(targetEntity="User", inversedBy="my_mentors")
* #ORM\JoinTable(name="mentor_and_mentee_relationship",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="mentors_or_mentees_user_id", referencedColumnName="id")}
* )
*/
protected $my_mentees;
public function __construct()
{
parent::__construct();
$this->my_mentors = new ArrayCollection();
$this->my_mentees = new ArrayCollection();
}
public function __toString()
{
return $this->getUsername();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Add my_mentors
*
* #param Fitness\FitBundle\Entity\User $myMentors
*/
public function addUser(\Fitness\FitBundle\Entity\User $myMentors)
{
$this->my_mentors[] = $myMentors;
}
/**
* Get my_mentors
*
* #return Doctrine\Common\Collections\Collection
*/
public function getMyMentors()
{
return $this->my_mentors;
}
/**
* Get my_mentees
*
* #return Doctrine\Common\Collections\Collection
*/
public function getMyMentees()
{
return $this->my_mentees;
}
}
I created the self reference because a Mentee(which is a User) will subscribe to a Mentor(which is also a User). I tried to do this using the following function:
public function subscribeAction($menteeID, $mentorID)
{
$em = $this->getDoctrine()
->getEntityManager();
$mentor = $em->getRepository('TestBundle:User')
->find($mentorID);
$mentee = $em->getRepository('TestBundle:User')
->find($menteeID);
$currentMentors = $mentee->getMyMentors();
if ($currentMentors->contains($mentor))
$this->get('session')->setFlash('subscribe-notice', 'You have already signed up to this mentor!');
else
{
$mentee->setIsMentor(false);
$mentee->addUser($mentor);
$mentor->addUser($mentee);
$em->persist($mentee);
$em->persist($mentor);
$em->flush();
$this->get('session')->setFlash('subscribe-notice', 'Subscription succesful!');
}
return $this->redirect($this->generateUrl('TestBundle_testpage', array('id' => $mentor->getMentorProfile()->getId()) ));
}
The problem here is that when i check the database, it does not persist the data. The mentor-mentee relationship information is not stored in the table "mentor_and_mentee_relationship" as declared by the annotation.
I persisted both $mentor and $mentee in an attempt to get it to work, but apparently it doesnt.
Could my ORM annotation be declared wrongly?
You are using the same function (addUser) to add a mentor and to add a mentee. This is wrong. First you need two different setters in your entity (I changed the name of addUser to make it clear)
/**
* Add my_mentors
*
* #param Fitness\FitBundle\Entity\User $myMentors
*/
public function addMentor(\Fitness\FitBundle\Entity\User $myMentors)
{
$this->my_mentors[] = $myMentors;
}
/**
* Add my_mentees
*
* #param Fitness\FitBundle\Entity\User $myMentees
*/
public function addMentee(\Fitness\FitBundle\Entity\User $myMentees)
{
$this->my_mentees[] = $myMentees;
}
Then in your controller do:
$mentee->addMentor($mentor);
$mentor->addMentee($mentee);