Show data from JTable in Jtextfield with 2 JFrames - java

I am making a program for school.
My program has two JFrame's
The first Jframe = Basisscherm
The second Jframe = Toetsenbord
On the Jframe basisscherm i've got a Jtable filled with data from MYSQL Database. This Table showing labels and with this labels are specific text so each label has his own text this is in the same data base
Now on the Jframe toetsenbord i've got a Jtextfield with the name: Tekst
Now my problem is i want to show the text in the jtextfield by selecting the label from the jtable and clicking on a ok button but i don't now where to start

Have a look at this. using which you can get the selected text in JTable.
JTable table = new JTable();
if (table.getColumnSelectionAllowed()
&& !table.getRowSelectionAllowed()) {
// Column selection is enabled
// Get the indices of the selected columns
int[] vColIndices = table.getSelectedColumns();
} else if (!table.getColumnSelectionAllowed()
&& table.getRowSelectionAllowed()) {
// Row selection is enabled
// Get the indices of the selected rows
int[] rowIndices = table.getSelectedRows();
} else if (table.getCellSelectionEnabled()) {
// Individual cell selection is enabled
// In SINGLE_SELECTION mode, the selected cell can be retrieved using
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
int rowIndex = table.getSelectedRow();
int colIndex = table.getSelectedColumn();
// In the other modes, the set of selected cells can be retrieved using
table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
// Get the min and max ranges of selected cells
int rowIndexStart = table.getSelectedRow();
int rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
int colIndexStart = table.getSelectedColumn();
int colIndexEnd = table.getColumnModel().getSelectionModel()
.getMaxSelectionIndex();
// Check each cell in the range
for (int r=rowIndexStart; r<=rowIndexEnd; r++) {
for (int c=colIndexStart; c<=colIndexEnd; c++) {
if (table.isCellSelected(r, c)) {
// cell is selected
}
}
}
}

Related

How to individually set the width of a row on a table/scrollpane

i have a DefaultTableModel:
DefaultTableModel model = new DefaultTableModel(data, beschriftung)
{
// Returning the Class of each column will allow different
// renderers to be used based on Class
public Class getColumnClass(int column)
{
return getValueAt(0, column).getClass();
}
};
This is inside a table:
JTable table = new JTable(model);
table.setEnabled(false);
table.setRowHeight(50);
And the table is inside a scrollPane:
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(1215, 11, 300, 300);
scrollPane.setWheelScrollingEnabled(true);
scrollPane.setEnabled(false);
getContentPane().add(scrollPane);
I have two rows, but want the first one to be shorter than the second one. Any suggestions?
This is how it looks like:
This is how I want it to look like:
Check out:
Check of the section from the Swing tutorial on Setting and Changing Columns Widths. It shows how you can manually set a preferred size for each column.
The basic code would be:
table.getColumnModel().getColumn(???).setPreferredWidth(???)
You can also check out the Table Column Adjuster for automatic sizing of columns based on the data contained in the model
The basic code for this approach is:
JTable table = new JTable( ... );
table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
for (int column = 0; column < table.getColumnCount(); column++)
{
TableColumn tableColumn = table.getColumnModel().getColumn(column);
int preferredWidth = tableColumn.getMinWidth();
int maxWidth = tableColumn.getMaxWidth();
for (int row = 0; row < table.getRowCount(); row++)
{
TableCellRenderer cellRenderer = table.getCellRenderer(row, column);
Component c = table.prepareRenderer(cellRenderer, row, column);
int width = c.getPreferredSize().width + table.getIntercellSpacing().width;
preferredWidth = Math.max(preferredWidth, width);
// We've exceeded the maximum width, no need to check other rows
if (preferredWidth >= maxWidth)
{
preferredWidth = maxWidth;
break;
}
}
tableColumn.setPreferredWidth( preferredWidth );
}
The TableColumnAdjuster class in the link contains other features as well.
Also check out the JTable API for the setAutoResizeMode(...) method to determine how space is allocated if the width of the table changes.

Prevent user from clicking the same button?

