JTable won't span up to JFrame's borders - java

I can't make the table span up to the JFrame border. I tried using setMinimumSize but it didn't work. What am I missing?
ADDED: I'm not interested in adding JScrollPane to the table (yet). I just want to know exactly how to make GridBagLayout resize a particular component to JFrame's borders.
public class Ost extends JFrame{
OstBridge bridge;
public Ost() {
Container cp=this.getContentPane();
GridBagConstraints c=new GridBagConstraints();
cp.setLayout(new GridBagLayout());
// Add button
JButton b1=new JButton("Button");
c.gridx=0;
c.gridy=0;
c.insets=new Insets(20,0,20,0);
cp.add(b1,c);
// Table data
String[] columns={"Album","Url"};
Object[][] data={
{"test1","tes2"}
};
// Add Table
JTable table=new JTable(data,columns);
c.gridx=0;
c.gridy=1;
c.weightx=1;
c.weighty=1;
c.gridwidth=c.REMAINDER;
table.setBackground(Color.RED);
table.setMinimumSize(new Dimension(400,400));
cp.add(table, c);
// Show All
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(320, 240);
this.setTitle("Test");
this.setVisible(true);
}
This is what I get:
And this is what I would like to get:

In the constraints for the table I should've used GridBagConstraints.fill:
// Add Table
JTable table=new JTable(data,columns);
c.gridx=0;
c.gridy=1;
c.weightx=1;
c.weighty=1;
c.gridwidth=c.REMAINDER;
c.fill=GridBagConstraints.HORIZONTAL; // this line solves the problem
table.setBackground(Color.RED);
table.setMinimumSize(new Dimension(400,400));
cp.add(table, c);
Hope this answer helps someone else who's trying to give firsts steps into java as me! :)

Related

using a GridBagLayout, JScrollpane doesn't work (or look appropriate) with JList

I'm aware there are several questions with the same title, and I've tried their answers but to no avail.
I'm getting the following result with my code:
It does not scroll as it should, and there's this empty little space to the right.
Here is the main code for the frame, mainpanel, list panel and the buttons panel that are inside the mainpanel.
public Tester2() {
JPanel mainPanel = new JPanel(); /////// MAIN PANEL
mainPanel.setLayout(new BorderLayout());
mainPanel.setPreferredSize(new Dimension(200, 400));
JPanel upperListPnl = new JPanel(); ////// LIST PANEL
upperPnlSetup(upperListPnl);
JPanel lowerBtnsPnl = new JPanel(); ///// BUTTONS PANEL
lowerBtnsPnl.setLayout(new BorderLayout());
JButton testButton = new JButton("Test the list");
testButton.addActionListener(e -> {
exampleModel.addElement("List has been tested");
updateExampleData();
});
lowerBtnsPnl.add(testButton);
mainPanel.add(upperListPnl, BorderLayout.CENTER);
mainPanel.add(lowerBtnsPnl, BorderLayout.SOUTH);
JFrame frame = new JFrame();
frame.add(mainPanel);
frame.setVisible(true);
frame.pack();
frame.setLocationRelativeTo(null);
}
Here is the code for the JList and the JScrollpane (upper panel):
public void upperPnlSetup(JPanel panel) {
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
exampleList = new JList<>(exampleModel);
JScrollPane jsp = new JScrollPane(exampleList, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
c.fill = GridBagConstraints.BOTH;
c.weighty = 1;
c.weightx = 0.75;
panel.add(exampleList, c);
c.weightx = 0.25;
panel.add(jsp, c);
}
And then the JList and model list as well as the data updating method:
private JList<String> exampleList;
private DefaultListModel<String> exampleModel = new DefaultListModel<>();
public void updateExampleData() {
exampleList.setModel(exampleModel);
}
I tried a FloatLayout, a BorderLayout, and a GridLayout (0,2 and 0,1) all of which didn't work. Finally, I settled for the GridBagLayout since it's seemingly always used for JLists and/or JScrollpanes, and I played with the GridBagConstraints as well as the positioning of the code but seem to always land on the same problem. I've tried giving the scroll pane a preferredSize, didn't do anything.
Okay so, apparently the problem was that I was adding the list to the panel. Adding it to the scrollpane, then adding the scrollpane to the panel was enough, so commenting out the
panel.add(exampleList, c);`
fixed the whole thing.

GridBagLayout allignement

Iam trying to find out how GridBagLayout works,because i have had never used it. I will post source code and picture of that gui. i have problem with components to allign. i want to put button to be in the middle of two components(on one side checkboxgroup and on the other is JTextArea. and i managed but it is alligned in the bottom and i want to allign it to be in the middle of the height of both components.
public class GUI extends JFrame {
public GUI(){
setSize(600,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setTitle("ridBagLayout[![enter image description here][1]][1]");
JPanel panel=new JPanel(new GridBagLayout());
GridBagConstraints c=new GridBagConstraints();
String[]niz={"C Sharp","Java","PHP","VisualBasic"};
c.anchor=GridBagConstraints.PAGE_START;
c.weighty=1.0;
c.gridx=0;
c.gridy=0;
c.insets=new Insets(30,30,0,0);
panel.add(new JComboBox(niz),c);
c.gridx=1;
//c.insets=new Insets(10,0,0,0);
panel.add(new JButton("Get drop down item"),c);
c.gridx=2;
c.ipadx=20;
panel.add(new JTextField(15),c);
JCheckBox visualBasic=new JCheckBox("Visual Basic");
JCheckBox cSharp=new JCheckBox("C Sharp");
JCheckBox java=new JCheckBox("Java");
JCheckBox php=new JCheckBox("PHP");
JPanel checkbox=new JPanel();
checkbox.setLayout(new GridLayout(4,0,5,5));
checkbox.add(visualBasic);
checkbox.add(cSharp);
checkbox.add(java);
checkbox.add(php);
javax.swing.border.Border raisedetched = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
checkbox.setBorder(raisedetched);
c.insets=new Insets(0,20,0,0);
c.gridx=0;
c.gridy=1;
panel.add(checkbox,c);
c.gridx=1;
c.ipadx=30;
c.anchor=GridBagConstraints.CENTER;
panel.add(new JButton("Selected Item"),c);
c.gridx=2;
c.gridy=1;
c.ipadx=20;
c.anchor=GridBagConstraints.NORTH;
panel.add(new JTextArea(7,15),c);
add(panel);
setVisible(true);
}
}
GridBagLayout is one of the most powerful layouts to use in Java, but it requires some nesting in order to obtain a good result.
In your case, maybe you need to put that button inside a panel and set its alignments properties to CENTER.
There is lot of documentation about GridBagLayout but another way to see how it works could be to create a new project in an IDE like NetBeans and create that GUI through its graphical editor and see the generated code.

Is it possible to set a JPanel's size when creating a new JPanel?

I was wondering if there is a way to change the size of a JPanel when creating one.
My code looks like this:
add(scoreArea, BorderLayout.NORTH);
add(gameArea, BorderLayout.CENTER);
add(new JPanel(), BorderLayout.WEST);
add(new JPanel(), BorderLayout.EAST);
add(new JPanel(), BorderLayout.SOUTH);
I used the JPanels to create a border, but I would like to make them thinner. I am new to swing and I was just wondering if you could change the size in the same statement or if I would have to make JPanel objects and set the size there?
I tried this but it doesn't seem to work:
add(new JPanel(){
setPreferredSize(new Dimension(10, 300));
}, BorderLayout.EAST);
Is there a way to do something like this?
Edit: Really downvotes? Just asking a question, I dont see the need for a downvote. What a community.
You can set margin for JPanel (contaiter) using EmptyBorder class:
EmptyBorder margin = new EmptyBorder(top, left, bottom, right);
getContentPane().setBorder(border);
Proper way to setup prefered size is:
Dimension size = new Dimension(width, height);
JPanel panel;
add(panel = new JPanel(), BorderLayout.WEST);
panel.setPreferredSize(size);
add(panel = new JPanel(), BorderLayout.EAST);
panel.setPreferredSize(size);
add(panel = new JPanel(), BorderLayout.SOUTH);
panel.setPreferredSize(size);

How to get rid of the border with a JTable / JScrollPane

If you run the small sample below you'll see a border around the center region. I'm not sure why this border is showing.
It happens when a JTable is in a JScrollPane. I tried various things to remove it but so far no luck. A JTable without the JScrollPane shows no border.
See sample below. TIA.
public class TestScrollPane extends JFrame {
public static void main(String[] args) {
JFrame frame = new TestScrollPane();
JPanel panel = new JPanel();
JTable table = new JTable();
panel.setLayout(new BorderLayout());
panel.add(new JLabel("NORTH"), BorderLayout.NORTH);
panel.add(new JLabel("SOUTH"), BorderLayout.SOUTH);
JScrollPane sp = new JScrollPane(table);
// None of these have any effect
sp.setBorder(null);
sp.getInsets().set(0, 0, 0, 0);
sp.setViewportBorder(null);
sp.getViewport().setBorder(null);
sp.getViewport().getInsets().set(0, 0, 0, 0);
sp.getViewport().setOpaque(true);
panel.add(sp, BorderLayout.CENTER);
// Adding the table alone shows no border
// panel.add(table, BorderLayout.CENTER);
frame.add(panel);
frame.setVisible(true);
}
public TestScrollPane() throws HeadlessException {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setMinimumSize(new Dimension(100, 100));
}
}
Use BorderFactory.createEmptyBorder() instead of null...
by using:
sp.setBorder(createEmptyBorder());
it works.
Your main method becomes:
public static void main(String[] args) {
JFrame frame = new TestScrollPane();
JPanel panel = new JPanel();
JTable table = new JTable();
panel.setLayout(new BorderLayout());
panel.add(new JLabel("NORTH"), BorderLayout.NORTH);
panel.add(new JLabel("SOUTH"), BorderLayout.SOUTH);
JScrollPane sp = new JScrollPane(table);
sp.setBorder(BorderFactory.createEmptyBorder());
panel.add(sp, BorderLayout.CENTER);
frame.add(panel);
frame.setVisible(true);
}
Interestingly the border disappears when you remove this line:
sp.setBorder(null);
I was looking for the answer for the same question but above answers could not do... so I found a better answer:
JScrollPane jsp = new JScrollPane();
//ur other codes
jsp.setViewportBorder(null);
For JTable table.setIntercellSpacing(new Dimension(0, 0)) works.
I think the proper fix is to set the border on the viewportView to 'null'.
To remove the border from all parts of the JScrollPane including the vertical and horizontal bar the following code works
JScrollPane jsp = new JScrollPane();
jsp.getVerticalScrollBar().setBorder(null);
jsp.getHorizontalScrollBar().setBorder(null);
jsp.setBorder(null);

JScrollPane for a panel containing a set of labels with BoxLayout

I'd like to use a JScrollPane for a panel which has an arbitrary list of labels in it using box layout. I'm trying to get it so that the scrollbar would appear if there were too many items (labels) to display.
I tried adding a JScrollPane to the panel and then add the labels but then I don't see any scroll bar.
Any ideas?
TIA
For this kind of thing, you'd normally use a JList or JTable (if you need custom rendering).
Make sure that you call validate() or revalidate() on the JScrollPane after adding an item, to force the preferred size of the panel to be recalculated.
Here's how I did it.
JPanel midPanel = new JPanel();
midPanel.setLayout(new BoxLayout(midPanel, BoxLayout.Y_AXIS));
midPanel.add(new JLabel("<html><u>Label</u>"));
Box box = Box.createVerticalBox();
for (Item item : data.getInventory()) {
inventory.add(box.add(new JLabel(item.getName())));
}
JScrollPane jscrlpBox = new JScrollPane(box);
midPanel.add(jscrlpBox);
add(midPanel, BorderLayout.CENTER);
From:
http://www.java2s.com/Code/Java/Swing-JFC/JScrollPanetoholdscrollablecomponent.htm
Did you remember to set the preferred size of the content panel?
final JFrame frame = new JFrame("Scroll Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
final Box textArea = Box.createVerticalBox();
final JScrollPane textAreaScroll = new JScrollPane(textArea);
textAreaScroll.setPreferredSize(new Dimension(80,150)); /* essential! */
JButton addButton = new JButton("ADD");
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
textArea.add(new JLabel("abc"));
textArea.revalidate();
}
});
frame.getContentPane().add(textAreaScroll, BorderLayout.SOUTH);
frame.getContentPane().add(Box.createRigidArea(new Dimension(10,10)), BorderLayout.CENTER);
frame.getContentPane().add(addButton, BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
In this example, the scroll bar works correctly, but if you remove the line marked as "essential", it will not work anymore.

Categories

Resources