JTable not showing up on JFrame (Java) - java

I'm having a problem with a JFrame not showing a JTable that is added to it. I've tried getContentPane().add(..), I've switched to just add to keep the code a little shorter. Any help is more than appreciated!
package com.embah.Accgui;
import java.awt.*;
import javax.swing.*;
public class accCreator extends JFrame {
private String[] columnNames = {"Username", "Password", "Members", "World"};
private Object[][] data = {{"b", "b", "b", "b"},
{ "e", "e", "e", "e"}};
private JTable tbl_Accounts;
private JScrollPane scrollPane;
private JLabel lbl_Account = new JLabel();
private JLabel lbl_Username = new JLabel();
private JLabel lbl_Password = new JLabel();
private JLabel lbl_Homeworld = new JLabel();
private JButton btn_Select = new JButton();
private JButton btn_Addacc = new JButton();
private JButton btn_Delacc = new JButton();
private JTextArea txt_Username = new JTextArea();
private JTextArea txt_Password = new JTextArea();
private JTextArea txt_Homeworld = new JTextArea();
private JCheckBox cbox_Members = new JCheckBox();
private JCheckBox cbox_RanWrld = new JCheckBox();
public accCreator() {
setLayout(null);
setupGUI();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void setupGUI() {
tbl_Accounts = new JTable(data, columnNames);
tbl_Accounts.setLocation(5, 30);
tbl_Accounts.setPreferredScrollableViewportSize(new Dimension(420, 250));
tbl_Accounts.setFillsViewportHeight(true);
tbl_Accounts.setVisible(true);
add(tbl_Accounts);
scrollPane = new JScrollPane(tbl_Accounts);
add(scrollPane);
lbl_Account.setLocation(4, 5);
lbl_Account.setSize(100, 20);
lbl_Account.setText("Select Account:");
add(lbl_Account);
lbl_Username.setLocation(5, 285);
lbl_Username.setSize(70, 20);
lbl_Username.setText("Username:");
add(lbl_Username);
lbl_Password.setLocation(5, 310);
lbl_Password.setSize(70, 20);
lbl_Password.setText("Password:");
add(lbl_Password);
lbl_Homeworld.setLocation(310, 310);
lbl_Homeworld.setSize(80, 20);
lbl_Homeworld.setText("Home World:");
add(lbl_Homeworld);
btn_Select.setLocation(305, 5);
btn_Select.setSize(120, 20);
btn_Select.setText("Select Account");
add(btn_Select);
btn_Addacc.setLocation(300, 285);
btn_Addacc.setSize(60, 20);
btn_Addacc.setText("Add");
btn_Addacc.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
String worldSel = "";
if(cbox_RanWrld.isSelected()){
worldSel = "Random";
} else {
worldSel = txt_Homeworld.getText();
}
Object[] row = {txt_Username.getText(), txt_Password.getText(), cbox_Members.isSelected(), worldSel};
DefaultTableModel model = (DefaultTableModel) tbl_Accounts.getModel();
model.addRow(row);
}
});
add(btn_Addacc);
btn_Delacc.setLocation(365, 285);
btn_Delacc.setSize(60, 20);
btn_Delacc.setText("Del");
btn_Delacc.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel model = (DefaultTableModel) tbl_Accounts.getModel();
}
});
add(btn_Delacc);
txt_Username.setLocation(80, 285);
txt_Username.setSize(100, 20);
txt_Username.setText("");
txt_Username.setRows(5);
txt_Username.setColumns(5);
add(txt_Username);
txt_Password.setLocation(80, 310);
txt_Password.setSize(100, 20);
txt_Password.setText("");
txt_Password.setRows(5);
txt_Password.setColumns(5);
txt_Password.setTabSize(0);
add(txt_Password);
txt_Homeworld.setLocation(395, 310);
txt_Homeworld.setSize(30, 20);
txt_Homeworld.setText("82");
txt_Homeworld.setRows(5);
txt_Homeworld.setColumns(5);
txt_Homeworld.setTabSize(0);
add(txt_Homeworld);
cbox_Members.setLocation(185, 285);
cbox_Members.setSize(80, 20);
cbox_Members.setText("Members");
cbox_Members.setSelected(false);
add(cbox_Members);
cbox_RanWrld.setLocation(185, 310);
cbox_RanWrld.setSize(115, 20);
cbox_RanWrld.setText("Random World");
cbox_RanWrld.setSelected(false);
add(cbox_RanWrld);
setTitle("Account Manager");
setSize(440, 370);
setVisible(true);
setResizable(false);
}
public static void main(String args[]) {
new accCreator();
}
}

