Why applied Font is removed upon font.dispose() in swt? - java

I have created an SWT Table and added columns to it. I want to apply bold font to header row alone. So my code looks like below
Table table= new Table(top, tableStyle);
Font font = new Font(null, StringUtils.EMPTY, 9, SWT.BOLD);
for (int i = 0; i < titles.length; i++)
{
new TableColumn(table, SWT.NONE);
header.setFont(i, font);
header.setText(i, titles[i]);
}
font.dispose();
In the above code, I have disposed as it is a good practice to do. But this is removing the font style from the header. If I remove the last line, font remains applied.
Is there any mistake over here? Or is this the expected behavior?

You need to wait and only dispose() the Font when you no longer need it. You could tie the disposal to the dispose event of the table so you don't have to manually dispose it:
public static void main(String[] args)
{
final Display d = new Display();
Shell s = new Shell(d);
s.setLayout(new FillLayout());
Table table = new Table(s, SWT.NONE);
Font font = new Font(null, "", 12, SWT.BOLD);
for (int i = 0; i < 3; i++)
{
TableItem item = new TableItem(table, SWT.NONE);
item.setFont(font);
item.setText("" + i);
}
table.addListener(SWT.Dispose, e -> font.dispose());
s.pack();
s.open();
while (!s.isDisposed())
{
if (!d.readAndDispatch())
d.sleep();
}
d.dispose();
}

Related

Create GridLayout With Rows of Equal Height

