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

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

Related

I can't make JScrollPane show the list of JLabels

What I have: there are names of fonts on my computer (fontMassive.getFont[]);
What I need: Scrollable list of JLabel components named by these fonts;
Java shows to me one String without scroll;
I tried to replace FlowLayout with BorderLayout so that JScrollPane would understand that I need scroll, but the scroll pane just disappeared.
What am I doing wrong?
import javax.swing.*;
import java.awt.*;
public class Window extends JFrame {
public Window() {
JPanel mainPanel = new JPanel();
JPanel secondaryPanel = new JPanel();
ArrayOfFonts fontMassive = new ArrayOfFonts();
//Font font = new Font("Sitka Banner",Font.PLAIN, 14);
JScrollPane scroll = new JScrollPane();
setBounds(100,100,600,600);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("FontView");
setLayout( new FlowLayout());
JLabel[] jLabels = new JLabel[fontMassive.getLength()];
for (int i = 0; i < fontMassive.getLength(); i++) {
jLabels[i] = new JLabel(fontMassive.getFont(i));
jLabels[i].setFont(new Font(fontMassive.getFont(i),Font.PLAIN, 14));;
secondaryPanel.add(jLabels[i]);
}
secondaryPanel.setLayout(new FlowLayout());
scroll.setViewportView(secondaryPanel);
mainPanel.add(scroll);
setContentPane(mainPanel);
setVisible(true);
}
}

Java GUI - Possible to store JPanels inside a single main JPanel?

I am working on a semester project that I have and I was wondering if it was possible to store 3-4 JPanels instead one single "main" JPanel. The reason for me asking this is because I a trying to make a GUI checkbook program and my checkbook has 7 buttons that should open a new window once I click on it. To switch between each window I'm going to have to use the CardLayout, but my understand of the CardLayout is that I can only assign one single JPanel to that card so I can't assign multiple JPanels to a single Card layout so when the user clicks on a different card 3-4 different JPanels appear.
The reason that I am asking this is because I asked for help earlier and received help for creating my first window in this project, it produces the output I want PERFECTLY, but uses more than 1 JPanel in doing so. Since this prevents me from continuing on to the other steps of my 7 GUI Windows, I am stuck.
Here is the code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class checkbook extends JPanel implements ActionListener {
private static final String title = "Use The Buttons Below To Manage Transactions";
private static final String[] bottomButtons = { "Create a New Account",
"Load a Trans from a File", "Add New Transactions",
"Search Transactions", "Sort Transactions",
"View/Delete Transactions", "Backup Transaction", "Exit" };
static JButton Button[] = new JButton[8];
static ActionListener AL = new checkbook();
public checkbook() {
JLabel titleLabel = new JLabel(title, SwingConstants.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 18));
JPanel titlePanel = new JPanel();
titlePanel.add(titleLabel); // put it in a JPanel so it will expand to fill BoxLayout
JTextField textfield = new JTextField();
JPanel accountBalancePanel = new JPanel();
accountBalancePanel.add(new JLabel("Account Name:"));
accountBalancePanel.add(new JTextField(10));
accountBalancePanel.add(Box.createHorizontalStrut(4));
accountBalancePanel.add(new JLabel("Balance:"));
textfield = new JTextField("0.0", 10);
textfield.setHorizontalAlignment(JTextField.RIGHT);
accountBalancePanel.add(textfield);
JPanel northPanel = new JPanel();
northPanel.setLayout(new BoxLayout(northPanel, BoxLayout.PAGE_AXIS));
northPanel.add(titlePanel);
northPanel.add(accountBalancePanel);
JPanel southBtnPanel = new JPanel(new GridLayout(2, 4, 1, 1));
for(int i = 0; i < 8; i++){
Button[i] = new JButton(bottomButtons[i]);
southBtnPanel.add(Button[i]);
Button[i].addActionListener(AL);
}
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
setLayout(new BorderLayout());
add(northPanel, BorderLayout.NORTH);
add(Box.createRigidArea(new Dimension(100, 100))); // just an empty placeholder
add(southBtnPanel, BorderLayout.SOUTH);
}
private static void createAndShowGui() {
checkbook mainPanel = new checkbook();
JFrame frame = new JFrame("Checkbook");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
createAndShowGui();
}
});
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == Button[7]) {
System.exit(0);
}
}
}
Credit goes to Hovercraft Full Of Eels for showing me the above example
If there is anything that is unclear about my question, please ask and I will do the best I can to fix it.
Here is what the code produces:
http://i.stack.imgur.com/WY0c3.png

