Java Swing Layout - java

I would like the following lay out...
JButtons on top along side eachother.
The JTextArea should be under the buttons.
The JTextArea should also have a scrollbar.
...for the code below.
JPanel jp = new JPanel();
One = new JButton("One");
Two = new JButton("Two");
TestOutput = new JTextArea();
jp.add(One);
jp.add(Two);
jp.add(TestOutput);

Use a nested layout: To a JPanel having BorderLayout,
add a JPanel having FlowLayout for the buttons to the NORTH
and a JScrollPane for the JTextArea to the CENTER.

The keyword is layering - having JPanel on JPanel.

Use a GridBagLayout
See this for more help : How to Use GridBagLayout
Now note that the JTextarea to have a scrollbar have nothing to do with layouts.
See this for more help in that context : How to Use Scroll Panes

The FlowLayout in a JPanel for the JButton instances is one way to go. You might also use a JToolBar for the buttons.
import java.awt.*;
import javax.swing.*;
class ButtonsAndTextAreaLayout {
ButtonsAndTextAreaLayout() {
JPanel gui = new JPanel(new BorderLayout(5,5));
// use a toolbar for the buttons
JToolBar tools = new JToolBar();
// use firstWordLowerCase for attribute/method names.
JButton one = new JButton("One");
JButton two = new JButton("Two");
tools.add(one);
tools.add(two);
// provide hints as to how large the text area should be
JTextArea testOutput = new JTextArea(5,20);
gui.add(tools, BorderLayout.NORTH);
gui.add(new JScrollPane(testOutput), BorderLayout.CENTER);
JOptionPane.showMessageDialog(null, gui);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ButtonsAndTextAreaLayout();
}
});
}
}

You can either use a GridBagLayout as suggested, or nest multiple layout managers such as:
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
JPanel buttonPanel = new JPanel();
JButton oneButton = new JButton("One");
JButton twoButton = new JButton("Two");
buttonPanel.add(oneButton);
buttonPanel.add(twoButton);
JTextArea output = new JTextArea();
JScrollPane scrollPane = new JScrollPane(output);
frame.add(buttonPanel, BorderLayout.NORTH);
frame.add(scrollPane);
frame.pack();
frame.setVisible(true);

Related

How do I create the following GUI in Java Swing?

