How to add JTable in JPanel with null layout? - java

I want to add JTable into JPanel whose layout is null. JPanel contains other components. I have to add JTable at proper position.

Nested/Combination Layout Example
The Java Tutorial has comprehensive information on using layout managers. See the Laying Out Components Within a Container lesson for further details.
One aspect of layouts that is not covered well by the tutorial is that of nested layouts, putting one layout inside another to get complex effects.
The following code puts a variety of components into a frame to demonstrate how to use nested layouts. All the layouts that are explicitly set are shown as a titled-border for the panel on which they are used.
Notable aspects of the code are:
There is a combo-box to change PLAF (Pluggable Look and Feel) at run-time.
The GUI is expandable to the user's need.
The image in the bottom of the split-pane is centered in the scroll-pane.
The label instances on the left are dynamically added using the button.
Nimbus PLAF
NestedLayoutExample.java
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.border.TitledBorder;
/** A short example of a nested layout that can change PLAF at runtime.
The TitledBorder of each JPanel shows the layouts explicitly set.
#author Andrew Thompson
#version 2011-04-12 */
class NestedLayoutExample {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
final JFrame frame = new JFrame("Nested Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel gui = new JPanel(new BorderLayout(5,5));
gui.setBorder( new TitledBorder("BorderLayout(5,5)") );
//JToolBar tb = new JToolBar();
JPanel plafComponents = new JPanel(
new FlowLayout(FlowLayout.RIGHT, 3,3));
plafComponents.setBorder(
new TitledBorder("FlowLayout(FlowLayout.RIGHT, 3,3)") );
final UIManager.LookAndFeelInfo[] plafInfos =
UIManager.getInstalledLookAndFeels();
String[] plafNames = new String[plafInfos.length];
for (int ii=0; ii<plafInfos.length; ii++) {
plafNames[ii] = plafInfos[ii].getName();
}
final JComboBox plafChooser = new JComboBox(plafNames);
plafComponents.add(plafChooser);
final JCheckBox pack = new JCheckBox("Pack on PLAF change", true);
plafComponents.add(pack);
plafChooser.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent ae) {
int index = plafChooser.getSelectedIndex();
try {
UIManager.setLookAndFeel(
plafInfos[index].getClassName() );
SwingUtilities.updateComponentTreeUI(frame);
if (pack.isSelected()) {
frame.pack();
frame.setMinimumSize(frame.getSize());
}
} catch(Exception e) {
e.printStackTrace();
}
}
} );
gui.add(plafComponents, BorderLayout.NORTH);
JPanel dynamicLabels = new JPanel(new BorderLayout(4,4));
dynamicLabels.setBorder(
new TitledBorder("BorderLayout(4,4)") );
gui.add(dynamicLabels, BorderLayout.WEST);
final JPanel labels = new JPanel(new GridLayout(0,2,3,3));
labels.setBorder(
new TitledBorder("GridLayout(0,2,3,3)") );
JButton addNew = new JButton("Add Another Label");
dynamicLabels.add( addNew, BorderLayout.NORTH );
addNew.addActionListener( new ActionListener(){
private int labelCount = 0;
public void actionPerformed(ActionEvent ae) {
labels.add( new JLabel("Label " + ++labelCount) );
frame.validate();
}
} );
dynamicLabels.add( new JScrollPane(labels), BorderLayout.CENTER );
String[] header = {"Name", "Value"};
String[] a = new String[0];
String[] names = System.getProperties().
stringPropertyNames().toArray(a);
String[][] data = new String[names.length][2];
for (int ii=0; ii<names.length; ii++) {
data[ii][0] = names[ii];
data[ii][1] = System.getProperty(names[ii]);
}
DefaultTableModel model = new DefaultTableModel(data, header);
JTable table = new JTable(model);
try {
// 1.6+
table.setAutoCreateRowSorter(true);
} catch(Exception continuewithNoSort) {
}
JScrollPane tableScroll = new JScrollPane(table);
Dimension tablePreferred = tableScroll.getPreferredSize();
tableScroll.setPreferredSize(
new Dimension(tablePreferred.width, tablePreferred.height/3) );
JPanel imagePanel = new JPanel(new GridBagLayout());
imagePanel.setBorder(
new TitledBorder("GridBagLayout()") );
BufferedImage bi = new BufferedImage(
200,200,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
GradientPaint gp = new GradientPaint(
20f,20f,Color.red, 180f,180f,Color.yellow);
g.setPaint(gp);
g.fillRect(0,0,200,200);
ImageIcon ii = new ImageIcon(bi);
JLabel imageLabel = new JLabel(ii);
imagePanel.add( imageLabel, null );
JSplitPane splitPane = new JSplitPane(
JSplitPane.VERTICAL_SPLIT,
tableScroll,
new JScrollPane(imagePanel));
gui.add( splitPane, BorderLayout.CENTER );
frame.setContentPane(gui);
frame.pack();
frame.setLocationRelativeTo(null);
try {
// 1.6+
frame.setLocationByPlatform(true);
frame.setMinimumSize(frame.getSize());
} catch(Throwable ignoreAndContinue) {
}
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
Other Screen Shots
Windows PLAF
Mac OS X Aqua PLAF
Ubuntu GTK+ PLAF

Don't use a null layout. Learn to use LayoutManagers:
http://download.oracle.com/javase/tutorial/uiswing/layout/using.html
LayoutManagers allow you to properly handle things window resizing or dynamic component counts. They might seem intimidating at first, but they are worth the effort to learn.

As I can remember, the null layout means an absolute position so it will be pretty hard you to count the X point for your JTable left upper corner location. But if you just want to have all panel components one by one you can use FlowLayout() manager as
JPanel panel=new JPanel(new FlowLayout());
panel.add(new aComponent());
panel.add(new bComponent());
panel.add(new JTable());
or if you need to fill the panel you should use GridLayout() as...
int x=2,y=2;
JPanel panel=new JPanel(new GridLayout(y,x));
panel.add(new aComponent());
panel.add(new bComponent());
panel.add(new JTable());
Good luck

If you are using null layout manager you always need to set the bounds of a component.
That is the problem in your case.
You should do what everyone suggest here and go and use some layout manager believe they save time.
Go and check out the tutorial in #jzd's post.
Enjoy, Boro.

JTable should be added into the JScrollPane which actually should be added into the JPanel.
The JPanel should have some layout manager.
If you don't care about the precision of components size you can use pure BorderLayout and combine it with FlowLayout and GridLayout. if you need precision - use jgoodies FormLayout.
The FormLayout is really tricky one, but you can play a little with WindowBuilder (which is embedded into Eclipse) and a look at the code it generates. It may look complicated but it is just an ignorance.
Good luck.

First, you should seriously consider other Layout managers, for example the BorderLayoutManager (new JPanel(new BorderLayout())) is a good start.
Also when designing your dialog, remember that you can and should nest your layouts: one JPanel inside another JPanel (e.g. a GridLayout inside a BorderLayout). Please note: a 'good' dialog should resize properly, so that if the user resizes your Frame, you want to automatically extend your information objects such as your table, and not show large areas of JPanel background. That's something you cannot achieve with a NullLayout.
But there are probably cases - somewhere in this big world - where a NullLayout is just the thing. So here's an example:
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class JTableInNullLayout
{
public static void main(String[] argv) throws Exception {
DefaultTableModel model = new DefaultTableModel(
new String[][] { { "a", "123"} , {"b", "456"} },
new String[] { "name", "value" } );
JTable t = new JTable(model);
JPanel panel = new JPanel(null);
JScrollPane scroll = new JScrollPane(t);
scroll.setBounds( 0, 20, 150, 100 ); // x, y, width, height
panel.add(scroll);
JFrame frame = new JFrame();
frame.add(panel);
frame.setPreferredSize( new Dimension(200,200));
frame.pack();
frame.setVisible(true);
}
}

When a component have a "null" layout, you have to manage the layout by yourself, that means you have to calculate the dimensions and locations for the children of the component to decide where they are drawn. Quite tedious unless it is absolutely necessary.
If you really want that fine-grained control, maybe try GridBagLayout first before going mudding with the UI arrangement.

JPanel panel = new JPanel();
JTable table = new JTable(rowData, colData);
JScrollPane scrollPane = new JScrollPane(table);
panel.add(scrollPane, BorderLayout.CENTER);
panel.setSize(800, 150);
panel.add(table);
panel.setLocationRelativeTo(null);
panel.setVisible(true);
Hope this helps.

JFrame frame = new JFrame("Sample Frame");
frame.setSize(600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
DefaultTableModel dfm = new DefaultTableModel(data, columnNames);
JTable table = new JTable(dfm);
JScrollPane scrollPane = new JScrollPane(table);
panel.add(scrollPane);
frame.add(panel);
frame.setVisible(true);
table model depends on your requirement

this.setTitle("Sample");
JPanel p = new JPanel(new BorderLayout());
WindowEvent we = new WindowEvent(this, WindowEvent.WINDOW_CLOSED);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
// Create columns names
String columnNames[] = { "FirstCol", "SecondCol",
"ThirdCol", "FourthCol" };
dataModel = new DefaultTableModel();
for (int col = 0; col < columnNames.length; col++) {
dataModel.addColumn(columnNames[col]);
}
// Create a new table instance
table = new JTable(dataModel);
table.setPreferredScrollableViewportSize(new Dimension(200, 120));
table.setFillsViewportHeight(true);
table.setShowGrid(true);
table.setAutoscrolls(true);
// Add the table to a scrolling pane
scrollPane = new JScrollPane(table,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setPreferredSize(new Dimension(700, 700));
JPanel jpResultPanel = new JPanel();
jpResultPanel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Result",
TitledBorder.CENTER, TitledBorder.TOP));
jpResultPanel.add(scrollPane);
add(jpResultPanel);
pack();
setSize(720, 720);
setVisible(true);
Try this.

You can make use of the following code. To add JTable to JPanel.
JPanel panel = new JPanel();
this.setContentPane(panel);
panel.setLayout(null);
String data[][] = {{"1.", "ABC"}, {"2.", "DEF"}, {"3.", "GHI" }};
String col[] = {"Sr. No", "Name"};
JTable table = new JTable(data,col);
table.setBounds(100, 100, 100, 80);
panel.add(table);
setVisible(true);
setSize(300,300);

Related

Contents of JScrollPane are not visible

I have a main class:
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("Hex");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent inputs = new InputPanel();
JComponent hexGrid = new HexGridPanel(10,10,30);
JComponent outputs = new OutputPanel();
JComponent toolbar = new ToolbarPanel(); // This one is having problems
Container pane = frame.getContentPane();
pane.add(inputs, BorderLayout.LINE_START);
pane.add(hexGrid, BorderLayout.CENTER);
pane.add(outputs, BorderLayout.LINE_END);
pane.add(toolbar, BorderLayout.PAGE_END); // This one is having problems
frame.pack();
frame.setVisible(true);
}
}
And all of my other panels work except for ToolbarPanel that for some reason does not show its content:
public ToolbarPanel(){
JPanel content = new JPanel();
content.setLayout(new BoxLayout(content, BoxLayout.X_AXIS));
ButtonGroup buttonGroup = new ButtonGroup();
JRadioButton button = new JRadioButton("Test");
buttonGroup.add(button );
content.add(button );
JScrollPane scroll = new JScrollPane(content);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
content.setBorder(new LineBorder(Color.RED));
scroll.setBorder(new LineBorder(Color.GREEN));
this.add(scroll);
this.setPreferredSize(new Dimension(900, 200));
this.setBorder(new LineBorder(Color.BLACK)); // Only this is showing up in the UI
}
The ToolbarPanel itself shows up, but not the scroll pane or the radio buttons. It should show up inside of the black rectangle at the bottom of this image:
Well, you didn't include a MRE and I don't see the declaration of your class but I'm guessing you are using:
public class ToolbarPanel extends JComponent
The problem is that by default a JComponent doesn't have a layout manager so you won't see your components.
If you use:
public class ToolbarPanel extends JPanel
It will be a little better, but all the components will be displayed in a small square.
So you will also want to add
setLayout( new BorderLayout() );
to your constructor.
Note:
This is why a minimal reproducible example should be included with every question. We should not have to spend time guessing what you may or may not be doing.

