eliminate gap between Jpanel in borderLayout - java

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

Related

JTable not showing up on JFrame (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

JTable is not showing. How do I fix it?

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.

Using CardLayout with a JTable, and JTable.getSelectedRow() always returns -1

I want to use a CardLayout to use several JTable and with that the JTable.getSelectedRow() doesn't work. Here is what I've tried:
public void createWindow() {
// creation du tableau d'article
this.ajouterLesArticles();
// Contener principal
main = new JPanel();
this.setContentPane(main);
main.setLayout(new BorderLayout());
// Panel du haut
top = new JPanel();
title = new JLabel(titlewindow);
welcome = new JLabel("Bonjour, ");
top.setLayout(new BoxLayout(top, BoxLayout.LINE_AXIS));
top.setBackground(Color.decode("#E5E5E5"));
title.setForeground(Color.decode("#E56302"));
title.setFont(new Font("Calibri", Font.PLAIN, 20));
welcome.setFont(new Font("Calibri", Font.PLAIN, 20));
welcome.setForeground(Color.decode("#E56302"));
// Ajout des composants au panel
top.add(Box.createRigidArea(new Dimension(50, 100)));
top.add(title);
top.add(Box.createHorizontalGlue());
top.add(welcome);
top.add(Box.createRigidArea(new Dimension(40, 100)));
// top.add(piclabel);
top.add(Box.createRigidArea(new Dimension(60, 100)));
// Panel de Gauche
left = new JPanel();
left.setLayout(new GridLayout(6, 1));
left.setPreferredSize(new Dimension(150, 0));
left.setBackground(Color.decode("#E5E5E5"));
home = new JButton("<-- Accueil");
btnleft1 = new JButton(labels[0]);
btnleft2 = new JButton(labels[1]);
btnleft3 = new JButton(labels[2]);
btnleft4 = new JButton(labels[3]);
// Listeners des boutons de gauche
// btnleft4.addActionListener(new OpenParametres());
btnleft1.addActionListener(new changerPanelStock());
btnleft2.addActionListener(new changerPanelClient());
// home.addActionListener(new BackHome());
// Ajout des composants au Panel
left.add(home);
left.add(btnleft1);
left.add(btnleft2);
left.add(btnleft3);
left.add(btnleft4);
// Panel central
center = new JPanel();
center.setLayout(cl);
center.setBorder(new EmptyBorder(10, 10, 10, 10));
center.add(creationPanelStock(), "stock");
center.add(creationPanelClient(), "client");
cl.show(center,"stock");
// Ajout des panel au panel principal
main.add(top, BorderLayout.NORTH);
main.add(left, BorderLayout.WEST);
main.add(center, BorderLayout.CENTER);
}
public JPanel creationPanelStock(){
this.ajouterLesArticles();
line1 = new JPanel();
line2 = new JPanel();
line3 = new JPanel();
searchtitle = new JLabel("Rechercher un article : ");
tfsearch = new JTextField();
tfsearch.setColumns(22);
tfsearch.getDocument().addDocumentListener(new Filtre());
gsearch = new TextPrompt("Entrez un nom ou une référence",tfsearch);
add = new JButton ("Créer un article...");
remove = new JButton ("Supprimer...");
modify = new JButton ("Modifer...");
modify.setEnabled(false);
modify.addActionListener(new modifierArticle());
remove.setEnabled(false);
remove.addActionListener(new supprimer());
search = new JButton ("Rechercher");
listeArticle.setSize(300,100);
listeArticle.getSelectionModel().addListSelectionListener(new selectionliste());
listeArticle.setAutoCreateRowSorter(true);
//liste.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
//Première ligne de "center"
line1.add(add);
add.addActionListener(new NewArticle());
line1.add(modify);
line1.add(remove);
//Deuxième ligne de "center"
line2.add(searchtitle);
line2.add(tfsearch);
line2.add(search);
//troisième ligne de "center"
JScrollPane js = new JScrollPane(listeArticle);
js.setPreferredSize(new Dimension(600,120));
line3.add(js);
panelStock = new JPanel(new GridLayout(3,1,10,10));
panelStock.add(line1);
panelStock.add(line2);
panelStock.add(line3);
return panelStock;
}
I create windows with two panel and each of them has a JTable but I can't selected anything, and this listener doesn't work:
public class selectionliste implements ListSelectionListener{
#Override
public void valueChanged(ListSelectionEvent e) {
// TODO Auto-generated method stub
if (listeArticle.getSelectedRow() > -1) {
modify.setEnabled(true);
remove.setEnabled(true);
}else{
modify.setEnabled(false);
remove.setEnabled(false);
}
}
}
The table's ListSelectionModel uses -1 to indicate that the selection is empty. In the example below, each card gets its own table, and each table gets its own listener. Flip among the cards to see how the selection "sticks" to the table in each card.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.util.Random;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
/**
* #see http://stackoverflow.com/a/37644011/230513
* #see http://stackoverflow.com/a/36392696/230513
* #see http://stackoverflow.com/a/36243395/230513
*/
public class CardPanel extends JPanel {
private static final Random r = new Random();
private static final JPanel cards = new JPanel(new CardLayout());
private final String name;
public CardPanel(String name) {
super(new GridLayout(0, 1));
this.name = name;
this.add(new JLabel(name, JLabel.CENTER));
JTable table = new JTable(new String[][]{
{"A0", "B0"}, {"A1", "B1"}
}, new String[]{"A", "B"});
this.add(table);
JLabel label = new JLabel("None", JLabel.CENTER);
this.add(label);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
label.setText("Selected row: " + table.getSelectedRow());
}
}
});
}
#Override
public String toString() {
return name;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
create();
}
});
}
private static void create() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (int i = 1; i < 9; i++) {
CardPanel p = new CardPanel("Table " + String.valueOf(i));
cards.add(p, p.toString());
}
JPanel control = new JPanel();
control.add(new JButton(new AbstractAction("\u22b2Prev") {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout) cards.getLayout();
cl.previous(cards);
}
}));
control.add(new JButton(new AbstractAction("Next\u22b3") {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cl = (CardLayout) cards.getLayout();
cl.next(cards);
}
}));
f.add(cards, BorderLayout.CENTER);
f.add(control, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}