I want to create the following GUI with Java Swing.
Since I'm not experienced enough with Java Swing, I'm not sure how to exactly recreate that GUI.
I've tried using GridLayout which looks like this:
I've tried other LayoutManagers but due to my inexperience, I couldn't get anything even remotely resembling the GUI I want to achieve.
I probably have to use GridBagLayout but I've tried it and simply wasn't able to get anything done.
I'm not sure how to exactly use GridBagLayout, especially since there is a variance of the amount of colums needed (2, 2 and then 3).
Here is the code used for creating the second GUI:
import java.awt.*;
import javax.swing.*;
public class GUITest extends JFrame {
public GUITest() {
super("Testing Title");
Container pane = getContentPane();
pane.setLayout(new GridLayout(3,1));
pane.add(getHeader());
pane.add(getTextArea());
pane.add(getButtonPanel());
}
public JComponent getHeader() {
JPanel labelPanel = new JPanel();
labelPanel.setLayout(new GridLayout(1,2));
labelPanel.setSize(getPreferredSize());
JLabel labelLocal = new JLabel("Left value: ", JLabel.CENTER);
JLabel labelDB = new JLabel("Right value: ", JLabel.CENTER);
labelPanel.add(labelLocal);
labelPanel.add(labelDB);
return labelPanel;
}
public JComponent getTextArea() {
JPanel textPanel = new JPanel();
textPanel.setLayout(new GridLayout(1,2,5,0));
JTextArea testTextArea = new JTextArea();
testTextArea.setEditable(false);
JScrollPane sp1 = new JScrollPane(testTextArea);
JTextArea testTextArea2 = new JTextArea();
JScrollPane sp2 = new JScrollPane(testTextArea2);
testTextArea2.setEditable(false);
testTextArea.setText("Hello Hello Hello\nTesting!\ntesterino\ntesteroni");
testTextArea2.setText("Hello Hello Hello\nTesting!\ntest\nABC123\ncdef123\nhijk123");
textPanel.add(sp1);
textPanel.add(sp2);
return textPanel;
}
public JComponent getButtonPanel() {
JPanel inner = new JPanel();
inner.setLayout(new FlowLayout((FlowLayout.CENTER),0,100));
inner.add(new JButton("Do something"));
inner.add(new JButton("Do something different"));
inner.add(new JButton("Do something even more different"));
return inner;
}
public static void main(String[] args) {
GUITest e = new GUITest();
e.setSize(700, 500);
e.setVisible(true);
e.setResizable(false);
e.setDefaultCloseOperation(EXIT_ON_CLOSE);
e.setLocationRelativeTo(null);
}
}
I'm thankful for any kind of support!
You could try something like this:
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
public class Example {
public static void main(String[] args) {
JFrame jFrame = new JFrame();
jFrame.setTitle("Testing Title");
jFrame.setLocationRelativeTo(null);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
JPanel listPanel = new JPanel(new GridLayout(0, 2, 10, 0));
JPanel leftListPanel = new JPanel(new BorderLayout(0, 10));
JLabel leftLabel = new JLabel("Left value:");
JTextArea leftTextArea = new JTextArea("Hello Hello Hello\nTesting!\ntest");
JScrollPane leftScrollPane = new JScrollPane(leftTextArea);
leftListPanel.add(leftLabel, BorderLayout.NORTH);
leftListPanel.add(leftScrollPane, BorderLayout.CENTER);
JPanel rightListPanel = new JPanel(new BorderLayout(0, 10));
JLabel rightLabel = new JLabel("Right value:");
JTextArea rightTextArea = new JTextArea("Hello Hello Hello\nTesting!\ntest");
JScrollPane rightScrollPane = new JScrollPane(rightTextArea);
rightListPanel.add(rightLabel, BorderLayout.NORTH);
rightListPanel.add(rightScrollPane, BorderLayout.CENTER);
listPanel.add(leftListPanel);
listPanel.add(rightListPanel);
mainPanel.add(listPanel, BorderLayout.CENTER);
JPanel buttonsPanel = new JPanel(new BorderLayout());
buttonsPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
buttonsPanel.add(new JButton("Do something"), BorderLayout.WEST);
buttonsPanel.add(new JButton("Do something different"), BorderLayout.CENTER);
buttonsPanel.add(new JButton("Do something even more different"), BorderLayout.EAST);
mainPanel.add(buttonsPanel, BorderLayout.SOUTH);
jFrame.setContentPane(mainPanel);
jFrame.pack();
jFrame.setVisible(true);
}
}
Explanation:
Firstly I created a main JPanel with a BorderLayout. This JPanel will be split horizontally, the CENTRE component will be another JPanel containing the text areas and labels, and the SOUTH component will be a JPanel containing the buttons.
The JPanel that contains the text areas is given a GridLayout so that it can be easily split vertically, and is also given a hgap of 10 to add some spacing.
The left and right JPanels that are put into that are both the same. They have a BorderLayout with a vgap to add spacing. The NORTH component is a JLabel and the CENTRE component is a JScrollPane containing a JTextArea.
Finally, the SOUTH component of the main JPanel is another JPanel which is given a BorderLayout again. Three JButtons are added with WEST, CENTRE and EAST attributes allocated accordingly.
The overall result looks like:
Here is your code with just some little changes :)
import java.awt.*;
import javax.swing.*;
public class GUITest extends JFrame {
public GUITest() {
super("Testing Title");
Container pane = getContentPane();
pane.setLayout(new BorderLayout());//Modified Layout to BorderLayout
pane.add(getHeader(),BorderLayout.NORTH); //BorderLayout.NORTH
pane.add(getTextArea(),BorderLayout.CENTER);//BorderLayout.CENTER
pane.add(getButtonPanel(),BorderLayout.SOUTH);//BorderLayout.SOUTH
}
public JComponent getHeader() {
JPanel labelPanel = new JPanel();
labelPanel.setLayout(new GridLayout(1,2));
labelPanel.setSize(getPreferredSize());
JLabel labelLocal = new JLabel("Left value: ", JLabel.CENTER);
JLabel labelDB = new JLabel("Right value: ", JLabel.CENTER);
labelPanel.add(labelLocal);
labelPanel.add(labelDB);
return labelPanel;
}
public JComponent getTextArea() {
JPanel textPanel = new JPanel();
textPanel.setLayout(new GridLayout(1,2,5,0));
JTextArea testTextArea = new JTextArea();
testTextArea.setEditable(false);
JScrollPane sp1 = new JScrollPane(testTextArea);
JTextArea testTextArea2 = new JTextArea();
JScrollPane sp2 = new JScrollPane(testTextArea2);
testTextArea2.setEditable(false);
testTextArea.setText("Hello Hello Hello\nTesting!\ntesterino\ntesteroni");
testTextArea2.setText("Hello Hello Hello\nTesting!\ntest\nABC123\ncdef123\nhijk123");
textPanel.add(sp1);
textPanel.add(sp2);
return textPanel;
}
public JComponent getButtonPanel() {
JPanel inner = new JPanel();
inner.setLayout(new FlowLayout());//Modified to standard FlowLayout
inner.add(new JButton("Do something"));
inner.add(new JButton("Do something different"));
inner.add(new JButton("Do something even more different"));
return inner;
}
public static void main(String[] args) {
GUITest e = new GUITest();
e.pack(); //Modified setSize(700,500) to pack()
e.setVisible(true);
e.setResizable(false);
e.setDefaultCloseOperation(EXIT_ON_CLOSE);
e.setLocationRelativeTo(null);
}
}
GridLayout sizes all cells the same, i.e. your outer layout with 3 rows and 1 column makes 3 cells of all the same size.
Instead, use BorderLayout for your outer container and add the top, mid and lower panels with constraints BorderLayout.NORTH, BorderLayout.CENTER and BorderLayout.SOUTH respectively