How to add scrollbar automatic in jscrollpane?

I try to program a GUI like this. When a button clicked every time a new button is created and placed at specific position but after adding some buttons in jscrollpane, scrollbar not activated, so I unable to see all created buttons.
My code is here:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Test{
private JFrame frame;
private JPanel panel1,panel2;
private JScrollPane pane;
private JButton button;
int i = 1, y = 10;
public Test()
{
panel2 = new JPanel(null);
panel2.setBounds(0,0,280,300);
button = new JButton("Add Button");
button.setBounds(90,10,120,30);
pane = new JScrollPane();
pane.setBounds(10,50,280,300);
panel1 = new JPanel(null);
panel1.setPreferredSize(new Dimension(300,400));
panel1.setBackground(Color.WHITE);
frame = new JFrame("Test");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel1);
frame.pack();
panel1.add(pane);
panel1.add(button);
pane.add(panel2);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
panel2.add(new JButton("Button "+i)).setBounds(80,y,120,30);
i += 1;
y += 35;
}
});
}
public static void main(String[] args) {
new Test();
}
}
Don't use a null layout. Don't use setBounds().
The scrollbars will only appear automatically when the preferred size of the panel is greater that the size of the scroll pane.
It is the job of the layout manager to:
set the location of a component
set the size of a component
calculate the preferred size of the panel.
So the solution is to use the appropriate layout manager on your panel.
So for example you can use a BoxLayout:
//panel2 = new JPanel(null);
panel2 = new JPanel();
panel2.setLayout( new BoxLayout(panel2, BoxLayout.Y_AXIS) );
And then when you add components to a visible frame you need to revalidate() the panel to invoke the layout manager:
//panel2.add(new JButton("Button "+i)).setBounds(80,y,120,30);
panel2.add(new JButton("Button "+i));
panel2.revalidate();
There is no need for panel1. Just add the components to the frame:
//panel1.add(pane);
//panel1.add(button);
frame.add(button, BorderLayout.PAGE_START);
frame.add(pane, BorderLayout.CENTER);
But there are other issues:
pane = new JScrollPane();
You actually need to add the panel to the scroll pane. So the code should be:
pane = new JScrollPane(panel2);
Since a component can only have a single parent, you need to remove:
pane.add(panel2);
Since the panel2 has been added to the scroll pane.
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel1);
frame.pack();
The above logic is wrong.
You should only invoked pack() and setVisible( true ) AFTER all the component have been added to the frame.
So most of the code posted is wrong.
Start by reading the section from the Swing turtorial on Layout Managers. Download the working demo code and learn how to better structure your code. The modify the code for your specific example.

