Can someone explain me something? How can I create a yellow hint/notification with Java swt?
I want that popup a small notice when I move over a cell in a table. Something like this:
This is my Java-Code:
protected void checkAction() throws Exception {
//Erstellen einer neuen Shell
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");
}
// 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();
//MouseListener
table.addListener(SWT.MouseHover, new Listener() {
public void handleEvent(Event event) {
Rectangle clientArea = table.getClientArea();
Point pt = new Point(event.x, event.y);
int index = table.getTopIndex();
// System.out.println("TopIndex: "+index);
while (index < table.getItemCount()) {
boolean visible = false;
TableItem item = table.getItem(index);
for (int i = 0; i < (table.getItemCount()+1); i++) {
Rectangle rect = item.getBounds(i);
if (rect.contains(pt)) {
String selected = table.getItem(index).getText(i);
if (selected.equals("562910")){
String real = "Jonas";
System.out.println(real);
}
else{
System.out.println("Ausgewählt: "+selected);
}
}
if (!visible && rect.intersects(clientArea)) {
visible = true;
}
}
if (!visible)
return;
index++;
}
}
});
// Shell öffnen
shell.open();
}
Using just SWT use the code in SWT Snippet 125.
If you can use JFace then ColumnViewerToolTipSupport is rather easier.
You should start using jface TableViewer. To create table column, you will use TableViewerColumn.
For each column, add CellLabelProvider which has getToolTipXXX() methods.
TableViewerColumn.setLabelProvider(CellLabelProvider)
here is good article to start with
http://www.vogella.com/tutorials/EclipseJFaceTable/article.html
Related
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).
I am trying to highlight Java syntax using StyleRanges in SWT StyledText boxes. Here is the relevant code.
String code = text.getText();
int fromIndex = 0;
String keyword = "public";
if(code.toLowerCase().contains(keyword.toLowerCase())){
System.out.println("Match found");
Shell shell = text.getShell();
Display display = shell.getDisplay();
System.out.println("Got shell and display...");
Color orange = new Color(display, 255, 127, 0);
int index = code.indexOf(keyword, fromIndex);
int length = keyword.length();
StyleRange styleRange = new StyleRange(0, 22, orange, null,SWT.BOLD);
text.setStyleRange(styleRange);
System.out.println("colored...");
fromIndex = index;
}
but the StyleRanges do nothing? Can someone help me out with this?
Edit: If i use this new code
`private void Color_Code(StyledText text) {
Shell shell = this.getShell();
Display display = shell.getDisplay();
String[] lines = text.getText().split("\\n");
String keyWord = "public";
Color red = display.getSystemColor(SWT.COLOR_RED);
int offset = 0;
for (String line : lines)
{
int index = line.indexOf(keyWord);
if (index != -1)
{
StyleRange range = new StyleRange(index + offset, keyWord.length(), red, null, SWT.BOLD);
text.setStyleRange(range);
}
offset += line.length() + 1; // +1 for the newline character
}
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}`
Tree population code: private void Populate_Method_Tree(Tree tree) {
// TODO Auto-generated method stub
for (int i = 0; i < SampleHandler.f.MCCCLONES.size(); i++) {
int id = SampleHandler.f.MCCCLONES.get(i).getMCCID();
TreeItem temp = new TreeItem(tree, SWT.V_SCROLL);
temp.setText("MCCID: " + id);
Populate_Drop_Down(id);
}
}
Dropdown Population code:
protected void Populate_Drop_Down(int id) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
for (int i = 0; i < SampleHandler.f.MCCCLONES.size(); i++) {
if (id == SampleHandler.f.MCCCLONES.get(i).getMCCID()) {
ArrayList<String> Method_Names = new ArrayList<>();
for (int j = 0; j < SampleHandler.f.MCCCLONES.get(i)
.getMethod_Clones().size(); j++) {
String name = SampleHandler.f.MCCCLONES.get(i)
.getMethod_Clones().get(j).getMethod()
.getFileName();
String[] parts = name.split("[\\\\ .]");
Method_Names.add(parts[parts.length - 2]
+ " "
+ Integer
.toString(SampleHandler.f.MCCCLONES
.get(i).getMethod_Clones()
.get(j).getMethod()
.getMethodID()));
}
String[] Methds = new String[Method_Names.size()];
Methds = Method_Names.toArray(Methds);
combo.setItems(Methds);
combo.setText(Methds[0]);
String[] parts = Methds[0].split("[\\s+]");
int MID = Integer.parseInt(parts[1]);
Fill_Code(MID);
}
}
}
Textbox filling code:
private void Fill_Code(int MID) {
// TODO Auto-generated method stub
for (int i = 0; i < SampleHandler.f.METHODS.size(); i++) {
if (SampleHandler.f.METHODS.get(i).getMethodID() == MID) {
text.setText(SampleHandler.f.METHODS.get(i).getCode());
//Color_Code(text);
}
}
}
it highlight the word public in my first instance but stops populating my dropdown menu and tree.
There has to be something wrong with your other code. Everything works just fine here.
Here is an example:
public static void main(String[] args)
{
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("StackOverflow");
shell.setLayout(new FillLayout());
StyledText text = new StyledText(shell, SWT.BORDER | SWT.MULTI | SWT.WRAP);
text.setText("public class Text\n{\n public static void main(String[] args)\n {\n System.out.println(\"Text\");\n }\n}");
String[] lines = text.getText().split("\\n");
String keyWord = "public";
Color red = display.getSystemColor(SWT.COLOR_RED);
int offset = 0;
for (String line : lines)
{
int index = line.indexOf(keyWord);
if (index != -1)
{
StyleRange range = new StyleRange(index + offset, keyWord.length(), red, null, SWT.BOLD);
text.setStyleRange(range);
}
offset += line.length() + 1; // +1 for the newline character
}
shell.pack();
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
}
Looks like this:
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;
...
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);
I want to select JTable zeroth row be selected by default
I am using following code but it gets the zeroth to be focused, not selected
jtblProduct.setCellSelectionEnabled(true);
jtblProduct.changeSelection(0, 0, false, false);
jtblProduct.requestFocus();
jtblProduct.scrollRectToVisible(new Rectangle(jtblProduct.getCellRect(0, 0, true)));
When I get the selected row by using the following code it returns -1, which means none selected.
jtblProduct.getSelectedRow()
Please provide me the way to select the zeroth row by default.
I haven't any issue with that, meaning
a) table.changeSelection(row, col, false, false);
or
b) table.getSelectedRow()
maybe everything depends of how is set value for ListSelectionModel
for better help sooner edit your question with a SSCCE
code
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.DefaultTableModel;
public class TableSelectionGood implements ListSelectionListener {
private JTable[] tables;
private boolean ignore = false;
public TableSelectionGood() {
Object[][] data1 = new Object[100][5];
Object[][] data2 = new Object[50][5];
//Object[][] data3 = new Object[50][5];
for (int i = 0; i < data1.length; i++) {
data1[i][0] = "Company # " + (i + 1);
for (int j = 1; j < data1[i].length; j++) {
data1[i][j] = "" + (i + 1) + ", " + j;
}
}
for (int i = 0; i < data2.length; i++) {
data2[i][0] = "Company # " + ((i * 2) + 1);
for (int j = 1; j < data2[i].length; j++) {
data2[i][j] = "" + ((i * 2) + 1) + ", " + j;
}
}
/*for (int i = 0; i < data3.length; i++) {
data3[i][0] = "Company # " + (i * 2);
for (int j = 1; j < data3[i].length; j++) {
data3[i][j] = "" + (i * 2) + ", " + j;
}
}*/
String[] headers = {"Col 1", "Col 2", "Col 3", "Col 4", "Col 5"};
DefaultTableModel model1 = new DefaultTableModel(data1, headers);
DefaultTableModel model2 = new DefaultTableModel(data2, headers);
//DefaultTableModel model3 = new DefaultTableModel(data3, headers);
final JTable jTable1 = new JTable(model1);
jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JScrollPane sp1 = new JScrollPane();
sp1.setPreferredSize(new Dimension(600, 100));
sp1.setViewportView(jTable1);
final JTable jTable2 = new JTable(model2);
jTable2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JScrollPane sp2 = new JScrollPane();
sp2.setPreferredSize(new Dimension(600, 100));
sp2.setViewportView(jTable2);
/*final JTable jTable3 = new JTable(model3);
jTable3.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JScrollPane sp3 = new JScrollPane();
sp3.setPreferredSize(new Dimension(600, 100));
sp3.setViewportView(jTable3);
TableSelectionGood tableSelection = new TableSelectionGood(jTable1, jTable2, jTable3);*/
TableSelectionGood tableSelection = new TableSelectionGood(jTable1, jTable2);
JPanel panel1 = new JPanel();
//panel1.setLayout(new GridLayout(3, 0, 10, 10));
panel1.setLayout(new GridLayout(2, 0, 10, 10));
panel1.add(sp1);
panel1.add(sp2);
//panel1.add(sp3);
JFrame frame = new JFrame("tableSelection");
frame.add(panel1);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public TableSelectionGood(JTable... tables) {
for (JTable table : tables) {
table.getSelectionModel().addListSelectionListener(this);
}
this.tables = tables;
}
private JTable getTable(Object model) {
for (JTable table : tables) {
if (table.getSelectionModel() == model) {
return table;
}
}
return null;
}
private void changeSelection(JTable table, String rowKey) {
int col = table.convertColumnIndexToView(0);
for (int row = table.getRowCount(); --row >= 0;) {
if (rowKey.equals(table.getValueAt(row, col))) {
table.changeSelection(row, col, false, false);
return;
}
}
table.clearSelection();
}
#Override
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() || ignore) {
return;
}
ignore = true;
try {
JTable table = getTable(e.getSource());
int row = table.getSelectedRow();
String rowKey = table.getValueAt(row, table.convertColumnIndexToView(0)).toString();
for (JTable t : tables) {
if (t == table) {
continue;
}
changeSelection(t, rowKey);
JViewport viewport = (JViewport) t.getParent();
Rectangle rect = t.getCellRect(t.getSelectedRow(), 0, true);
Rectangle r2 = viewport.getVisibleRect();
t.scrollRectToVisible(new Rectangle(rect.x, rect.y, (int) r2.getWidth(), (int) r2.getHeight()));
System.out.println(new Rectangle(viewport.getExtentSize()).contains(rect));
System.out.println(table.getSelectedRow());
}
} finally {
ignore = false;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TableSelectionGood tableSelection = new TableSelectionGood();
}
});
}
}
Have you tried jtable.setRowSelectionInterval(..) ?
Addition from comment: also try jtable.addRowSelectionInterval(..).