JButtons only appear on JFrame if in BorderLayout.CENTER, not SOUTH or NORTH

So I'm trying to create a gui, I've tinkered with gui's before in java but I'm still new to them. So my issued here is that my JLabels (butLabel & cbLabel) are filled with buttons and checkboxes. Sadly my JFrame will only show whichever is set to the BorderLayout.CENTER. NORTH & SOUTH don't ever show, even if I only set the butLabel to SOUTH and don't even use the cbLabel. What am I overlooking?? It's much appreciated, thanks!
public class mainWindow
{
JFrame frame = new JFrame("Main Window");
JLabel butLabel = new JLabel();
JLabel cbLabel = new JLabel();
JButton showBut = new JButton("Show");
JButton exitBut = new JButton("Exit");
JButton addBut = new JButton("Add");
JButton remBut = new JButton("Remove");
JCheckBox aCB = new JCheckBox("Airplane");
JCheckBox bCB = new JCheckBox("Boat");
JCheckBox cCB = new JCheckBox("Clock");
public mainWindow()
{
frame.setLayout(new BorderLayout()); //I know this is set by default to BorderLayout but I just did it when I was out of options to try.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setMinimumSize(new Dimension(360, 480));
butLabel.setLayout(new GridLayout(1,4));
cbLabel.setLayout(new GridLayout(2, 2));
butLabel.add(showBut);
butLabel.add(exitBut);
butLabel.add(addBut);
butLabel.add(remBut);
cbLabel.add(aCB);
cbLabel.add(bCB);
cbLabel.add(cCB);
frame.add(butLabel, BorderLayout.CENTER);
frame.add(cbLabel, BorderLayout.NORTH);
}
public void setVisible()
{
butLabel.setVisible(true);//Didn't think I needed butLabel.setVisible or the cbLabel.setVisible but
cbLabel.setVisible(true);//again I was trying things that I thought might make sense.
frame.setVisible(true);
}
}
do not use Label for grouping elements, use JPanel instead
I have tried replace all
Label
with
Panel
it works