I want to have a composite with some labels, and all the labels should have the same height, but they should be vertically centered.
So far I have the following:
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final Composite composite = new Composite(shell, SWT.VERTICAL);
composite.setLayout(GridLayoutFactory.fillDefaults().numColumns(1).equalWidth(true).spacing(0, 0).create());
for (int i = 0; i < 10; i++) {
final Label label = new Label(composite, SWT.WRAP);
label.setAlignment(SWT.CENTER);
label.setText(i < 5 ? "small " + i : "a very big text for the row that is named " + i);
label.setToolTipText(label.getText());
label.setLayoutData(GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.CENTER).grab(true, true).create());
}
shell.setSize(100, 600);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
As you can see, the labels are vertically centered in their rows, but the ones which wrap take more space than the other ones.
If I add hint(SWT.DEFAULT, 60) to the GridData, I can force the labels to have the same height, but then they won't be vertically centered anymore.
I could probably wrap all the labels in composites, set the height hint on the composite and center the labels, but let's see of there is another option first.
How do I create vertically centered rows of equal height?
Since you're trying to uniformly arrange widgets which may be different sizes, I think a good option would be to place each Label into a Composite. That way each Composite can have the same size, and the Label will be centered within.
By adding a ControlListener to the parent Composite, you can check the size of each child Composite, then set the height hint of each child to be the height of the largest child:
public static void main(final String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
final Composite composite = new Composite(shell, SWT.VERTICAL);
composite.setLayout(GridLayoutFactory.fillDefaults().numColumns(1).equalWidth(true).spacing(0, 0).create());
final List<Composite> children = new ArrayList<Composite>();
for (int i = 0; i < 10; i++) {
final Composite c = new Composite(composite, SWT.BORDER);
c.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
c.setLayout(new GridLayout());
final Label label = new Label(c, SWT.WRAP);
label.setAlignment(SWT.CENTER);
label.setText(i < 5 ? "small " + i : "a very big text for the row that is named " + i);
label.setToolTipText(label.getText());
label.setLayoutData(GridDataFactory.fillDefaults().align(SWT.CENTER, SWT.CENTER).grab(true, true).create());
children.add(c);
}
composite.addControlListener(new ControlAdapter() {
#Override
public void controlResized(final ControlEvent e) {
int maxHeight = 0;
for (final Composite c : children) {
if (c.getClientArea().height > maxHeight) {
maxHeight = c.getClientArea().height;
}
}
for (final Composite c : children) {
((GridData) c.getLayoutData()).heightHint = maxHeight;
}
}
});
shell.setSize(100, 600);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
Result:
And after resizing:

Show Table in a View - Eclipse Plugin

I'm trying to develop a plugin for Eclipse. I follow tutorials online and I have done a plugin with sample perspective and a sample views.
Now the view show this:
public Object[] getElements(Object parent)
{
return new String[] { "One", "Two", "Three" };
}
Instead of string I need to insert a table. I follow another tutorial to create a TreeTable, but I have no idea how to put this table Tree into my plugin's view.
This is the code of TreeTable:
public class TreeTableCreation
{
public static void main(String[] args)
{
Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
Tree tree = new Tree(shell, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL);
tree.setHeaderVisible(true);
TreeColumn column1 = new TreeColumn(tree, SWT.LEFT);
column1.setText("Column 1");
column1.setWidth(200);
TreeColumn column2 = new TreeColumn(tree, SWT.CENTER);
column2.setText("Column 2");
column2.setWidth(200);
TreeColumn column3 = new TreeColumn(tree, SWT.RIGHT);
column3.setText("Column 3");
column3.setWidth(200);
for (int i = 0; i < 4; i++) {
TreeItem item = new TreeItem(tree, SWT.NONE);
item.setText(new String[] { "item " + i, "abc", "defghi" });
for (int j = 0; j < 4; j++) {
TreeItem subItem = new TreeItem(item, SWT.NONE);
subItem.setText(new String[] { "subitem " + j, "jklmnop", "qrs" });
for (int k = 0; k < 4; k++) {
TreeItem subsubItem = new TreeItem(subItem, SWT.NONE);
subsubItem.setText(new String[] { "subsubitem " + k, "tuv", "wxyz" });
}
}
}
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
Your view should have a createPartControl(Composite parent) method inherited from ViewPart. Put your tree table creation code there and use the parent parameter as the tree's parent (instead of shell in your code).

This is my code to print the jtable on frame

I added MouseListener to select a particular row from table,the content of row is getting printed on console but I want to print this content on new frame what should I do for this.
I attached my code along with the screenshot of the table.
thanks for help.
This is my code.
final JTable table = new JTable(data, columnNames);
JScrollPane scrollPane = new JScrollPane( table );
cp.add(scrollPane,BorderLayout.CENTER);
frame.add(cp);
frame.setSize(300,300);
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
if(e.getClickCount()==1){
JTable target = (JTable)e.getSource();
System.out.println(target);
int row = target.getSelectedRow();
System.out.println(row);
Object [] rowData = new Object[table.getColumnCount()];
Object [] colData = new Object[table.getRowCount()];
for(int j = 0;j < table.getRowCount();j++)
for(int i = 0;i < table.getColumnCount();i++)
{
rowData[i] = table.getValueAt(j, i);
System.out.println(rowData[i]);
}
}
}
});
}
First of all, if you make a graphical interface with swing, you can't use System.out.print.
You need to set every row in a Label and print it out that way. If it is a Label then you can select it with your mouse
In the Mouse Listener method, Call the new JFrame,
in that JFrame , put the Contents of selected Row to Constructor Parameters.
JFrame newframe=new JFrame("Selected Contents);
When you output the result (System.out.println(rowData[i]);) just create a new JFrame and place the text you want to output here :
...
JFrame secondFrame = new JFrame();
JPanel myPanel = new JPanel();
for(int j = 0;j < table.getRowCount();j++){
for(int i = 0;i < table.getColumnCount();i++){
rowData[i] = table.getValueAt(j, i);
JLabel label = new JLabel(rowData[i]);
myPanel.add(label);
}
}
secondFrame.add(myPanel);
secondFrame.setVisible(true);
....

SWT Label with horizontal line not showing correctly

I'm trying to display a label in a 2-columned GridLayout. I can't seem to make it work to display both text and the horizontal line underneath:
public void foo(){
popupShell = new Shell(Display.getDefault(), SWT.NO_TRIM | SWT.ON_TOP | SWT.MODELESS);
//popupShell.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
popupShell.setLayout(createNoMarginLayout(2, false));
Label history = new Label(popupShell, SWT.SEPARATOR | SWT.SHADOW_OUT | SWT.HORIZONTAL);
history.setText("History");
history.setVisible(true);
Label fill = new Label(popupShell, SWT.NONE);
fill.setSize(0,30);
}
public static GridLayout createNoMarginLayout(int numColumns, boolean makeColumnsEqualWidth) {
GridLayout layout = new GridLayout(numColumns, makeColumnsEqualWidth);
layout.verticalSpacing = 0;
layout.horizontalSpacing = 0;
layout.marginTop = 0;
layout.marginBottom = 0;
layout.marginLeft = 0;
layout.marginRight = 0;
layout.marginWidth = 0;
layout.marginHeight = 0;
return layout;
}
What I'm getting is just the line with no text.
What am I doing wrong?
A Label with the SWT.SEPARATOR style does not display any text value. You must use a separate control to display the text.
From the Label source, showing that setText is completely ignored for SWT.SEPARATOR:
public void setText (String string) {
checkWidget();
if (string == null) error (SWT.ERROR_NULL_ARGUMENT);
if ((style & SWT.SEPARATOR) != 0) return;
...

Tooltip in other colums with Java SWT?

I have a table with 4 columns. I try to integrate a ToolTip for all cells of the third column.
With my Code the ToolTip only appears for the cells of the first column.
This is my Code:
protected void checkAction() throws Exception {
System.out.println("Start Test");
//Erstellen einer neuen Shell
final Shell shell = new Shell();
shell.setSize(280, 300);
shell.setText("Testtabelle");
//Erstellen einer neuen Tabelle
final Table table = new Table(shell, SWT.MULTI | SWT.BORDER | SWT.FULL_SELECTION);
table.setLinesVisible(true);
table.setHeaderVisible(true);
//Einlesen der Überschriften und Vergabe der Namen
String[] titles = {"Element", "Stage", "Type", "Generate-User", "Change-User" };
for (int i = 0; i < titles.length; i++) {
TableColumn column = new TableColumn(table, SWT.NONE);
column.setText(titles[i]);
}
// Inhalte hinzufügen
final int count = 4;
for (int i = 0; i < count; i++) {
TableItem item = new TableItem(table, SWT.NONE);
item.setText(0, "Test "+i);
item.setText(1, ""+(i+1));
item.setText(2, "Testtype");
item.setText(3, "562910");
item.setText(4, "423424");
}
// Disable native tooltip
table.setToolTipText ("");
// Implement a "fake" tooltip
final Listener labelListener = new Listener () {
public void handleEvent (Event event) {
Label label = (Label)event.widget;
Shell shell = label.getShell ();
switch (event.type) {
case SWT.MouseDown:
Event e = new Event ();
e.item = (TableItem) label.getData ("_TABLEITEM");
// Assuming table is single select, set the selection as if
// the mouse down event went through to the table
table.setSelection (new TableItem [] {(TableItem) e.item});
table.notifyListeners (SWT.Selection, e);
shell.dispose ();
table.setFocus();
break;
case SWT.MouseExit:
shell.dispose ();
break;
}
}
};
Listener tableListener = new Listener () {
Shell tip = null;
Label label = null;
public void handleEvent (Event event) {
switch (event.type) {
case SWT.Dispose:
case SWT.KeyDown:
case SWT.MouseMove: {
if (tip == null) break;
tip.dispose ();
tip = null;
label = null;
break;
}
case SWT.MouseHover: {
TableItem item = table.getItem (new Point (event.x, event.y));
if (item != null) {
if (tip != null && !tip.isDisposed ()) tip.dispose ();
tip = new Shell (shell, SWT.ON_TOP | SWT.NO_FOCUS | SWT.TOOL);
FillLayout layout = new FillLayout ();
layout.marginWidth = 2;
tip.setLayout (layout);
label = new Label (tip, SWT.NONE);
label.setData ("_TABLEITEM", item);
if (item.getText().equals("Test 3")){
label.setText ("Jonas Intfeld");
}
else{
label.setText (item.getText ());
}
label.addListener (SWT.MouseExit, labelListener);
label.addListener (SWT.MouseDown, labelListener);
Point size = tip.computeSize (SWT.DEFAULT, SWT.DEFAULT);
Rectangle rect = item.getBounds (0);
Point pt = table.toDisplay (rect.x, rect.y);
tip.setBounds (pt.x, pt.y, size.x, size.y);
tip.setVisible (true);
}
}
}
}
};
table.addListener (SWT.Dispose, tableListener);
table.addListener (SWT.KeyDown, tableListener);
table.addListener (SWT.MouseMove, tableListener);
table.addListener (SWT.MouseHover, tableListener);
// Tabelle und Shell Packen
for (int i = 0; i < titles.length; i++) {
table.getColumn(i).pack();
}
table.setSize(table.computeSize(SWT.DEFAULT, 200));
shell.pack();
// Shell öffnen
try { shell.open();
} catch (SWTException e) {
System.out.println("Test: "+e);
shell.close();
}
}
Is there any way to activate the Tooltip for the 3. Column ?
At the moment when I move over the cells in the 3. column the Tooltip appears for the 1. column.
Maybe the best option is to search the column by title?
Your problem is this line:
Rectangle rect = item.getBounds(0);
You are asking for the bounds of the first column. Just change the index to the column where you want your tooltip to appear and you'll be fine:
Rectangle rect = item.getBounds(2);
If you need to get the column index from the mouse position, use this code:
Point point = new Point(event.x, event.y);
int column = 0;
for (int i = 0; i < table.getColumnCount(); i++)
{
if (item.getBounds(i).contains(point))
{
column = i;
break;
}
}
Rectangle rect = item.getBounds(column);

Categories