I am trying to make a JTable that has a width of 500. The problem is that the JScrollPane associated with the table doesn't appear next to the table.
Here is the relevant code:
// Create authorsPanel
JPanel authorsPanel = new JPanel(new BorderLayout(5,5));
authorsPanel.setBorder( new TitledBorder("Author Selection") );
// Configure author table
DefaultTableModel authorstableModel = new DefaultTableModel(new String[80][1], new String[]{"Authors"}) {
#Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
};
JTable authorsTable = new JTable(authorstableModel);
authorsTable.getColumnModel().getColumn(0).setPreferredWidth(500);
authorsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
try {
authorsTable.setAutoCreateRowSorter(true);
} catch(Exception continuewithNoSort) {
}
JScrollPane tableScroll = new JScrollPane(authorsTable);
Dimension tablePreferred = tableScroll.getPreferredSize();
tableScroll.setPreferredSize(new Dimension(500, tablePreferred.height/3));
authorsPanel.add(tableScroll);
Here is a screenshot:
When I get rid of the line:
authorsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
Then the table returns to being the full width of the panel, so it seems like I need this line.
The java docs on BorderLayout states :
The components are laid out according to their preferred sizes and the
constraints of the container's size. The NORTH and SOUTH components
may be stretched horizontally; the EAST and WEST components may be
stretched vertically; the CENTER component may stretch both
horizontally and vertically to fill any space left over.
You have used authorsPanel.add(tableScroll) to add the JScrollPane to the JPanel. So you are basically adding it to the center. So this is going to occupy the whole space that is lying vacant.
The solution to your problem lies in choosing a different layout. I could suggest MigLayout which is very versatile and you can get all kinds of effects using it.
You add your scroll pane to a panel with BorderLayout. BorderLayout does not care about preferred size. Use e.g GridBagLayout with proper constraints or you can BoxLayout (with horizontal flow) placing the table first and an empty panel second as place holder.
Related
I have a tablePanel which is a JScrollPane,and initialized with a JTable, the JTable initialized with a defaultTableModel.When I trying to add some rows to the table, but didn't see the scroll bar, appriciated for any reply.
JFrame jFrame = new JFrame();
//rows will be added dynamically.
DefaultTableModel defautTableModel = new DefaultTableModel(null,columnNames){
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
JTable jTable = new JTable(defautTableModel);
jTable.setLocation(20,60);
jTable.setSize(950,450);
jTable.setRowHeight(25);
jTable.getColumn("No.").setMaxWidth(45);
jTable.getColumn("position").setMaxWidth(45);
...
JTableHeader jTableHeader = jTable.getTableHeader();
jTableHeader.setLocation(20,30);
jTableHeader.setSize(950,30);
jTableHeader.setFont(new Font(null, Font.BOLD, 16));
jTableHeader.setResizingAllowed(true);
jTableHeader.setReorderingAllowed(true);
JScrollPane tablePanel = new JScrollPane(jTable);
tablePanel.setLayout(null);
tablePanel.add(jTableHeader);
tablePanel.add(jTable);
jFrame.setContentPane(tablePanel);
tablePanel.setLayout(null); is the primary cause of your problem. A JScrollPane has its own layout manager which is used to manage the scrollbars, view port and headers.
tablePanel.add is your next problem, as you shouldn't be adding components to the JScrollPane. Instead, you should be setting the JScrollPane's JViewPort.
But, since you're using JScrollPane tablePanel = new JScrollPane(jTable);, there's actually no need for the three lines which follow it.
I would highly recommend that you take a closer look at:
How to us tables
How to use scroll panes
Laying Out Components Within a Container
Now, before you tell me how nothing I've suggested actually works, go and re-read Laying Out Components Within a Container - this is the corner stone concept you will need to understand and master before Swing really begins to work for you
JScrollPane tablePanel = new JScrollPane(jTable);
// No need for the below code
/*tablePanel.setLayout(null);
tablePanel.add(jTableHeader);
tablePanel.add(jTable);*/
jFrame.setContentPane(tablePanel);
I have a JScrollPane with a number of JLabel objects in a panel using a GridBagLayout. Each of the labels is displaying HTML text with rich elements which varies at run time.
I would like all labels to have the same width (driven by the width of the scroll pane) but vary in height depending on their content with the text wrapping (as is handled automatically by JLabel). If the labels exceed the scroll pane's height then a vertical scroll bar should appear.
Here is some sample code to demonstrate the problem:
public class ScrollLabels extends JFrame {
private final JPanel labelPanel = new JPanel(new GridBagLayout());
private final GridBagConstraints c = new GridBagConstraints();
public ScrollLabels() throws HeadlessException {
super("Scroll Labels");
}
public void createUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scroller = new JScrollPane(labelPanel);
add(scroller);
c.gridx = 0;
c.gridy = GridBagConstraints.RELATIVE;
c.fill = GridBagConstraints.HORIZONTAL;
addLabel("Here is <em>Rich Text</em>");
addLabel("Here is <ul><li>A</li><li>List</li></ul>");
addLabel("Here is <table><tr><th>A</th><th>Table></th></tr></table");
addLabel("Here is more <em>Rich Text</em>");
addLabel("Here is even more <b>Rich Text</b>");
addLabel("Here is a long sentence that should wrap when the panel "
+ "is too small for the text.");
pack();
}
private void addLabel(String text) {
JLabel label = new JLabel("<html>" + text + "</html>");
label.setBorder(BorderFactory.createEtchedBorder());
labelPanel.add(label, c);
}
public static void main(String[] args) {
ScrollLabels frame = new ScrollLabels();
frame.createUI();
frame.setVisible(true);
}
}
It correctly resizes the labels horizontally and shows scroll bars where appropriate. What it doesn't do is resize labels vertically to fit them within the scroll pane.
Here are the various things I have tried:
Changing the GridBagConstraint values. There are good controls for how to expand and contract components but I can't see any way to set a min or max width.
Setting the JScrollPane scroll bar policy to never show horizontal scroll bars. This just cuts off the label text rather than wrapping the text.
Manually setting the label size - i.e. setting the width from the scroll pane and the height depending on the text. I can't see an easy way to get the correct height of rich HTML text given a fixed width. In any case I'd prefer to have a layout manager that can do the job rather than manually coding preferred sizes.
The one thing I haven't tried yet is creating a custom layout manager. I suspect this might be the right answer but would like to see if any of you have an easier solution that I'm not seeing.
I would like all labels to have the same width (driven by the width of the scroll pane) but vary in height depending on their content
You need to implement the Scrollable interface on your panel and override the getScrollableTracksViewportWidth() method to return true. You will also need to provide default implementations for the other methods of the interface.
Or you can use the Scrollable Panel which provides method that allow you to set the scrolling properties.
I tried a lot of layout managers but none could solve my problem:
I want the items in a scrollPane to keep their size (preferred or minimum) and not being resized (reduced) to fit the viewport Panel. Since if it is a JTextArea, and if the text area has blank space and it is bigger then the viewport, it would reduce it so the blank text area won't be shown. I want the blank text area to be shown for appearance issues.
Im stacking one item after another using BoxLayout, and it seems to me that for text areas the setMinimum method fails.
If the text area has blank space, then the scrollbar of the ScrollPane won't appear, instead it only appears it there are no blank space left.
Any solution?
JScrollPane materialPane = new FScrollPane();
this.materialPaneView = new TPanel();
this.materialPaneView.setMinimumSize(new Dimension((int)(WIDTH*0.95), (int)(HEIGHT/2)));
this.materialPaneView.setLayout(new BoxLayout(this.materialPaneView, BoxLayout.Y_AXIS));
materialPane.setViewportView(materialPaneView);
materialPane.setMinimumSize(new Dimension((int)(WIDTH*0.95), (int)(HEIGHT/2)));
for(Material mat: this.unit.getMaterial()){
this.addMaterial(mat);
}
centerPanel.add(sectionPane);
centerPanel.add(exercisePane);
centerPanel.add(materialPane);
this.add(upperPanel, BorderLayout.NORTH);
this.add(centerPanel, BorderLayout.CENTER);
public void addMaterial(Material mat){
JTextField matName = new JTextField(30);
JPanel fieldButtonPanel = new TPanel();
fieldButtonPanel.setLayout(new GridLayout(1,2));
JPanel fieldPanel = new TPanel(new FlowLayout(FlowLayout.LEFT));
JPanel deleteMatButtonPanel = new TPanel(new FlowLayout(FlowLayout.RIGHT));
matName.setText(mat.getName());
matName.setMaximumSize(new Dimension(FFont.def.getSize()*20, 30));
fieldPanel.add(matName);
JButton deleteMat = new JButton("Delete Material");
deleteMatButtonPanel.add(deleteMat);
fieldButtonPanel.add(fieldPanel);
fieldButtonPanel.add(deleteMatButtonPanel);
fieldButtonPanel.setAlignmentX(LEFT_ALIGNMENT);
JTextArea matText = new FTextArea(mat.getDesc(), (int)(WIDTH*0.95), (int)(HEIGHT/3.4));
matText.setMinimumSize(new Dimension((int)(WIDTH*0.95), (int)(HEIGHT/3.5)));
/*matText.setMaximumSize(new Dimension((int)(WIDTH*0.95), (int)(HEIGHT/3.4)));*/
matText.setText(mat.getDesc());
matText.setAlignmentX(LEFT_ALIGNMENT);
this.materialPaneView.add(fieldButtonPanel);
this.materialPaneView.add(matText);
matName.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
mat.setName(matName.getText());
}
});
HEIGHT and WIDTH are constants, and TPanel FScrollPane are my predefined transparent panels. The BoxLayout panel is the viewport of a scrollPane, and still, it would resize the text areas.
I am not sure i get what you are asking for so please tell me if i totally missed the point...
As far as i know the Viewport size is controlled by the component inside the JScrollPane and the JScrollPane size wont change no matter what happens to the viewport.
You either want to:
A) Resize the JScrollPane to the same size as it's content.
I would implement listeners to look for the content size change and resize the ScrollPane accordingly but you need to pay attention to resize the whole Hierarchy too.
B) You want to resize the viewport so that it fits in the JScrollPane? Y'know without scrollbars.
I had this problem and fixed it by using a ScrollablePanel component. Check this answer, follow the link to download the .class and use it to use a JPanel that resizes to fit the ScrollPane.
Those arent very detailed answers but i will need more information about what you are trying to do before expanding on it. And your code isnt complete, always share a code that we can CTRL+C/V and readily verify the problem in our end.
JPanel grid = new JPanel();
GridLayout layout = new GridLayout (6,7,0,0);
grid.setLayout (layout);
slot = new ImageIcon ("");
for (int x = 0; x < 42; ++x)
{
slotbtn = new JButton(slot);
slotbtn.setContentAreaFilled (false);
//slotbtn.setBorderPainted (false);
slotbtn.setBorder (BorderFactory.createEmptyBorder (0,0,0,0));
slotbtn.setFocusPainted (false);
grid.add(slotbtn);
}
This is the output I get:
I am creating a 6x7 grid. The output I need is for there to be no space in between the rows and columns, everything should be compressed together. I tried pack and it didn't work. What am I doing wrong?
-- I tried FlowLayout but I had to resize the frame and I have other buttons on the frame so I don't think I'd prefer resizing it to make the buttons fit in their proper places.
-- I placed this JPanel inside another jpanel(which uses borderlayout and contains two other panels) and I placed it at the center, the two other panels North and South.
this issue because you divide the grid (the whole size of grid) to 7*6 so if you re-size the window you will see this gaps changed so if you wan't to remove this gab
calculate the size of the window (ex: width = 7* width of your image , hight = 6*hight of your mage)
or re-size your image
JButton employs a margin property to provide additional padding to the content area of the button, you could try using...
slotbtn.setMargin(new Insets(0, 0, 0, 0));
I would also try using something like slotbtn.setBorder(new LineBorder(Color.RED)); to determine if the spacing is from the button, icon or layout
GridLayout will also provide each cell with equal amount of space, based on the available space to the container, this means that the cell may increase beyond the size of the icon.
While a little more work, GridBagLayout would (if configured properly) honour the preferred size of each component.
Have a look at How to use GridBagLayout for more ideas.
I get no margins using your code, with any image I use. Check your image. And maybe post a runnable example replicating the problem. Maybe there's something going on you're not showing us. I'd start by checking the image for margins. Check it against this. If it still has margins, than its your image. Also, Don't set the size to anything! You may be stretching the panel unnecessarily, which will cause the gaps. Also if there an of your other panels are larger than the grip panel, it will also cause it to stretch. But take all your set(Xxx)sizes out and see what happens. Just pack()
import java.awt.GridLayout;
import javax.swing.*;
public class TestButtonGrid {
public TestButtonGrid() {
ImageIcon icon = new ImageIcon(getClass().getResource("/resources/stackoverflow3.png"));
JPanel panel = new JPanel(new GridLayout(6, 7));
for (int i = 0; i < 42; i++) {
JButton slotbtn = new JButton(icon);
slotbtn.setContentAreaFilled(false);
//slotbtn.setBorderPainted (false);
slotbtn.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
slotbtn.setFocusPainted(false);
panel.add(slotbtn);
}
JFrame frame = new JFrame();
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new TestButtonGrid();
}
}
I have a BoxLayout (in a panel of a BorderLayout) in which I've put a JTable and a button vertically. I would like the table to have a fixed width and that the height should resize itself up to filling the panel. At the moment, I'm fine with the displayed width but not that it's filling up the whole panel height. For example, if there are zero data in the table, I would like only the column names to be shown. I've tried things like setViewportView() and setPreferredSize(), but can't really make it work. Any suggestions? Is it in the layout or scrollpane?
String[] columnNames = { "Date", "Type"
};
Object[][] data = {
};
JTable myTable = new JTable(data, columnNames);
JButton okButton = new JButton("OK");
JPanel panWest = new JPanel();
panWest.setLayout(new BoxLayout(panWest, BoxLayout.PAGE_AXIS));
JScrollPane scrollPane = new JScrollPane(myTable);
panWest.add(scrollPane);
panWest.add(okButton);
EDIT
This is what ended up working:
Dimension dimension = new Dimension();
dimension.height = (myTable.getRowCount()*myTable.getRowHeight())+
myTable.getTableHeader().getPreferredSize().height;
dimension.width = myTable.getColumnModel().getTotalColumnWidth();
scrollPane.setMaximumSize(dimension);
I would like the table to have a fixed width and that the height
should resize itself up to filling the panel.
and
I have a BoxLayout (in a panel of a BorderLayout) in which I've put a
JTable and a button vertically.
there are three (mentioned only simple) ways
use built_in LayoutManager for JPanel - FlowLayout (FLowLayout.CENTER),
override FLowLayout.LEFT or RIGHT in the case that you want to aling,
JComponent laid by FlowLayout never will be resizable without programatically to change XxxSize and notified by revalidate & repaint,
set proper size for JScrollPane by override JTable.setPreferredScrollableViewportSize(new Dimension(int, int));,
JScrollPane accepts this Dimension as initial size, required is usage of JFrame.pack(), before JFrame.setVisible(true)
BoxLayout accepts min, max and preferred size, override all these three sizes for JScrollPane
(half solution, but most comfortable) change LayoutManager for JPanel to BorderLayout,
put JScrollPane with JTable to BorderLayout.EAST/WEST area,
then override JTable.setPreferredScrollableViewportSize(new Dimension(int, int));,
JScrollPane will occupy whole area for BorderLayout.EAST/WEST and will be resizeable only on heights coordinates
use MigLayout, here are a few posts about MigLayout and JScrollPane (with JTextArea, JTable)