Problem with the layouts in making a JAVA GUI - java

Here is a screenshot of my JFrame. This will be the main window to my application.
So the problem is that all the buttons are inline with each other, whereas I want them to be one under the other i.e. Add Contact under Show Contacts.
So how can I do that?
Here is my code for the JFrame.
public class CRUDFrame extends JFrame {
public CRUDFrame(){
super("AppCRUD");
setLayout(new FlowLayout());
JButton button1, button2, button3, button4;
button1 = new JButton(" Show Contacts ");
button2 = new JButton(" Add Contact ");
button3 = new JButton(" Update Number in a Contact ");
button4 = new JButton(" Delete a Contact ");
add(button1);
add(button2);
add(button3);
add(button4);
}
}
`

There have been some good answers centered around 'use a layout'. This example espouses the same advice, but also introduces the concept of nesting one layout within another. E.G. the JPanel containing the JButtons has a GridLayout. That panel is placed in the NORTH of a panel that is then added to the WEST of the main 'gui' panel.
The other components are added in order to show how the column of buttons might go together with other components in the main user interface.
Contact.java
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
class Contact {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
JPanel gui = new JPanel(new BorderLayout(5,5));
gui.setBorder( new EmptyBorder(3,3,3,3) );
JPanel controls = new JPanel( new BorderLayout(5,5) );
JPanel buttons = new JPanel(new GridLayout(0,1,4,4));
buttons.add( new JButton("Show") );
buttons.add( new JButton("Add") );
buttons.add( new JButton("Update Number") );
buttons.add( new JButton("Delete") );
buttons.setBorder( new TitledBorder("Contact") );
controls.add( buttons, BorderLayout.NORTH );
controls.add(new JScrollPane(new JTree()), BorderLayout.CENTER);
gui.add(controls, BorderLayout.WEST);
gui.add(new JTextArea("CardLayout for CRUD components.",10,30));
gui.add(new JLabel("Output label.."), BorderLayout.SOUTH);
JToolBar toolbar = new JToolBar();
toolbar.add(new JCheckBox("Auto save", true));
toolbar.add(new JCheckBox("Always On Top"));
gui.add(toolbar, BorderLayout.NORTH);
JOptionPane.showMessageDialog(null, gui);
}
};
SwingUtilities.invokeLater(r);
}
}
Screenshot

Use box layout and set dimension for each button. Check the below link.
http://download.oracle.com/javase/tutorial/uiswing/layout/box.html

Take a look at http://download.oracle.com/javase/tutorial/uiswing/layout/visual.html which discusses the various layout managers that Swing offers. GridBagLayout is probably what you need.

Related

swing BoxLayout not working

I have read many subjects here but I can't make my window with the layout I want.
I simply want all my graphic object to be in a row style like in the first picture here : http://docs.oracle.com/javase/tutorial/uiswing/layout/box.html
I've tried GridLayout but it still make my first button giant and then, as I add textfields, it's getting smaller and smaller?!
Here is my code without all the imports:
public class TestScrollPane extends JFrame implements ActionListener{
Dimension dim = new Dimension(200 , 50);
JButton button;
JPanel panel = new JPanel();
JScrollPane scrollpane = new JScrollPane(panel);
public TestScrollPane(){
scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
this.add(scrollpane);
//panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
this.setSize(300, 400);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
button = new JButton("click me");
button.setPreferredSize(dim);
panel.add(button);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == button ){
JTextField txt = new JTextField(); // we add a new button
txt.setPreferredSize(dim);
panel.add(txt);
SwingUtilities.updateComponentTreeUI(this); // refresh jframe
}
}
public static void main(String[] args){
TestScrollPane test = new TestScrollPane();
}
}
I just want to have one button per row.
A BoxLayout will respect the minimum/maximum sizes of a component.
For some reason the maximum height of a text field is unlimited so the text field gets all the space available.
So you can do something like:
JTextField txt = new JTextField(10); // we add a new button
//txt.setPreferredSize(dim); // don't hardcode a preferrd size of a component.
txt.setMaximumSize(txt.getPreferredSize());
Also:
//SwingUtilities.updateComponentTreeUI(this); // refresh jframe
Don't use the above method. That is used for a LAF change.
Instead when you add/remove components from a visible GUI you should use:
panel.revalidate();
panel.repaint();

Button layout outside of a GridLayout

I'm currently doing a quite simple GUI and was wondering how I could get the button in question out from the GridLayout and put it in its own say BorderLayout, if that's a bit vague I'll attach images to show you what I mean:
With that picture I would like the button to not be with the grid layout and for it to fill all the way across at the bottom of the program as it would in a border layout. My code is as follows:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/**
* Write a description of class HW4GUI here.
*
* #author (your name)
* #version (a version number or a date)
*/
public class HW4GUI extends JFrame implements ActionListener
{
private JButton jbtAction;
private JTextField jtfFName;
private JTextField jtfLName;
private JTextField jtfLibNo;
private int nextLibNo;
private JPanel textPanel;
/**
* The constructor for the GUI, also initalises nextLibNo number
*/
public HW4GUI()
{
super("Adding a borrower");
makeFrame();
showFrame();
nextLibNo = 1001;
}
/**
*
*/
private void makeFrame()
{
setLayout(new GridLayout(4,0));
setResizable(false);
textPanel = new JPanel();
//textPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
textPanel.setLayout(new BorderLayout());
jtfFName = new JTextField(15);
JLabel fNLbl = new JLabel("First Name: ");
add(fNLbl);
add(jtfFName);
// add(textPanel);
fNLbl.setHorizontalAlignment(JLabel.RIGHT);
jtfFName.setEditable(true);
jtfLName = new JTextField(15);
JLabel lNLbl = new JLabel("Last Name: ");
add(lNLbl);
add(jtfLName);
//add(textPanel);
lNLbl.setHorizontalAlignment(JLabel.RIGHT);
jtfLName.setEditable(true);
jtfLibNo = new JTextField(15);
JLabel lNOLbl = new JLabel("Library Number: ");
add(lNOLbl);
add(jtfLibNo);
// add(textPanel);
lNOLbl.setHorizontalAlignment(JLabel.RIGHT);
jtfLibNo.setEditable(false);
jbtAction = new JButton("Add Borrower");
add(jbtAction, BorderLayout.SOUTH);
jbtAction.addActionListener(this);
}
/**
* displays the frame window where you can set the size of it and also other variables
*/
private void showFrame()
{
setSize(400,200);
setResizable(false);
setLocationRelativeTo( null);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
String fn = jtfFName.getText();
String ln = jtfLName.getText();
boolean valid = true;
if (e.getActionCommand().equals("Add Borrower"))
{
if (fn.equals("") && (ln.equals("")))
{
jtfLibNo.setText("No Names");
valid = false;
}
else if (fn.equals("") )
{
jtfLibNo.setText("No First Name");
valid = false;
}
else if (ln.equals(""))
{
jtfLibNo.setText("No Last Name");
valid = false;
}
else
if (valid == true)
{
String lib = Integer.toString(nextLibNo++);
jtfLibNo.setText(lib);
jbtAction.setText("Confirm");
}
}
if (e.getActionCommand().equals("Confirm"))
{
jtfLibNo.setText("");
jbtAction.setText("Add Borrower");
}
}
}
As you have said that you want the Button outside your GridLayout, you can do:
Declare a new Panel, like mainPanel or something like that.
JPanel mp = new JPanel();
Set its layout to 3x1 using GridLayout.
mp.setlayout(new GridLayout(3,1));
Add you labels and text-fields to that panel.
mp.add(fNLbl);// and the rest.
Add this panel to your frame.
add(mp, BorderLayout.CENTER);
Then add the Button at the end, using, BorderLayout.SOUTH.
add(jbtAction, BorderLayout.SOUTH);
But as far as my knowledge goes, then your button will occupy the width of the whole frame. So, instead, you can add the button to a panel, and then add that panel to it. Like:
add( new JPanel(){{ add(jbtAction);}}, BorderLayout.SOUTH); // this is double-brace initialization.
The following code works fine:
private void makeFrame()
{
JPanel mp = new JPanel();
mp.setLayout(new GridLayout(3,1));
setResizable(false);
textPanel = new JPanel();
//textPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
textPanel.setLayout(new BorderLayout());
jtfFName = new JTextField(15);
JLabel fNLbl = new JLabel("First Name: ");
mp.add(fNLbl);
mp.add(jtfFName);
// add(textPanel);
fNLbl.setHorizontalAlignment(JLabel.RIGHT);
jtfFName.setEditable(true);
jtfLName = new JTextField(15);
JLabel lNLbl = new JLabel("Last Name: ");
mp.add(lNLbl);
mp.add(jtfLName);
//add(textPanel);
lNLbl.setHorizontalAlignment(JLabel.RIGHT);
jtfLName.setEditable(true);
jtfLibNo = new JTextField(15);
JLabel lNOLbl = new JLabel("Library Number: ");
mp.add(lNOLbl);
mp.add(jtfLibNo);
// add(textPanel);
lNOLbl.setHorizontalAlignment(JLabel.RIGHT);
jtfLibNo.setEditable(false);
jbtAction = new JButton("Add Borrower");
add(mp, BorderLayout.CENTER);
add( new JPanel(){{ add(jbtAction);}}, BorderLayout.SOUTH);
jbtAction.addActionListener(this);
}
With that picture I would like the button to not be with the grid layout and for it to fill all the way across at the bottom of the program as it would in a border layout
Then use a BorderLayout. The default layout manager for a JFrame is a BorderLayout. So you would do somethinglike:
Create a panel using a GridLayout. Add the first 5 components to this panel. Then add the panel to the "CENTER" of the frame.
Create your button. Add the button the the "PAGE_END" of the frame.
The idea of layout managers is that you can nest panels with different layouts to achieve your final layout.
I also agree, the main panel with multiple buttons should probably be a GridBagLayout as it will size each column to the width of the widest component in the column instead of making every column width identical, which will make the panel look better. Read the section from the Swing tutorial on How to Use GridBagLayout for more information and working examples.

how to repaint a jpanel with button click and also switch between 2 panels

I am trying to repaint a panel with a button click, but its not happening. i tried using many methods like setEnabled(true), setVisible(true), repaint(), but none of these are working. And also i want to switch between two panels, like, if i click the "Total Vote" button, one panel should display, when i click on "Departmentwise Vote", another panel should display in the same place.
please help. Thanks in advance.
here i m providing the code :
public class RSummary extends JFrame implements ActionListener
{
JFrame rframe = new JFrame();
JPanel panel1, panel2, panel3, panel4, panel5;
JTable table;
JScrollPane scroll;
JSplitPane splitPane;
JButton butx;
public RSummary()
{
rframe.setSize(550,300);
rframe.setLocationRelativeTo(null);
setSize(550,300);
rframe.setTitle("Summary Report");
/* Total Vote & Department wise vote buttons */
panel1= new JPanel();
JButton but1 = new JButton("TOTAL VOTE");
JButton but2 = new JButton("DEPTARTMENT WISE VOTE");
but1.addActionListener(this);
panel1.add(but1);
panel1.add(but2);
/* Report contents according to button */
panel2 = new JPanel();
String[] columnNames = {"Name", "Department","Phno","LUID","Select"};
DefaultTableModel model1 = new DefaultTableModel();
model1.setColumnIdentifiers(columnNames);
table = new JTable();
table.setModel(model1);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
scroll = new JScrollPane(table);
panel2.add(scroll);
panel2.setVisible(false);
/* close button */
panel3 = new JPanel();
JButton but4= new JButton("CLOSE");
but4.addActionListener(this);
panel3.add(but4);
/* Page heading */
panel4 = new JPanel();
JLabel lab =new JLabel("VOTE SUMMARY REPORT");
panel4.add(lab);
/* dummy panel */
panel5 = new JPanel();
JButton butx = new JButton("Hello butx");
panel5.add(butx);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, panel1, panel2);
rframe.add(splitPane);
rframe.add(panel3,BorderLayout.SOUTH);
rframe.add(panel4,BorderLayout.NORTH);
rframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
rframe.setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
String action=ae.getActionCommand();
if(action == "CLOSE")
{
rframe.setVisible(false);
}
if(action == "TOTAL VOTE")
{
panel2.setVisible(true); //this code is not working, i want the solution here.
}
}
public static void main(String args[]) throws ClassNotFoundException, SQLException
{
new RSummary();
}
}
The first problem is you're comparing the object references of your String values and not there contents...
if(action == "TOTAL VOTE")
Because of the way Strings are managed by Java, it is very unlikely that these will ever be equal.
String comparison in Java is done using String#equals
if ("TOTAL VOTE".equals(action))
Your second problem may be related to the fact the setVisible may not be invalidating the container hierarchy, which would tell the layout framework that the containers need to be updated.
You have two solutions, the first would be to call revalidate on the parent container, the second, and better, would be to use a CardLayout, which is designed to just what you are trying to do...
Take a look at How to use Card Layout for more details
Update after running the Code
You have a series of compounding issues...
You never set the action command of any of the buttons, so when the actionPerformed event is raised, the action is actually null
RSummary extends from JFrame, yet you create a second JFrame called rframe. This is very confusing and could potentially lead to more problems if you're not dealing with the correct frame.
Start by setting the actionCommand property of your buttons...
JButton but1 = new JButton("TOTAL VOTE");
but1.setActionCommand("TOTAL VOTE");
Then remove extends JFrame from RSummary, as it is doing nothing but adding to the confusion and adds no benefit
Setting a frame invisible will not "close" it. Instead use JFrame#dispose
Finally, making a component visible while it's part of split pane won't resize the split divider. Once you've made the corrections, you will need to manually move the divider.
You may consider placing a empty panel into the split pane and using a CardLayout, add the other components to it, switching them in and out using the CardLayout
Updated with modified code
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class RSummary extends JFrame implements ActionListener {
JFrame rframe = new JFrame();
JPanel panel1, panel2, panel3, panel4, panel5;
JTable table;
JScrollPane scroll;
JSplitPane splitPane;
JButton butx;
public RSummary() {
rframe.setSize(550, 300);
rframe.setLocationRelativeTo(null);
setSize(550, 300);
rframe.setTitle("Summary Report");
/* Total Vote & Department wise vote buttons */
panel1 = new JPanel();
JButton but1 = new JButton("TOTAL VOTE");
but1.setActionCommand("TOTAL VOTE");
JButton but2 = new JButton("DEPTARTMENT WISE VOTE");
but1.addActionListener(this);
panel1.add(but1);
panel1.add(but2);
/* Report contents according to button */
panel2 = new JPanel();
String[] columnNames = {"Name", "Department", "Phno", "LUID", "Select"};
DefaultTableModel model1 = new DefaultTableModel();
model1.setColumnIdentifiers(columnNames);
table = new JTable();
table.setModel(model1);
table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setFillsViewportHeight(true);
scroll = new JScrollPane(table);
panel2.add(scroll);
panel2.setVisible(false);
/* close button */
panel3 = new JPanel();
JButton but4 = new JButton("CLOSE");
but4.addActionListener(this);
panel3.add(but4);
/* Page heading */
panel4 = new JPanel();
JLabel lab = new JLabel("VOTE SUMMARY REPORT");
panel4.add(lab);
/* dummy panel */
panel5 = new JPanel();
JButton butx = new JButton("Hello butx");
panel5.add(butx);
splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, panel1, panel2);
rframe.add(splitPane);
rframe.add(panel3, BorderLayout.SOUTH);
rframe.add(panel4, BorderLayout.NORTH);
rframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
rframe.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
String action = ae.getActionCommand();
if ("CLOSE".equals(action)) {
rframe.dispose();
}
if ("TOTAL VOTE".equals(action)) {
panel2.setVisible(true); //this code is not working, i want the solution here.
panel2.getParent().revalidate();
}
}
public static void main(String args[]) throws ClassNotFoundException, SQLException {
new RSummary();
}
}
To switch panels you can do:
rframe.remove (panelToRemove);
rframe.add(panelToShow);
Is this the answer to your question or why do you want to repaint?
Geosearchef
UPDATE:
To summarize:
MadProgrammer is right, you have to replace if(action == "TOTAL VOTE") by if(action.equals("TOTAL VOTE")) (same for CLOSE)
and you have to add an actionCommand:
JButton but1 = new JButton("TOTAL VOTE");
but1.addActionListener(this);
but1.setActionCommand("TOTAL VOTE");
To change panels:
if (action.equals("TOTAL VOTE")) {
try{rframe.remove(panel1;)}catch(Exception e){}//clear window, maybe there is a method
try{rframe.remove(panel2;)}catch(Exception e){}
try{rframe.remove(panel3;)}catch(Exception e){}
rframe.add(panel2);//the panel you want to show
}
Of course, you have to get references to the panels to actionPerformed(ActionEvent ae).

Blank screen when invoking in applet viewer

This is my first time posting here.
I am using GUI in java for the very first time while working on some homework. I have started incrementally coding a Italian restaurant menu.
The below code is compiling fine with no errors. After compiling I run applet viewer Italian.html and the applet viewer screen only displays a blank window. I am a little confused as I have no errors to work with. Am I missing something simple.
Thanks for any help.
import javax.swing.*;
import java.awt.*;
public class Italian extends JApplet {
//Declare and array for a list of Pastas
private String [] pastas = {"Spaghetti", "Angel Hair Pasta", "Tortellini",
"Ziti"};
private String [] sauces = {"Maranaria", "Alfredo", "Spicy Marania"};
public Italian() {
//Create the base panel for the restaurant page
JPanel i1 = new JPanel();
i1.setLayout(new GridLayout(2, 1));
i1.add(new JComboBox(pastas));
i1.add(new JComboBox(sauces));
HTML
<html>
<head>
<title>Java Applet Demo</title>
</head>
<body>
<applet
code = "Italian.class"
width = 250
height = 250>
</applet>
</body>
</html>
You haven't added anything to the applet for the applet to show on the screen.
Either in your constructor or you init method you need to add the panel you've created to the content pane.
getContentPane().setLayout(new BorderLayout()); // Just to make sure
getContentPane().add(i1);
you shoud add something to applet to make them work.here is a link
http://math.hws.edu/eck/cs124/javanotes4/c6/index.html which will help you to know applets and graphics.
this eg. will help you which adds different buttons with proper lay out:
/*
This applet demonstrates various layout managers.
The applet itself uses a border layout with a JPanel in
the center, a JComboBox menu to the North, and a JLabel
to the south. The center panel uses a CardLayout.
Each card in the card layout contains a number of
buttons and uses a different layout manager. The
JComboBox menu is used to select among these cards.
The JLabel reports events as they occur.
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class LayoutDemo extends JApplet
implements ActionListener, ItemListener {
CardLayout cards; // the layout manager for the center panel
JPanel cardPanel; // the center panel
JComboBox panelChoice; // menu for selecting which card to show
JLabel message; // a message shown at the bottom of the applet
public void init() {
panelChoice = new JComboBox(); // Set up the menu
panelChoice.setBackground(Color.white);
panelChoice.addItem("FlowLayout"); // Add in the names of the cards.
panelChoice.addItem("FlowLayout with Big Hgap");
panelChoice.addItem("Vertical BoxLayout");
panelChoice.addItem("Horizontal BoxLayout with Struts");
panelChoice.addItem("BorderLayout");
panelChoice.addItem("GridLayout(3,2)");
panelChoice.addItem("GridLayout(1,0)");
panelChoice.addItem("GridLayout(0,1)");
panelChoice.addItemListener(this);
message = new JLabel("Layout Demo", JLabel.CENTER); // Set up the mesage
message.setBackground(Color.white);
message.setOpaque(true); // so background color will show
message.setBorder(BorderFactory.createEmptyBorder(5,0,3,0));
message.setForeground(Color.red);
cardPanel = new JPanel(); // Set up the center panel
cardPanel.setBackground(Color.white);
cards = new CardLayout();
cardPanel.setLayout(cards);
setBackground(Color.blue);
getContentPane().setBackground(Color.blue);
getContentPane().setLayout(new BorderLayout(3,3));
getContentPane().add("Center",cardPanel);
getContentPane().add("North",panelChoice);
getContentPane().add("South",message);
JPanel panel; // Will represent various cards to be added to the center panel.
Box box; // For the cards that use a BoxLayout.
// Set up each "card" in the center panel to have its own layout
// manager and to contain a variety of buttons.
panel = new JPanel();
// use default FlowLayout for panel
panel.setBackground(Color.white);
cardPanel.add(panel, "FlowLayout");
addButton(panel,"First Button"); // ( addButton is a untility method, defined below )
addButton(panel,"Second Button");
addButton(panel,"Third Button");
addButton(panel,"Fourth Button");
addButton(panel,"Fifth Button");
addButton(panel,"Sixth Button");
addButton(panel,"Seventh Button");
panel = new JPanel();
panel.setLayout(new FlowLayout(FlowLayout.CENTER,30000,5));
panel.setBackground(Color.white);
cardPanel.add(panel,"FlowLayout with Big Hgap");
addButton(panel," A Button");
addButton(panel,"Another Button");
addButton(panel,"A Third Button");
addButton(panel,"A Fourth Button");
addButton(panel,"A Final Button");
box = Box.createVerticalBox();
box.setBackground(Color.white);
cardPanel.add(box,"Vertical BoxLayout");
addButton(box,"Button One");
addButton(box,"Button Two");
addButton(box,"Button Three");
addButton(box,"Button Four");
addButton(box,"Button Five");
addButton(box,"Button Six");
box = Box.createHorizontalBox();
box.setBackground(Color.white);
cardPanel.add(box,"Horizontal BoxLayout with Struts");
addButton(box,"1st");
addButton(box,"2nd");
box.add( Box.createHorizontalStrut(10) );
addButton(box,"3rd");
addButton(box,"4th");
box.add( Box.createHorizontalStrut(10) );
addButton(box,"5th");
panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBackground(Color.white);
cardPanel.add(panel,"BorderLayout");
addButton(panel,"Center Button", BorderLayout.CENTER);
addButton(panel,"North Button", BorderLayout.NORTH);
addButton(panel,"South Button", BorderLayout.SOUTH);
addButton(panel,"East Button", BorderLayout.EAST);
addButton(panel,"West Button", BorderLayout.WEST);
panel = new JPanel();
panel.setLayout(new GridLayout(3,2));
panel.setBackground(Color.white);
cardPanel.add(panel,"GridLayout(3,2)");
addButton(panel,"Button 1");
addButton(panel,"Button 2");
addButton(panel,"Button 3");
addButton(panel,"Button 4");
addButton(panel,"Button 5");
addButton(panel,"Button 6");
panel = new JPanel();
panel.setLayout(new GridLayout(1,0));
panel.setBackground(Color.white);
cardPanel.add(panel,"GridLayout(1,0)");
addButton(panel,"Button 1");
addButton(panel,"Button 2");
addButton(panel,"Button 3");
addButton(panel,"Button 4");
panel = new JPanel();
panel.setLayout(new GridLayout(0,1));
panel.setBackground(Color.white);
cardPanel.add(panel,"GridLayout(0,1)");
addButton(panel,"Button 1");
addButton(panel,"Button 2");
addButton(panel,"Button 3");
addButton(panel,"Button 4");
addButton(panel,"Button 5");
addButton(panel,"Button 6");
} // end init()
public Insets getInsets() {
// specify borders around the edges of the applet
return new Insets(3,3,3,3);
}
void addButton(Container p, String name) {
// Create a button with the given name and add it
// to the given panel. Set up the button to send
// events to the applet.
JButton b = new JButton(name);
p.add(b);
b.addActionListener(this);
}
void addButton(JPanel p, String name, Object option) {
// Same as above, but use the "option" object
// as an additional parameter in the add method.
JButton b = new JButton(name);
p.add(b, option);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
// A button was pressed. Report the name
// of the button by setting the message text.
String buttonName = evt.getActionCommand();
message.setText("Button \"" + buttonName + "\" was pressed.");
}
public void itemStateChanged(ItemEvent evt) {
// The user has selected an item from the JComboBox.
// Change the displayed card to match.
String panelName = (String)panelChoice.getSelectedItem();
cards.show(cardPanel, panelName);
message.setText("Panel \"" + panelName + "\" was selected.");
}
} // end class LayoutDemo

Java Swing Layout

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

Categories