Why does my components go out of boundaries, please help me to align it with the necessary code

import net.java.dev.designgridlayout.Tag;
import net.java.dev.designgridlayout.DesignGridLayout;
import javax.swing.table.DefaultTableModel;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
class alignmentprob
{
JFrame JF;
Container C,C5;
JDesktopPane JDP;
JInternalFrame JIF5;
JLabel i5l1,i5l2,i5l3,i5l4,i5l5,i5l6,i5l7;
JTextField i5t1,i5t2,i5t3;
JComboBox<String> i5cb1;
JButton i5b1,i5b2,i5b3;
JSeparator i5sep1,i5sep2,i5sep3,i5sep4,i5sep5,i5sep6;
JTable i5Table1;
DefaultTableModel i5Model;
String[] i5Credit = {"A","B"};
String[] i5ColumnNames = {"Name","Qty","Rate/kg","rate/dzn","total amt."};
JScrollPane i5t1sp1;
public alignmentprob()
{
JF = new JFrame();
JDP = new JDesktopPane();
JF.setVisible(true);
JF.setSize(800,600);
JIF5 = new JInternalFrame("Daily Analysis",true,true, true, true);
C=JF.getContentPane();
C.add(JDP,BorderLayout.CENTER);
JIF5.setVisible(true);
JIF5.setBounds(10, 10, 600, 500);
C5 = JIF5.getContentPane();
DesignGridLayout layout5 = new DesignGridLayout(C5);
i5l1 = new JLabel("FREIGHT DETAILS");
i5l2 = new JLabel("Date : ");
i5l3 = new JLabel("SALE DETAILS");
i5l4 = new JLabel("Cash Sales : Rs. ");
i5l5 = new JLabel("Credit : ");
i5l6 = new JLabel("EXPENSES");
i5l7 = new JLabel("Food & Tea : Rs. ");
i5t1 = new JTextField(20);
i5t2 = new JTextField(20);
i5t3 = new JTextField(20);
i5cb1 = new JComboBox<String>(i5Credit);
i5b1 = new JButton("Save");
i5b2 = new JButton("Reset");
i5b3 = new JButton("Close");
i5sep1 = new JSeparator();
i5sep2 = new JSeparator();
i5sep3 = new JSeparator();
i5sep4 = new JSeparator();
i5sep5 = new JSeparator();
i5sep6 = new JSeparator();
i5Model = new DefaultTableModel(i5ColumnNames,5);
i5Table1 =new JTable(i5Model){#Override
public boolean isCellEditable(int arg0, int arg1)
{
return false;
}
};
i5t1sp1 = new JScrollPane(i5Table1);
layout5.row().left().add(i5sep1).fill().withOwnRowWidth();
layout5.row().center().add(i5l1);
layout5.row().left().add(i5sep2).fill().withOwnRowWidth();
layout5.row().grid(i5l2).add(i5t1);
layout5.row().left().add(i5sep3).fill().withOwnRowWidth();
layout5.row().center().add(i5l3);
layout5.row().left().add(i5sep4).fill().withOwnRowWidth();
layout5.row().grid(i5l4).add(i5t2);
layout5.row().grid(i5l5).add(i5cb1);
layout5.row().left().add(i5t1sp1);
layout5.row().left().add(i5sep5).fill().withOwnRowWidth();
layout5.row().center().add(i5l6);
layout5.row().left().add(i5sep6).fill().withOwnRowWidth();
layout5.row().grid(i5l7).add(i5t3);
layout5.row().center().add(i5b1).add(i5b2).add(i5b3);
JDP.add(JIF5);
}
public static void main(String args[])
{
new alignmentprob();
}
}
My problem is that the textfields are too long and go out of bounds. The table I made consists of 5 rows, but it tends to take up more space. I actually wanted to align the FREIGHT DETAILS & SALES DETAILS in parallel, separated using a vertical line. Please help me with code to do all this, so that my form looks neat and is fully visible.
My problem is that the textfields are too long and go out of bounds.
I wasn't able to reproduce the issue based on the code you've posted. Maybe there's something else I'm not seeing that causes this behaviour.
I actually wanted to align the FREIGHT DETAILS & SALES DETAILS in
parallel, separated using a vertical line.
Even when working with third-party layout managers such as DesignGridLayout you can follow a Nested Layout approach using JPanel's to group Freight details and Sales detail components.
About the vertical separator, don't think it's possible with DesignGridLayout. While you can have components spanning several rows it doesn't work with JSeparator.
Please help me with code to do all this, so that my form looks neat
and is fully visible.
StackOverflow is not a code factory so in most cases people won't do your job for you but they can provide useful examples. However as I've had to copy all your code to test it and I've made some changes using nested layouts approach, I'll make an exception here. Hope it be helpful:
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import net.java.dev.designgridlayout.DesignGridLayout;
public class Demo {
private void createAndShowGUI() {
JLabel i5l1 = new JLabel("FREIGHT DETAILS");
JLabel i5l2 = new JLabel("Date : ");
JLabel i5l3 = new JLabel("Vehicle No. : ");
JLabel i5l4 = new JLabel("From : ");
JLabel i5l5 = new JLabel("Item : ");
JLabel i5l6 = new JLabel("Quantity : ");
JLabel i5l7 = new JLabel("Kg.");
JLabel i5l8 = new JLabel("Rate : Rs.");
JLabel i5l15 = new JLabel("SALE DETAILS");
JLabel i5l16 = new JLabel("Cash Sales : Rs. ");
JLabel i5l17 = new JLabel("Credit : Rs. ");
JLabel i5l18 = new JLabel("EXPENSES");
JLabel i5l19 = new JLabel("Food & Tea : Rs. ");
JLabel i5l20 = new JLabel("Wages : Rs. ");
JLabel i5l21 = new JLabel("Miscellaneous Expenses : Rs. ");
JTextField i5t1 = new JTextField(20);
JTextField i5t2 = new JTextField(20);
JTextField i5t3 = new JTextField(20);
JTextField i5t4 = new JTextField(20);
JTextField i5t11 = new JTextField(20);
JTextField i5t12 = new JTextField(20);
JTextField i5t13 = new JTextField(20);
JTextField i5t14 = new JTextField(20);
JComboBox i5cb1 = new JComboBox<>();
JComboBox i5cb2 = new JComboBox<>();
JComboBox i5cb3 = new JComboBox<>();
JButton i5b1 = new JButton("Save");
JButton i5b2 = new JButton("Reset");
JButton i5b3 = new JButton("Close");
JSeparator i5sep1 = new JSeparator();
JSeparator i5sep2 = new JSeparator();
JSeparator i5sep3 = new JSeparator();
JSeparator i5sep4 = new JSeparator();
JSeparator i5sep5 = new JSeparator();
JSeparator i5sep6 = new JSeparator();
Object[] columnNames = new Object[]{"Column # 1", "Column # 2", "Column # 3", "Column # 4"};
DefaultTableModel model = new DefaultTableModel(columnNames, 10);
JTable table = new JTable(model);
JScrollPane i5t1sp1 = new JScrollPane(table);
JPanel freightPanel = new JPanel();
DesignGridLayout layout1 = new DesignGridLayout(freightPanel);
layout1.row().left().add(i5sep1).fill().withOwnRowWidth();
layout1.row().center().add(i5l1);
layout1.row().left().add(i5sep2).fill().withOwnRowWidth();
layout1.row().grid(i5l2).add(i5t1);
layout1.row().grid(i5l3).add(i5t2);
layout1.row().grid(i5l4).add(i5cb1);
layout1.row().grid(i5l5).add(i5cb2);
layout1.row().grid(i5l6).add(i5t3).add(i5l7);
layout1.row().grid(i5l8).add(i5t4);
layout1.row().left().add(i5sep5).fill().withOwnRowWidth();
layout1.row().center().add(i5l18);
layout1.row().left().add(i5sep6).fill().withOwnRowWidth();
layout1.row().grid(i5l19).add(i5t12);
layout1.row().grid(i5l20).add(i5t13);
layout1.row().grid(i5l21).add(i5t14);
JPanel salePanel = new JPanel();
DesignGridLayout layout2 = new DesignGridLayout(salePanel);
layout2.row().left().add(i5sep3).fill().withOwnRowWidth();
layout2.row().center().add(i5l15);
layout2.row().left().add(i5sep4).fill().withOwnRowWidth();
layout2.row().grid(i5l16).add(i5t11);
layout2.row().grid(i5l17).add(i5cb3);
layout2.row().grid().add(i5t1sp1);
JInternalFrame internalFrame = new JInternalFrame("Daily Analysis",true,true, true, true);
DesignGridLayout mainLayout = new DesignGridLayout(internalFrame.getContentPane());
mainLayout.row().grid().add(freightPanel).add(salePanel);
mainLayout.row().left().add(new JSeparator()).fill().withOwnRowWidth();
mainLayout.row().center().add(i5b1).add(i5b2).add(i5b3);
internalFrame.pack();
internalFrame.setVisible(true);
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(internalFrame);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Demo().createAndShowGUI();
}
});
}
}
Screenshot

Why aren't the Jpanels working?

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

Categories