I'm really new to java and i'm learning javafx while doing this project.The code sends rows and cols to another class when a button is clicked. My logic send the row and col accordingly to another class. But i want to prevent the user from clicking the same button. How would i go about doing that. I know there's a setDisable function but how would go implementing it.
for (row = 0; row < 10; row++) {
for (coloumn = 0; coloumn < 10; coloumn++) {
button[row][coloumn] = new Button();
// button[row][coloumn].setStyle("-fx-background-color: red");
button[row][coloumn].setPrefSize(50, 50);
button[row][coloumn].setOnAction(new clickEvents(row, coloumn));
//no setters, directly passed rows and cols to clickEvents Class
tileGrid.add(button[row][coloumn], row, coloumn); //adds buttons to the tile grid
//node , row position in grid, column position in grid
}
}
Revised
for (row = 0; row < 10; row++) {
for (coloumn = 0; coloumn < 10; coloumn++) {
button[row][coloumn] = new Button();
// button[row][coloumn].setStyle("-fx-background-color: red");
button[row][coloumn].setPrefSize(50, 50);
button[row][coloumn].setOnAction(new clickEvents(row, coloumn));
temprow= row;
tempcol=coloumn;
//if(row==temprow && coloumn == tempcol )
if(button[row][coloumn].isPressed()) {
button[row][coloumn].setDisable(true);
}
//no setters, directly passed rows and cols to clickEvents Class
tileGrid.add(button[row][coloumn], row, coloumn); //adds buttons to the tile grid
//node , row position in grid, column position in grid
}
Read the doc.
button.setDisable(true);
Works on any component that inherits from Node, by the way, so you can disable pretty much anything in your scene.
When you create the button, set a boolean called clicked, initialized to false. When the user clicks the button, the handler fires, and sets the boolean to true. Then you have a bit of logic that branches on clicked. If true, do nothing (since the button was already previously disabled), if false, disable the button.

Why does this produce only one button on the grid?

When I run this, it creates only one button. I'm trying to create a gridPane of buttons, 10x10 and when a button is clicked it would send the row column(x,y) coordinates to another class which would handle its purpose (a battleship game)
Button button[][] = new Button[10][10];
public static int rows, columns, gridSize;
for (rows = 0; rows < 10; rows++) {
for (columns = 0; columns < 10; columns++) {
button[rows][columns] = new Button();
button[rows][columns].setStyle("-fx-background-color: red");
button[rows][columns].setPrefSize(50, 50);
button[rows][columns].setOnMouseClicked(new clickEvents(rows, columns));
//no setters, directly passed rows and cols to clickEvents Class
tileGrid.getChildren().add(button[rows][columns]); //adds buttons to the tile grid
}
}
container.getChildren().addAll(tileGrid);
ScrollPane scrollPane = new ScrollPane(container);
primaryStage.setScene(new Scene(scrollPane));
primaryStage.show();
You aren't telling the system where to put the button in the GridPane.
Use gridPane.add(child, colIndex, rowIndex):
tileGrid.add(button[row][column], column, row);
I fixed spelling and removed plurality (trailing 's') from the row, column variables.
Alternately, you could set constraints on the node in the GridPane:
tileGrid.getChildren().add(button[row][column]);
GridPane.setConstraints(button[row][column], column, row);
But it is a less verbose to use the add method which specifies the constraints in initial add parameters (as in the prior example).
Without any constraints on the nodes added as children to the grid, all the children will be located at the default 0,0 grid location (all stacked on top of each other).
This line is the one giving you issues
tileGrid.getChildren().add(button[rows][columns]);
This is due to the fact that you are incorrectly adding your buttons. If you try something like
tileGrid.add(
button[rows][columns], // Specific node in the array
columns, // Set the specific column
rows // Set the specific row
); //adds buttons to the tile grid
it should work here is the full example code
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
Button button[][] = new Button[10][10];
int rows, columns, gridSize;
GridPane tileGrid = new GridPane();
for (rows = 0; rows < 10; rows++) {
for (columns = 0; columns < 10; columns++) {
button[rows][columns] = new Button();
button[rows][columns].setStyle("-fx-background-color: red");
button[rows][columns].setPrefSize(50, 50);
//button[rows][columns].setOnMouseClicked(new clickEvents(rows, columns));
//no setters, directly passed rows and cols to clickEvents Class
tileGrid.add(
button[rows][columns], // Specific node in the array
columns, // Set the specific column
rows // Set the specific row
); //adds buttons to the tile grid
}
}
ScrollPane scrollPane = new ScrollPane(new VBox(tileGrid));
primaryStage.setScene(new Scene(scrollPane));
primaryStage.show();
}
}
EDIT: 2 Min too slow but I'm going to leave it here so he can see the example if he needs it

Last column does not appear on screen in a JTable