I know thats not the problem tho because everything else shows up just fine
Oh... really? Not in my computer...
Let's have a picture of your actual GUI shown in my PC:
Does the GUI looks the same in your computer? I bet no.
But... why does it looks like that in my PC?
Well, as stated above in the comments by #MadProgrammer this is because of the setLayout(null); line. You might want to read Why is it frowned upon to use a null layout in Java Swing? for more information.
Now, that being said, you should also want to read and learn how to use the various layout managers that will let you create complex GUIs.
In your code you never set the location / bounds for scrollPane, and the size of it, so the component has a default size of 0, 0.
But... I think it's better to show you how you can get a really similar GUI (I'm in a hurry so I didn't make an even more similar GUI). You can copy-paste my code and see the same output (with slight differences because of the OS maybe) but text won't be cropped.
The code that produces the above image is this one:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridLayout;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class AccountCreator {
private JFrame frame;
private JPanel mainPane;
private JPanel topPane;
private JPanel tablePane;
private JPanel bottomPane;
private JLabel selectAccountLabel;
private JLabel userNameLabel;
private JLabel passwordLabel;
private JLabel homeWorldLabel;
private JTextField userNameField;
private JTextField homeWorldField;
private JPasswordField passwordField;
private JCheckBox membersBox;
private JCheckBox randomBox;
private JButton selectAccountButton;
private JButton addButton;
private JButton deleteButton;
private JTable table;
private JScrollPane scroll;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new AccountCreator().createAndShowGui();
}
});
}
public void createAndShowGui() {
frame = new JFrame(getClass().getSimpleName());
int rows = 30;
int cols = 3;
String[][] data = new String[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
data[i][j] = i + "-" + j;
}
}
String[] columnNames = { "Column1", "Column2", "Column3" };
table = new JTable(data, columnNames);
scroll = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
table.setPreferredScrollableViewportSize(new Dimension(420, 250));
table.setFillsViewportHeight(true);
selectAccountLabel = new JLabel("Select Account");
userNameLabel = new JLabel("Username: ");
passwordLabel = new JLabel("Password: ");
homeWorldLabel = new JLabel("Home world");
selectAccountButton = new JButton("Select Account");
addButton = new JButton("Add");
deleteButton = new JButton("Del");
userNameField = new JTextField(10);
passwordField = new JPasswordField(10);
homeWorldField = new JTextField(3);
membersBox = new JCheckBox("Members");
randomBox = new JCheckBox("Random world");
topPane = new JPanel();
topPane.setLayout(new BorderLayout());
topPane.add(selectAccountLabel, BorderLayout.WEST);
topPane.add(selectAccountButton, BorderLayout.EAST);
tablePane = new JPanel();
tablePane.add(scroll);
bottomPane = new JPanel();
bottomPane.setLayout(new GridLayout(0, 5, 3, 3));
bottomPane.add(userNameLabel);
bottomPane.add(userNameField);
bottomPane.add(membersBox);
bottomPane.add(addButton);
bottomPane.add(deleteButton);
bottomPane.add(passwordLabel);
bottomPane.add(passwordField);
bottomPane.add(randomBox);
bottomPane.add(homeWorldLabel);
bottomPane.add(homeWorldField);
mainPane = new JPanel();
mainPane.setLayout(new BoxLayout(mainPane, BoxLayout.PAGE_AXIS));
frame.add(topPane, BorderLayout.NORTH);
frame.add(tablePane, BorderLayout.CENTER);
frame.add(bottomPane, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Also, you might have noticed that the main() method is different, well, the code inside it is placing the program on the Event Dispatch Thread (EDT).
So, be sure to include it in your future programs

Related

I want my button not in the same row as my choose buttons in my gui? How will I do that?

How do I add a break to put my "Make pokemon" buttons and textarea not in the same row as my "Pokemon choice." I'm trying to put an empty JLabel, but I don't think it works.
public class PokemonPanel extends JPanel {
private JLabel lTitle = new JLabel("Pokemon");
private JLabel lMsg = new JLabel(" ");
private JButton bDone = new JButton(" Make Pokemon ");
private JButton bClear = new JButton(" Clear ");
private JPanel topSubPanel = new JPanel();
private JPanel centerSubPanel = new JPanel();
private JPanel bottomSubPanel = new JPanel();
private GUIListener listener = new GUIListener();
private Choice chSpe = new Choice();
private JLabel lEmp = new JLabel(" ");
private PokemonGUILizylf st;
private final int capacity = 10;
private PokemonGUILizylf[ ] stArr = new PokemonGUILizylf[capacity];
private int count = 0;
private String sOut = new String("");
private JTextArea textArea = new JTextArea(400, 500);
private JTextArea textArea2 = new JTextArea(400, 500);
private JScrollPane scroll = new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
public PokemonPanel() {
this.setLayout(new BorderLayout());
this.setPreferredSize(new Dimension(400, 500));
topSubPanel.setBackground(Color.cyan);
centerSubPanel.setBackground(Color.white);
bottomSubPanel.setBackground(Color.white);
topSubPanel.add(lTitle);
this.add("North", topSubPanel);
JLabel lSpe = new JLabel("Pokemon Available: ");
JLabel lEmp = new JLabel(" ");
JLabel lNew = new JLabel("New Pokemon: ");
//add choices to the choice dropdown list
chSpe.add("Choose");
chSpe.add("Bulbasaur");
chSpe.add("Venusaur");
chSpe.add("Ivysaur");
chSpe.add("Squirtle");
chSpe.add("Wartortle");
chSpe.add("Blastoise");
chSpe.add("Charmander");
chSpe.add("Charmeleon");
chSpe.add("Charizard");
centerSubPanel.add(lSpe);
centerSubPanel.add(chSpe);
centerSubPanel.add(lEmp);
centerSubPanel.add(bDone);
centerSubPanel.add(lNew);
textArea.setPreferredSize(new Dimension(500, 200));
textArea.setEditable(false);
textArea2.setPreferredSize(new Dimension(500, 200));
textArea2.setEditable(false);
textArea.setBackground(Color.white);
textArea.setEditable(false);
scroll.setBorder(null);
centerSubPanel.add(scroll); //add scrollPane to panel, textArea inside.
scroll.getVerticalScrollBar().setPreferredSize(new Dimension(10, 0));
add("Center", centerSubPanel);
bottomSubPanel.add(lMsg);
bDone.addActionListener(listener); //add listener to button
bottomSubPanel.add(bClear);
bClear.addActionListener(listener); //add listener to button
//add bottomSubPanel sub-panel to South area of main panel
add("South", bottomSubPanel);
}
This is what my GUI looks like:
enter image description here
But it should show like this:
enter image description here
Can someone explain to me how I can do that?
Use a different layout manager (other then default FlowLayout which JPanel uses)
See Laying Out Components Within a Container for more details.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.DefaultComboBoxModel;
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.JTextArea;
import javax.swing.border.EmptyBorder;
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 PokemonPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PokemonPanel extends JPanel {
private JLabel lTitle = new JLabel("Pokemon");
// private JLabel lMsg = new JLabel(" ");
private JButton bDone = new JButton("Make Pokemon ");
private JButton bClear = new JButton("Clear");
private JPanel topSubPanel = new JPanel();
private JPanel centerSubPanel = new JPanel(new GridBagLayout());
private JPanel bottomSubPanel = new JPanel();
// private GUIListener listener = new GUIListener();
private JComboBox<String> chSpe = new JComboBox<>();
private JLabel lEmp = new JLabel(" ");
// private PokemonGUILizylf st;
private final int capacity = 10;
// private PokemonGUILizylf[] stArr = new PokemonGUILizylf[capacity];
// private int count = 0;
// private String sOut = new String("");
// private JTextArea textArea = new JTextArea(400, 500);
// private JTextArea textArea2 = new JTextArea(400, 500);
//
// private JScrollPane scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
// JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
public PokemonPanel() {
this.setLayout(new BorderLayout());
// this.setPreferredSize(new Dimension(400, 500));
topSubPanel.setBackground(Color.cyan);
centerSubPanel.setBackground(Color.white);
bottomSubPanel.setBackground(Color.white);
topSubPanel.add(lTitle);
this.add("North", topSubPanel);
JLabel lSpe = new JLabel("Pokemon Available: ");
JLabel lNew = new JLabel("New Pokemon: ");
//add choices to the choice dropdown list
DefaultComboBoxModel<String> chSpeModel= new DefaultComboBoxModel<>();
chSpeModel.addElement("Choose");
chSpeModel.addElement("Bulbasaur");
chSpeModel.addElement("Venusaur");
chSpeModel.addElement("Ivysaur");
chSpeModel.addElement("Squirtle");
chSpeModel.addElement("Wartortle");
chSpeModel.addElement("Blastoise");
chSpeModel.addElement("Charmander");
chSpeModel.addElement("Charmeleon");
chSpeModel.addElement("Charizard");
chSpe.setModel(chSpeModel);
centerSubPanel.setBorder(new EmptyBorder(4, 4, 4, 4));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(4, 4, 4, 4);
gbc.anchor = GridBagConstraints.LINE_END;
centerSubPanel.add(lSpe, gbc);
gbc.gridx++;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = GridBagConstraints.REMAINDER;
centerSubPanel.add(chSpe);
gbc.anchor = GridBagConstraints.NORTH;
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy++;
centerSubPanel.add(bDone, gbc);
gbc.gridx++;
gbc.anchor = GridBagConstraints.FIRST_LINE_END;
centerSubPanel.add(lNew, gbc);
gbc.gridx++;
gbc.gridheight = gbc.REMAINDER;
centerSubPanel.add(new JScrollPane(new JTextArea(10, 10)), gbc);
// textArea.setEditable(false);
// textArea2.setEditable(false);
//
// textArea.setBackground(Color.white);
// textArea.setEditable(false);
// scroll.setBorder(null);
// centerSubPanel.add(scroll); //add scrollPane to panel, textArea inside.
// scroll.getVerticalScrollBar().setPreferredSize(new Dimension(10, 0));
add("Center", centerSubPanel);
// bottomSubPanel.add(lMsg);
// bDone.addActionListener(listener); //add listener to button
bottomSubPanel.add(bClear);
// bClear.addActionListener(listener); //add listener to button
//add bottomSubPanel sub-panel to South area of main panel
add("South", bottomSubPanel);
}
}
}
Also, avoid using setPreferredSize, let the layout managers do their job. In the example I'm used insets (from GridBagConstraints) and an EmptyBorder to add some additional space around the components
Also, be careful of using AWT components (ie Choice), they don't always play nicely with Swing. In this case, you should be using JComboBox

How to make a new JButton instance in a existing button group everytime a Jbutton is pressed(clicked)

This may come off as an odd question, but I would like to make a program that makes a new Jbutton instance in an existing group every time a button(called new) is pressed. It will be added under the previously added button, all buttons must be part of a group(so when one button is pressed it will deselect previously selected button if the button in the group is pressed) and should be able to make an infinite number of buttons given n number of clicks. Here is what I have so far, but honestly I don't even know how to approach this one.
public static void makebuttonpane() {
buttonpane.setLayout(new GridBagLayout());
GridBagConstraints d = new GridBagConstraints();
nbutton = new JButton("New");
d.insets = new Insets(10, 10, 0, 10);
d.anchor = GridBagConstraints.PAGE_START;
buttonpane.add(nbutton,d);
nbutton.addActionListener(new ButtonMaker());
//d.anchor = GridBagConstraints.CENTER;
}
public static void addbutton(JButton button) {
System.out.println("button made");
buttonpane.removeAll();
nbutton = new JButton("New");
d.insets = new Insets(10, 10, 0, 10);
d.anchor = GridBagConstraints.PAGE_START;
buttonpane.add(nbutton,d);
nbutton.addActionListener(new ButtonMaker());
d.gridx=0;
System.out.println(ButtonMaker.getNumb());
d.gridy= ButtonMaker.getNumb();
buttonpane.add(button,d);
frame.setVisible(true);
buttonpane.validate();
}
public static void makebuttonpane() {
buttonpane.setLayout(new GridBagLayout());
GridBagConstraints d = new GridBagConstraints();
nbutton = new JButton("New");
d.insets = new Insets(10, 10, 0, 10);
d.anchor = GridBagConstraints.PAGE_START;
buttonpane.add(nbutton,d);
nbutton.addActionListener(new ButtonMaker());
//d.anchor = GridBagConstraints.CENTER;
}
public static void addbutton(JButton button) {
System.out.println("button made");
buttonpane.removeAll();
nbutton = new JButton("New");
d.insets = new Insets(10, 10, 0, 10);
d.anchor = GridBagConstraints.PAGE_START;
buttonpane.add(nbutton,d);
nbutton.addActionListener(new ButtonMaker());
d.gridx=0;
System.out.println(ButtonMaker.getNumb());
d.gridy= ButtonMaker.getNumb();
buttonpane.add(button,d);
frame.setVisible(true);
buttonpane.validate();
}
class ButtonMaker implements ActionListener{
public static int i=1;
public void actionPerformed(ActionEvent e) {
//System.out.println("I hear you");
//System.out.println(i);
JButton button = new JButton("Button "+i);
MultiListener.addbutton(button);
i++;
}
public static int getNumb() {
return i;
}
}
It adds the first button instance but pressing 'New' only changes that first created button instead of making a new one underneath
I created a GUI that adds a JButton when you click on the "Add Button" button.
Feel free to modify this any way you want.
Mainly, I separated the construction of the JFrame, the construction of the JPanel, and the action listener. Focusing on one part at a time, I was able to code and test this GUI quickly.
import java.awt.BorderLayout;
import java.awt.Dimension;
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.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public class JButtonCreator implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JButtonCreator());
}
private static int buttonCount = 0;
private JButtonPanel buttonPanel;
#Override
public void run() {
JFrame frame = new JFrame("JButton Creator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buttonPanel = new JButtonPanel();
JScrollPane scrollPane = new JScrollPane(
buttonPanel.getPanel());
frame.add(scrollPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public class JButtonPanel {
private ButtonGroup buttonGroup;
private JPanel buttonPanel;
private JPanel panel;
public JButtonPanel() {
createPartControl();
}
private void createPartControl() {
panel = new JPanel();
panel.setPreferredSize(new Dimension(640, 480));
panel.setLayout(new BorderLayout());
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(0, 5));
buttonGroup = new ButtonGroup();
panel.add(buttonPanel, BorderLayout.CENTER);
JButton newButton = new JButton("Add Button");
newButton.addActionListener(new ButtonListener(this));
panel.add(newButton, BorderLayout.AFTER_LAST_LINE);
}
public void addJButton() {
String text = "Button " + ++buttonCount;
JButton button = new JButton(text);
buttonPanel.add(button);
buttonGroup.add(button);
}
public JPanel getPanel() {
return panel;
}
}
public class ButtonListener implements ActionListener {
private JButtonPanel buttonPanel;
public ButtonListener(JButtonPanel buttonPanel) {
this.buttonPanel = buttonPanel;
}
#Override
public void actionPerformed(ActionEvent event) {
buttonPanel.addJButton();
buttonPanel.getPanel().revalidate();;
}
}
}

How do I get the textfields and the labels to sit in a 7x3 grid?

The first column in my grid always comes out right but then the rest begin replacing the other cells. Also the border layout does not seem to be functioning. I do not know what the problem is. It should have the title on top, a 7x3 grid in the center and the buttons on the bottom. Please help! Thank you!
import java.awt.BorderLayout;
import java.awt.GridLayout;
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;
import javax.swing.JTextField;
public class GUI extends JFrame{
private JPanel mainPanel,titlePanel, fieldPanel, buttonPanel;
private JLabel title, teams, totalP, wlt;
private JTextField team1, team2, team3, team4, team5, team6, total1, total2, total3, total4, total5, total6, wlt1, wlt2, wlt3, wlt4, wlt5, wlt6;
private JButton read, calc, champWin, earthCW, exit;
final private int WINDOW_HEIGHT = 400;
final private int WINDOW_WIDTH = 900;
public GUI(){
buildtitlePanel();
buildfieldPanel();
buildbuttonPanel();
buildmainPanel();
setTitle("Desert Soccer League");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void buildmainPanel() {
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(titlePanel, BorderLayout.NORTH);
mainPanel.add(fieldPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
add(mainPanel);
}
private void buildtitlePanel() {
titlePanel = new JPanel();
title = new JLabel();
title.setText("2014 Desert Soccer League Totals");
titlePanel.add(title);
}
private void buildfieldPanel() {
fieldPanel = new JPanel();
fieldPanel.setLayout(new GridLayout(7, 3));
teams = new JLabel();
teams.setText("Teams");
totalP = new JLabel();
totalP.setText("Total Points");
wlt = new JLabel();
wlt.setText("Win-Loss-Tie");
team1 = new JTextField(10);
team2 = new JTextField(10);
team3 = new JTextField(10);
team4 = new JTextField(10);
team5 = new JTextField(10);
team6 = new JTextField(10);
total1 = new JTextField(10);
total2 = new JTextField(10);
total3 = new JTextField(10);
total4 = new JTextField(10);
total5 = new JTextField(10);
total6 = new JTextField(10);
wlt1 = new JTextField(10);
wlt2 = new JTextField(10);
wlt3 = new JTextField(10);
wlt4 = new JTextField(10);
wlt5 = new JTextField(10);
wlt6 = new JTextField(10);
team1.setEditable(false);
team2.setEditable(false);
team3.setEditable(false);
team4.setEditable(false);
team5.setEditable(false);
team6.setEditable(false);
total1.setEditable(false);
total2.setEditable(false);
total3.setEditable(false);
total4.setEditable(false);
total5.setEditable(false);
total6.setEditable(false);
wlt1.setEditable(false);
wlt2.setEditable(false);
wlt3.setEditable(false);
wlt4.setEditable(false);
wlt5.setEditable(false);
wlt6.setEditable(false);
fieldPanel.add(teams);
fieldPanel.add(team1);
fieldPanel.add(team2);
fieldPanel.add(team3);
fieldPanel.add(team4);
fieldPanel.add(team5);
fieldPanel.add(team6);
fieldPanel.add(totalP);
fieldPanel.add(total1);
fieldPanel.add(total2);
fieldPanel.add(total3);
fieldPanel.add(total4);
fieldPanel.add(total5);
fieldPanel.add(total6);
fieldPanel.add(wlt);
fieldPanel.add(wlt1);
fieldPanel.add(wlt2);
fieldPanel.add(wlt3);
fieldPanel.add(wlt4);
fieldPanel.add(wlt5);
fieldPanel.add(wlt6);
}
private void buildbuttonPanel() {
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 5));
read = new JButton();
calc = new JButton();
champWin = new JButton();
earthCW = new JButton();
exit = new JButton();
read.setText("Read Input File");
read.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
calc.setText("Calculate Points");
calc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
champWin.setText("Championship Winner");
champWin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
earthCW.setText("Earth Cup Winner");
earthCW.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
exit.setText("Exit");
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
buttonPanel.add(read);
buttonPanel.add(calc);
buttonPanel.add(champWin);
buttonPanel.add(earthCW);
buttonPanel.add(exit);
}
}
mainPanel = new JPanel();
mainPanel.add(titlePanel, BorderLayout.NORTH);
mainPanel.add(fieldPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
By default a JPanel uses a FlowLayout. If you want to use a BorderLayout, then you need to set the layout on the panel:
mainPanel = new JPanel( new BorderLayout() );
The GridLayout fills out the rows first so the code should be:
fieldPanel.add(teams);
fieldPanel.add(totalP);
fieldPanel.add(wlt);
fieldPanel.add(team1);
fieldPanel.add(total1);
fieldPanel.add(wlt1);
...
Also note that in your code you are adding the total? fields twice (which won't do anything), instead of the team? fields.
Another way to specify the grid is to just use:
fieldPanel.setLayout(new GridLayout(0, 3));
This tells the grid to add 3 components to each row then move on to the next row. This way you don't have to worry about the exact number of rows.
To add to camickr answer you're also adding the same total fields multiple times, so change this:
fieldPanel.add(teams);
fieldPanel.add(total1);
fieldPanel.add(total2);
fieldPanel.add(total3);
fieldPanel.add(total4);
fieldPanel.add(total5);
fieldPanel.add(total6);
to
fieldPanel.add(teams);
fieldPanel.add(team1);
fieldPanel.add(team2);
fieldPanel.add(team3);
fieldPanel.add(team4);
fieldPanel.add(team5);
fieldPanel.add(team6);
This is what is causing your display issue.
Your code should look like:
fieldPanel.add(teams);
fieldPanel.add(totalP);
fieldPanel.add(wlt);
fieldPanel.add(team1);
fieldPanel.add(total1);
fieldPanel.add(wlt1);
fieldPanel.add(team2);
fieldPanel.add(total2);
fieldPanel.add(wlt2);
// etc.

Auto-scroll JTextArea with ScrollPane?

I'm trying to build a dynamic log window (basically a auto-scrolling jtext-area).
The problem I'm having is that although I'm printing 500 lines in the text area, it displays as below:
Below you have my code:
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.DefaultCaret;
public class Main {
private static JFrame mainFrame;
public static void main(String args[]) {
mainFrame = new JFrame();
mainFrame.setSize(500, 500);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ControlPanel cp = new ControlPanel();
mainFrame.add(cp);
mainFrame.setVisible(true);
}
}
class ControlPanel extends JPanel {
private JButton resetButton = new JButton("Reset");
private JPanel logPanel = new JPanel();
private JLabel actionLogsLabel = new JLabel("Action Log");
private JLabel pointsLogsLabel = new JLabel("Points Log");
private JTextArea actionLog = new JTextArea();
private JTextArea pointsLog = new JTextArea();
private JScrollPane actionScroll;
private JScrollPane pointsScroll;
public ControlPanel() {
init();
this.add(resetButton);
this.add(logPanel);
}
private void init() {
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.setAlignmentX(LEFT_ALIGNMENT);
this.logPanel.setLayout(new BoxLayout(logPanel, BoxLayout.Y_AXIS));
this.logPanel.setAlignmentX(LEFT_ALIGNMENT);
actionLog.setPreferredSize(new Dimension(500, 300));
actionLog.setMaximumSize(actionLog.getPreferredSize());
actionLog.setEditable(false);
actionLog.setWrapStyleWord(true);
DefaultCaret caret = (DefaultCaret) actionLog.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
pointsLog.setPreferredSize(new Dimension(500, 300));
pointsLog.setMaximumSize(pointsLog.getPreferredSize());
pointsLog.setEditable(false);
pointsLog.setWrapStyleWord(true);
pointsScroll = new JScrollPane(pointsLog, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
actionScroll = new JScrollPane(actionLog, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
logPanel.add(actionLogsLabel);
logPanel.add(actionScroll);
for(int i = 0; i < 500; i++) {
actionLog.setText(actionLog.getText() + "Line: " + i + "\n");
}
logPanel.add(pointsLogsLabel);
logPanel.add(pointsScroll);
}
}
Hopefully someone with a bit more Swing experience can take the time to point me the right way with this.
Never do this:
actionLog.setPreferredSize(new Dimension(500, 300));
Since by doing this you artificially restrict the size of the JTextArea causing the effect that is currently vexing you. Note also that it's generally a good idea to avoid setting preferred sizes on anything.
Instead set the column and row counts of the JTextARea. This can be done via setter methods or via a simple constructor call: JTextArea myTextArea = new JTextArea(rows, columns);
As an aside: I wonder if a JList will work better for you.
MCVE Example:
import javax.swing.*;
import javax.swing.text.DefaultCaret;
public class Main2 {
private static void createAndShowGUI() {
JPanel mainPanel = new ControlPanel();
JFrame frame = new JFrame("Main2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
class ControlPanel extends JPanel {
private static final int LOG_ROWS = 15;
private static final int LOG_COLS = 40;
private JButton resetButton = new JButton("Reset");
private JPanel logPanel = new JPanel();
private JLabel actionLogsLabel = new JLabel("Action Log");
private JLabel pointsLogsLabel = new JLabel("Points Log");
private JTextArea actionLog = new JTextArea();
private JTextArea pointsLog = new JTextArea();
private JScrollPane actionScroll;
private JScrollPane pointsScroll;
public ControlPanel() {
init();
this.add(resetButton);
this.add(logPanel);
}
private void init() {
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.setAlignmentX(LEFT_ALIGNMENT);
this.logPanel.setLayout(new BoxLayout(logPanel, BoxLayout.Y_AXIS));
this.logPanel.setAlignmentX(LEFT_ALIGNMENT);
// !! actionLog.setPreferredSize(new Dimension(500, 300));
// !! actionLog.setMaximumSize(actionLog.getPreferredSize());
actionLog.setRows(LOG_ROWS); // !!
actionLog.setColumns(LOG_COLS); // !!
actionLog.setEditable(false);
actionLog.setWrapStyleWord(true);
DefaultCaret caret = (DefaultCaret) actionLog.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
// !! pointsLog.setPreferredSize(new Dimension(500, 300));
// !! pointsLog.setMaximumSize(pointsLog.getPreferredSize());
pointsLog.setRows(LOG_ROWS); // !!
pointsLog.setColumns(LOG_COLS); // !!
pointsLog.setEditable(false);
pointsLog.setWrapStyleWord(true);
pointsScroll = new JScrollPane(pointsLog,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
actionScroll = new JScrollPane(actionLog,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
logPanel.add(actionLogsLabel);
logPanel.add(actionScroll);
for (int i = 0; i < 500; i++) {
actionLog.setText(actionLog.getText() + "Line: " + i + "\n");
}
logPanel.add(pointsLogsLabel);
logPanel.add(pointsScroll);
}
}
Edit
Example with nested layouts and JLists:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class Main2B {
private static void createAndShowGUI() {
ControlPanel2B controlPanel = new ControlPanel2B();
controlPanel.setBorder(BorderFactory.createEtchedBorder());
JPanel mainPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
mainPanel.add(controlPanel, gbc);
JFrame frame = new JFrame("Main2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
#SuppressWarnings("serial")
class ControlPanel2B extends JPanel {
private static final int LOG_ROWS = 15;
private static final int LIST_WIDTH = 500;
private JButton resetButton = new JButton("Reset");
private JPanel logPanel = new JPanel();
private JLabel actionLogsLabel = new JLabel("Action Log");
private JLabel pointsLogsLabel = new JLabel("Points Log");
private DefaultListModel<String> actionLogListModel = new DefaultListModel<>();
private JList<String> actionLogList = new JList<String>(actionLogListModel);
private DefaultListModel<String> pointsLogListModel = new DefaultListModel<>();
private JList<String> pointsLogList = new JList<String>(pointsLogListModel);
private JScrollPane actionScroll;
private JScrollPane pointsScroll;
public ControlPanel2B() {
init();
this.add(resetButton);
this.add(logPanel);
}
private void init() {
actionLogList.setVisibleRowCount(LOG_ROWS);
pointsLogList.setVisibleRowCount(LOG_ROWS);
actionLogList.setFixedCellWidth(LIST_WIDTH);
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
this.setAlignmentX(LEFT_ALIGNMENT);
this.logPanel.setLayout(new BoxLayout(logPanel, BoxLayout.Y_AXIS));
this.logPanel.setAlignmentX(LEFT_ALIGNMENT);
pointsScroll = new JScrollPane(pointsLogList,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
actionScroll = new JScrollPane(actionLogList,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
logPanel.add(actionLogsLabel);
logPanel.add(actionScroll);
for (int i = 0; i < 500; i++) {
actionLogListModel.addElement("Line: " + i);
}
logPanel.add(pointsLogsLabel);
logPanel.add(pointsScroll);
}
}

eliminate gap between Jpanel in borderLayout

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));
...
}

Categories