I have a JPanel (yellow) placed in JScrollPane.
When I enter some text in JTextPane, it resizes, but the vertical scrollbar is still not active. yelowPanel.getSize() returns the same value it was before.`(You can see it on redPanel).
So how can I refresh yellowPanel? I want to scroll panel vertically.
I tried to:
panelCreating.revalidate();
panelCreating.invalidate();
panelCreating.repaint();
Works only panelCreating.setPreferredSize(new Dimension(333, 777)); but I don't know what size to set. It depends on content.
There is a small example:
package swingtest;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
public class SwingTest extends JFrame {
public SwingTest() {
initComponents();
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new SwingTest().setVisible(true);
}
});
}
private JPanel panelCenter, panelCreating;
private JScrollPane scrollPaneCreating, scrollPaneCenter;
private JTextPane textPane1, textPane2;
private JButton button1;
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setMinimumSize(new Dimension(300, 300));
panelCreating = new JPanel();
panelCreating.setMinimumSize(new Dimension(160, 200));
panelCreating.setPreferredSize(new Dimension(160, 200));
scrollPaneCreating = new JScrollPane(panelCreating,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
textPane1 = new JTextPane();
textPane1.setText("a\na");
textPane2 = new JTextPane();
textPane2.setText("b\nb");
button1 = new JButton("+++");
panelCenter = new JPanel();
panelCenter.setBackground(Color.blue);
scrollPaneCenter = new JScrollPane(panelCenter);
// ----------------- Left Panel Init -----------------------
panelCreating.setLayout(new GridBagLayout());
panelCreating.setBackground(Color.ORANGE);
panelCreating.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(0, 0, 4, 4);
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.weightx = c.weighty = 0;
c.gridx = 0;
c.gridy = GridBagConstraints.RELATIVE;
c.gridwidth = GridBagConstraints.REMAINDER;
c.gridheight = 1;
c.fill = GridBagConstraints.BOTH;
panelCreating.add(textPane1, c);
button1.addActionListener(new ActionListener() {
int height = 50;
#Override
public void actionPerformed(ActionEvent e) {
textPane1.setText(textPane1.getText() + "\na");
textPane1.setPreferredSize(new Dimension(150, height));
textPane2.setText(textPane2.getText() + "\nb");
textPane2.setPreferredSize(new Dimension(150, height));
height += 30;
panelCreating.revalidate();
panelCreating.repaint();
scrollPaneCreating.revalidate();
}
});
panelCreating.add(button1, c);
panelCreating.add(textPane2, c);
// -------------------------------------------------------
getContentPane().setLayout(new GridBagLayout());
c = new GridBagConstraints();
c.ipadx = c.ipady = 0;
c.insets = new Insets(0, 0, 0, 0);
c.weighty = 0;
c.gridheight = 1;
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 1;
c.weightx = 0;
c.fill = GridBagConstraints.BOTH;
getContentPane().add(scrollPaneCreating, c);
c.gridx = 1;
c.gridy = 1;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1;
c.weighty = 1;
getContentPane().add(scrollPaneCenter, c);
}
}
Yellow panel also uses GridBagLayout.
Sorry for my English
Instead of setting a preferred size on panelCreating, set it on scrollPaneCreating. And don't set a preferred size on the text components, they will grow as you add new lines of text to them. The idea is to have the panel inside the scroll pane grow as large as it needs to, and just restrict the size of the scroll pane itself.
// [...]
panelCreating = new JPanel();
//panelCreating.setMinimumSize(new Dimension(160, 200));
//panelCreating.setPreferredSize(new Dimension(160, 200));
scrollPaneCreating = new JScrollPane(panelCreating,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPaneCreating.setMinimumSize(new Dimension(160, 200));
scrollPaneCreating.setPreferredSize(new Dimension(160, 200));
// [...]
#Override
public void actionPerformed(ActionEvent e) {
textPane1.setText(textPane1.getText() + "\na");
//textPane1.setPreferredSize(new Dimension(150, height));
textPane2.setText(textPane2.getText() + "\nb");
//textPane2.setPreferredSize(new Dimension(150, height));
//height += 30;
// This isn't necessary either
//panelCreating.revalidate();
//panelCreating.repaint();
//scrollPaneCreating.revalidate();
}
Edited to add: another alternative is to set sizes on the JViewport that is attached to the scroll pane. The viewport is where the content is displayed. You can sort of think of the scroll pane as being composed of the viewport plus scrollbars. If the scroll pane is set to a fixed size, then the viewport size is determined by subtracting the scroll bar size. But if the viewport is set to a fixed size, then the scroll pane size is determined by adding the scroll bar size to the viewport size. Setting a fixed size on the viewport is preferable if you want to precisely control how much content should be displayed on screen, because scroll bar sizes can vary by operating system.
scrollPaneCreating.getViewport().setMinimumSize(new Dimension(160, 200));
scrollPaneCreating.getViewport().setPreferredSize(new Dimension(160, 200));
The default layout of JPanel is FlowLayout. Try GridLayout instead. There's a related example here. For example,
panelCreating = new JPanel(new GridLayout());
scrollPaneCreating = new JScrollPane(panelCreating);
Addendum: Also consider nested layouts. The example below uses BoxLayout for the left panel.
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
/** #see https://stackoverflow.com/questions/9184476 */
public class SwingTest extends JFrame {
private static final int N = 8;
public SwingTest() {
initComponents();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new SwingTest().setVisible(true);
}
});
}
private JPanel panelCenter, panelCreating;
private JScrollPane scrollPaneCreating, scrollPaneCenter;
private void initComponents() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panelCreating = new JPanel();
scrollPaneCreating = new JScrollPane(panelCreating,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
panelCenter = new JPanel();
panelCenter.setBackground(Color.blue);
scrollPaneCenter = new JScrollPane(panelCenter);
// ----------------- Left Panel Init -----------------------
panelCreating.setLayout(new BoxLayout(panelCreating, BoxLayout.Y_AXIS));
panelCreating.setBackground(Color.orange);
panelCreating.setBorder(BorderFactory.createEmptyBorder(N, N, N, N));
panelCreating.add(createTextPane());
panelCreating.add(Box.createVerticalStrut(N));
panelCreating.add(createTextPane());
panelCreating.add(Box.createVerticalStrut(N));
panelCreating.add(createTextPane());
// -------------------------------------------------------
setLayout(new GridLayout(1, 0));
add(scrollPaneCreating);
add(scrollPaneCenter);
pack();
}
private JTextPane createTextPane() {
JTextPane pane = new JTextPane();
pane.setText(""
+ "Twas brillig and the slithy toves\n"
+ "Did gyre and gimble in the wabe;\n"
+ "All mimsy were the borogoves,\n"
+ "And the mome raths outgrabe.");
pane.setBorder(BorderFactory.createEmptyBorder(N, N, N, N));
return pane;
}
}
I fixed your problem adding 1 line.
panelCreating.setPreferredSize(new Dimension((int) panelCreating.getPreferredSize().getWidth(),
(int)(panelCreating.getPreferredSize().getHeight()+30)));
The line must be inserted after the following lines;
#Override
public void actionPerformed(ActionEvent e) {
textPane1.setText(textPane1.getText() + "\na");
textPane1.setPreferredSize(new Dimension(150, height));
textPane2.setText(textPane2.getText() + "\nb");
textPane2.setPreferredSize(new Dimension(150, height));
height += 30;
Explanation:
The grid bag layout do not set it's pane preferred size when you set the preferred size of the textPanes inside it, but the scrollPane only scrolls based on the preferred size of the pane in it. So you must set the new preferred size of the pane every time you change the size of the components in it, then the scrollPane will know exactly what he must do. That's what i did, a add a line that increased the preferred size of creatingPanel, wich is the one inside the scrollPanel
Related
I try to make a simple app in SWING: using BorderLayout layout on the JFrame, i put on SOUTH an executing button, on WEST a panel that contains a combobox and on EAST a panel that contains 2 JTextAreas. The problem is, both JTextArea are damn small. Any help and explanation will be welcomed.
This is the code for the panel with the 2 text areas
package cipher;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.Border;
class TextPanel extends JPanel {
private JTextArea inputArea, outputArea;
public TextPanel() {
initSize();
initTextArea();
initBorder();
initLayout();
packing();
}
private void packing() {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.weighty = 1;
add(inputArea,gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1;
gbc.weighty = 1;
add(outputArea,gbc);
}
private void initBorder() {
Border outer = BorderFactory.createEmptyBorder(5, 5, 5, 5);
Border inner = BorderFactory.createTitledBorder("Text");
setBorder(BorderFactory.createCompoundBorder(outer,inner));
}
private void initLayout() {
setLayout(new GridBagLayout());
}
private void initTextArea() {
inputArea = new JTextArea();
inputArea.setPreferredSize(new Dimension(385,400));
outputArea = new JTextArea();
outputArea.setPreferredSize(new Dimension(385,400));
}
private void initSize() {
Dimension size = getPreferredSize();
size.width = 390;
setPreferredSize(size);
}
}
I've tried using setSize(x,y) but without success. I've tried using JTextArea(rows,columns) but without success. I've used even setPreferredSize with a Dimension but no succeed.
The probable cause of your issue is the container area is smaller than the preferred size of the text area, GridBagLayout will then default to the minimum size instead.
This is a good example of why you should avoid setting these properties directly and instead make use of the layout manager and the components properties.
To start with, make use of the JTextArea's column and rows properties. This will make a better "guess" at the amount of space it needs to display text to fit within these confines.
Second, use GridBagConstraints#fill to override GridBagLayout and force it to make use of the available space
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TextPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TextPanel extends JPanel {
private JTextArea inputArea, outputArea;
public TextPanel() {
initTextArea();
initBorder();
initLayout();
packing();
}
private void packing() {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
add(inputArea, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
add(outputArea, gbc);
}
private void initBorder() {
Border outer = BorderFactory.createEmptyBorder(5, 5, 5, 5);
Border inner = BorderFactory.createTitledBorder("Text");
setBorder(BorderFactory.createCompoundBorder(outer, inner));
}
private void initLayout() {
setLayout(new GridBagLayout());
}
private void initTextArea() {
// The borders are just here so you can see the different text areas
inputArea = new JTextArea(10, 20);
inputArea.setBorder(new LineBorder(Color.BLACK));
outputArea = new JTextArea(10, 20);
outputArea.setBorder(new LineBorder(Color.BLACK));
}
}
}
I'd also change...
inputArea = new JTextArea(10, 20);
inputArea.setBorder(new LineBorder(Color.BLACK));
outputArea = new JTextArea(10, 20);
outputArea.setBorder(new LineBorder(Color.BLACK));
and make use of JScrollPanes instead of LineBorder
From my code I expect my JTextArea to fill the top left border seen below:
But as you can see its taking up a tiny section in the middle.
I am using GridBagConstraints on the panel which contains the components.
There is a main class which calles up a class called frame. This class creates the JFrame and sets the size as well as other things. This is then called from the MainFrame.java which has extended the jframe which creates 3 panels and sets their layout. this is seen below
import javax.swing.*;
import java.awt.*;
public class MainFrame extends JFrame
{
private Panel1 storyPanel;
private Panel2 statsPanel;
private Panel3 commandsPanel;
public MainFrame(String title)
{
super(title);
// Setting Layout
GridBagConstraints gbc = new GridBagConstraints();
storyPanel = new Panel1();
storyPanel.setLayout(new GridBagLayout());
statsPanel = new Panel2();
commandsPanel = new Panel3();
Container p = getContentPane();
p.add(storyPanel, BorderLayout.WEST);
p.add(statsPanel, BorderLayout.EAST);
p.add(commandsPanel, BorderLayout.SOUTH);
}
}
The panel in questions is Panel1 or storyPanel. I have set the layout and the code calls the Panel1.java as seen below:
import javax.swing.*;
import java.awt.*;
public class Panel1 extends JPanel
{
public Panel1()
{
GridBagConstraints gbc = new GridBagConstraints();
//Set size of Panel1
int xsizeP1 = (Frame.xsize() / 2);
int ysizeP1 = (Frame.ysize() / 3 * 2);
setPreferredSize(new Dimension(xsizeP1, ysizeP1));
setBorder(BorderFactory.createLineBorder(Color.black));
//Adding JTextArea and adding settings to it
JTextArea storyLine = new JTextArea(" test ");
storyLine.setLineWrap(true);
storyLine.setWrapStyleWord(true);
storyLine.setEditable(false);
//Adding JScrollPane to the JTextArea and making it have a vertical scrollbar
JScrollPane scroll = new JScrollPane(storyLine);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
//GridBagConstraints setup for components
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.fill = GridBagConstraints.VERTICAL;
add(scroll, gbc);
}
}
I don't understand why my gbc.fill isnt making the JTextArea fill the top left border of the screen shot.
Thanks in advance for any reply's
-Tom T
changing the layout to border layout
import javax.swing.*;
import java.awt.*;
public class Panel1 extends JPanel
{
public Panel1()
{
//GridBagConstraints gbc = new GridBagConstraints();
//gbc.weightx = 0.1;
//gbc.weighty = 0.1;
BorderLayout b = new BorderLayout();
//Set size of Panel1
int xsizeP1 = (Frame.xsize() / 2);
int ysizeP1 = (Frame.ysize() / 3 * 2);
setPreferredSize(new Dimension(xsizeP1, ysizeP1));
setBorder(BorderFactory.createLineBorder(Color.black));
//Adding JTextArea and adding settings to it
JTextArea storyLine = new JTextArea(" test ");
storyLine.setLineWrap(true);
storyLine.setWrapStyleWord(true);
storyLine.setEditable(false);
//Adding JScrollPane to the JTextArea and making it have a vertical scrollbar
JScrollPane scroll = new JScrollPane(storyLine);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
//gbc.gridx = 0;
//gbc.gridy = 0;
//gbc.weightx = 1;
//gbc.weighty = 1;
//gbc.fill = GridBagConstraints.BOTH;
add(scroll, b.CENTER);
}
}
Don't set the layout of storyPanel, as it's contents have already been added and laid out, so changing the layout manager here will discard any properties you applied. Instead, set the layout in Panel1's constructor before you add any components.
Use GridBagConstraints.BOTH for the fill property. The fill property can only have one specified value
Use weightx and weighty to specify how much of the available space the component should use
For example...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MainFrame extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new MainFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private Panel1 storyPanel;
// private Panel2 statsPanel;
// private Panel3 commandsPanel;
public MainFrame(String title) {
super(title);
storyPanel = new Panel1();
Container p = getContentPane();
p.add(storyPanel, BorderLayout.WEST);
p.add(new JLabel("East"), BorderLayout.EAST);
p.add(new JLabel("South"), BorderLayout.SOUTH);
}
public class Panel1 extends JPanel {
public Panel1() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
//Set size of Panel1
setBorder(BorderFactory.createLineBorder(Color.black));
//Adding JTextArea and adding settings to it
JTextArea storyLine = new JTextArea(20, 20);
storyLine.setLineWrap(true);
storyLine.setWrapStyleWord(true);
storyLine.setEditable(false);
//Adding JScrollPane to the JTextArea and making it have a vertical scrollbar
JScrollPane scroll = new JScrollPane(storyLine);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
//GridBagConstraints setup for components
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1;
gbc.weighty = 1;
add(scroll, gbc);
}
}
}
Having said all that, a BorderLayout would be simpler
public class Panel1 extends JPanel {
public Panel1() {
setLayout(new BorderLayout());
//Set size of Panel1
setBorder(BorderFactory.createLineBorder(Color.black));
//Adding JTextArea and adding settings to it
JTextArea storyLine = new JTextArea(20, 20);
storyLine.setLineWrap(true);
storyLine.setWrapStyleWord(true);
storyLine.setEditable(false);
//Adding JScrollPane to the JTextArea and making it have a vertical scrollbar
JScrollPane scroll = new JScrollPane(storyLine);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
add(scroll);
}
}
i tried a border layout and set it to center expecting it to resize but that failed as well
Would suggest that you're making a fundamental mistake some where, as it works fine for me. Remember, set the layout BEFORE you add any components to the container
First, hier is the Code:
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JComponent;
import javax.swing.JButton;
import javax.swing.JToolBar;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableColumn;
#SuppressWarnings("serial")
public class Spielklasse extends JPanel{
private int iEntries = 1;
public Spielklasse(String strTitle){
setLayout(new GridBagLayout());
//dummy to fill vertical space
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1000;
c.fill = GridBagConstraints.BOTH;
c.weightx=1;
c.weighty=1;
c.gridwidth = 2;
add(new JLabel(" "),c);
}
public void addEntry(JComponent component){
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.NORTHWEST;
c.gridx = 1;
c.gridy = iEntries;
c.weightx = 1;
c.insets = new Insets(10, 20, 10, 20);
c.fill = GridBagConstraints.HORIZONTAL;
add(component, c);
iEntries++;
}
public static JPanel addExampleTablePanel() {
String[] columnNames = { "first", "second", "third", "fourth", "fifth", "sixth" };
String[][] strArr = new String[100][columnNames.length];
for (int i = 0; i < strArr.length; i++) {
for (int j = 0; j < strArr[0].length; j++) {
strArr[i][j] = i + " xxxxx " + j;
}
}
JTable table = new JTable(strArr, columnNames) {
#Override
public Dimension getPreferredScrollableViewportSize() {
int headerHeight = getTableHeader().getPreferredSize().height;
int height = headerHeight + (10 * getRowHeight());
int width = getPreferredSize().width;
return new Dimension(width, height);
}
};
JScrollPane scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumn column = null;
for (int i = 0; i < columnNames.length; i++) {
column = table.getColumnModel().getColumn(i);
column.setPreferredWidth(50);
column.setMaxWidth(50);
column.setMinWidth(50);
}
JToolBar toolBar = new JToolBar();
JButton btn = new JButton("test123");
toolBar.add(btn);
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridy = 0;
c.weightx = 1;
c.weighty = 1;
c.gridwidth = 1;
c.anchor = GridBagConstraints.LINE_START;
panel.add(toolBar, c);
c.gridy = 1;
panel.add(scrollPane, c);
return panel;
}
public static void main(String[] args) {
Spielklasse mainPanel = new Spielklasse("test");
mainPanel.addEntry(addExampleTablePanel());
mainPanel.addEntry(addExampleTablePanel());
mainPanel.addEntry(addExampleTablePanel());
JFrame frame = new JFrame();
frame.setSize(300, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new JScrollPane(mainPanel));
frame.setVisible(true);
}
}
The class "Spieklasse" should create a JPanel with multiple entries of different types like tables, textboxes etc.
In this example here, just 3 JTable-containing panels should be added.
This JTable is inside a JSrollPane and should have fixed column widths.
This JScrollPane is inside a JPanel, wich contains a Toolbar above the Table to perform some actions etc.
This JPanel is added to the main panel of the type "Spielklasse".
The main panel is inside another JScrolLPane.
Here are the problem:
- The Table-Panel should have a fixed height wich i can set like i want. In the code example, the size is already fixed, but i dont know why and its the wrong size too :-)
- At the table a horizontal scrollbar should appear, when the size of the frame is smaller than the size of the table (all columns together). When the frame is bigger, everying should be stretched horizontal (works already)
I hope my explanation is good enough and someone can help me :-)
edit: updated with improvement of camickr, vertical size problem solved.
the size is already fixed, but i dont know why and its the wrong size too :-)
The size of the scroll pane is determined from the getPreferredScrollableViewportSize() method of JTable.
When the table is created the following is hardcoded in the JTable:
setPreferredScrollableViewportSize(new Dimension(450, 400));
So if you want to control the default width/height of the scroll pane you need to override the getPreferredScrollableViewportSize() method to return a reasonable value. The height should include the column header as well as the number of rows in the table you wish to display.
Maybe something like:
#Override
public Dimension getPreferredScrollableViewportSize()
{
int headerHeight = table.getTableHeader().getPreferredSize().height;
int height = headerHeight + (10 * getRowHeight());
int width = getPreferredSize().width;
return new Dimension(width, height);
}
Edit:
To use the ScrollablePanel you can change your code to:
//public class Table8 extends JPanel{
public class Table8 extends ScrollablePanel{
private int iEntries = 1;
public Table8(String strTitle){
setLayout(new GridBagLayout());
setScrollableWidth( ScrollablePanel.ScrollableSizeHint.FIT );
Another problem is the GridBagLayout. If there is not enough space to display the component at its preferred size, then the component snaps to is minimum size. This causes problems with the scroll pane so you will also need to add:
scrollPane.setMinimumSize( scrollPane.getPreferredSize() );
Or it may be easier to use another layout manager. Maybe a vertical BoxLayout.
Here is what I have:
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.LineBorder;
public class Main {
// Field members
static JPanel panel = new JPanel();
static Integer indexer = 1;
static List<JLabel> listOfLabels = new ArrayList<JLabel>();
static List<JTextField> listOfTextFields = new ArrayList<JTextField>();
static JScrollPane scrollPane;
public static void main(String[] args) {
// Construct frame
JFrame frame = new JFrame();
frame.setLayout(new GridBagLayout());
//frame.setPreferredSize(new Dimension(990, 990));
frame.setTitle("My Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Frame constraints
//GridBagConstraints frameConstraints = new GridBagConstraints();
// Construct button
JButton addButton = new JButton("Add");
addButton.addActionListener(new ButtonListener());
// Add button to frame
//frameConstraints.gridx = 0;
//frameConstraints.gridy = 0;
//frame.add(addButton, frameConstraints);
frame.add(addButton);
// Construct panel
panel.setPreferredSize(new Dimension(1000, 1000));
panel.setLayout(new GridBagLayout());
panel.setBorder(LineBorder.createBlackLineBorder());
scrollPane = new JScrollPane(panel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setPreferredSize(new Dimension(600, 600));
// Add panel to frame
//frameConstraints.gridx = 0;
//frameConstraints.gridy = 1;
//frameConstraints.weighty = 1;
//frame.add(panel, frameConstraints);
frame.add(scrollPane);
// Pack frame
frame.pack();
// Make frame visible
frame.setVisible(true);
}
static class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
// Clear panel
panel.removeAll();
// Create label and text field
//JTextField jTextField = new JTextField();
//jTextField.setSize(100, 200);
//listOfTextFields.add(jTextField);
listOfLabels.add(new JLabel("" + indexer));
// Create constraints
//GridBagConstraints textFieldConstraints = new GridBagConstraints();
GridBagConstraints labelConstraints = new GridBagConstraints();
// Add labels and text fields
for (int i = 0; i < indexer; i++) {
// Text field constraints
//textFieldConstraints.gridx = 1;
//textFieldConstraints.fill = GridBagConstraints.HORIZONTAL;
//textFieldConstraints.weightx = 0.5;
//textFieldConstraints.insets = new Insets(10, 10, 10, 10);
//textFieldConstraints.gridy = i;
// Label constraints
labelConstraints.gridx = 0;
labelConstraints.gridy = i;
labelConstraints.insets = new Insets(0, 0, 0, 0);
// Add them to panel
panel.add(listOfLabels.get(i), labelConstraints);
//panel.add(listOfTextFields.get(i), textFieldConstraints);
}
// Align components top-to-bottom
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = indexer;
c.weighty = 1;
c.ipady = 0;
panel.add(new JLabel(), c);
System.out.println("indexer is " + indexer);
// Increment indexer
indexer++;
panel.updateUI();
if(indexer ==2){
listOfLabels.set(0, new JLabel("Test"));
}
}
private int getWidth() {
// TODO Auto-generated method stub
return 0;
}
}
}
Here is the output:
What Am I doing wrong? I want the labels to be justified all the way to the left. I don't have any padding set to the left so I am confused.
FYI, I found this code on stackoverflow and my goal is to have labels that I can dynamically add and update, hence I commented out the textboxes.
Don't call setPreferredSize on the scroll pane, this isn't what you should setting, use GridBagConstraints weightx/y and fill properties.
Don't call updateUI, it doesn't do what you think it does, call revalidate instead, if you have to
The main reasons you're having problems is
You're call setPreferredSize on the panel. When adding components to a GridBagLayout, it will attempt to lay out components around the centre of the container
You've not specified a weightx or anchor property for the GridBagConstraints when adding the labels
I have cretaed textfields and labels on clicking 'add' button. I have given x and y coordinates, but textbox appearing is in improper manner.
how to correct it? and also how to increase width of textbox ???
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;
public class SS
{
// Field members
static JPanel panel = new JPanel();
static Integer indexer = 1;
static List<JLabel> listOfLabels = new ArrayList<JLabel>();
static List<JTextField> listOfTextFields = new ArrayList<JTextField>();
public static void main(String[] args)
{
// Construct frame
JFrame frame = new JFrame();
frame.setLayout(new GridBagLayout());
frame.setPreferredSize(new Dimension(800, 800));
frame.setTitle("My Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Frame constraints
GridBagConstraints frameConstraints = new GridBagConstraints();
// Construct button
JButton addButton = new JButton("Add");
addButton.addActionListener(new ButtonListener());
// Add button to frame
frameConstraints.gridx = 0;
frameConstraints.gridy = 0;
frame.add(addButton, frameConstraints);
// Construct panel
panel.setPreferredSize(new Dimension(400, 400));
panel.setLayout(new GridBagLayout());
panel.setBorder(LineBorder.createBlackLineBorder());
// Add panel to frame
frameConstraints.gridx = 0;
frameConstraints.gridy = 1;
frameConstraints.weighty = 20;
frame.add(panel, frameConstraints);
// Pack frame
frame.pack();
// Make frame visible
frame.setVisible(true);
}
static class ButtonListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent arg0)
{
// Clear panel
panel.removeAll();
// Create label and text field
listOfTextFields.add(new JTextField());
listOfLabels.add(new JLabel("Name " + indexer));
// Create constraints
GridBagConstraints textFieldConstraints = new GridBagConstraints();
GridBagConstraints labelConstraints = new GridBagConstraints();
// Add labels and text fields
for(int i = 0; i < indexer; i++)
{
// Text field constraints
textFieldConstraints.gridx = 20;
textFieldConstraints.gridy = i;
// Label constraints
labelConstraints.gridx = 1;
labelConstraints.gridy = i;
// Add them to panel
panel.add(listOfTextFields.get(i), textFieldConstraints);
panel.add(listOfLabels.get(i), labelConstraints);
}
// Align components top-to-bottom
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = indexer;
c.weighty = 1;
panel.add(new JLabel(), c);
// Increment indexer
indexer++;
}
}
}
To get the frame to refresh with the text box you need to call pack at the bottom of your actionPerformed method.
frame.pack();
For this you need to have frame as a class variable.
static JFrame frame;
For the size the grid bag layout will override your setSize so you can give it a weight and make it stretch to fill in the space. This can go just after your other textFieldContraints calls.
textFieldConstraints.weightx = 1;
textFieldConstraints.fill = GridBagConstraints.HORIZONTAL;
This should make the text boxes appear when you hit the button and take up the box.
Increase width of textfield.
listOfTextFields.add(new JTextField(null,10));