How to get a JScrollPane to resize with its parent JPanel

My question is similar to this one (How to get JScrollPanes within a JScrollPane to follow parent's resizing), but that question wasn't clear and the answer there didn't help me..
I have this SSCCE (using MigLayout):
public static final int pref_height = 500;
public static void main(String[] args) {
JPanel innerPanel = new JPanel(new MigLayout());
innerPanel.setBorder(new LineBorder(Color.YELLOW, 5));
for(int i = 0; i < 15; i++) {
JTextArea textArea = new JTextArea();
textArea.setColumns(20);
textArea.setRows(5);
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
JScrollPane jsp = new JScrollPane(textArea);
innerPanel.add(new JLabel("Notes" + i));
innerPanel.add(jsp, "span, grow");
}
JScrollPane jsp = new JScrollPane(innerPanel) {
#Override
public Dimension getPreferredSize() {
setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
Dimension dim = new Dimension(super.getPreferredSize().width + getVerticalScrollBar().getSize().width, pref_height);
setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
return dim;
}
};
jsp.setBorder(new LineBorder(Color.green, 5));
JPanel outerPanel = new JPanel();
outerPanel.setBorder(new LineBorder(Color.RED, 5));
outerPanel.add(jsp);
JFrame frame = new JFrame();
JDesktopPane jdp = new JDesktopPane();
frame.add(jdp);
jdp.setPreferredSize(new Dimension(800, 600));
frame.pack();
JInternalFrame jif = new JInternalFrame("Title", true, true, true, true);
jif.pack();
jif.add(outerPanel);
jdp.add(jif);
jif.pack();
jif.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
I want the JScrollPane to resize whenever the parent JPanel is resized. Basically, I want the green border to line up with the red border. Right now, the green border stays the same size no matter the red border (unless you resize too small).
JPanel outerPanel = new JPanel();
A JPanel uses a FlowLayout by default which always respects the size of the component added to it. As a guess, maybe you can use:
JPanel outerPanel = new JPanel( new BorderLayout() );
A BorderLayout give all the space available to the component added to the panel. By default a JInternalFrame also uses a BorderLayout. So since all the parent components of your scroll pane use a BorderLayout all the space should go to the scroll pane.
When you post a SSCCE you should post code using classes from the JDK that simulates your problem so that everybody can test your SSCCE.
I noticed this did not have an answer that uses the original layout so here is one.
In order to make the JScrollPane resize when the parent JPanel is resized you need to do two things.
1) Set the layout of the panel to grow. This can be using the following code.
new MigLayout("", //Layout Constraints
"grow", //Column Constraints
"grow"); //Row Constraints
2) Set the component to grow. This is as simple as adding an extra argument in the add() function.
add(jsp, "grow");
ExtraIn order to make the JTextArea column grow when you resize the JScrollPane you can change the layout to only make the second column change. For example
new MigLayout("", //Layout Constraints
"[/*Column 1*/][grow /*Column 2*/]", //Column Constraints
""); //Row Constraints
Also, I would recommend you use wrap instead of span to use the next row as span refers using so many columns. For example span 2 //Means use 2 columns for this component. This would mean when you add your jsp to innerPanel it would become
innerPanel.add(jsp, "wrap, grow");
Edited SSSCE
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import net.miginfocom.swing.MigLayout;
public class JSPR extends JFrame {
public static final int pref_height = 500;
public static void main(String[] args) {
JPanel innerPanel = new JPanel(new MigLayout("", "[][grow]", ""));
innerPanel.setBorder(new LineBorder(Color.YELLOW, 5));
for(int i = 0; i < 15; i++) {
JTextArea textArea = new JTextArea();
textArea.setColumns(20);
textArea.setRows(5);
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
JScrollPane jsp = new JScrollPane(textArea);
innerPanel.add(new JLabel("Notes" + i));
innerPanel.add(jsp, "wrap, grow");
}
JScrollPane jsp = new JScrollPane(innerPanel) {
#Override
public Dimension getPreferredSize() {
setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
Dimension dim = new Dimension(super.getPreferredSize().width + getVerticalScrollBar().getSize().width, pref_height);
setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
return dim;
}
};
jsp.setBorder(new LineBorder(Color.green, 5));
JPanel outerPanel = new JPanel(new MigLayout("", "grow", "grow"));
outerPanel.setBorder(new LineBorder(Color.RED, 5));
outerPanel.add(jsp, "grow");
JFrame frame = new JFrame();
JDesktopPane jdp = new JDesktopPane();
frame.add(jdp);
jdp.setPreferredSize(new Dimension(800, 600));
frame.pack();
JInternalFrame jif = new JInternalFrame("Title", true, true, true, true);
jif.pack();
jif.add(outerPanel);
jdp.add(jif);
jif.pack();
jif.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Adding elements (i.e. JLabels) outside of the set layout

As part of a project we've got to have 9 boxes, here I've just implemented alternating colors as an example in place of the images we should be using. But whilst I want these 9 JLabels in this grid layout (3,3), I also want to have a message at the top (a JLabel) that I can just centralize, like a welcoming message as well as having around four JButtons underneath? Can somebody please point me in the right direction as to how to achieve this?
Thank you!
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class HomeController extends JPanel implements MouseListener
{
HomeController()
{
setLayout(new GridLayout(3,3));
JLabel apl1 = new JLabel("");
apl1.setBackground(Color.WHITE);
apl1.setOpaque(true);
this.add(apl1);
JLabel apl2 = new JLabel("");
apl2.setBackground(Color.BLACK);
apl2.setOpaque(true);
this.add(apl2);
JLabel apl3 = new JLabel("");
apl3.setBackground(Color.WHITE);
apl3.setOpaque(true);
this.add(apl3);
JLabel apl4 = new JLabel("");
apl4.setBackground(Color.BLACK);
apl4.setOpaque(true);
this.add(apl4);
JLabel apl5 = new JLabel("");
apl5.setBackground(Color.WHITE);
apl5.setOpaque(true);
this.add(apl5);
JLabel apl6 = new JLabel("");
apl6.setBackground(Color.BLACK);
apl6.setOpaque(true);
this.add(apl6);
JLabel apl7 = new JLabel("");
apl7.setBackground(Color.WHITE);
apl7.setOpaque(true);
this.add(apl7);
JLabel apl8 = new JLabel("");
apl8.setBackground(Color.BLACK);
apl8.setOpaque(true);
this.add(apl8);
JLabel apl9 = new JLabel("");
apl9.setBackground(Color.WHITE);
apl9.setOpaque(true);
this.add(apl9);
JLabel message = new JLabel("hello world");
this.add(message);
}
}
You can combine multiple panels with different layouts. For details take a look at A Visual Guide to Layout Managers.
For example, default layout of JFrame is BorderLayout. Using BorderLayout, you can place the title at BorderLayout.NORTH, panel with buttons at BorderLayout.SOUTH and panel with grid of labels at BorderLayout.CENTER. Each panel may have its own more complex layout. For example, grid of labels is using GridLayout, and buttons panel is using FlowLayout.
Here is a very simple example based on the posted code that demonstrates this approach:
import java.awt.*;
import javax.swing.*;
public class TestGrid {
public TestGrid() {
final JFrame frame = new JFrame("Grid");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel(new GridLayout(3, 3));
for (int idx = 0; idx < 9; idx++) {
JLabel label = new JLabel();
label.setBackground(idx % 2 == 0 ? Color.WHITE : Color.BLACK);
label.setOpaque(true);
mainPanel.add(label);
}
mainPanel.setPreferredSize(new Dimension(200, 200));
frame.add(mainPanel, BorderLayout.CENTER);
frame.add(new JLabel("Title", JLabel.CENTER), BorderLayout.NORTH);
JPanel buttonsPanel = new JPanel();
buttonsPanel.add(new JButton("Start"));
buttonsPanel.add(new JButton("Stop"));
frame.add(buttonsPanel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestGrid();
}
});
}
}

