Java Swing - Background of a JPanel - java

I want to design a JPanel which should have the color coding as shown in the following diagram:
(source: compendiumblog.com)
How can I code the colors of a JPanel. What I think is that add 5 JPanels (for 5 blocks shown above) on a main JPanel. Set the background of each JPanel to light Gray.
But then how can I achieve the dark color lines as shown in the diagram.
Any hints or suggestions?

Try using a JTable and then alternating the colors of the row. This way you can write a generic JComponent (AlternatingColorTable) and use it just like a regular JTable in those 4 panels.
Something like this maybe:
public class AlternatingColorTable extends JTable {
public AlternatingColorTable () {
super();
}
public AlternatingColorTable(TableModel tableModel) {
super(tableModel);
}
/** Extends the renderer to alternate row colors */
public Component prepareRenderer(TableCellRenderer renderer, int row, int col) {
Component returnComp = super.prepareRenderer(renderer, row, col);
Color alternateColor = Color.GRAY;
Color mainColor = Color.DARK_GRAY;
if (!returnComp.getBackground().equals(getSelectionBackground())) {
Color background = (row % 2 == 0 ? alternateColor : mainColor );
returnComp.setBackground(background);
background = null;
}
return returnComp;
}
}

Just make each of the colored bars themselves panels with a different background color. Don't forget to make the panels explicitly opaque with setOpaque(true) - panels are transparent by default transparent in most look and feels.
A note on aesthetics; I would start with the first line in each group shaded differently.

Related

Add border BETWEEN cells in JTable

I'm trying to display a JTable as a grid, with lines between the cells. I've only been able to add borders within individual cells, though, which never looks correct; if I add full borders, I get a bunch of disconnected boxes, which looks ugly and wrong. Using MatteBorders (as the below code) looks a little better, but results in gaps where border lines don't quite meet.
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component stamp = super.prepareRenderer(renderer, row, column);
int top = 1;
int left = 1;
int bottom = row == 7 ? 1 : 0; //Grid is always 8x8, this ensures the bottom/right will have full borders.
int right = column == 7 ? 1 : 0;
MatteBorder border = new MatteBorder(top, left, bottom, right, Color.BLACK);
if (stamp instanceof JComponent) {
((JComponent) stamp).setBorder(border);
}
return stamp;
}
I feel like there must be some way to do this properly, so that I just get grid lines between cell elements. What am I missing? If nothing else, is there a way to get MatteBorder to stretch across the gaps, or to push a normal border out slightly further so that the borders of adjacent cells overlap?
EDIT: Got it working with setShowGrid(true) and setGridColor(Color.BLACK).
Use JTable.setShowGrid(true) to show default border or use setShowHorizontalLines(boolean showHorizontalLines) or setShowVerticalLines(boolean showVerticalLines) to show only horizontal or vertical lines

JPanel detached border selection

I have a List of JPanel and each element of a list have 10 JPanel elements inside it which contains a picture. (as the Picture)
I set Float layout for aligning them horizontally one after another. (Each row JPanel elements)
I put each element of this list on another outer JPanel vertically and everything is ok. (Each Vertical JPanel)
now I want to put the above label F1 till F10 exactly at the center of the first now elements ? how am going to do that ? any recommendation ?
Take note I can't use TitledBorder (with title and no border) for the first row elements because I have a selection function for each element and If I do this, It select the whole first row element (element + titledborder) which is pretty ugly and not similar to the other rows ?
do you hae any solution ?
Make the top row a JPanel having the default layout, FlowLayout. Add ten instances of a custom JLabel in which you override getPreferredSize() to return the nominal picture width and a height no less than that returned by the parent's implementation.
private static final int W = 50;
private static class MyLabel extends JLabel {
public MyLabel(String text) {
super(text);
this.setHorizontalAlignment(CENTER);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(W, super.getPreferredSize().height);
}
}

Change default row colors in jtable

I'm developing a simple java application using swing. I use JTable element.
The problem is that by default rows of tables are white and grey like in this post Setting color in a row of a Jtable .
I want to make them the same color, for example all rows white.
You can override the prepareRenderer method of JTable like this
JTable table = new JTable(...)
{
public Component prepareRenderer(
TableCellRenderer renderer, int row, int column)
{
Component c = super.prepareRenderer(renderer, row, column);
c.setBackground(Color.WHITE);
return c;
}
};
Or you could create your own TableCellRenderer which does the same thing (picking the background color to render) but on a Cell level and use that renderer for each of your columns.

Dynamically Increase JTable row height when editing, and decrease when finish edit