GUI not showing as intended

I'm trying to draw a gui like shown in the figure, but somehow I'm not able to place the objects in right place (I guess that the problem is with the layout) the textArea is suppose to go in the middle... but is not showing at all
package Chapter22Collections;
import javax.swing.*;
import java.awt.*;
public class Exercise226 extends JFrame {
private JButton jbSort;
private JButton jbReverse;
private JButton jbAdd;
private JButton jbShuffle;
private JLabel jlAddnum;
private JTextArea jTextDisplay;
private JTextField jTextAdd;
public Exercise226() {
jbSort = new JButton("Sort");
jbReverse = new JButton("Reverse");
jbShuffle = new JButton("Shuffle");
jbAdd = new JButton("Add");
jlAddnum = new JLabel("Add number here: ");
jTextDisplay = new JTextArea();
jTextAdd = new JTextField(8);
setLayout(new BorderLayout());
JPanel p1 = new JPanel(new GridLayout(1,3));
p1.add(jlAddnum);
p1.add(jTextAdd);
p1.add(jbAdd);
JPanel p2 = new JPanel(new GridLayout(1,3));
p2.add(jbSort);
p2.add(jbReverse);
p2.add(jbShuffle);
add(p1, BorderLayout.NORTH);
add(jTextDisplay, BorderLayout.CENTER);
add(p2, BorderLayout.SOUTH);
}
public static void main(String... args) {
Exercise226 gui = new Exercise226();
gui.setTitle("Numbers");
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(300, 200);
gui.setLocationRelativeTo(null);
gui.setVisible(true);
}
}
The JTextArea is actually where you expect it to be but has no outline border. It is usual to place the component in a JScrollPane which will give this effect:
add(new JScrollPane(jTextDisplay), BorderLayout.CENTER);
or simply
add(new JScrollPane(jTextDisplay));
To make the textArea re-size with the window, try BoxLayout. Box is "A lightweight container that uses a BoxLayout object as its layout manager."
Box p1 = new Box(BoxLayout.X_AXIS);
How could I add spacing/padding between the elements in the frame? So the text area is more visible and centered.
Borders and padding. E.G.
Compared with:
import javax.swing.*;
import java.awt.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
public class Exercise226 {
private JButton jbSort;
private JButton jbReverse;
private JButton jbAdd;
private JButton jbShuffle;
private JLabel jlAddnum;
private JTextArea jTextDisplay;
private JTextField jTextAdd;
private JPanel gui;
public Exercise226() {
gui = new JPanel(new BorderLayout(5,5));
jbSort = new JButton("Sort");
jbReverse = new JButton("Reverse");
jbShuffle = new JButton("Shuffle");
jbAdd = new JButton("Add");
jlAddnum = new JLabel("Add number here: ");
// set the size constraints using columns/rows
jTextDisplay = new JTextArea("Here I am!", 6,20);
jTextAdd = new JTextField(8);
JPanel p1 = new JPanel(new GridLayout(1,3,3,3));
p1.add(jlAddnum);
p1.add(jTextAdd);
p1.add(jbAdd);
JPanel p2 = new JPanel(new GridLayout(1,3,3,3));
p2.add(jbSort);
p2.add(jbReverse);
p2.add(jbShuffle);
JPanel textAreaContainer = new JPanel(new GridLayout());
textAreaContainer.add(new JScrollPane(jTextDisplay));
textAreaContainer.setBorder(new TitledBorder("Text Area Here"));
gui.add(p1, BorderLayout.PAGE_START);
gui.add(textAreaContainer, BorderLayout.CENTER);
gui.add(p2, BorderLayout.PAGE_END);
gui.setBorder(new EmptyBorder(4,4,4,4));
}
public Container getGui() {
return gui;
}
public static void main(String... args) {
JFrame f = new JFrame();
Exercise226 gui = new Exercise226();
f.setContentPane(gui.getGui());
f.setTitle("Numbers");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
}
This code:
Primarily provides 'white space' in the GUI using different constructors for the layouts that accept 2 int arguments for horizontal & vertical spacing.
Also adds 2 borders:
An empty border around the entire GUI to provide some spacing between it and the frame decorations.
A titled border around the text area, to make it very obvious.
Does implement a change for one unnecessary part of the original code. Instead of extending frame, it simply retains an instance of one.
Uses the JScrollPane container for the text area, as suggested by #Reimeus. It adds a nice beveled border of its own to an element that needs no scroll bars.
Creates a textAreaContainer specifically so that we can set a titled border to surround the scroll pane - without interfering with its existing border. It is possible to use a CompoundBorder for the scroll pane that consists of the existing border (scroll.getBorder()) & the titled border. However that gets complicated with buttons & other elements that might change borders on selection or action. So to set an 'outermost border' for a screen element (like the text area here) - I generally prefer to wrap the entire component in another container first.
Does not create and show the GUI on the EDT. Swing GUIs should be created and modified on the EDT. Left as an exercise for the user. See Concurrency in Swing for more details.
Old Code
The original code on this answer that provides the 'comparison GUI image' seen above. IT is closely based on the original code but with the text area wrapped in a scroll pane (and gaining a beveled border because of that) & given some text to display.
import javax.swing.*;
import java.awt.*;
public class Exercise226 extends JFrame {
private JButton jbSort;
private JButton jbReverse;
private JButton jbAdd;
private JButton jbShuffle;
private JLabel jlAddnum;
private JTextArea jTextDisplay;
private JTextField jTextAdd;
public Exercise226() {
jbSort = new JButton("Sort");
jbReverse = new JButton("Reverse");
jbShuffle = new JButton("Shuffle");
jbAdd = new JButton("Add");
jlAddnum = new JLabel("Add number here: ");
// set the size constraints using columns/rows
jTextDisplay = new JTextArea("Here I am!", 6,20);
jTextAdd = new JTextField(8);
setLayout(new BorderLayout());
JPanel p1 = new JPanel(new GridLayout(1,3));
p1.add(jlAddnum);
p1.add(jTextAdd);
p1.add(jbAdd);
JPanel p2 = new JPanel(new GridLayout(1,3));
p2.add(jbSort);
p2.add(jbReverse);
p2.add(jbShuffle);
add(p1, BorderLayout.NORTH);
add(new JScrollPane(jTextDisplay), BorderLayout.CENTER);
add(p2, BorderLayout.SOUTH);
}
public static void main(String... args) {
Exercise226 gui = new Exercise226();
gui.setTitle("Numbers");
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//gui.setSize(300, 200);
gui.pack();
//gui.setLocationRelativeTo(null);
gui.setLocationByPlatform(true);
gui.setVisible(true);
}
}

JScrollPane In JFrame with two panels

I want to add a scroll bar to my JTextArea but it just won't show up. I have read a lot of stuff on forums but all in vain. Any suggestions are highly appreciated.
Thanks in advance. Below is my code.
JPanel pan, pan2;
JTextArea text = new JTextArea();
JTextField fname = new JTextField(18);
JLabel filename = new JLabel("Filename");
JButton view = new JButton("View");
public FileReading() {
setLayout(new BorderLayout());
pan = new JPanel();
pan2 = new JPanel();
JScrollPane scroll = new JScrollPane(text);
//scroll.setBounds(400,400,400,400);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
text.setEditable(false);
scroll.setViewportView(text);
pan2.add(scroll);
//scrollpane.setViewportView(text);
pan2.setLayout(new BorderLayout());
//pan2.add(scrollpane);
pan.setLayout(new FlowLayout());
pan.add(filename, FlowLayout.LEFT);
pan.add(fname, FlowLayout.CENTER);
pan.add(view, FlowLayout.RIGHT);
view.addActionListener(this);
fname.addActionListener(this);
pan2.add(text, BorderLayout.CENTER);
pan2.add(pan, BorderLayout.SOUTH);
//BorderLayout.EAST
//add(pan, BorderLayout.SOUTH);
add(pan2);//, BorderLayout.CENTER
setVisible(true);
}
public static void main(String args[]) {
FileReading frame = new FileReading();
frame.setTitle("Enter The Full Path to the File");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(400,400,400,400);
//frame.setSize(400,400);
}
You need to add scroll (JScrollPane) to the pan2 not to the text (JTextArea)
try this
pan2.add(scroll, BorderLayout.CENTER);
in place of pan2.add(text, BorderLayout.CENTER);
EDIT
JTextArea gets added automatically when we add JScrollPane into the panel, as you have added text (JTextArea) inside JScrollPane
here -> JScrollPane scroll = new JScrollPane(text);
Can try this
add(scroll);//, BorderLayout.CENTER
add(pan, BorderLayout.SOUTH);
instead of
add(pan2);//, BorderLayout.CENTER
This way we are directly adding the scrollpane to main frame and putting other things below

Refresh JTabbedPane component

I am trying to implement JTabbedPane. In the following code I have presented a case very similar to what I want to implement. I have created a tab by adding a JPanel to the JTabbedPane. I have added a JButton and JScrollPane to the JPanel. On click of the JButton I want to add a new JPanel having some JRadioButtons to the JScrollPane. But these are not shown even after refreshing the JScrollPane or main JPanel. Please help. The code is given below.
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Test {
static JFrame frame;
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
//Create and set up the window.
frame = new JFrame("DynamicTreeDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tp = new JTabbedPane();
final JScrollPane jsp = new JScrollPane();
JPanel jp = new JPanel();
JButton jb = new JButton("Refresh");
jb.setActionCommand("Show");
jb.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equalsIgnoreCase("Show")){
JRadioButton jrb1 = new JRadioButton("First Option");
JRadioButton jrb2 = new JRadioButton("Second Option");
JRadioButton jrb3 = new JRadioButton("Third Option");
ButtonGroup bg = new ButtonGroup();
bg.add(jrb1);
bg.add(jrb2);
bg.add(jrb3);
JPanel p = new JPanel(new GridLayout(0,1));
p.add(jrb1);
p.add(jrb2);
p.add(jrb3);
jsp.add(p);
jsp.revalidate();
jsp.repaint();
}
}
});
jp.setLayout(new GridLayout(0,1));
jp.add(jb);
jp.add(jsp);
tp.add("First Tab", jp);
frame.getContentPane().add(tp);
//Display the window.
frame.pack();
frame.setVisible(true);
}
}
To add something to JScrollPane use its JViewport rather than directly calling add(). In your example replace:
jsp.add(p);
with:
jsp.getViewport().add(p);
Alternatively, initialize JScrollPane with a JPanel that holds other components. Based on your example:
final JPanel panel = new JPanel();
final JScrollPane jsp = new JScrollPane(panel);
panel.add(new JRadioButton("First Option"));
panel.add(new JRadioButton("Second Option"));
panel.add(new JRadioButton("Third Option"));
See How to Use Scroll Panes for more details.
The components should be added to the JPanel called jp rather than directly to the scroll pane.
JScrollPane only works with a single "View". You cannot add components to the scrollPane. If you want, you can change the "View" using setViewPortView(). To achieve the behaviour you are looking for, do the following:
JPanel centralView = new JPanel();
// possibly configure that central view with appropriate layout and other stuffs
JScrollPane jsp = new JScrollPane(centralView);
...
// Now you can add your components to centralView instead of your jsp.add(...) calls.
You should add the JPanel to the JScollPanes viewport using getViewport(), then repack the JFrame to get the sizing issue sorted using pack();:
jsp.getViewport().add(p);
frame.pack();
instead of:
jsp.add(p);
jsp.revalidate();
jsp.repaint();

Categories