Adding components into JPanel inside a JFrame

Since im a beginner and i don't want to get involved with the layout managers, i was simply adding a JPanel into my main JFrame and giving spesific location to each component in the panel. But somehow the output appears way too wrong..
frame = new JFrame(email + " (Offline)");
frame.setSize(400, 400);
frame.setLocation(0, 0);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
// out.println("BYE");
// out.flush();
frame.dispose();
thread.stop();
}
});
panel = new JPanel();
frame.add(panel);
chat = new JTextArea();
chat.setSize(400, 200);
chat.setLocation(0, 0);
chat.setEditable(false);
panel.add(chat);
panel.validate();
JLabel you = new JLabel("You:");
you.setSize(you.getPreferredSize());
you.setLocation(0, 210);
panel.add(you);
panel.validate();
input = new JTextArea();
input.setSize(200, 200);
input.setLocation(0, 220 + chat.getSize().height);
panel.add(input);
panel.validate();
send = new JButton("Send");
send.setSize(send.getPreferredSize());
send.setLocation(210, 220 + chat.getSize().height);
panel.add(send);
panel.validate();
frame.setVisible(true);
The outcome of this frame is that text areas are invisible, a You: label in the middle and next to the right of it the button.. What am i missing here?
Again, don't use null layout since it makes updating and maintaining your GUI much more difficult than it should be, and can lead to ugly GUI's if you plan on having them run on multiple platforms. Instead
Use several JPanels, each one holding a core group of components and each using its best layout manager
Nest these JPanels in other JPanels that use the best layout manager to display them
and that will allow your GUI to be resizeable without need of extra code.
Put your JTextAreas in JScrollPanes so that you can see all text even if it goes beyond the text area.
Never set the size of the JTextArea as that will not allow it to scroll. Instead set its columns and rows.
As a very simple example, run this to see what I mean:
import java.awt.*;
import javax.swing.*;
public class FooSwing2 {
public static void main(String[] args) {
JTextArea chatArea = new JTextArea(8, 40);
chatArea.setEditable(false);
chatArea.setFocusable(false);
JScrollPane chatScroll = new JScrollPane(chatArea);
JPanel chatPanel = new JPanel(new BorderLayout());
chatPanel.add(new JLabel("Chat:", SwingConstants.LEFT), BorderLayout.PAGE_START);
chatPanel.add(chatScroll);
JTextField inputField = new JTextField(40);
JButton sendBtn = new JButton("Send");
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.LINE_AXIS));
inputPanel.add(inputField);
inputPanel.add(sendBtn);
JPanel youLabelPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
youLabelPanel.add(new JLabel("You:"));
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
mainPanel.add(chatPanel);
mainPanel.add(Box.createVerticalStrut(10));
mainPanel.add(youLabelPanel);
mainPanel.add(inputPanel);
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
This would result in a simple (non-functioning) GUI that looked like this:
Now say you want to change this and add another button, an "exit" JButton to the right of the send JButton. If you used null layout, you'd have to resize your GUI, you'd have to move the send button over to the left and make sure that your math was without error, etc. If you used layout managers, you'd need just two new lines of code (to change the display, not the functionality of course):
JTextField inputField = new JTextField(40);
JButton sendBtn = new JButton("Send");
JButton exitBtn = new JButton("Exit"); // ***** added
JPanel inputPanel = new JPanel();
inputPanel.setLayout(new BoxLayout(inputPanel, BoxLayout.LINE_AXIS));
inputPanel.add(inputField);
inputPanel.add(sendBtn);
inputPanel.add(exitBtn); // ***** added
That's it, and this would display:

Categories

Resources