I am writing a small POS application, which shows a JTable with ticket information inside its cells. CellRenderer is a class which extends JPanel and implements TableCellRenderer, and contains a few JTextFields showing basic information (quantity, descripcion, price).
Also, I have another class extending JPanel and implementing TableCellEditor, which is used as CellEditor. This class contains more JTextFields and also a few jButtons.
What I need is simple: when I edit any cell by clicking with the mouse (or touching the screen, which is, as far as I know, the same event), dynamically increase the height of the cell I'm going to edit, so it can show all the components inside the editor. And when I finish editing, return cell height to its previous value.
Any idea about doing it?
Thanks in advance. :-)
CellRenderer is a class which extends JPanel and implements TableCellRenderer, and contains a few JTextFields showing basic information (quantity, descripcion, price). Also, I have another class extending JPanel and implementing TableCellEditor, which is used as CellEditor. This class contains more JTextFields and also a few jButtons.
better could be to create popup window (JDialog) based on event from JPopupMenu,
Dynamically Increase JTable row height when editing, and decrease when finish edit
don't confused users and wrong concept could be caused by jumping JTables row on the screen
What I need is simple: when I edit any cell by clicking with the mouse (or touching the screen, which is, as far as I know, the same event), dynamically increase the height of the cell I'm going to edit, so it can show all the components inside the editor. And when I finish editing, return cell height to its previous value.
don't do that, but have to override, is possible by
DefaultCellEditor#setClickCountToStart(int) for TableCellEditor
start, stop and cancelEdit for CellEditor
have to notify or re_Layout JTable, the same on stop and cancelEdit
Not an answer to how-to-adjust-rowHeights, but for an alternative mentioned in my comment: "oversize" the editorComponent only instead of updating the complete rowHeight (which I think would be too irritating to users, but up to you to decide, of course :)
// fake a bigger editing component
JTextField oversized = new JTextField() {
#Override
public Dimension getPreferredSize() {
Dimension dim = super.getPreferredSize();
dim.height *= 5;
return dim;
}
};
TableCellEditor editor = new DefaultCellEditor(oversized);
JTable table = new JTable(new AncientSwingTeam()) {
#Override
public boolean editCellAt(int row, int column, EventObject e) {
boolean result = super.editCellAt(row, column, e);
if (result) {
// adjust cell bounds of the editing component
Rectangle bounds = getEditorComponent().getBounds();
bounds.height = getEditorComponent().getPreferredSize().height;
getEditorComponent().setBounds(bounds);
}
return result;
}
#Override
public void removeEditor() {
int editingColumn = getEditingColumn();
super.removeEditor();
if (editingColumn >= 0) {
// cleanup
repaint();
}
}
};
table.getColumnModel().getColumn(0).setCellEditor(editor);
Didn't try it, but I would say implementing MouseListener's mouseClicked() method is the way to go. Keep track of whether the cells height was already increased, and change the height accordingly.
Since MouseListener is an interface, CellRenderer could implement this interface too, keeping all cell-behavior in one class.

Java GridLayout is laying out all my JPanels in the top left corner

SOLVED:
Just found out what the problem was, after trying to make an SSCCE.
It had to do with my cell class, I didn't realise I was overriding getX() and getY() from the JComponent class.
After renaming these accessors it all works as expected
========================================
I have a JPanel with a GridLayout set at 3 rows x 3 cols.
I'm trying to add JPanels to each cell in the gridlayout to fill up all 9 cells.
Each one of these JPanels has an overriden paintChildren method which will paint some kind of rectangle starting at the top left of the JPanel - the end result will be each cell has a rectangle in it starting at the top left of the cell.
After adding all the JPanels to the gridlayout, they all appear in the top left corner overlapping each other (I have confirmed they are overlapping), instead of being laid out in a 3x3 grid.
How can I get them arranged in the 3x3 grid?
(Simplified) Code:
public class Panel extends JPanel {
public Panel(int x, int y) {
layout = new GridLayout(x, y, 2, 2);
setLayout(layout);
populateGrid();
}
public void populateGrid() {
removeAll();
for (int i = 0; i < 9; i++)
add(new Cell(50,50));
}
}
public class Cell extends JPanel {
public Cell(int x, int y) {
// x/y values used to define rectangle
setBorder(BorderFactory.createLineBorder(new Color(0,0,0)));
setBackground(Color.WHITE);
}
public void paintChildren(Graphics g) {
g.setColor(Color.BLUE);
g.fillRect(0, 0, x, y);
}
}
Make sure you import the right Panel. (And not the java.awt.Panel class.) Or, better, rename your class to GridPanel or something similar to avoid confusion / clashes.
You probably don't want to override paintChildren. Overriding paintComponent sounds like a better option in this case.
You may want to set minimum / preferred / maximum size for the Cell class.
Hard to make more observations without the actual code that instantiates and uses your Panel class.

Categories