I create a JTable at runtime. The number of columns will vary from a few to hundreds.
I have a database routine which populates a vector of vectors.
The topmost row is used as the header.
The data in the columns vary in size, and the column sizes are computed and set to the maximum width for that column. That is to say, each column will vary in size.
The table header in the table and the scroll pane are hidden via:
Common.myTBL.setTableHeader(null);
Common.myScrollPanel.setColumnHeaderView(null);
Common.myScrollPanel.setViewportView(Common.myTBL);
pack();
When the number of columns in the table is small - say 5 or 6 - I don't have any problems.
Common.myTBL.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
But there is a particular case where the number of columns is 174 (0 to 173). The last column does not appear on the screen. I tried adding an extra dummy column (175th) and part of column 174 appeared.
This is the code that creates the Table Model and Table Object
public void createTableModel() {
int noOfColumns = 0;
int noOfRows = 0;
noOfRows = Common.tableData.size();
noOfColumns = Common.tableData.get(0).size();
System.out.println("\nNumber of Rows in the VECTOR = "+noOfRows);
System.out.println("\nNumber of columns in the VECTOR = "+noOfColumns);
Common.myTableModel = new AttributiveCellTableModel(noOfRows, noOfColumns);
System.out.println("\nNumber of Rows in the MODEL= "+Common.myTableModel.getRowCount());
System.out.println("\nNumber of columns in the MODEL = "+Common.myTableModel.getColumnCount());
Common.theRoots = Common.tableData.get(0);
Common.myTableModel.setDataVector(Common.tableData, Common.theRoots);
Common.cellAtt = (CellSpan)Common.myTableModel.getCellAttribute();
}
public void createTableObject() {
Common.myTBL = new MultiSpanCellTable(Common.myTableModel) {
public Component prepareRenderer(TableCellRenderer renderer, int Index_row, int Index_col) {
Component comp = super.prepareRenderer(renderer, Index_row, Index_col);
JComponent jcomp = (JComponent) comp;
Common.originalBorder = jcomp.getBorder();
comp.setBackground(setRowColor(Index_row));
jcomp.setToolTipText(getToolTip(Index_row, Index_col));
comp.setFont(Common.defaultFont14);
comp.setForeground(setGenderColor(Index_row, Index_col));
jcomp.setBorder(setBorderType(Index_row, Index_col));
return comp;
}
};
Common.myTBL.setRowHeight(25);
Common.myTBL.setBorder(null);
Common.myTBL.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
Common.myTBL.setCellSelectionEnabled(true);
Common.myTBL.setGridColor(new java.awt.Color(0, 51, 255));
Common.myTBL.setFillsViewportHeight(true);
Common.myTBL.revalidate();
}

Auto/best fit JTable columns, but stretch the last column

I have the following JTable (Actually it's a ETable from Netbeans). It stretches across the container it's in - I'd like to keep that, and not use JTable.AUTO_RESIZE_OFF
I'd like to fit it programatically like below, resizing each column to fit the only the cell content, or column header text and having the rightmost column fill the remaining space. How can I do that ?
You do have to set autoResize to OFF (setAutoResizeMode(JTable.AUTO_RESIZE_OFF);), but you also need a helper method to resize your columns.
This is inside a custom class that extends JTable, but you can just as easily reference an existing JTable:
public void resizeColumnWidth() {
int cumulativeActual = 0;
int padding = 15;
for (int columnIndex = 0; columnIndex < getColumnCount(); columnIndex++) {
int width = 50; // Min width
TableColumn column = columnModel.getColumn(columnIndex);
for (int row = 0; row < getRowCount(); row++) {
TableCellRenderer renderer = getCellRenderer(row, columnIndex);
Component comp = prepareRenderer(renderer, row, columnIndex);
width = Math.max(comp.getPreferredSize().width + padding, width);
}
if (columnIndex < getColumnCount() - 1) {
column.setPreferredWidth(width);
cumulativeActual += column.getWidth();
} else { //LAST COLUMN
//Use the parent's (viewPort) width and subtract the previous columbs actual widths.
column.setPreferredWidth((int) getParent().getSize().getWidth() - cumulativeActual);
}
}
}
Call resizeColumnWidth() whenever you add a row.
Optionally add a listener to the table so that the columns are also resized when the table itself is resized:
public MyCustomJTable() {
super();
addHierarchyBoundsListener(new HierarchyBoundsAdapter() {
#Override
public void ancestorResized(HierarchyEvent e) {
super.ancestorResized(e);
resizeColumnWidth();
}
});
setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
}
You can turn off auto resize. In this case the columns will resize automatically according to content. But in this case, if total column width is less than table's width, blank space will be there on right side. If it is greater, horizontal scroll bar will appear.
You can assign preferred width to each column using TableColumn.setPreferredWidth. Swing will try to distribute extra space according to that. But this is also not guaranteed.

Categories

Resources