Using GridbagLayout, I'm trying to display a JTable. Here's my code (simplified). The jpanel code that I'll put is shown after a button click.
My Panel :
optionspane = new JPanel();
optionspane.setLayout(new GridBagLayout());
optionspane.setBounds(0, 0, myframe.getWidth(), myframe.getHeight());
My Panel's Children :
GridBagConstraints dgbc=new GridBagConstraints();
dgbc.gridx=0;
dgbc.gridy=0;
dgbc.weightx = 1.0;
dgbc.weighty = 1.0;
dgbc.anchor=GridBagConstraints.CENTER;
dgbc.fill=GridBagConstraints.BOTH;
dgbc.insets=new Insets(5,10,10,5);
datapane.add(ServiceInterface.eighthpanel(), dgbc);
dgbc.gridx=0;
dgbc.gridy=1;
gbc.anchor=GridBagConstraints.SOUTH;
dgbc.fill=GridBagConstraints.BOTH;
dgbc.insets=new Insets(5,0,5,5);
datapane.add(ServiceInterface.ninethpanel(), dgbc);
Here is the panel method that contains the JPanel :
public static JPanel eighthpanel() throws IOException{
pane.setLayout(new GridBagLayout());
GridBagConstraints gbc=new GridBagConstraints();
pane.setBorder(BorderFactory.createLineBorder(Color.BLACK));
JLabel datawelcome=new JLabel("Please Enter the QoS values'");
datawelcome.setFont(new Font("Ubuntu", Font.BOLD, 16));
gbc.gridx = 0;
gbc.gridy = 1;
gbc.fill=GridBagConstraints.BOTH;
gbc.fill=GridBagConstraints.REMAINDER;
gbc.insets=new Insets(10,20,10,20);
pane.add(datawelcome, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.weightx=1;
gbc.weightx=1;
gbc.fill=GridBagConstraints.BOTH;
gbc.fill=GridBagConstraints.REMAINDER;
gbc.insets=new Insets(10,20,10,20);
//pane.add(new JScrollPane(displayJTable), gbc);
pane.add(myscrol, gbc);
return pane;
}
Here is how I fill my JTable (inside a button listener):
mytableclass=new Mytable();
displayJTable = new JTable(myModel);
displayJTable.getColumnModel().getColumn(0).setPreferredWidth(60);
displayJTable.setPreferredScrollableViewportSize(new Dimension(525,250));
displayJTable.setFillsViewportHeight(true);
displayJTable.setLocation(5,5);
myscrol.add(displayJTable);
myscrol.getViewport().setViewPosition(new Point(0,0));
myscrol.setPreferredSize(new Dimension(600,400));
principalpane.setVisible(false);
datapane.setVisible(true);
}
}});
I resolved my problem. I added an other panel (default layout) and I added the scrollPane to this panel inside the button.actionlistener.
I think because of the Static characteristic of the gridbaglayout.
Related
I am a beginner in Java Swing and I am trying to put a multiple JPanels in a JScrollPanel. The matter is, the JSCrollPannel (named jp in the code) should not fill all the JFrame but it does even if I fix a size with setSize() and a maximal size with setMaximalSize(). What is the trouble? How can I make the JSCrollPane smaller than the JFrame?
package GUI;
import java.awt.*;
import javax.swing.*;
public class MultiPanels {
private JScrollPane getContent() {
Dimension d = new Dimension(300,200);
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc= new GridBagConstraints();
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
panel.add(getPanel(d, 6, Color.red), gbc);
panel.add(getPanel(d, 4, Color.green.darker()), gbc);
panel.add(getPanel(d, 4, Color.orange), gbc);
panel.add(getPanel(d, 12, Color.blue), gbc);
panel.add(getEmptyPanel(d), gbc);
return new JScrollPane(panel);
}
private JScrollPane getPanel(Dimension d, int rows, Color color) {
JPanel panel = new JPanel(new GridBagLayout());
panel.setBackground(color);
GridBagConstraints gbc= new GridBagConstraints();
gbc.insets = new Insets(10,5,10,5);
gbc.weightx = 1.0;
for(int i = 0, j = 1; i < rows; i++) {
gbc.gridwidth = GridBagConstraints.RELATIVE;
panel.add(new JButton(String.valueOf(j++)), gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
panel.add(new JButton(String.valueOf(j++)), gbc);
}
JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.setPreferredSize(d);
return scrollPane;
}
private JScrollPane getEmptyPanel(Dimension d) {
JPanel panel = new JPanel() {
protected void paintComponent(Graphics g) {
int w = getWidth();
int h = getHeight();
GradientPaint gp = new GradientPaint(0,0,Color.red,
0,h,Color.cyan);
((Graphics2D)g).setPaint(gp);
g.fillRect(0,0,w,h);
}
};
panel.setPreferredSize(new Dimension(300,400));
JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.setPreferredSize(d);
return scrollPane;
}
public static void main(String[] args) {
JFrame f = new JFrame();
JScrollPane jp = new MultiPanels().getContent();
jp.setSize(new Dimension(200, 200));
jp.setMaximumSize(new Dimension(200,200));
jp.setPreferredSize(new Dimension(200,200));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(jp);
f.setSize(400,400);
f.setLocation(200,200);
f.setResizable(false);
f.setVisible(true);
}
}
Any time things don't size or arrange correctly, you have to look into Layouts.
Generally, spend more time on:
http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
To be specific, the default layout of a JPanel and JFrame is BorderLayout which is a very simple layout manager indeed. When you add to a component managed by BorderLayout without saying where, it is automatically added to the center and fills to use all available space:
http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html#border
It is possible to use "none" (Absolute Positioning) as the layout, but this is almost always a bad idea and you want to think about what you really want to do with the rest of the space in the JFrame: perhaps by letting new child components, with their own size demands, take up some of the space that the main panel is now swallowing up.
It's easiest to explain with a picture, so here it goes. This is how it looks right now:
I am trying to get all JButtons to to be same size, i.e to fill out the BoxLayout completely vertically.
Here is my code:
public class TestarBara extends JFrame implements ActionListener{
JButton heyy;
public static void main(String[] args){
new TestarBara();
}
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
public TestarBara(){
super("knapparnshit");
panel.setLayout(new GridLayout(3,3,2,2));
for(int x=1; x < 10; x++){
String y = Integer.toString(x);
JButton button = new JButton(y);
button.addActionListener(this);
panel.add(button);
}
add(panel, BorderLayout.CENTER);
JButton b1 = new JButton("this");
JButton b2 = new JButton("does");
JButton b3 = new JButton("not");
JButton b4 = new JButton("work");
panel2.setLayout(new BoxLayout(panel2, BoxLayout.PAGE_AXIS));
panel2.add(b1);
panel2.add(Box.createRigidArea(new Dimension(0,4)));
panel2.add(b2);
panel2.add(Box.createRigidArea(new Dimension(0,4)));
panel2.add(b3);
panel2.add(Box.createRigidArea(new Dimension(0,4)));
panel2.add(b4);
panel2.setBorder(BorderFactory.createBevelBorder(1));
add(panel2, BorderLayout.WEST);
Dimension dim = panel2.getPreferredSize();
b1.setPreferredSize(dim);
b2.setPreferredSize(dim);
b3.setPreferredSize(dim);
b4.setPreferredSize(dim);
setResizable(true);
setSize(300,300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
Object button = e.getSource();
if(button instanceof JButton){
((JButton) button).setEnabled(false);
((JButton) button).setText("dead");
Toolkit.getDefaultToolkit().beep();
}
}
}
What do I need to do so the JButtons all are the same size, and all of them going all the way to the left?
The problem is BoxLayout will honour the preferredSize of the individual components, you'd be better off with a layout manager that provided you with more control, like GridBagLayout, for example...
panel2.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(0, 0, 4, 0);
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
panel2.add(b1, gbc);
panel2.add(b2, gbc);
panel2.add(b3, gbc);
gbc.insets = new Insets(0, 0, 0, 0);
panel2.add(b4, gbc);
Or GridLayout...
panel2.setLayout(new GridLayout(0, 1, 0, 4));
panel2.add(b1);
panel2.add(b2);
panel2.add(b3);
panel2.add(b4);
Why are the JLabel, JTextField and JButton components on the FieldBox panel not displaying?
Please let me know if I can add anything to this question to make it more answerable!
The field box (one of which is created for each of several instance fields):
public class FieldBox extends javax.swing.JPanel {
JLabel label;
JTextField textField;
public FieldBox() {
setBackground(Color.RED);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
label = new JLabel();
gbc.gridx = 0;
gbc.gridy = 0;
add(label,gbc);
textField = new JTextField();
gbc.gridx = 1;
gbc.gridy = 0;
add(textField, gbc);
JButton editBtn = new JButton("edit");
gbc.gridx = 2;
gbc.gridy = 0;
add(editBtn, gbc);
JButton saveBtn = new JButton ("save");
gbc.gridx = 3;
gbc.gridy = 0;
add(saveBtn, gbc);
label.setVisible(true);
label.setBackground(Color.yellow);
setVisible(true);
initComponents();
}
The panel onto which the boxes are added: (the panel appears. I know this panel loads because I can see its background. I can also see the "tit" JLabel, which I'm using for testing. Also, when I load the boxes onto it using a gridLayout (as shown below), I see the background of one of the boxes, but none of its contents are displayed, and also there should be three boxes shown but I only see one. Using a GridBagLayout
public class ShowBook extends javax.swing.JPanel {
public ShowBook(Book b) {
setLayout(new GridLayout(1,6));
setBackground(Color.GREEN);
String[] fieldTitles = {"title", "catalog", "publisher" };
JLabel tit = new JLabel("tit");
add(tit);
for (String s : fieldTitles){
FieldBox fb = new FieldBox();
fb.label.setText(s + ": ");
fb.textField.setText(getField(b, s));
System.out.println("in text field" + fb.textField.getText());
fb.revalidate();
fb.setVisible(true);
add (fb);
}
revalidate();
setVisible(true);
}
The panel onto which the ShowBook panel (above) is added. This panel also contains a listbox, which lists books in the collection, and a button to launch a ShowBook panel with the selected book as parameter.
public class ShowLib extends javax.swing.JPanel {
/**
* Creates new form ShowLib
*/
public ShowLib(Library l) {
setLayout(new BorderLayout()) ;
setBackground(Color.WHITE);
JPanel listPanel = new JPanel();
listPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
final JList bookList = new JList();
bookList.setVisible(true);
bookList.setPreferredSize(new Dimension(150, 600));
bookList.setBackground(Color.yellow);
DefaultListModel dlm = new DefaultListModel();
for (Book b : l.libList){
dlm.addElement(b);
}
bookList.setModel(dlm);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = gbc.BOTH;
listPanel.add(bookList, gbc);
JButton showBtn = new JButton("show");
gbc.gridy = gbc.RELATIVE;
listPanel.add(showBtn, gbc);
showBtn.addActionListener(new ActionListener () {
#Override
public void actionPerformed(ActionEvent e){
Book b = (Book) bookList.getSelectedValue();
ShowBook db = new ShowBook (b);
System.out.println("Clicked");
add (db, BorderLayout.CENTER);
revalidate();
}
});
revalidate();
setVisible(true);
add(listPanel, BorderLayout.WEST);
}
Where the ShowLib panel is added to the main JFrame. I know this works because that panel displays properly
void showLib() {
ShowLib sl = new ShowLib(l);
sl.setVisible(true);
setContentPane(sl);
revalidate();
// this.revalidate();
// this.pack();
System.out.println("showlibClicked");
}
The problem was the line initComponents(); at the bottom of the FieldBox class.
Lesson learned: If you're not using NetBeans visual GUI editor, GET RID OF THIS LINE!
I am coding a contact list application in eclipse using Java Swing.
How can I get a simple table layout that contains just columns and rows?
I don't want row or column labels.
Something like this:
first name: john
middle name: franklin
last name: doe
Where the names would be editable text boxes etc.
What's the best component to use?
I will also have buttons below the text fields.
Currently I have a JFrame which is running correctly. It pulls up a window that has my menu options correct. But when I try to do this:
myFrame.setLayout(new GridLayout(6, 2));
I get an error. I would like to have a grid layout of two columns and 5 rows (maybe 6).
I want to have a label on the left column, and a text box on the right column.
then two buttons at the bottom, centered.
You'd better of breaking your fields and controls (buttons) into separate panels, this allows you to supply different layout managers for each.
I'd start with a base JPanel using a BorderLayout.
Onto this, I'd add the "fields" panel at the CENTER position and the controls (buttons) at the SOUTH position.
For the fields, I'd use a GridBagLayout, but I'm picky like that, and for the controls panel I'd probably use a FlowLayout (unless you have access to a nice ButtonLayout manager ;))
This means you could end up with something like
UPDATED with code sample
public class FormPanel extends JPanel {
private JTextField fldFirstName;
private JTextField fldMiddleName;
private JTextField fldLastName;
private JTextField fldDateOfBirth;
private JTextField fldEMail;
private JButton okButton;
private JButton cancelButton;
public FormPanel() {
setLayout(new BorderLayout());
add(createFieldsPane());
add(createButtonsPane(), BorderLayout.SOUTH);
}
public JPanel createButtonsPane() {
JPanel panel = new JPanel(new FlowLayout());
panel.add((okButton = createButton("Ok")));
panel.add((cancelButton = createButton("Cancel")));
return panel;
}
protected JButton createButton(String text) {
return new JButton(text);
}
public JPanel createFieldsPane() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(2, 2, 2, 2);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
panel.add(createLabel("First Name:"), gbc);
gbc.gridy++;
panel.add(createLabel("Middle Name:"), gbc);
gbc.gridy++;
panel.add(createLabel("Last Name:"), gbc);
gbc.gridy++;
panel.add(createLabel("Date of Birth:"), gbc);
gbc.gridy++;
panel.add(createLabel("EMail:"), gbc);
gbc.gridy = 0;
gbc.gridx++;
gbc.weightx = 1;
panel.add((fldFirstName = createField()), gbc);
gbc.gridy++;
panel.add((fldLastName = createField()), gbc);
gbc.gridy++;
panel.add((fldMiddleName = createField()), gbc);
gbc.gridy++;
panel.add((fldDateOfBirth = createField()), gbc);
gbc.gridy++;
panel.add((fldEMail = createField()), gbc);
JPanel filler = new JPanel();
filler.setOpaque(false);
gbc.gridy++;
gbc.weightx = 1;
gbc.weighty = 1;
panel.add(filler, gbc);
return panel;
}
protected JLabel createLabel(String text) {
return new JLabel(text);
}
protected JTextField createField() {
JTextField field = new JTextField(12);
return field;
}
}
I have the structure as you can see in the picture.
For both panels, GridBagLayout is used.
The problem is that the text field inside the scrollpane is not entirely visible.
The parent panel stretches only for the buttons to become visible, but when the scroll bar appears, it just overlap with the text field.
Is there an easy solution to fix this (don't want to deal with setting custom / preferred / minimum heights)?
Panel structure :
Problem :
Ok, here is an SSCCE
public class Main {
JFrame frame;
private JPanel mainPanel;
private JButton button1;
private JButton button2;
private JTextField someTextTextField;
public static void main(String[] args) {
Main main = new Main();
main.show();
}
private void show() {
frame = new JFrame("Frame");
frame.setContentPane(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
{
$$$setupUI$$$();
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* #noinspection ALL
*/
private void $$$setupUI$$$() {
mainPanel = new JPanel();
mainPanel.setLayout(new GridBagLayout());
mainPanel.setPreferredSize(new Dimension(209, 30));
final JPanel panel1 = new JPanel();
panel1.setLayout(new GridBagLayout());
GridBagConstraints gbc;
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 0.5;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
mainPanel.add(panel1, gbc);
button1 = new JButton();
button1.setText("Button");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
panel1.add(button1, gbc);
button2 = new JButton();
button2.setText("Button");
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
panel1.add(button2, gbc);
final JScrollPane scrollPane1 = new JScrollPane();
scrollPane1.setAlignmentX(0.0f);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0.5;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
mainPanel.add(scrollPane1, gbc);
someTextTextField = new JTextField();
someTextTextField.setText("some text");
scrollPane1.setViewportView(someTextTextField);
}
/**
* #noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return mainPanel;
}
}
Try and use a JTextArea instead of a JTextField. And if you don't want to set custom/preferred/minimum sizes, you can use the JTextArea.setRows(int rows) method. I hope that helps.