image
In the picture I attached(link) above, JTable is supposed to be shown under forward, Backward, and Remove buttons with JTable headers: X / Y / Width / Height
But, it is not. Can anyone please help me? what am i doing wrong here ?
import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
public class Whiteboard extends JFrame {
public static void main(String[] args) {
new Whiteboard();
}
private static final long serialVersionUID = 1L;
private String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };
public Whiteboard() {
JButton setColor = new JButton("Color");
JPanel colorPanel = new JPanel();
colorPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
colorPanel.setLayout(new BoxLayout(colorPanel, BoxLayout.X_AXIS));
colorPanel.add(setColor);
JButton addRect = new JButton("Rect");
JButton addOval = new JButton("Oval");
JButton addLine = new JButton("Line");
JButton addText = new JButton("Text");
JPanel addPanel = new JPanel();
addPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
addPanel.setLayout(new BoxLayout(addPanel, BoxLayout.X_AXIS));
addPanel.add(addRect);
addPanel.add(addOval);
addPanel.add(addLine);
addPanel.add(addText);
JTextField setText = new JTextField("");
JComboBox<String> changeFont = new JComboBox<String>(petStrings);
JPanel textPanel = new JPanel();
textPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
textPanel.setLayout(new BoxLayout(textPanel, BoxLayout.X_AXIS));
textPanel.add(setText);
textPanel.add(changeFont);
JButton sendForward = new JButton("Forward");
JButton sendBackward = new JButton("Backward");
JButton removeObj = new JButton("Remove");
JPanel orderPanel = new JPanel();
orderPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
orderPanel.setLayout(new BoxLayout(orderPanel, BoxLayout.X_AXIS));
orderPanel.add(sendForward);
orderPanel.add(sendBackward);
orderPanel.add(removeObj);
DefaultTableModel tableModel = new DefaultTableModel(new String[] { "X", "Y", "Width", "Height" }, 0);
JTable infoTable = new JTable(tableModel);
JScrollPane tablePanel = new JScrollPane();
infoTable.setPreferredScrollableViewportSize(infoTable.getPreferredSize());
infoTable.setFillsViewportHeight(true);
tablePanel.add(infoTable);
tableModel.addRow(new String[] { "TEST1", "TEST2", "TEST3", "TEST4" });
JPanel control = new JPanel();
control.setLayout(new BoxLayout(control, BoxLayout.Y_AXIS));
control.add(colorPanel);
control.add(addPanel);
control.add(textPanel);
control.add(orderPanel);
control.add(tablePanel);
Canvas canvas = new Canvas();
canvas.setLayout(new BoxLayout(canvas, BoxLayout.PAGE_AXIS));
JPanel window = new JPanel();
window.add(control);
window.add(canvas);
getContentPane().add(window);
pack();
setLocationRelativeTo(null);
setTitle("Whiteboard");
setLayout(new BorderLayout());
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
tablePanel.add(infoTable);
Don't add components directly to a JScrollPane. The component should be added to the JViewport of the scroll panel.
Instead you can use:
JScrollPane tablePanel = new JScrollPane(infoTable); // easiest way,
or
tablePanel.getViewport().setViewportView( infoTable );
Also, don't use the Canvas class. That is an AWT component. You should be using a JPanel.
Related
I want to ask some question about Java GUI, especially on JPanel syntax. I'm really confused how to configure the panel exactly, try to use BorderLayout, and GridLayout, but it still doesn't meet my requirement.
I want to make form like below:
Current Result:
From the image, I need to configure that 2 points
The padding / margin between Input Panel and the Button Panel
The Padding / margin between tablePanel and the inputPanel
Code
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.BevelBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;
public class manageForm extends JFrame {
//Vector<String> header=new Vector<String>();
//Vector<Vector<String>>data=new Vector<Vector<String>>();
DefaultTableModel defaultTableModel;
JTable table;
JScrollPane scrollPane;
JLabel titleLabel=new JLabel("Manage Handphone");
JTable hpTable = new JTable();
JLabel idLabel = new JLabel("ID");
JLabel nameLabel = new JLabel("Name");
JLabel priceLabel = new JLabel("Price");
JLabel weightLabel = new JLabel("Weight");
JLabel cableLabel = new JLabel("Cable Length");
JLabel typeLabel = new JLabel("Type");
JTextField idtxt = new JTextField();
JTextField nametxt = new JTextField();
JTextField pricetxt = new JTextField();
JTextField weighttxt = new JTextField();
JTextField cabletxt = new JTextField();
JComboBox typeBox = new JComboBox();
JButton insertBtn = new JButton("INSERT");
JButton updateBtn = new JButton("UPDATE");
JButton deleteBtn = new JButton("DELETE");
JButton confirmBtn = new JButton("CONFIRM");
JButton cancelBtn = new JButton("CANCEL");
String header[] = {"ID","Name","Type","Price","Weight","Cable Length"};
String data[][] = {
{"2","Bose Quite","In-Ear","Price","Weight","Cable Length"},
{"2","Bose Quite","In-Ear","Price","Weight","Cable Length"},
{"2","Bose Quite","In-Ear","Price","Weight","Cable Length"}
};
public manageForm() {
JPanel headerPanel = new JPanel();
JPanel tablePanel = new JPanel();
tablePanel.setBorder(new EmptyBorder(0,0,0,0));
JPanel inputPanel = new JPanel(new GridLayout(6,2));
inputPanel.setBorder(new EmptyBorder(20,10,20,10));
//inputPanel.setBorder(new LineBorder(Color.black));
JPanel buttonPanel = new JPanel(new GridLayout(1,5));
buttonPanel.setBorder(new EmptyBorder(100,20,100,20));
JPanel footerPanel = new JPanel(new GridLayout (2,1,0,0));
headerPanel.add(titleLabel);
inputPanel.add(idLabel);
inputPanel.add(idtxt);
inputPanel.add(nameLabel);
inputPanel.add(nametxt);
inputPanel.add(priceLabel);
inputPanel.add(pricetxt);
inputPanel.add(weightLabel);
inputPanel.add(weighttxt);
inputPanel.add(cableLabel);
inputPanel.add(cabletxt);
inputPanel.add(typeLabel);
inputPanel.add(typeBox);
buttonPanel.add(confirmBtn);
buttonPanel.add(cancelBtn);
buttonPanel.add(insertBtn);
buttonPanel.add(updateBtn);
buttonPanel.add(deleteBtn);
footerPanel.add(inputPanel);
footerPanel.add(buttonPanel);
/*
JPanel panel0=new JPanel();
JPanel panel1=new JPanel();
JPanel panel2=new JPanel();
JPanel panel3=new JPanel();
JPanel panel4=new JPanel();
JPanel panel5=new JPanel();
JPanel panel6 = new JPanel();
JPanel panel7 = new JPanel();
JPanel panel8 = new JPanel();
panel1.setLayout(new GridLayout(1, 6));
panel2.setLayout(new GridLayout(1, 2));
panel2.add(idLabel);
panel2.add(idtxt);
panel3.setLayout(new GridLayout(1, 2));
panel3.add(nameLabel);
panel3.add(nametxt);
panel4.setLayout(new GridLayout(1, 2));
panel4.add(priceLabel);
panel4.add(pricetxt);
panel5.setLayout(new GridLayout(1, 2));
panel5.add(weightLabel);
panel5.add(weighttxt);
panel6.setLayout(new GridLayout(1, 2));
panel6.add(cableLabel);
panel6.add(cabletxt);
panel7.setLayout(new GridLayout(1, 2));
panel7.add(typeLabel);
panel7.add(typeBox);
panel8.setLayout(new GridLayout(1, 5));
mainPanel.add(panel0);
mainPanel.add(panel1);
mainPanel.add(panel2);
mainPanel.add(panel3);
mainPanel.add(panel4);
mainPanel.add(panel5);
mainPanel.add(panel6);
mainPanel.add(panel7);
mainPanel.add(panel8);
*/
/*
header.add("ID");
header.add("Name");
header.add("Type");
header.add("Price");
header.add("Weight");
header.add("Cable Length");
*/
defaultTableModel=new DefaultTableModel(data, header);
hpTable =new JTable(defaultTableModel);
scrollPane=new JScrollPane(hpTable);
// tablePanel.add(scrollPane);
setLayout(new BorderLayout(0,5));
setTitle("Manage Form");
setSize(800,600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
add(headerPanel,BorderLayout.NORTH);
add(scrollPane,BorderLayout.CENTER);
add(footerPanel,BorderLayout.SOUTH);
pack();
}
public static void main(String[] args) {
new manageForm();
}
}
How exactly to manage the panel layout to meet our requirement?
I have tried EmptyBorder, but the result, it's only making a big space between the other panel.
Use GridBagLayout it is a powerful and best fit to your requirement. It is arranges the components in a horizontal and vertical manner.
You can put component in a grid using cells and rows. As a example:
read more - GridBagLayout
Strongly disagree with the suggestion to use GridBagLayout. That layout is basically a punchline for any Swing programmer.
If you're going to be programming Swing, do yourself a huge favor and use MiGLayout. It's the layout manager that Swing should have built-in.
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.JList;
import javax.swing.JSplitPane;
import javax.swing.JLabel;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.event.ListSelectionEvent;
public class MenuPage extends JFrame{
final static int extraWindowWidth = 100;
JSplitPane jSplitPane, jSplitPane2,jSplitPane3,jSplitPane4;
JPanel jPanel2a, jPanel2b, jPanel3;
public static JFrame frame;
public MenuPage(){
}
private final JList<String> list1=new JList<>(new String[]{"A","B"});
private final JList<String> list2 = new JList<>();
private final List<DefaultListModel> models = new ArrayList<>();
public void addComponentToPane(Container pane) {
JTabbedPane tabbedPane = new JTabbedPane();
// Create the "cards".
JPanel card1 = new JPanel() {
// Make the panel wider than it really needs, so
// the window's wide enough for the tabs to stay
// in one row.
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.width += extraWindowWidth;
return size;
}
};
DefaultListModel<String> model1 = new DefaultListModel<>();
model1.addElement("A1");
model1.addElement("A2");
model1.addElement("A3");
models.add(model1);
DefaultListModel<String> model2 = new DefaultListModel<>();
model2.addElement("B1");
model2.addElement("B2");
models.add(model2);
list2.setModel(model1);
list1.addListSelectionListener((ListSelectionEvent e) -> {
if (!e.getValueIsAdjusting()) {
list2.setModel(models.get(list1.getSelectedIndex()));
}
});
jPanel2a = new JPanel();
jPanel2b = new JPanel();
jPanel3 = new JPanel();
jSplitPane2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, jPanel2a, jPanel2b);
jSplitPane3 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, list1, list2);
jSplitPane4 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,jSplitPane3,jPanel3);
// panelin icerisine component eklendi
JLabel lblHelloWorld = new JLabel("Hello World!");
jPanel2a.add(lblHelloWorld);
jSplitPane2.setOneTouchExpandable(true);
jSplitPane2.setDividerLocation(100);
jSplitPane3.setOneTouchExpandable(true);
jSplitPane3.setDividerLocation(150);
jSplitPane4.setOneTouchExpandable(true);
jSplitPane4.setDividerLocation(300);
JPanel card3 = new JPanel();
JPanel card4 = new JPanel();
JPanel card5 = new JPanel();
JPanel card6 = new JPanel();
JPanel card7 = new JPanel();
JPanel card8 = new JPanel();
card3.add(jSplitPane3,jSplitPane4);
tabbedPane.addTab("Main", jSplitPane2);
tabbedPane.addTab("Leagues",jSplitPane4);
tabbedPane.addTab("Teams",card3 );
tabbedPane.addTab("Ratios", card4);
tabbedPane.addTab("Competitions", card5);
tabbedPane.addTab("Analyze", card6);
tabbedPane.addTab("Help", card7);
tabbedPane.addTab("About", card8);
pane.add(tabbedPane, BorderLayout.CENTER);
}
/**
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event dispatch thread.
*/
public static void createAndShowGUI() {
// Create and set up the window.
frame = new JFrame("BetAnalyzer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(594, 310);
// Create and set up the content pane.
MenuPage demo = new MenuPage();
demo.addComponentToPane(frame.getContentPane());
// Display the window.
frame.pack();
frame.setVisible(true);
frame.setBounds(100, 100, 635, 251);
}
}
I want the list1, list2, and jpanel3 which takes part 2 JSplitPane to be in the league tab There is something wrong in my code. Just jSplitPane3 or jSplitPane4 could be appear in the layout.
Also, I tried to add two JSplitPane into Box then I put the Box in tabbedpane but this's not working neither.
Your code has several issues.
do not inherit without reason
Your class inherits from JFrame but its does not extend its behavior (it does not override a public or protected method of JFrame).
Components can only be added once
In contrast to the other points this is not an issue per se but part of your problem.
jSplitPane4 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,jSplitPane3,jPanel3);
// ...
card3.add(jSplitPane3,jSplitPane4);
When the second statement is executed the jSplitPane3 is removed from the jSplitPane4 and only shown as content of card3.
use of standard layouts
The (dummy) content of your panels is rather small so that their preferedSize is less then the available space in the parent container.
The JPanels default Layout is FlowLayout which reduces each of its components to its preferedSize.
You should set the Layout of your JPanels to BorderLayout which allows its content to stretch out over the complete space.
In turn you cannot use JPanels varag method .add(Component, component)
anymore.
here are the relevant changes:
jPanel2a = new JPanel(new BorderLayout());
jPanel2b = new JPanel(new BorderLayout());
jPanel3 = new JPanel(new BorderLayout());
jSplitPane2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, jPanel2a, jPanel2b);
jSplitPane3 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, list1, list2);
jSplitPane4 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, jSplitPane3, jPanel3);
// panelin icerisine component eklendi
JLabel lblHelloWorld = new JLabel("Hello World!");
jPanel2a.add(lblHelloWorld);
// jSplitPane2.setOneTouchExpandable(true);
jSplitPane2.setDividerLocation(100);
//
// jSplitPane3.setOneTouchExpandable(true);
jSplitPane3.setDividerLocation(150);
//
// jSplitPane4.setOneTouchExpandable(true);
jSplitPane4.setDividerLocation(300);
JPanel card3 = new JPanel(new BorderLayout());
JPanel card4 = new JPanel(new BorderLayout());
JPanel card5 = new JPanel(new BorderLayout());
JPanel card6 = new JPanel(new BorderLayout());
JPanel card7 = new JPanel(new BorderLayout());
JPanel card8 = new JPanel(new BorderLayout());
// card3.add(jSplitPane3);
card3.add(jSplitPane4,BorderLayout.SOUTH);
tabbedPane.addTab("Main", jSplitPane2);
I am trying to write a program with JPanels and for the life of me, I can't seem to get the JPanels to go into the proper positions. I don't have a clue what I am doing wrong.
Here is some of the code I have so far:
package mainGUIWindowFrames;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class CustomerWindow extends JFrame
{
//Attribute
private JTextField textTF;
private JButton copyButton;
private JLabel copyLabel;
private Border panelEdge;
//Constructor
public CustomerWindow()
{
this.setBounds(100,100,800,600);
panelEdge = BorderFactory.createEtchedBorder();
JPanel mainPanel = new JPanel(new BorderLayout(5, 5));
mainPanel.add(createCustomerPanel(), BorderLayout.NORTH);
mainPanel.add(createCustomerInfoPanel(), BorderLayout.EAST);
mainPanel.add(createSearchPanel(), BorderLayout.WEST);
}
//Operational Methods
public JPanel createCustomerPanel()
{
JPanel customerPanel = new JPanel();
JLabel customerL = new JLabel("Clients",SwingConstants.CENTER);
customerL.setForeground(Color.blue);
customerL.setFont(new Font("Copperplate Gothic Bold",Font.BOLD,48));
customerPanel.add(customerL);
customerPanel.setBorder(panelEdge);
return customerPanel;
}
public JPanel createCustomerInfoPanel()
{
JPanel infoPanel = new JPanel();
infoPanel.setBorder(panelEdge);
JLabel infoL = new JLabel("Clients",SwingConstants.CENTER);
infoL.setForeground(Color.blue);
infoL.setFont(new Font("Copperplate Gothic Bold",Font.BOLD,48));
infoPanel.add(infoL);
//add a text field
textTF = new JTextField(50);
infoPanel.add(textTF);
//add a button
copyButton = new JButton("Copy Text");
copyButton.addActionListener(new ButtonListener());
infoPanel.add(copyButton);
copyLabel = new JLabel("-----------------");
infoPanel.add(copyLabel);
return infoPanel;
}
public JPanel createSearchPanel()
{
JPanel lowerPanel = new JPanel();
JLabel label = new JLabel("Text Transferred from JList:");
//the spot where the data shows up
lowerPanel.add(label);
return lowerPanel;
}
The only Panel that shows up is the CreateCustomerPanel(). I have no idea what I need to do to get the other two panels to work.
If you could help me out that would be great!!
well I eventually wound up solving it by creating another panel and moving the panels I had out of the main constructor.
public CustomerWindow() {
panelEdge = BorderFactory.createEtchedBorder();
}
public JPanel createNorthPanel()
{
JPanel customerPanel = new JPanel();
JLabel customerL = new JLabel("Clients",SwingConstants.CENTER);
customerL.setForeground(Color.blue);
customerL.setFont(new Font("Copperplate Gothic Bold",Font.BOLD,48));
customerPanel.add(customerL);
customerPanel.setBorder(panelEdge);
return customerPanel;
}
//Operational Methods
public JPanel createCustomerPanel()
{
JPanel mainPanel = new JPanel(new BorderLayout(5, 5));
mainPanel.add(createNorthPanel(), BorderLayout.NORTH);
mainPanel.add(createCustomerInfoPanel(), BorderLayout.EAST);
mainPanel.add(createSearchPanel(), BorderLayout.WEST);
return mainPanel;
}
public JPanel createCustomerInfoPanel()
{
JPanel infoPanel = new JPanel();
Box vBox = Box.createVerticalBox();
infoPanel.setBorder(panelEdge);
JLabel infoL = new JLabel("Clients",SwingConstants.CENTER);
infoL.setForeground(Color.blue);
infoL.setFont(new Font("Copperplate Gothic Bold",Font.BOLD,48));
infoPanel.add(infoL);
//add a text field
clientId = new JTextField(10);
vBox.add(clientId);
vBox.add(Box.createVerticalStrut(25));
fName = new JTextField(10);
vBox.add(fName);
vBox.add(Box.createVerticalStrut(25));
lName = new JTextField(10);
vBox.add(lName);
vBox.add(Box.createVerticalStrut(25));
address = new JTextField(10);
vBox.add(address);
vBox.add(Box.createVerticalStrut(25));
postalCode = new JTextField(10);
vBox.add(postalCode);
vBox.add(Box.createVerticalStrut(25));
number = new JTextField(10);
vBox.add(number);
vBox.add(Box.createVerticalStrut(25));
type = new JTextField(10);
vBox.add(type);
infoPanel.add(vBox);
return infoPanel;
Ive still got a lot of work to do but thanks to all those who helped me out!!
Based on your example, nothing should show up, as you've not added mainPanel to anything.
Once I did that, I was able to get
to show up...
Modified code example
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.Border;
public class CustomerWindow extends JFrame {
//Attribute
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) {
}
CustomerWindow frame = new CustomerWindow();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
private JTextField textTF;
private JButton copyButton;
private JLabel copyLabel;
private Border panelEdge;
//Constructor
public CustomerWindow() {
this.setBounds(100, 100, 800, 600);
panelEdge = BorderFactory.createEtchedBorder();
JPanel mainPanel = new JPanel(new BorderLayout(5, 5));
mainPanel.add(createCustomerPanel(), BorderLayout.NORTH);
mainPanel.add(createCustomerInfoPanel(), BorderLayout.EAST);
mainPanel.add(createSearchPanel(), BorderLayout.WEST);
add(mainPanel);
}
//Operational Methods
public JPanel createCustomerPanel() {
JPanel customerPanel = new JPanel();
JLabel customerL = new JLabel("Clients", SwingConstants.CENTER);
customerL.setForeground(Color.blue);
customerL.setFont(new Font("Copperplate Gothic Bold", Font.BOLD, 48));
customerPanel.add(customerL);
customerPanel.setBorder(panelEdge);
return customerPanel;
}
public JPanel createCustomerInfoPanel() {
JPanel infoPanel = new JPanel();
infoPanel.setBorder(panelEdge);
JLabel infoL = new JLabel("Clients", SwingConstants.CENTER);
infoL.setForeground(Color.blue);
infoL.setFont(new Font("Copperplate Gothic Bold", Font.BOLD, 48));
infoPanel.add(infoL);
//add a text field
textTF = new JTextField(50);
infoPanel.add(textTF);
//add a button
copyButton = new JButton("Copy Text");
// copyButton.addActionListener(new ButtonListener());
infoPanel.add(copyButton);
copyLabel = new JLabel("-----------------");
infoPanel.add(copyLabel);
return infoPanel;
}
public JPanel createSearchPanel() {
JPanel lowerPanel = new JPanel();
JLabel label = new JLabel("Text Transferred from JList:");
//the spot where the data shows up
lowerPanel.add(label);
return lowerPanel;
}
}
You didn't add the mainpanel in the constructor.
add(mainPanel);
I am trying to get my JTextArea to display under all other contents of the llpPanel. My code is below with a screenshot of what my code displays. In the code you will see that I have set my dimensions for the JTextArea to (50, 50). Then in the llpPanel I have added BorderLayout.PAGE_END. I have also tried to (instead of PAGE_END) put CENTER and SOUTH. When I put SOUTH, it shows a white line at the very bottom of the program but you cannot do anything with it.
import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class TestApplication implements ActionListener {
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setSize(1000, 1000);
frame.setTitle("RBA Test Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
JButton initialize = new JButton("Initialize");
JButton connect = new JButton("Connect");
JButton disconnect = new JButton("Disconnect");
JButton shutdown = new JButton("Shut Down");
JButton portsettings = new JButton("Port Settings");
JButton online = new JButton("Go Online");
JButton offline = new JButton("Go Offline");
JButton status = new JButton("Status");
JButton reboot = new JButton("Reboot");
JButton account = new JButton("Account");
JButton amount = new JButton("Amount");
JButton reset = new JButton("Reset");
JButton approvordecl = new JButton("Approve / Decline");
JTextArea logbox = new JTextArea(50, 50);
JPanel testPanel = new JPanel();
testPanel.add(button);
testPanel.add(button2);
testPanel.add(checkbox2);
JPanel posPanel = new JPanel();
posPanel.add(test);
posPanel.add(testing);
posPanel.add(checkbox);
JPanel llpPanel = new JPanel();
llpPanel.add(online);
llpPanel.add(offline);
llpPanel.add(status);
llpPanel.add(reboot);
llpPanel.add(account);
llpPanel.add(amount);
llpPanel.add(reset);
llpPanel.add(approvordecl);
llpPanel.add(logbox, BorderLayout.PAGE_END);
JPanel buttonPanel = new JPanel();
buttonPanel.add(initialize);
buttonPanel.add(connect);
buttonPanel.add(disconnect);
buttonPanel.add(shutdown);
buttonPanel.add(portsettings);
frame.add(buttonPanel);
frame.add(buttonPanel, BorderLayout.NORTH);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("LLP", null, llpPanel, "Low Level Protocol");
tabbedPane.addTab("POS",null, posPanel, "Point Of Sale");
tabbedPane.addTab("Test", null, testPanel, "Test");
JPanel tabsPanel = new JPanel(new BorderLayout());
tabsPanel.add(tabbedPane);
frame.add(tabsPanel, BorderLayout.CENTER);
frame.pack();
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
Updated code with screenshot is below...
import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class TestApplication implements ActionListener {
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setSize(1000, 1000);
frame.setTitle("RBA Test Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
JTextArea logbox = new JTextArea(50, 50);
JButton initialize = new JButton("Initialize");
JButton connect = new JButton("Connect");
JButton disconnect = new JButton("Disconnect");
JButton shutdown = new JButton("Shut Down");
JButton portsettings = new JButton("Port Settings");
JButton online = new JButton("Go Online");
JButton offline = new JButton("Go Offline");
JButton status = new JButton("Status");
JButton reboot = new JButton("Reboot");
JButton account = new JButton("Account");
JButton amount = new JButton("Amount");
JButton reset = new JButton("Reset");
JButton approvordecl = new JButton("Approve / Decline");
JButton test = new JButton("Test Button #1");
JButton testing = new JButton("Test Button #2");
JRadioButton button = new JRadioButton("Radio Button");
JRadioButton button2 = new JRadioButton("Radio Button");
JCheckBox checkbox = new JCheckBox("Check Box");
JCheckBox checkbox2 = new JCheckBox("Check Box");
JPanel newButtonPanel = new JPanel();
newButtonPanel.add(online);
newButtonPanel.add(offline);
newButtonPanel.add(status);
newButtonPanel.add(reboot);
newButtonPanel.add(account);
newButtonPanel.add(amount);
newButtonPanel.add(reset);
newButtonPanel.add(approvordecl);
JPanel testPanel = new JPanel();
testPanel.add(button);
testPanel.add(button2);
testPanel.add(checkbox2);
JPanel posPanel = new JPanel();
posPanel.add(test);
posPanel.add(testing);
posPanel.add(checkbox);
JPanel llpPanel = new JPanel();
llpPanel.setLayout(new BorderLayout());
llpPanel.add(newButtonPanel);
llpPanel.add(logbox, BorderLayout.PAGE_END);
JPanel buttonPanel = new JPanel();
buttonPanel.add(initialize);
buttonPanel.add(connect);
buttonPanel.add(disconnect);
buttonPanel.add(shutdown);
buttonPanel.add(portsettings);
frame.add(buttonPanel);
frame.add(buttonPanel, BorderLayout.NORTH);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("LLP", null, llpPanel, "Low Level Protocol");
tabbedPane.addTab("POS",null, posPanel, "Point Of Sale");
tabbedPane.addTab("Test", null, testPanel, "Test");
JPanel tabsPanel = new JPanel(new BorderLayout());
tabsPanel.add(tabbedPane);
frame.add(tabsPanel, BorderLayout.CENTER);
frame.pack();
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
JPanels use FlowLayout by default so applying BorderLayout constraints such as PAGE_END will have no effect. You need to set the layout of the panel:
llpPanel.setLayout(new BorderLayout());
Then you will encounter the problem of components displacing themselves in the BorderLayout.CENTER position. The solution is to create another JPanel as a container for the components other than logbox on llpPanel.
JPanel newButtonPanel = new JPanel();
newButtonPanel.add(online);
...
llpPanel.add(newButtonPanel);
JScrollPane scrollPane = new JScrollPane(logbox) {
#Override
public java.awt.Dimension getPreferredSize() {
return new Dimension(500, 500);
};
};
llpPanel.add(scrollPane, BorderLayout.PAGE_END);
Use a JScrollPane rather than adding the JTextArea directly to the container.
Set the component's preferred size property rather than its size, and add it to BorderLayout.SOUTH. For BorderLayout layouts, the container will try to use preferred sizes for the edges (north,south,east and west) and resize the center accordingly.
A short snipped example to illustrate. The view is a panel, which will have the text area at the bottom that is 50 high. This is done by adding the JTextArea component at BorderLayout.SOUTH and set the preferred size property at Dimension(0,50). The rest of the view is filled with a panel. This panel is placed at the BorderLayout.CENTER and will be resized by the layout manager.
JPanel view = new JPanel( );
view.setSize( 800, 600 );
view.setLayout( new BorderLayout( ) );
JPanel topArea = new JPanel( );
JTextArea textArea = new JTextArea( );
textArea.setPreferredSize( new Dimension( 0, 50 ) );
view.add( topArea, BorderLayout.CENTER );
view.add( textArea, BorderLayout.SOUTH );
I am adding a 2 jpanel (CENTER AND PAGE_END) to another Jpanel that goes in a JFrame. There is a HUGE gap between the 2 panels (panneauDateDebut and panneauDateFin) that I would like to eliminate. I have tried to set them in different configurations (start/center, start/end, center/end) but without luck. How can this be done ?
edit to have a working code
import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class CreerModificationAbsence extends JDialog {
private JPanel modificationAbsence1, modificationAbsence2,
modificationAbsence3, panneauDateDebut, panneauDateFin;
private JButton modifier, annuler;
private JLabel raison, prenomNomEmpl, prenomNomChef;
private JComboBox<String> raisonC, heureDebutC, heureFinC, minuteDebutC,
minuteFinC;
private JTextField prenomNomEmplT, prenomnomChefT;
private final String[] raisonAbsence = { "Malade" };
private JLabel dateDebut, dateFin;
private JTextField dateDebutT, dateFinT;
private final String[] heures = { "00" };
private final String[] minutes = { "00", "15", "30", "45" };
private BorderLayout gestionnaireComposant;
private GridLayout gridGestionnaireComposant;
private FlowLayout panneauMilieuLayout;
final FlowLayout gestionnaireComposantBas;
public CreerModificationAbsence() {
super((Frame) null, "Modification - Absence d'employé", true);
setPreferredSize(new Dimension(600, 250));
setAlwaysOnTop(true);
setResizable(false);
setLocation(400, 200);
setAlwaysOnTop(true);
gestionnaireComposant = new BorderLayout();
this.getContentPane().setLayout(gestionnaireComposant);
// Modification Panneau Haut
modificationAbsence1 = new JPanel();
gridGestionnaireComposant = new GridLayout(3, 2, 2, 2);
modificationAbsence1.setLayout(gridGestionnaireComposant);
raison = new JLabel("Raison : ");
raisonC = new JComboBox<>(raisonAbsence);
raisonC.setEditable(true);
prenomNomEmpl = new JLabel("Prénom et Nom de l'employé : ");
prenomNomEmplT = new JTextField();
prenomNomChef = new JLabel("Prénom et Nom du chef d'équipe : ");
prenomnomChefT = new JTextField();
modificationAbsence1.add(raison);
modificationAbsence1.add(raisonC);
modificationAbsence1.add(prenomNomEmpl);
modificationAbsence1.add(prenomNomEmplT);
modificationAbsence1.add(prenomNomChef);
modificationAbsence1.add(prenomnomChefT);
// Modification Panneau Milieu
modificationAbsence2 = new JPanel();
panneauDateDebut = new JPanel();
panneauDateFin = new JPanel();
panneauMilieuLayout = new FlowLayout();
panneauDateDebut.setLayout(panneauMilieuLayout);
panneauDateDebut.setPreferredSize(new Dimension(600, 0));
panneauDateDebut.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
panneauDateFin.setLayout(panneauMilieuLayout);
panneauDateFin.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
panneauDateFin.setPreferredSize(new Dimension(600, 113));
modificationAbsence2.setLayout(new BorderLayout(0,0));
dateDebutT = new JTextField(12);
heureDebutC = new JComboBox<>(heures);
minuteDebutC = new JComboBox<>(minutes);
dateFinT = new JTextField(12);
heureFinC = new JComboBox<>(heures);
minuteFinC = new JComboBox<>(minutes);
dateDebut = new JLabel("Date de début :");
dateFin = new JLabel("Date de fin :");
dateDebutT.setPreferredSize(new Dimension(125, 20));
dateFinT.setPreferredSize(new Dimension(125, 20));
dateDebut.setPreferredSize(new Dimension(125, 20));
dateFin.setPreferredSize(new Dimension(125, 20));
heureDebutC.setPreferredSize(new Dimension(130, 20));
minuteDebutC.setPreferredSize(new Dimension(130, 20));
heureFinC.setPreferredSize(new Dimension(130, 20));
minuteFinC.setPreferredSize(new Dimension(130, 20));
panneauDateDebut.add(dateDebut);
panneauDateDebut.add(dateDebutT);
panneauDateDebut.add(heureDebutC);
panneauDateDebut.add(minuteDebutC);
panneauDateFin.add(dateFin);
panneauDateFin.add(dateFinT);
panneauDateFin.add(heureFinC);
panneauDateFin.add(minuteFinC);
modificationAbsence2.add(panneauDateDebut, BorderLayout.CENTER);
modificationAbsence2.add(panneauDateFin, BorderLayout.PAGE_END);
// Modification Panneau Bas
modificationAbsence3 = new JPanel();
gestionnaireComposantBas = new FlowLayout(FlowLayout.RIGHT);
modificationAbsence3.setLayout(gestionnaireComposantBas);
modifier = new JButton("Modifier");
annuler = new JButton("Annuler");
modificationAbsence3.add(modifier);
modificationAbsence3.add(annuler);
this.add(modificationAbsence1, BorderLayout.NORTH);
this.add(modificationAbsence2, BorderLayout.CENTER);
this.add(modificationAbsence3, BorderLayout.SOUTH);
/*this.*/setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.pack();
/*this.*/setVisible(true);
}
public static void main(String s[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
CreerModificationAbsence textf = new CreerModificationAbsence();
}
});
}
}
Well for starters (and for enders, don't know if this is english or not): don't call setPreferredSize()! This is what is causing all your problems. Stop using that (forever in your life ~ bad sense of humour, don't take it harsh) and you will solve all your problems.
Try this instead:
import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class CreerModificationAbsence extends JDialog {
private JPanel modificationAbsence1, modificationAbsence2, modificationAbsence3, panneauDateDebut, panneauDateFin;
private JButton modifier, annuler;
private JLabel raison, prenomNomEmpl, prenomNomChef;
private JComboBox<String> raisonC, heureDebutC, heureFinC, minuteDebutC, minuteFinC;
private JTextField prenomNomEmplT, prenomnomChefT;
private final String[] raisonAbsence = { "Malade" };
private JLabel dateDebut, dateFin;
private JTextField dateDebutT, dateFinT;
private final String[] heures = { "00" };
private final String[] minutes = { "00", "15", "30", "45" };
private BorderLayout gestionnaireComposant;
private GridLayout gridGestionnaireComposant;
private FlowLayout panneauMilieuLayout;
final FlowLayout gestionnaireComposantBas;
public CreerModificationAbsence() {
super((Frame) null, "Modification - Absence d'employé", true);
// setPreferredSize(new Dimension(600, 250));
setAlwaysOnTop(true);
setResizable(false);
setAlwaysOnTop(true);
gestionnaireComposant = new BorderLayout();
this.getContentPane().setLayout(gestionnaireComposant);
// Modification Panneau Haut
modificationAbsence1 = new JPanel();
gridGestionnaireComposant = new GridLayout(3, 2, 2, 2);
modificationAbsence1.setLayout(gridGestionnaireComposant);
raison = new JLabel("Raison : ");
raisonC = new JComboBox(raisonAbsence);
raisonC.setEditable(true);
prenomNomEmpl = new JLabel("Prénom et Nom de l'employé : ");
prenomNomEmplT = new JTextField();
prenomNomChef = new JLabel("Prénom et Nom du chef d'équipe : ");
prenomnomChefT = new JTextField();
modificationAbsence1.add(raison);
modificationAbsence1.add(raisonC);
modificationAbsence1.add(prenomNomEmpl);
modificationAbsence1.add(prenomNomEmplT);
modificationAbsence1.add(prenomNomChef);
modificationAbsence1.add(prenomnomChefT);
// Modification Panneau Milieu
modificationAbsence2 = new JPanel();
panneauDateDebut = new JPanel();
panneauDateFin = new JPanel();
panneauMilieuLayout = new FlowLayout();
panneauDateDebut.setLayout(panneauMilieuLayout);
panneauDateDebut.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
panneauDateFin.setLayout(panneauMilieuLayout);
panneauDateFin.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
dateDebutT = new JTextField(12);
heureDebutC = new JComboBox(heures);
minuteDebutC = new JComboBox(minutes);
dateFinT = new JTextField(12);
heureFinC = new JComboBox(heures);
minuteFinC = new JComboBox(minutes);
dateDebut = new JLabel("Date de début :");
dateFin = new JLabel("Date de fin :");
panneauDateDebut.add(dateDebut);
panneauDateDebut.add(dateDebutT);
panneauDateDebut.add(heureDebutC);
panneauDateDebut.add(minuteDebutC);
panneauDateFin.add(dateFin);
panneauDateFin.add(dateFinT);
panneauDateFin.add(heureFinC);
panneauDateFin.add(minuteFinC);
modificationAbsence2.add(panneauDateDebut, BorderLayout.CENTER);
modificationAbsence2.add(panneauDateFin, BorderLayout.PAGE_END);
// Modification Panneau Bas
modificationAbsence3 = new JPanel();
gestionnaireComposantBas = new FlowLayout(FlowLayout.RIGHT);
modificationAbsence3.setLayout(gestionnaireComposantBas);
modifier = new JButton("Modifier");
annuler = new JButton("Annuler");
modificationAbsence3.add(modifier);
modificationAbsence3.add(annuler);
this.add(modificationAbsence1, BorderLayout.NORTH);
this.add(modificationAbsence2, BorderLayout.CENTER);
this.add(modificationAbsence3, BorderLayout.SOUTH);
/*this.*/setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.pack();
setLocationRelativeTo(null);
/*this.*/setVisible(true);
}
public static void main(String s[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
CreerModificationAbsence textf = new CreerModificationAbsence();
}
});
}
}
The problem you're experiencing is because you used setPreferredSize on the JDialog. So what happens is that the Dialog is required to be the given size. Because it now has to be that size, somethings got to give. That's where the LayoutManagers take over. In BorderLayout, whatever is in the Center will always stretch.
You can see what's happening if you set the background of your two panels you're having problems with:
panneauDateDebut = new JPanel();
panneauDateDebut.setOpaque(true);
panneauDateDebut.setBackground(Color.blue);
panneauDateFin = new JPanel();
panneauDateFin.setOpaque(true);
panneauDateFin.setBackground(Color.green);
The solution (that Guillaume pointed out as I'm writing) is to stop using the setPreferredSize. So if your constructor looks like the following, you problem should be fixed:
public PageCentering() {
super((Frame) null, "Modification - Absence d'employé", true);
//setPreferredSize(new Dimension(600, 250));
...
}