Placing of JPanels on the JFrames is not correct

I wrote a program to compose a GUI using swing/awt framework for my assignment. So far, I am able to get the pieces working together, but when I put them all into a JFrame, they are not coming out as expected.
I have recently started working on Java GUI framework, and not sure what is missing in my code. How can I get this working properly?
I am also attaching the screen shots (see at the bottom) of the output I am getting.
public class MainFrame extends JFrame {
public MainFrame() {
addComponentsToPane(this.getContentPane());
}
private void addComponentsToPane(Container pane) {
// Set layout
GridBagConstraints gbc = new GridBagConstraints();
this.setTitle("Test tool");
this.setSize(600, 650);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new GridLayout(2, 1));
// Add video JComponent
mMainPanel = new MainPanel();
pane.add(mMainPanel, 0);
// Add conference screen panel
mFeedPanel = new FeedPanel();
pane.add(mFeedPanel, 1);
// Add a button panel
mButtonPanel = new ButtonPanel();
pane.add(mButtonPanel, 2);
this.setResizable(true);
this.setVisible(true);
this.pack();
}
}
// In actual output, there is 1 screen in this panel.
// mScreen1 is derived from JComponent object.
public class MainPanel() extends JPanel {
public MainPanel() {
addMainPanelComponents();
}
private void addMainPanelComponents() {
this.setSize(352, 240);
setBackground(Color.yellow);
setLayout(new GridLayout(1, 2));
add(mScreen);
setVisible(true);
}
}
// In actual output, there are 3 screens in this panel. I have shown code for 1 screen only
// mScreen1 is derived from JComponent object.
public class FeedPanel extends JPanel {
public FeedPanel() {
addFeedPanelComponents();
}
private void addFeedPanelComponents() {
String img1 = "images/screen1.png";
setSize(352, 150);
setBackground(Color.yellow);
setLayout(new GridLayout(1, 3));
Image image1 = ImageIO.read(new File(img1));
mScreen1.setImage(image1);
add(mScreen1);
setVisible(true);
}
}
public class ButtonPanel extends JPanel {
public ButtonPanel() {
addButtonPanelComponents();
}
private void addButtonPanelComponents() {
this.setSize(352, 150);
this.setBackground(Color.yellow);
this.setLayout(new GridLayout(1,
5));
// Add Button to panel
mStartButton = new JButton("Start");
this.add(mStartButton);
mStartButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
StartButtonActionListener(ae);
}
});
mStopButton = new JButton("Stop");
this.add(mStopButton);
mStopButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
StopButtonActionListener(ae);
}
});
setVisible(true);
}
}
This comes by default on running the code.
This comes after manually resizing the frame.
The combination of BorderLayout , GirdLayout and BoxLayout can do this for you(Actually it's not the only choice).
Here is the code:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GridLayoutTest {
public void createUI(){
JFrame frame = new JFrame();
JPanel topPanel = new TopPanel();
JPanel buttomPanel = new ButtomPanel();
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(topPanel,BorderLayout.CENTER);
mainPanel.add(buttomPanel,BorderLayout.SOUTH);
frame.add(mainPanel,BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
GridLayoutTest test = new GridLayoutTest();
test.createUI();
}
#SuppressWarnings("serial")
class TopPanel extends JPanel{
public TopPanel(){
setLayout(new GridLayout(2, 3));
ImageIcon icon = new ImageIcon("capture.png");
JLabel label1 = new JLabel(icon);
label1.setVisible(false);
JLabel label2 = new JLabel(icon);
JLabel label3 = new JLabel(icon);
label3.setVisible(false);
JLabel label4 = new JLabel(icon);
JLabel label5 = new JLabel(icon);
JLabel label6 = new JLabel(icon);
add(label1);
add(label2);
add(label3);
add(label4);
add(label5);
add(label6);
}
}
#SuppressWarnings("serial")
class ButtomPanel extends JPanel{
public ButtomPanel(){
JButton startButton = new JButton("start");
JButton stopButton = new JButton("stop");
JButton recordButton = new JButton("record");
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(Box.createHorizontalGlue());
add(startButton);
add(Box.createHorizontalStrut(10));
add(stopButton);
add(Box.createHorizontalStrut(10));
add(recordButton);
add(Box.createHorizontalGlue());
}
}
}
BoxLayout is so good too provide white space and help you to center the component.
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(Box.createHorizontalGlue());
add(startButton);
add(Box.createHorizontalStrut(10));
add(stopButton);
add(Box.createHorizontalStrut(10));
add(recordButton);
add(Box.createHorizontalGlue());
Add Glue before the first component and after the last component will help you too center the component and add strut can help you to provide white space you want. you can refer to https://stackoverflow.com/a/22525005/3378204 for more details.
Here is the effect:
The BoxLayout won't affect your component's size. Hope it can help you.
Try this :
public class Main{
private JFrame f;
private JLabel l1, l2, l3,l4;
private JPanel p1, p2, p3;
private JButton b1, b2, b3;
public Main(){
this.f = new JFrame();
this.f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.f.setLayout(new GridLayout(3,1));
this.p1 = new JPanel();
this.p1.setLayout(null)
this.p1.setSize(yoursize);
this.l1 = new JLabel();
this.l1.setBounds(x,y,xspan,yspan);
this.p1.add(l1);
this.p2 = new JPanel();
this.p2.setLayout(new GridLayout(1,3));
this.l2 = new JLabel();
this.l3 = new JLabel();
this.l4 = new JLabel();
this.p2.add(l2);
this.p2.add(l3);
this.p2.add(l4);
this.p3 = new JPanel();
this.p3.setLayout(new GridLayout(1,3));
this.b1 = new JButton();
this.b2 = new JButton();
this.b3 = new JButton();
this.p3.add(b1);
this.p3.add(b2);
this.p3.add(b3);
this.f.add(p1);
this.f.add(p2);
this.f.add(p3);
this.f.pack();
this.f.setResizeable(false)
}}
Add your video components instead of labels and you can change the color of the components as you wish.
Also if you want more control over the size and position of the components, use null layout and place them individually using setBounds() function as once shown in the program above. It is surely time consuming but makes the layout perfect.

Resizable Swing layout with buttons arranged according to variable dimensions

I would like to make a layout using Java Swing which looks like the following drawing.
(source: braun-abstatt.de)
On the left is a JPanel which is drawn through paintComponent() in a way that the graphics automatically scale when the window is resized. (The question isn't about that panel. That one's already done.)
Now I need some buttons (the black boxes, added in Photoshop for the drawing) to the right of the JPanel mentioned before. The height of the reddish areas at the top and bottom, next to which there should be just empty space, is calculated along the lines of CONSTANT_FACTOR * getHeight(). Next to each compartment on the left, there should be a group of buttons, lined up to the center of the respective compartment (see the blue lines).
The JPanel containing the buttons knows about the CONSTANT_FACTOR and the number of compartments, so it should be possible to feed this information into a layout manager.
Which layout manager would I best use to achieve this layout? I've read about all the different layout managers, but I can't quite figure out which one or which combination of them best fits in this case.
For example, by use of a different LayoutManager, a very easy and simple container, takes no more than 15-20 minutes:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public class ThinLineFrame {
private JFrame frame = new JFrame();
private JScrollPane scrollPane;
private JPanel panel = new JPanel();
private JPanel panelNorth = new JPanel();
private JPanel panelCenter = new JPanel();
private JPanel panelCenterCh1 = new JPanel();
private JPanel panelCenterCh2 = new JPanel();
private JPanel panelCenterCh3 = new JPanel();
private JPanel panelCenterCh4 = new JPanel();
private JPanel panelCenterCh5 = new JPanel();
private JPanel panelSouth = new JPanel();
public ThinLineFrame() {
panelNorth.setBackground(Color.red.darker());
panelNorth.setPreferredSize(new Dimension(80, 30));
//
panelCenter.setBackground(Color.darkGray);
panelCenter.setLayout(new GridLayout(5, 1, 2, 2));
//
panelCenterCh1.setLayout(new BorderLayout());
JButton panelCenterCh1Button = new JButton();
panelCenterCh1.add(panelCenterCh1Button, BorderLayout.CENTER);
//
JButton panelCenterCh2Button1 = new JButton();
JButton panelCenterCh2Button2 = new JButton();
panelCenterCh2.setLayout(new GridLayout(2, 1, 2, 2));
panelCenterCh2.add(panelCenterCh2Button1);
panelCenterCh2.add(panelCenterCh2Button2);
//
JButton panelCenterCh3Button1 = new JButton();
JButton panelCenterCh3Button2 = new JButton();
panelCenterCh3.setLayout(new GridLayout(2, 1, 2, 2));
panelCenterCh3.add(panelCenterCh3Button1);
panelCenterCh3.add(panelCenterCh3Button2);
//
JButton panelCenterCh4Button1 = new JButton();
JButton panelCenterCh4Button2 = new JButton();
panelCenterCh4.setLayout(new GridLayout(2, 1, 2, 2));
panelCenterCh4.add(panelCenterCh4Button1);
panelCenterCh4.add(panelCenterCh4Button2);
//
panelCenterCh5.setLayout(new BorderLayout());
JButton panelCenterCh5Button = new JButton();
panelCenterCh5.add(panelCenterCh5Button, BorderLayout.CENTER);
//
panelCenter.add(panelCenterCh1);
panelCenter.add(panelCenterCh2);
panelCenter.add(panelCenterCh3);
panelCenter.add(panelCenterCh4);
panelCenter.add(panelCenterCh5);
//
panelSouth.setBackground(Color.red.darker());
panelSouth.setPreferredSize(new Dimension(80, 30));
//
panel.setLayout(new BorderLayout(2, 2));
panel.add(panelNorth, BorderLayout.NORTH);
panel.add(panelCenter, BorderLayout.CENTER);
panel.add(panelSouth, BorderLayout.SOUTH);
//
scrollPane = new JScrollPane(panel);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(80, 600));
frame.setLocation(100, 150);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ThinLineFrame dlg = new ThinLineFrame();
}
});
}
}
You should try looking at MigLayout. It's a super flexible LayoutManager that is also very simple.
The code would look something like:
MigLayout layout = new MigLayout("flowy");
panel.setLayoutManager(layout);
panel.add(button1);
panel.adD(button2);
etc..
Try adding debug, flowy to the constructor to get a visual idea of what is going on.
GBC without an anchor, just with plain vanilla GridBagConstraints and preferred size.
Centered JButton with fixed size:
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class MainWithFixSize {
public static void main(String[] argv) throws Exception {
JFrame frame = new JFrame();
Container container = frame.getContentPane();
GridBagLayout gbl = new GridBagLayout();
container.setLayout(gbl);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 1;
JButton component = new JButton();
component.setPreferredSize(new Dimension(25, 25));
gbl.setConstraints(component, gbc);
container.add(component);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(40, 90));
frame.pack();
frame.setVisible(true);
}
private MainWithFixSize() {
}
}

How to add JTable in JPanel with null layout?

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

Categories

Resources