i'm trying to make a window with GridBagLayout, here are my code:
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class ReadMessage extends JFrame implements ActionListener
{
JButton Last;
JButton Delete;
JButton Store;
JButton Next;
JTextArea MessageBox;
public ReadMessage()
{
setLayout(new FlowLayout());
JPanel Panel = new JPanel();
add(Panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
MessageBox = new JTextArea();
MessageBox.setEditable(false);
JScrollPane scrollPane = new JScrollPane(MessageBox, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
MessageBox.setLineWrap(true);
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 4;
c.weightx = 0.0;
c.ipady = 300;
c.ipadx = 300;
Panel.add(scrollPane, c);
Last = new JButton("Last");
c.gridx = 0;
c.gridy = 1;
c.ipady = 0;
c.weightx = 0.5;
Panel.add(Last, c);
Last.addActionListener(this);
Delete = new JButton("Delete");
c.gridx = 1;
c.gridy = 1;
c.ipady = 0;
c.weightx = 0.5;
Panel.add(Delete, c);
Delete.addActionListener(this);
Store = new JButton("Store");
c.gridx = 2;
c.gridy = 1;
c.ipady = 0;
c.weightx = 0.5;
Panel.add(Store, c);
Store.addActionListener(this);
Next = new JButton("Next");
c.gridx = 3;
c.gridy = 1;
c.ipady = 0;
c.weightx = 0.5;
Panel.add(Next, c);
Next.addActionListener(this);
}
}
and it turns out to be something like this
what i really want is like this
I know i did terribly wrong but i can't figure out what exactly i did wrong, I read the docs on oracle but couldn't find a thing, could you point out what i did wrong, and how to fix it? thank you very much
All your buttons have a gridwidth of 4 instead of 1.
You can nest panels each using a different layout manager to achieve your desired layout.
Create a main panel with a BorderLayout and add this panel to the frame
Add the JTextArea to the BorderLayout.CENTER of the main panel
Create a second panel for the buttons and use a FlowLayout. Then add the buttons to this panel. Then this panel can be added to the main panel at the BorderLayout.PAGE_END.
Related
I have created a simple Swing application which currently consists of a JToolBar, a JTree and a RSyntaxTextArea, all inside a GridBagLayout.
The JTree has currently only one top node and that has only one child node.
Complete UI with JToolBar, JTree and RSyntaxTextArea
When expanding the top node of the JTree, the whole GridBagLayout kind of "minimizes":
I've googled this phenominum, but since there's no error message or something else in the console, I'm kind of helpless right now.
I'm using the following code to create the UI:
RSyntaxTextArea textArea = new RSyntaxTextArea(50, 150);
textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);
textArea.setCodeFoldingEnabled(true);
RTextScrollPane sp = new RTextScrollPane(textArea);
cp.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
cp.add(createToolbar(), c);
c.gridx = 0;
c.gridy = 1;
c.ipadx = 90;
c.fill = GridBagConstraints.BOTH;
cp.add(createTree(), c);
c.gridx = 1;
c.gridy = 1;
c.fill = GridBagConstraints.HORIZONTAL;
cp.add(sp, c);
...
private JToolBar createToolbar() {
JToolBar tb = new JToolBar("Toolbar", JToolBar.HORIZONTAL);
JButton ob = new JButton(new ImageIcon("..."));
tb.add(ob);
tb.setFloatable(false);
tb.setRollover(true);
return tb;
}
...
private JTree createTree() {
DefaultMutableTreeNode top = new DefaultMutableTreeNode("Projects");
JTree tree = new JTree(top);
DefaultMutableTreeNode test = new DefaultMutableTreeNode("I'm a test!");
top.add(test);
return tree;
}
Update: A minimal code example to compile on your system for testing purposes:
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Tester extends JFrame {
public Tester () {
initializeComponent();
}
private void initializeComponent() {
JPanel cp = new JPanel(new BorderLayout());
JTextArea textArea = new JTextArea(50, 150);
JScrollPane sp = new JScrollPane(textArea);
cp.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
cp.add(createToolbar(), c);
c.gridx = 0;
c.gridy = 1;
c.ipadx = 90;
c.fill = GridBagConstraints.BOTH;
cp.add(createTree(), c);
c.gridx = 1;
c.gridy = 1;
c.fill = GridBagConstraints.HORIZONTAL;
cp.add(sp, c);
setContentPane(cp);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
}
private JTree createTree() {
DefaultMutableTreeNode top = new DefaultMutableTreeNode("Projects");
JTree tree = new JTree(top);
DefaultMutableTreeNode test = new DefaultMutableTreeNode("I'm a test!");
top.add(test);
return tree;
}
private JToolBar createToolbar() {
JToolBar tb = new JToolBar("Toolbar", JToolBar.HORIZONTAL);
JButton ob = new JButton("Button");
tb.add(ob);
tb.setFloatable(false);
tb.setRollover(true);
return tb;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Tester().setVisible(true);
}
});
}
}
When expanding the top node of the JTree, the whole GridBagLayout kind of "minimizes":
The GridBagLayout will shrink to the minimum size of a component when there is not enough space to display the entire component.
Swing application which currently consists of a JToolBar, a JTree and a RSyntaxTextArea, all inside a GridBagLayout.
I would just use the default BorderLayout of the frame:
add(toolbar, BorderLayout.PAGE_START);
add(treeScrollPane, BorderLayout.CENTER);
add(textAreaScrollPane, BorderLayout.PAGE_END);
Note how I added the JTree to a JScrollPane. Now scrollbars will appear for the tree when needed.
If you really want to use the GridBagLayout then read the section from the Swing tutorial on How to Use GridBagLayout for an explanation of how to use the various constraints. You may want to start with the "weightx/y" constraints which control which components get space as the frame size is changed. Also, look at the "fill" constraint.
I am having issues printing buttons to my java swing project. For class, I am suppose to replicate a GUI. Thus far, I have been able to do it just fine. But I am having an issue with the buttons overlapping each other in the same location as opposed to next to each other horizontally. Below is an image of how the buttons are being printed onto the the panel.
So I have two panels, one that houses the labels and text boxes (Toppane) and one that houses the buttons, 5 in total (bottomPane). I am trying to get the five buttons to print across the bottom of the GUI and am having a hard time. I feel like I am missing something simple.
--------------------------------------------------------------
| label [textfield] |
| label [textField] |
| label [textfield] |
|-------------------------------------------------------------
| [button] [button] [button] [button] [button] |
--------------------------------------------------------------
But i get this:
--------------------------------------------------------------
| label [textfield] |
| label [textField] |
| label [textfield] |
|-------------------------------------------------------------
| [ Button's 12345 ] |
--------------------------------------------------------------
Code:
package book;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
/**
*
* #author KJ4CC
*/
public class Book extends JFrame {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Book book = new Book();
book.bookingUI();
}
public static void bookingUI(){
//sets windows, and pane in the UI
JFrame frame = new JFrame("Ye old Book store");
JPanel toppane = new JPanel(new GridBagLayout());
JPanel bottomPane = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
frame.setSize(1000, 600);
frame.setVisible(true);
//adds labels to the window
JLabel num = new JLabel("Enter Number of Items in this Order");
JLabel bookID = new JLabel("111111");
JLabel quantityItem = new JLabel("222222");
JLabel itemInfo = new JLabel("333zfgfsfg333");
JLabel subtotal = new JLabel("4444444");
//adding the labels to the panel
c.anchor = GridBagConstraints.EAST;
c.weighty = 1;
c.gridx = 2;
c.gridy = 1;
toppane.add(num, c);
c.gridx = 2;
c.gridy = 2;
toppane.add(bookID, c);
c.gridx = 2;
c.gridy = 3;
toppane.add(quantityItem, c);
c.gridx = 2;
c.gridy = 4;
toppane.add(itemInfo,c);
c.gridx = 2;
c.gridy = 5;
toppane.add(subtotal,c);
bottomPane.setBackground(Color.GREEN);
frame.add(toppane,BorderLayout.EAST);
//adds textfields to the frame
JTextField amount = new JTextField();
JTextField id = new JTextField();
JTextField quantity = new JTextField();
JTextField info = new JTextField();
JTextField total = new JTextField();
//add textfield to panel
c.ipadx = 230;
c.gridx = 3;
c.gridy= 1;
toppane.add(amount, c);
c.gridx = 3;
c.gridy = 2;
toppane.add(id, c);
c.gridx = 3;
c.gridy = 3;
toppane.add(info, c);
c.gridx = 3;
c.gridy = 4;
toppane.add(total, c);
c.gridx = 3;
c.gridy = 5;
toppane.add(quantity,c);
//setting up buttons to be placed onto the bottompanel
JButton processItem = new JButton("Process Item");
JButton confirmItem = new JButton("Confirm Item");
JButton viewOrder = new JButton("View Order");
JButton finishOrder = new JButton("Finish Order ");
JButton newOrder = new JButton("New Order");
JButton exit = new JButton("Exit");
//adding the buttons to the pane.
GridBagConstraints b = new GridBagConstraints();
b.anchor = GridBagConstraints.NORTHWEST;
bottomPane.add(processItem, c);
bottomPane.add(confirmItem,c);
bottomPane.add(viewOrder, c);
bottomPane.add(finishOrder,c);
bottomPane.add(newOrder,c);
bottomPane.add(exit, c);
bottomPane.setBackground(Color.BLUE);
frame.add(bottomPane,BorderLayout.SOUTH);
}
}
Personally I feel like it has something to do with the layout manager that I am using. I don't know if I am using it properly for the right application. I have been using GridBagLayout, and that is all I have used for school thus far.
Your issue is that you are using the same constraint c for every one of your new buttons:
bottomPane.add(processItem, c);
bottomPane.add(confirmItem,c);
bottomPane.add(viewOrder, c);
bottomPane.add(finishOrder,c);
bottomPane.add(newOrder,c);
The last modification you made to c was up above when you did:
c.gridx = 3;
c.gridy = 5;
And then you're just reusing that same constraint for all 5 new buttons and thus adding them all to the same grid location.
You'll need to set the constraints accordingly (e.g. set c's values, you've got that stray unused b there, too) for each one.
GridBagLayout is outdated. And it is a pain to work with. With a modern layout manager like MigLayout, your code example can be created very quickly.
package com.zetcode;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;
/**
* MigLayout demonstration example.
* #author Jan Bodnar
* Website zetcode.com
*/
public class MigLayoutBookEx extends JFrame {
public MigLayoutBookEx() {
initUI();
}
private void initUI() {
JLabel lbl1 = new JLabel("Label");
JLabel lbl2 = new JLabel("Label");
JLabel lbl3 = new JLabel("Label");
JTextField field1 = new JTextField(15);
JTextField field2 = new JTextField(15);
JTextField field3 = new JTextField(15);
JButton btn1 = new JButton("Button");
JButton btn2 = new JButton("Button");
JButton btn3 = new JButton("Button");
JButton btn4 = new JButton("Button");
JButton btn5 = new JButton("Button");
createLayout(lbl1, field1, lbl2, field2, lbl3, field3,
btn1, btn2, btn3, btn4, btn5);
setTitle("MigLayoutExample");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void createLayout(JComponent... arg) {
setLayout(new MigLayout("ins 10lp, gap 5lp 8lp, fillx", "[center]"));
add(arg[0], "split 2, span");
add(arg[1], "wrap");
add(arg[2], "split 2, span");
add(arg[3], "wrap");
add(arg[4], "split 2, span");
add(arg[5], "wrap");
add(arg[6], "split 5, gapy 5lp, align left");
add(arg[7]);
add(arg[8]);
add(arg[9]);
add(arg[10]);
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MigLayoutBookEx ex = new MigLayoutBookEx();
ex.setVisible(true);
});
}
}
The layout is created with a combination of various constraints. Once you learn this, most practical layouts are a piece of cake. You can find out more on the manager's website.
Screenshot:
Ok so i set the bottom panel to a boxlayout and got the buttons horizontal!
Code with fix!
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package book;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.BoxLayout;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
/**
*
* #author KJ4CC
*/
public class UserInterface extends JFrame {
public void startUI(){
UserInterface gui = new UserInterface();
gui.bookingUI();
}
public static void bookingUI(){
//sets windows, and pane in the UI
JFrame frame = new JFrame("Ye old Book store");
JPanel toppane = new JPanel(new GridBagLayout());
JPanel bottomPane = new JPanel();
bottomPane.setLayout(new BoxLayout(bottomPane, BoxLayout.LINE_AXIS)); <---------------------------------------------Here is the fix
GridBagConstraints c = new GridBagConstraints();
frame.setSize(800, 300);
frame.setVisible(true);
//adds labels to the window
JLabel num = new JLabel("Enter Number of Items in this Order");
JLabel bookID = new JLabel("111111");
JLabel quantityItem = new JLabel("222222");
JLabel itemInfo = new JLabel("33333");
JLabel subtotal = new JLabel("4444444");
//adding the labels to the panel-----------------------------------------------------
c.insets = new Insets(5,0,0,0);
c.gridx = 2;
c.gridy = 1;
toppane.add(num, c);
c.gridx = 2;
c.gridy = 2;
toppane.add(bookID, c);
c.gridx = 2;
c.gridy = 3;
toppane.add(quantityItem, c);
c.gridx = 2;
c.gridy = 4;
toppane.add(itemInfo,c);
c.gridx = 2;
c.gridy = 5;
toppane.add(subtotal,c);
toppane.setBackground(Color.GREEN);
frame.add(toppane);
//adds textfields to the frame ----------------------------------------------------
JTextField amount = new JTextField();
JTextField id = new JTextField();
JTextField quantity = new JTextField();
JTextField info = new JTextField();
JTextField total = new JTextField();
//add textfield to panel
c.ipadx = 400;
c.insets = new Insets(5,10,0,0);
c.gridx = 3;
c.gridy= 1;
toppane.add(amount, c);
c.gridx = 3;
c.gridy = 2;
toppane.add(id, c);
c.gridx = 3;
c.gridy = 3;
toppane.add(info, c);
c.gridx = 3;
c.gridy = 4;
toppane.add(total, c);
c.gridx = 3;
c.gridy = 5;
toppane.add(quantity,c);
//----------------------------------------------------------BUTTOM PANE-------------------------
//setting up buttons to be placed onto the bottompanel
JButton processItem = new JButton("Process Item");
JButton confirmItem = new JButton("Confirm Item");
JButton viewOrder = new JButton("View Order");
JButton finishOrder = new JButton("Finish Order ");
JButton newOrder = new JButton("New Order");
JButton exit = new JButton("Exit");
//adding the buttons to the pane.---------------------------------------------------------------
GridBagConstraints b = new GridBagConstraints();
b.ipadx = 20;
b.ipady = 20;
b.gridx = 0;
b.gridy = 1;
bottomPane.add(processItem, c);
b.gridx = 0;
b.gridy = 2;
bottomPane.add(confirmItem,c);
b.gridx = 0;
b.gridy = 3;
bottomPane.add(viewOrder, c);
b.gridx = 0;
b.gridy = 4;
bottomPane.add(finishOrder,c);
b.gridx = 0;
b.gridy = 5;
bottomPane.add(newOrder,c);
b.gridx = 0;
b.gridy = 6;
bottomPane.add(exit, c);
bottomPane.setBackground(Color.BLUE);
frame.add(bottomPane,BorderLayout.SOUTH);
frame.setSize(810, 310);
}
}
You need to use Flow layout to your bottomPane. Is't better then GridLayout for this use.
I am trying to create an interface with some JLabels icons ( box icons )and an exit button. The thing is that, when I place the button under the labels, they split, according to the button's position like this:
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.VERTICAL; // Adding space before the labels
c.gridy = 0;
c.weighty = 1;
add(new JLabel(" "), c);
for(int i = 0; i < label.length; i++){ // Adding the JLabels
c.fill = GridBagConstraints.NONE;
c.weighty = 0;
c.gridy = 1;
c.gridx++;
add(label[i], c);
}
// Adding the button
c.gridy ++;
c.gridx = 2; // Changing the value of gridx, will move the button to that location and it will split another jlabel.
c.weighty = 0.09;
add(eButton, c);
revalidate();
repaint();
GridBagLayout works a lot like a grid paper, it has rows and columns, components are placed within those cells; you can specify how additional space is distributed and components are aligned within those cells.
Each row and column is sized based on the layout requirements of the other components in that row/column, this means that a component may have more space than it needs, because some other component in the same row/column needs more space to be laid out.
You can also allow a component to span across multiple rows/columns, allowing to occupy more space.
So, basically, what you need to do is tell the button that it can occupy all the columns for it's row (or at least the 5 columns which is occupied by the labels). You will need to then tell the button that it needs to be aligned to the center of it's area.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
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() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.VERTICAL; // Adding space before the labels
c.gridy = 0;
c.weighty = 1;
for (int i = 0; i < 5; i++) { // Adding the JLabels
c.fill = GridBagConstraints.NONE;
c.weighty = 0;
c.gridy = 1;
c.gridx++;
c.insets = new Insets(4, 4, 4, 4);
JLabel label = new JLabel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(20, 20);
}
};
label.setBorder(new LineBorder(Color.DARK_GRAY));
add(label, c);
}
c.gridy++;
c.gridx = 0;
c.gridwidth = GridBagConstraints.REMAINDER;
c.anchor = GridBagConstraints.NORTH;
// c.weighty = 0.09;
add(new JButton("Exit"), c);
}
}
}
Take a closer look at How to Use GridBagLayout for more details
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.
I have a question regarding making a specific Layout, first I'll show examples then I will add some extra clarification.
Layout when Friends and Messages are closed:
Layout when Friends and Messages are opened:
I intend to make this layout with Java Swing.
My intention is to firstly have the Frame divided in three areas, the top menu row, the main panel and the bottom menu row.
I was thinking of using a BorderLayout for this part.
Then the Friends and Messages buttons should be toggle button's, and on toggle they should show an overlay on top of the mainpanel (or whatever is there), containing a friend list and a message area. I realised I need to use a LayeredPane somehow for this.
Another important part is that the Layout should be viewable in any size, that is the user may resize the application and it will be used on a various amount of resolutions, so I don't really want anything with a fixed width and height.
But I am really lost as how to combine this, so therefore I ask your help.
Hopefully I have explained enough about the situation.
Regards.
this could be about overlay, because JPanel can contains other JComponents
use JLayer (Java7) based on JXLayer(Java6),
use GlassPane with JComponents layed to rellative to....
easiest could be to use JDialog(undecorated) layed to Point (setLocation(int, int)), setVisible() must be wrapped into invokeLater
I will use gridBagLayout.
Here is small example including button which hide your yellow panels:
package Core;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GridBagLayoutDemo {
public static void addComponentsToPane(Container pane) {
pane.setLayout(new GridBagLayout());
add1row(pane);
addmainRow(pane);
addLastRow(pane);
}
private static void addLastRow(Container pane) {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 3;
c.anchor = GridBagConstraints.PAGE_END;
JPanel bottonPanel = new JPanel();
bottonPanel.setBackground(Color.BLUE);
bottonPanel.setLayout(new GridBagLayout());
pane.add(bottonPanel, c);
JPanel messagePanel = new JPanel();
messagePanel.setBackground(Color.GRAY);
messagePanel.add(new JLabel("MESSAGES"));
c.fill = GridBagConstraints.VERTICAL;
c.anchor = GridBagConstraints.LINE_END;
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
bottonPanel.add(messagePanel, c);
}
private static void addmainRow(Container pane) {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = GridBagConstraints.CENTER;
JPanel mainManel = new JPanel();
mainManel.setBackground(Color.GREEN);
mainManel.setLayout(new GridBagLayout());
pane.add(mainManel, c);
final JPanel friendListPanel = new JPanel();
friendListPanel.setBackground(Color.YELLOW);
friendListPanel.add(new JLabel("FRIEND LIST"));
c.fill = GridBagConstraints.NONE;
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
c.weighty = 1;
c.anchor = GridBagConstraints.FIRST_LINE_END;
mainManel.add(friendListPanel, c);
c.fill = GridBagConstraints.NONE;
c.gridx = 0;
c.gridy = 1;
c.weightx = 0;
c.weighty = 0;
c.anchor = GridBagConstraints.CENTER;
JButton button = new JButton("On/Off");
mainManel.add(button, c);
final JPanel messageAreaPanel = new JPanel();
messageAreaPanel.setBackground(Color.YELLOW);
messageAreaPanel.add(new JLabel("MESSAGE PANEL"));
c.fill = GridBagConstraints.NONE;
c.gridx = 0;
c.gridy = 2;
c.weightx = 1;
c.weighty = 1;
c.anchor = GridBagConstraints.LAST_LINE_END;
mainManel.add(messageAreaPanel, c);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
friendListPanel.setVisible(!friendListPanel.isVisible());
messageAreaPanel.setVisible(!messageAreaPanel.isVisible());
}
});
}
private static void add1row(Container pane) {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.PAGE_START;
Panel headerPanel = new Panel();
headerPanel.setLayout(new GridBagLayout());
headerPanel.setBackground(Color.BLUE);
pane.add(headerPanel, c);
JPanel quitPanel = new JPanel();
quitPanel.setBackground(Color.GRAY);
quitPanel.add(new JLabel("QUIT"));
c.fill = GridBagConstraints.VERTICAL;
c.anchor = GridBagConstraints.LINE_START;
c.gridx = 0;
c.gridy = 0;
c.weightx = 1;
headerPanel.add(quitPanel, c);
JPanel friendsPanel = new JPanel();
friendsPanel.setBackground(Color.GRAY);
friendsPanel.add(new JLabel("FRIENDS"));
c.fill = GridBagConstraints.VERTICAL;
c.anchor = GridBagConstraints.LINE_END;
c.gridx = 1;
c.gridy = 0;
headerPanel.add(friendsPanel, c);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("GridBagLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame);
// uncoment to use full screen
// frame.setExtendedState(frame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
frame.setSize(new Dimension(400, 400));
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}