I'm working on a group project and I'm the one making the GUI figuring it'd be good to practice with it. The program is supposed to be a pizza ordering system (pretty standard stuff) and what I'm trying to accomplish is that I have a main class that creates an application window. Inside this window is a panel that uses CardLayout with a button that when pressed calls another JPanel from another class dedicated specifically to that panel and places it as a card in the layout to be swapped back and forth from as normal.
What I have so far are the different panels I wish to call and the main class which has the window and main card panel. I can have it swap easily between panels created within the main class but when I try to use the panels from the other classes it just swaps to a blank panel when it should show the other class's panel.
The main class
package PizzaGUI;
import java.awt.EventQueue;
import java.awt.CardLayout;
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Font;
public class PizzaSystem {
private JFrame frame;
Toppings toppingsPanel;
MainMenu menuPanel;
JButton loginBtn;
JPanel mainPanel;
CardLayout cl;
//MAIN
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaSystem window = new PizzaSystem();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Constructor
public PizzaSystem() {
initialize();
}
//Initialize the GUI
private void initialize() {
cl = new CardLayout();
frame = new JFrame();
frame.setBounds(100, 100, 893, 527);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
mainPanel = new JPanel();
mainPanel.setBounds(10, 10, 859, 470);
frame.getContentPane().add(mainPanel);
mainPanel.setLayout(cl);
JPanel panel_2 = new JPanel();
mainPanel.add(panel_2, "test");
panel_2.setLayout(null);
JLabel lblNewLabel = new JLabel("It Worked");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 45));
lblNewLabel.setBounds(282, 118, 312, 103);
panel_2.add(lblNewLabel);
JPanel panel_1 = new JPanel();
loginBtn = new JButton();
loginBtn.setText("Login");
loginBtn.setBounds(175, 72, 199, 154);
loginBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showCard("menu");
}
});
panel_1.add(loginBtn);
mainPanel.add(panel_1, "loginPanel");
JPanel menuPanel = new MainMenu();
mainPanel.add(menuPanel, "menu");
showCard("loginPanel");
}
//Call card matching the key
public void showCard(String key) {
cl.show(mainPanel, key);
}
}
and one of the classes with the panel (format is messed up but should work still)
package PizzaGUI;
import java.awt.Color;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.border.BevelBorder;
public class MainMenu extends JPanel {
public MainMenu() {
JPanel panel1 = new JPanel();
panel1.setBounds(100, 100, 893, 572);
panel1.setBackground(Color.PINK);
panel1.setLayout(null);
panel1.setVisible(true);
JLabel logoLabel = new JLabel("");
logoLabel.setBounds(10, 10, 100, 110);
panel1.add(logoLabel);
ImageIcon image1 = new ImageIcon("C:\\Users\\thera\\eclipse-workspace\\PizzaSystem\\Images\\MamaJane1.png");
logoLabel.setIcon(new ImageIcon("C:\\Users\\thera\\eclipse-workspace\\PizzaSystem\\Images\\MamaJane.png"));
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(133, 113, 548, 402);
tabbedPane.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
tabbedPane.setBackground(Color.PINK);
tabbedPane.setForeground(Color.GRAY);
tabbedPane.setFont(new Font("Tahoma", Font.PLAIN, 20));
tabbedPane.setToolTipText("");
panel1.add(tabbedPane);
JPanel panel = new JPanel();
tabbedPane.addTab("MENU", null, panel, null);
panel.setLayout(null);
//*******************************************************************************************************
//Pepperoni menu section
JLabel pizza1Image = new JLabel("IMAGE");
pizza1Image.setBounds(6, 25, 100, 100);
panel.add(pizza1Image);
ImageIcon image2 = new ImageIcon("C:\\Users\\thera\\eclipse-workspace\\PizzaSystem\\Images\\Pepperoni.jpg");
Image pizza1 = image2.getImage();
Image pepperoni = pizza1.getScaledInstance(100, 100, java.awt.Image.SCALE_SMOOTH);
image2 = new ImageIcon(pepperoni);
pizza1Image.setIcon(image2);
JLabel pepperoniLabel = new JLabel("PEPPERONI");
pepperoniLabel.setHorizontalAlignment(SwingConstants.CENTER);
pepperoniLabel.setBounds(110, 25, 86, 48);
pepperoniLabel.setFont(new Font("Tahoma", Font.PLAIN, 12));
panel.add(pepperoniLabel);
JButton pepperoniOrderBtn = new JButton("ORDER");
pepperoniOrderBtn.setBounds(110, 79, 86, 47);
panel.add(pepperoniOrderBtn);
pepperoniOrderBtn.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
//Pepperoni End
JButton accountButton = new JButton("Account");
accountButton.setBounds(10, 414, 113, 39);
accountButton.setBackground(Color.WHITE);
panel.add(accountButton);
JButton checkoutButton = new JButton("Checkout");
checkoutButton.setBounds(713, 438, 138, 31);
panel.add(checkoutButton);
JButton logoutButton = new JButton("Logout");
logoutButton.setBounds(10, 463, 113, 52);
panel.add(logoutButton);
JTextArea txtrOrderInfoGoes = new JTextArea();
txtrOrderInfoGoes.setBounds(703, 10, 154, 418);
txtrOrderInfoGoes.setText("Order Info\r\nGoes Here\r\n\r\nPepperoni Pizza x1\r\n$6.50");
panel.add(txtrOrderInfoGoes);
JButton clearOrderButton = new JButton("Clear");
clearOrderButton.setBounds(723, 479, 113, 36);
panel.add(clearOrderButton);
JLabel titleLabel = new JLabel("MAMA JANE'S PIZZERIA");
titleLabel.setBounds(147, 10, 534, 65);
panel.add(titleLabel);
titleLabel.setFont(new Font(titleLabel.getFont().getName(), Font.PLAIN, 50));
JLabel storeInfoLabel = new JLabel("<html>1234 Fakelane Rd <br> 10001, Faketopia, USA <br> 111-11-PIZZA <br> Mon-Fri 11AM to 10pm <br> Sat-Sun 10AM to 11pm");
storeInfoLabel.setBounds(10, 130, 113, 274);
panel.add(storeInfoLabel);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(406, 85, 2, 2);
panel.add(scrollPane);
logoutButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
}
I can't tell where I've gone wrong and I've spent roughly the last three hours trying to fix this and searching the internet for answers to no avail so thank you in advance if you can help me out.
Also I apologize in advance, I know I end up misusing the proper terminology for programming alot, I understand what things are just forget what to properly call them sometimes.
So, basically, I took out all the null layouts and "manual" layout code, as it's just going to mess with you to no end AND added add(panel1); to the end of the MainMenu constructor - as, I've said, NOTHING was added to MainMenu, so, nothing was going to get displayed.
Before you tell me that "this isn't the layout I want", understand that I understand that, but my point is, null layouts are a really bad idea, as almost the entire Swing API relies the layout managers in one way or another.
I appreciate that layout management can seem like a complex subject, but it solves some very complex problems and it's worth taking the time to learn them. Remember, you're not stuck to a single layout manager, you can use component components to adjust individual containers to their individual needs.
You can take a look at:
Layout using Java Swing
Which Layout Manager to use?
How I can do swing complex layout Java
How to use Java Swing layout manager to make this GUI?
*Which java swing layout should I use
to some ideas how you might approach designing a complex UI.
You should also take a look at Laying Out Components Within a Container
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
public class PizzaSystem {
private JFrame frame;
// Toppings toppingsPanel;
MainMenu menuPanel;
JButton loginBtn;
JPanel mainPanel;
CardLayout cl;
//MAIN
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PizzaSystem window = new PizzaSystem();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Constructor
public PizzaSystem() {
initialize();
}
//Initialize the GUI
private void initialize() {
cl = new CardLayout();
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainPanel = new JPanel(cl);
frame.getContentPane().add(mainPanel);
JPanel panel_1 = new JPanel(new GridBagLayout());
loginBtn = new JButton();
loginBtn.setText("Login");
loginBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showCard("menu");
}
});
panel_1.add(loginBtn);
mainPanel.add(panel_1, "loginPanel");
JPanel menuPanel = new MainMenu();
mainPanel.add(menuPanel, "menu");
frame.pack();
showCard("loginPanel");
}
//Call card matching the key
public void showCard(String key) {
cl.show(mainPanel, key);
}
public class MainMenu extends JPanel {
public MainMenu() {
JPanel panel1 = new JPanel(new BorderLayout());
JLabel logoLabel = new JLabel("Logo");
panel1.add(logoLabel, BorderLayout.NORTH);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setToolTipText("");
panel1.add(tabbedPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
tabbedPane.addTab("MENU", null, panel, null);
//*******************************************************************************************************
//Pepperoni menu section
JLabel pizza1Image = new JLabel("IMAGE");
panel.add(pizza1Image);
JLabel pepperoniLabel = new JLabel("PEPPERONI");
pepperoniLabel.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(pepperoniLabel);
JButton pepperoniOrderBtn = new JButton("ORDER");
pepperoniOrderBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
//Pepperoni End
JButton accountButton = new JButton("Account");
panel.add(accountButton);
JButton checkoutButton = new JButton("Checkout");
panel.add(checkoutButton);
JButton logoutButton = new JButton("Logout");
panel.add(logoutButton);
JTextArea txtrOrderInfoGoes = new JTextArea(10, 20);
txtrOrderInfoGoes.setText("Order Info\r\nGoes Here\r\n\r\nPepperoni Pizza x1\r\n$6.50");
panel.add(txtrOrderInfoGoes);
JButton clearOrderButton = new JButton("Clear");
panel.add(clearOrderButton);
JLabel titleLabel = new JLabel("MAMA JANE'S PIZZERIA");
panel.add(titleLabel);
titleLabel.setFont(new Font(titleLabel.getFont().getName(), Font.PLAIN, 50));
JLabel storeInfoLabel = new JLabel("<html>1234 Fakelane Rd <br> 10001, Faketopia, USA <br> 111-11-PIZZA <br> Mon-Fri 11AM to 10pm <br> Sat-Sun 10AM to 11pm");
panel.add(storeInfoLabel);
JScrollPane scrollPane = new JScrollPane();
panel.add(scrollPane);
logoutButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
add(panel1);
}
}
}
So I'm writing a program which utilizes a GUI. The GUI is built from a JFrame and a JPanel in Java. I have a JTextArea() and a JButton() that appears beside the JTextArea on the left. I also have an image which I imported locally using the method call below ("f" is the variable name of my JFrame):
f.setIconImage(ImageIO.read(new File("image.png")));
I don't mind allowing the users to resize the JFrame but what I dislike is that JFrame automatically reformats the components on my JFrame - specifically the distance between my image and the JTextArea(). I'd like, if possible, to keep the distance between my image and the JTextArea the same regardless of the size the user resizes the JFrame to. Here's the rest of my code if that helps:
public class GUI {
private JFrame f;
private JPanel p;
private JButton b1;
private JLabel lab;
private JTextArea tf;
private static final String FileName = "schedule.txt";
private static final String FileName2 = "schedule2.txt";
public void show()
{
f = new JFrame("Scheduler");
f.setSize(600, 400);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p = new JPanel();
//p.setPreferredSize(new Dimension(200, 400));
b1 = new JButton("Run");
p.add(b1);
f.add(p);
f.add(p, BorderLayout.SOUTH);
f.add(new JLabel(new ImageIcon("image.png")));
try {
f.setIconImage(ImageIO.read(new File("image.png")));
} catch(Exception z){
System.out.println("Trouble reading file");
}
tf = new JTextArea();
tf.setPreferredSize(new Dimension(300, 200));
p.add(tf);
b1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = tf.getText();
try {
FileWriter fw = new FileWriter(FileName);
fw.write(text);
fw.close();
parseInfo();
}
catch(Exception ex)
{
}
}
});
f.setVisible(true);
}
There are any number of ways you "might" achieve this, but the basic answer is, you need to choose one or more layout managers which better meets your needs.
For example, using a GridBagLayout, you can do something like...
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.LineBorder;
public class JavaApplication1 {
public static void main(String[] args) {
new JavaApplication1();
}
public JavaApplication1() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(8, 8, 8, 8);
JLabel label = new JLabel("Image placeholder") {
// This is done only for demonstration purposes
#Override
public Dimension getPreferredSize() {
return new Dimension(128, 128);
}
};
label.setBorder(new LineBorder(Color.DARK_GRAY));
add(label, gbc);
gbc.gridy++;
gbc.fill = GridBagConstraints.BOTH;
// This will cause the text area to occupy all the avalilable free space
//gbc.weightx = 1;
//gbc.weighty = 1;
JTextArea ta = new JTextArea(10, 20);
add(new JScrollPane(ta), gbc);
JButton btn = new JButton("Run");
gbc.gridy++;
// Reset the constraints
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0;
gbc.weighty = 0;
add(btn, gbc);
}
}
}
Take a look at Laying Out Components Within a Container for more details and ideas
Recommendations...
There are a few things in your code that are, "off", but this...
tf = new JTextArea();
tf.setPreferredSize(new Dimension(300, 200));
p.add(tf);
is probably the most striking.
Generally speaking, JTextArea will benefit from been wrapped in a JScrollPane. Also, due to the inconsistencies in how text is rendered across multiple platforms, you should avoid using setPreferredSize (in fact, you should avoid using it in general) and instead rely in the rows, columns constructor, which will make calculations based on the current font and graphics properties.
I am simply making a user interface and all i want it to do after the button is pressed is display thanks... I am pretty new to this but from what i see there are no errors? I have tried playing around with the set visible and to no avail...Any help is great thanks
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JList;
public class GuiApp1 {
public static void main(String args[]) {
String title = (args.length == 0 ? "CheckBox Sample" : args[0]);
JFrame frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel panel = new JPanel(new GridLayout(0, 1));
Border border = BorderFactory.createTitledBorder("Pizza Toppings");
panel.setBorder(border);
JLabel label1 = new JLabel("Enter name below:");
panel.add(label1);
JTextField field = new JTextField(20);
panel.add(field);
JCheckBox check = new JCheckBox("Car0");
panel.add(check);
check = new JCheckBox("Car1");
panel.add(check);
check = new JCheckBox("Car2");
panel.add(check);
check = new JCheckBox("Car3");
panel.add(check);
check = new JCheckBox("Car4");
panel.add(check);
JButton button = new JButton("Submit");
final JPanel listPanel = new JPanel();
listPanel.setVisible(false);
JLabel listLbl = new JLabel("Vegetables:");
listPanel.add(listLbl);
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
listPanel.setVisible(!listPanel.isVisible());
panel.setVisible(!panel.isVisible());
}
});
Container contentPane = frame.getContentPane();
contentPane.add(panel, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.SOUTH);
frame.setSize(300, 300);
frame.setResizable(true);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}
The reason for the vegetables panel not appearing is simple: Xou never add ist to the contentPane.
For the code to function properly you need to add/remove the panels in the ActionListener of the button:
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
listPanel.setVisible(!listPanel.isVisible());
panel.setVisible(!panel.isVisible());
if (listPanel.isVisible()) {
contentPane.remove(panel); // Vegetables are visible, so remove the Cars
contentPane.add(listPanel, BorderLayout.CENTER); // And add the Vegetables
} else {
contentPane.remove(listPanel); // Vice versa
contentPane.add(panel, BorderLayout.CENTER);
}
}
});
Then, you need to move the ActionListener below the contentPane declaration and make it final.
Also you should consider putting the different checkboxes is different variables, so you can read the state of them. If you don't want to have so many variables hanging you could put them into an array.
JCheckBox[] checks = new JCheckbox[5];
checks[0] = new JCheckBox("Car0");
panel.add(checks[0]);
...
I'm a complete noobie with swing. I'm trying to set a few JPanels and TextAreas to show up but after spending 2 days reading the APIs and trying to add panels to frames and textareas to panels and nothing is showing up.. I'm utterly confused. If anyone could explain how is the best way to do this I would be very grateful
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GUI {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLayout(new FlowLayout()); // J FRAME
JPanel panel = new JPanel(); // first panel on the left
panel.setLayout(new BoxLayout(panel, 1));
// frame.getContentPane().setBackground(Color.red);
frame.add(panel);
JLabel surname = new JLabel();
JLabel initial = new JLabel();
JLabel ext = new JLabel();
surname.setOpaque(true);
initial.setOpaque(true);
ext.setOpaque(true);
frame.add(surname);
panel.add(initial);
panel.add(ext);
JTextArea table = new JTextArea();
table.setEditable(false);
panel.add(table);
table.setVisible(true);
You're adding stuff to the JFrame after it's already visible. If you do that, you need to revalidate your JFrame so it knows to redo its layout.
You could also just wait to show your JFrame until after you've added everything.
Edit: Here is an example program that shows what I'm talking about. Try running this, then take out the call to revalidate() to see the difference.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Test {
public static void main(String[] args) {
final JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JButton show = new JButton("Show");
show.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent showE) {
frame.add(new JLabel("Test"), BorderLayout.SOUTH);
frame.revalidate(); //tell the JFrame to redo its layout!
}
});
frame.add(show);
frame.setSize(200, 200);
frame.setVisible(true);
}
}
You are adding an empty elements like:
JLabel surname = new JLabel();
Your elements is already added but have nothing to be display.
Try :
JLabel surname = new JLabel("UserName");
JLabel initial = new JLabel("Iinitial");
JLabel ext = new JLabel("Ext");
JTextArea table = new JTextArea(10, 5);
I'm trying to figure out how to create a vertical TitledBorder in a JPanel.
I've got this situation:
I'd like to have "Actuators st..." placed vertically, so user can read it.
Is there a way to do it, or should I implement my own customized JPanel & TitledBorder?
maybe crazy idea but is possible with JSeparator too :-)
required proper LayoutManager, maybe GridBagLayout (JComponent placed without GBC can take PreferrredSize from JComponent, but isn't resiziable), not GridLayout
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.SwingUtilities;
public class NestedLayout {
private JFrame frame = new JFrame();
private JPanel leftPanel = new JPanel();
private JSeparator sep = new JSeparator();
private JLabel label = new JLabel("<html> L<br>a<br>b<br>e<br>l<br></html>");
public NestedLayout() {
label.setOpaque(true);
sep.setOrientation(JSeparator.VERTICAL);
sep.setLayout(new GridLayout(3, 1));
sep.add(new JLabel());
sep.add(label);
sep.add(new JLabel());
leftPanel.setLayout(new BorderLayout());
leftPanel.setBorder(BorderFactory.createEmptyBorder(
10, //top
10, //left
10, //bottom
10)); //right
leftPanel.add(sep, BorderLayout.CENTER);
leftPanel.setPreferredSize(new Dimension(40, 220));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(leftPanel, BorderLayout.WEST);
//frame.add(label);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
NestedLayout nestedLayout = new NestedLayout();
}
});
}
}
As shown in How to Use Borders, you can create a compound border using an empty border and a titled border.
Addendum: As an alternative, you can use the border's getMinimumSize() method to ensure that the title is visible. See also this related Q&A.
f.add(createPanel("Actuator status"), BorderLayout.WEST);
f.add(createPanel("Indicator result"), BorderLayout.EAST);
...
private Box createPanel(String s) {
Box box = new Box(BoxLayout.Y_AXIS);
TitledBorder title = BorderFactory.createTitledBorder(null, s,
TitledBorder.CENTER, TitledBorder.DEFAULT_POSITION);
box.setBorder(title);
for (int i = 0; i < 6; i++) {
JButton b = new JButton(null, UIManager.getIcon("html.pendingImage"));
b.setAlignmentX(JButton.CENTER_ALIGNMENT);
box.add(b);
}
box.validate();
Dimension db = box.getPreferredSize();
int max = Math.max(title.getMinimumSize(box).width, db.width);
box.setPreferredSize(new Dimension(max, db.height));
return box;
}