JToolbar, Stop it going horizontal - java

I have a JToolbar. I was wondering if there was way to stop it going horizontal. I would prefer it to only go vertical. I do want it floating.
I have tried making a property changed listener and changing the orientation back to vertical but no luck.
Thanks

Just use an other layout than the default floating one. And use a vertical layout.
JToolbar toolbar= new JToolbar();
toolbar.setLayout(new BoxLayout(toolbar, BoxLayout.Y_AXIS));
You can also use no layout at all
toolbar.setLayout(null);
But this will be horizontal by default.

Have a look at this https://bugs.openjdk.java.net/browse/JDK-4203039, it has an example how you can filter where the JToolbar is allowed to dock.

You need to add the line:
toolBar.setOrientation(javax.swing.SwingConstants.VERTICAL);
Code Example:
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;
class VerticalJToolbar
{
public static void main(String args[])
{
JFrame frame = new JFrame("VerticalJToolbarTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(480, 480);
frame.setResizable(true);
frame.setLocationRelativeTo(null);
JPanel panelOrange = new JPanel();
panelOrange.setBackground(Color.ORANGE);
panelOrange.setPreferredSize(new Dimension(100, 100));
JPanel panelBlue = new JPanel();
panelBlue.setBackground(Color.BLUE);
panelBlue.setPreferredSize(new Dimension(100, 100));
JPanel panelGreen = new JPanel();
panelGreen.setBackground(Color.GREEN);
panelGreen.setPreferredSize(new Dimension(100, 100));
JPanel panelRed = new JPanel();
panelRed.setBackground(Color.RED);
panelRed.setPreferredSize(new Dimension(100, 100));
JMenu menu1 = new JMenu("Menu 1");
JMenu menu2 = new JMenu("Menu 2");
JMenu menu3 = new JMenu("Menu 3");
JMenu menu4 = new JMenu("Menu 4");
JToolBar toolBarHorizontal = new JToolBar();
toolBarHorizontal.add(menu1);
toolBarHorizontal.add(menu2);
toolBarHorizontal.add(menu3);
toolBarHorizontal.add(menu4);
JToolBar toolBarVertical = new JToolBar();
toolBarVertical.setOrientation(SwingConstants.VERTICAL);
toolBarVertical.add(panelOrange);
toolBarVertical.add(panelBlue);
toolBarVertical.add(panelGreen);
toolBarVertical.add(panelRed);
JPanel panelCenter = new JPanel();
panelCenter.setBackground(Color.WHITE);
frame.add(toolBarHorizontal, java.awt.BorderLayout.NORTH);
frame.add(toolBarVertical, java.awt.BorderLayout.WEST);
frame.add(panelCenter, java.awt.BorderLayout.CENTER);
frame.setVisible(true);
}
}
Screen capture:

Related

COMPOUND BORDER : Get a outline border with title outside the Jpanel in java Swing

My only problem is that I don't know how to put my border outside the panel. I've tried compound and some other border code but so far I am unable to put it outside. It either disappears or it doesn't change at all.
The output that I want:
The output that I'm getting :
I'm a newbie at swing and I have been searching and found out about compound border but I am still not so familiar on how it works with adding the buttons into the panel. (I've removed the code of me trying to do compound border because it was just a mess full of errors)
THE CODE :
package activityswing;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.Border;
public class swing {
public static void main (String args []) {
JFrame pa= new JFrame("Swing Activity");
//boarder
pa.setLayout(new BorderLayout());
//panels
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
//buttons
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
JButton button3 = new JButton("Button 3");
JButton button4 = new JButton("Button 4");
JButton button5 = new JButton("Button 5");
JButton button6 = new JButton("Button 6");
//label
JLabel lb1= new JLabel("Panel 1");
JLabel lb2= new JLabel("Panel 2");
//adding label to panel
lb1.add(panel1);
lb1.add(panel2);
//panel1
Border line1 = BorderFactory.createLineBorder(Color.blue);
panel1.setBorder(line1);
panel1.add(button1);
panel1.add(button2);
panel1.add(button3);
panel1.setBorder(BorderFactory.createTitledBorder("Panel 1"));
panel1.setBackground(Color.BLUE);
panel1.setPreferredSize(new Dimension(270,40));
//panel2
Font font2 = new Font("Verdana",Font.ITALIC,12);
Border line2 = BorderFactory.createLineBorder(Color.blue);
lb2.setFont(font2);
panel2.setBorder(line2);
LayoutManager layout = new FlowLayout();
panel2.setLayout(layout);
panel2.add(button4);
panel2.add(button5);
panel2.add(button6);
panel2.add(lb2);
panel2.setBorder(BorderFactory.createTitledBorder("Panel 2"));
panel2.setBackground(Color.GREEN);
panel2.setPreferredSize(new Dimension(270,40));
//FRAME
FlowLayout flow = new FlowLayout(FlowLayout.CENTER, 50,50);
pa.setLayout(flow);
pa.pack();
pa.add(panel1);
pa.add(panel2);
pa.setSize(700,200);
pa.setResizable(false);
pa.setVisible(true);
pa.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pa.setLocationRelativeTo(null);
}
}
Don't add component to labels
lb1.add(panel1);
lb1.add(panel2);
Labels calculate their preferred size based the label properties (text/icon/font/etc) and not the child components.
Don't mess with the preferredSize of the components unless you are absolutely certain you willing to take over all the responsibility to calculate the components size.
The simple solution would be to create a instance of TitledBorder yourself, for example...
Font font2 = new Font("Verdana", Font.ITALIC, 12);
TitledBorder border = new TitledBorder("Panel 1");
border.setTitleFont(font2);
I'd kind of tempted to create a factory method to make this easier, but you get the general idea
To get the border "separated" from the component, I would use a compound component approach, where the outer panel contains the title and then add the inner panel into it.
If needed, you could use CompoundBorder and use a EmptyBorder on the side of the outer panel
Have a look at:
JavaDocs for TitledBorder
How to Use Borders
... for more details
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.LayoutManager;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
public class Test {
public static void main(String args[]) {
JFrame pa = new JFrame("Swing Activity");
//boarder
pa.setLayout(new BorderLayout());
//panels
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
//buttons
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
JButton button3 = new JButton("Button 3");
JButton button4 = new JButton("Button 4");
JButton button5 = new JButton("Button 5");
JButton button6 = new JButton("Button 6");
Font font2 = new Font("Verdana", Font.ITALIC, 12);
TitledBorder border1 = new TitledBorder("Panel 1");
border1.setTitleFont(font2);
JPanel outter1 = new JPanel(new BorderLayout());
outter1.setBorder(border1);
panel1.add(button1);
panel1.add(button2);
panel1.add(button3);
panel1.setBackground(Color.BLUE);
outter1.add(panel1);
//panel2
LayoutManager layout = new FlowLayout();
TitledBorder border2 = new TitledBorder("Panel 2");
JPanel outter2 = new JPanel(new BorderLayout());
outter2.setBorder(border2);
panel2.setLayout(layout);
panel2.add(button4);
panel2.add(button5);
panel2.add(button6);
panel2.setBackground(Color.GREEN);
outter2.add(panel2);
//FRAME
FlowLayout flow = new FlowLayout(FlowLayout.CENTER, 50, 50);
pa.setLayout(flow);
pa.add(outter1);
pa.add(outter2);
pa.pack();
pa.setLocationRelativeTo(null);
pa.setVisible(true);
pa.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pa.setLocationRelativeTo(null);
}
}
You can nest JPanels. That is how I implemented the output you want.
The below code is not a correction of your code, it is an example of how to achieve the output you want. Since the two JPanels in your code are quite similar, the below code only displays a single JPanel. I assume you can make the appropriate changes.
package activityswing;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
public class Swing2 {
private JPanel createInner() {
JPanel inner = new JPanel();
inner.setBackground(Color.GREEN);
JButton button1 = new JButton("Button 1");
inner.add(button1);
JButton button2 = new JButton("Button 2");
inner.add(button2);
JButton button3 = new JButton("Button 3");
inner.add(button3);
return inner;
}
private JPanel createOuter() {
JPanel outer = new JPanel();
TitledBorder titledBorder = new TitledBorder(new LineBorder(Color.blue), "Panel 1");
Font font2 = new Font("Verdana", Font.BOLD + Font.ITALIC, 12);
titledBorder.setTitleFont(font2);
EmptyBorder emptyBorder = new EmptyBorder(10, 10, 10, 10);
CompoundBorder compoundBorder = new CompoundBorder(titledBorder, emptyBorder);
outer.setBorder(compoundBorder);
outer.add(createInner());
return outer;
}
private void showGui() {
JFrame frame = new JFrame("Swing2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createOuter());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new Swing2().showGui());
}
}
Running the above code displays the following window.

Swing JButton is glitching with JCheckBox focus state

I have a JPanel set with the Windows Look and Feel. I have 3 JCheckBoxes, including 2 disabled ones which don't interfere with this problem. However, the non-disabled one is glitching with the JButton I have later in this JPanel:
The JCheckBox code:
JCheckBox checkBox = new JCheckBox("TTxJIRA Bash");
checkBox.setSize(300, (checkBox.getFontMetrics(checkBox.getFont()).getHeight()));
checkBox.setLocation(10, 100);
checkBox.setVisible(true);
checkBox.setSelected(true);
checkBox.setBackground(new Color(0, 0, 0, 0));
checkBox.setFocusable(false);
add(checkBox);
And the JButton code:
JButton button = new JButton("Install");
button.setSize(80, 25);
button.setLocation(getWidth() - 100, getHeight() - 60);
button.setFocusable(false);
button.setVisible(true);
add(button);
When I hover on the button, then hover on the checkbox, this glitch occurs:
My wild guess makes me think this has to do with two components being focused at the same time, but adding the button.setFocusable(false); did not help.
Here's a little runnable example that shows you how you could use LayoutManagers for that, because LayoutManagers will fix your problems you had with absolute positioning. (Please note that this is probably not the best solution and that the LineBorders are just for visualization)
Kinda messy code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
public class LayoutManagerExample {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JButton button = new JButton("Install");
JCheckBox cb1 = new JCheckBox("1");
cb1.setEnabled(false);
JCheckBox cb2 = new JCheckBox("2");
cb2.setEnabled(false);
JCheckBox cb3 = new JCheckBox("3");
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10,10,10,10);
JPanel southPanel = new JPanel();
southPanel.setLayout(new BorderLayout());
southPanel.setBorder(new LineBorder(Color.BLACK));
JPanel westPanel = new JPanel();
westPanel.setLayout(new GridLayout(10,1));
westPanel.setBorder(new LineBorder(Color.BLACK));
JPanel southEastPanel = new JPanel();
southEastPanel.setBorder(new LineBorder(Color.BLACK));
mainPanel.add(southPanel,BorderLayout.SOUTH);
mainPanel.add(westPanel,BorderLayout.WEST);
southPanel.add(southEastPanel,BorderLayout.EAST);
westPanel.add(cb1);
westPanel.add(cb2);
westPanel.add(cb3);
southEastPanel.add(button, gbc);
frame.add(mainPanel);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setVisible(true);
}
}

Aligning buttons to center in BoxLayout

I am trying to set the buttons to the center using the Box.createHorizontalStrut() method. However if I use this.getWidth()/2 is does not work. How can I do to center it in the frame.
Code
package ch17;
import java.awt.Color;
import java.awt.Container;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class Q17_1 extends JFrame{
JButton left = new JButton("<=");
JButton right = new JButton("=>");
JPanel p1 = new JPanel();
JRadioButton rb1 = new JRadioButton("Red");
JRadioButton rb2 = new JRadioButton("Yellow");
JRadioButton rb3 = new JRadioButton("White");
JRadioButton rb4 = new JRadioButton("Gray");
JRadioButton rb5 = new JRadioButton("Green");
JPanel p2 = new JPanel();
Message m = new Message("Welcome to Java");
public Q17_1(){
setLayout(new GridLayout(3,1));
p1.setBorder(new TitledBorder("Select Message Panel Background"));
ButtonGroup group = new ButtonGroup();
group.add(rb1);group.add(rb2);group.add(rb3);group.add(rb4);group.add(rb5);
rb1.setMnemonic('R');rb2.setMnemonic('Y');rb3.setMnemonic('W');rb4.setMnemonic('G');
rb5.setMnemonic('N');
p1.setLayout(new GridLayout(1,5,5,5));
p1.add(rb1);p1.add(rb2);p1.add(rb3);p1.add(rb4);p1.add(rb5);
p2.setLayout(new BoxLayout(p2,BoxLayout.X_AXIS));
add(p1);
add(m);
p2.add(Box.createHorizontalStrut(250));
p2.add(left);
p2.add(Box.createHorizontalStrut(5));
p2.add(right);
add(p2);
left.addActionListener((ActionEvent) -> {
m.moveLeft();
repaint();
});
right.addActionListener((ActionEvent)-> {
m.moveRight();
repaint();
});
rb1.addActionListener(m);
rb2.addActionListener(m);
rb3.addActionListener(m);
rb4.addActionListener(m);
rb5.addActionListener(m);
}
public static void main(String[] args) {
Q17_1 frame = new Q17_1();
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
I have tried, this.getWidth()/2, p2.getWidth()/2, etc. However they don't work and the buttons are still starting from the beginning of the left side.
You could use a combination of Borderlayout, FlowLayout or GridBagLayout
For summary:
setLayout(new BorderLayout());
//...
p2.setLayout(new FlowLayout());
add(p1, BorderLayout.NORTH);
add(m);
//...
add(p2, BorderLayout.SOUTH);
The reason I might consider using BorderLayout of GridLayout for the core layout is it will give all the remaining space to the component in the CENTER position. This might not be what you want, but it's why I've used it.
Both GridBagLayout and FlowLayout will layout it's containers around the centre of the container, GridBagLayout doing it vertically and horizontally, FlowLayout doing it only horizontally (by default)
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.TitledBorder;
public class Q17_1 extends JFrame {
JButton left = new JButton("<=");
JButton right = new JButton("=>");
JPanel p1 = new JPanel();
JRadioButton rb1 = new JRadioButton("Red");
JRadioButton rb2 = new JRadioButton("Yellow");
JRadioButton rb3 = new JRadioButton("White");
JRadioButton rb4 = new JRadioButton("Gray");
JRadioButton rb5 = new JRadioButton("Green");
JPanel p2 = new JPanel();
JLabel m = new JLabel("Welcome to Java");
// Message m = new Message("Welcome to Java");
public Q17_1() {
setLayout(new BorderLayout());
p1.setBorder(new TitledBorder("Select Message Panel Background"));
ButtonGroup group = new ButtonGroup();
group.add(rb1);
group.add(rb2);
group.add(rb3);
group.add(rb4);
group.add(rb5);
rb1.setMnemonic('R');
rb2.setMnemonic('Y');
rb3.setMnemonic('W');
rb4.setMnemonic('G');
rb5.setMnemonic('N');
p1.setLayout(new GridLayout(1, 5, 5, 5));
p1.add(rb1);
p1.add(rb2);
p1.add(rb3);
p1.add(rb4);
p1.add(rb5);
p2.setLayout(new FlowLayout());
add(p1, BorderLayout.NORTH);
add(m);
p2.add(left);
p2.add(right);
add(p2, BorderLayout.SOUTH);
left.addActionListener((ActionEvent) -> {
// m.moveLeft();
// repaint();
});
right.addActionListener((ActionEvent) -> {
// m.moveRight();
// repaint();
});
// rb1.addActionListener(m);
// rb2.addActionListener(m);
// rb3.addActionListener(m);
// rb4.addActionListener(m);
// rb5.addActionListener(m);
}
public static void main(String[] args) {
Q17_1 frame = new Q17_1();
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
But If I want to use BoxLayout for practice for p2. What should I put for the arguments in order to center the buttons???
Because the container's size dynamic, you could use some horizontal glue instead
p2.add(Box.createHorizontalGlue());
p2.add(left);
p2.add(right);
p2.add(Box.createHorizontalGlue());

Adding a JTextArea to a TabbedPane

I am trying to get my JTextArea to display under all other contents of the llpPanel. My code is below with a screenshot of what my code displays. In the code you will see that I have set my dimensions for the JTextArea to (50, 50). Then in the llpPanel I have added BorderLayout.PAGE_END. I have also tried to (instead of PAGE_END) put CENTER and SOUTH. When I put SOUTH, it shows a white line at the very bottom of the program but you cannot do anything with it.
import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class TestApplication implements ActionListener {
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setSize(1000, 1000);
frame.setTitle("RBA Test Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
JButton initialize = new JButton("Initialize");
JButton connect = new JButton("Connect");
JButton disconnect = new JButton("Disconnect");
JButton shutdown = new JButton("Shut Down");
JButton portsettings = new JButton("Port Settings");
JButton online = new JButton("Go Online");
JButton offline = new JButton("Go Offline");
JButton status = new JButton("Status");
JButton reboot = new JButton("Reboot");
JButton account = new JButton("Account");
JButton amount = new JButton("Amount");
JButton reset = new JButton("Reset");
JButton approvordecl = new JButton("Approve / Decline");
JTextArea logbox = new JTextArea(50, 50);
JPanel testPanel = new JPanel();
testPanel.add(button);
testPanel.add(button2);
testPanel.add(checkbox2);
JPanel posPanel = new JPanel();
posPanel.add(test);
posPanel.add(testing);
posPanel.add(checkbox);
JPanel llpPanel = new JPanel();
llpPanel.add(online);
llpPanel.add(offline);
llpPanel.add(status);
llpPanel.add(reboot);
llpPanel.add(account);
llpPanel.add(amount);
llpPanel.add(reset);
llpPanel.add(approvordecl);
llpPanel.add(logbox, BorderLayout.PAGE_END);
JPanel buttonPanel = new JPanel();
buttonPanel.add(initialize);
buttonPanel.add(connect);
buttonPanel.add(disconnect);
buttonPanel.add(shutdown);
buttonPanel.add(portsettings);
frame.add(buttonPanel);
frame.add(buttonPanel, BorderLayout.NORTH);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("LLP", null, llpPanel, "Low Level Protocol");
tabbedPane.addTab("POS",null, posPanel, "Point Of Sale");
tabbedPane.addTab("Test", null, testPanel, "Test");
JPanel tabsPanel = new JPanel(new BorderLayout());
tabsPanel.add(tabbedPane);
frame.add(tabsPanel, BorderLayout.CENTER);
frame.pack();
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
Updated code with screenshot is below...
import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class TestApplication implements ActionListener {
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setSize(1000, 1000);
frame.setTitle("RBA Test Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
JTextArea logbox = new JTextArea(50, 50);
JButton initialize = new JButton("Initialize");
JButton connect = new JButton("Connect");
JButton disconnect = new JButton("Disconnect");
JButton shutdown = new JButton("Shut Down");
JButton portsettings = new JButton("Port Settings");
JButton online = new JButton("Go Online");
JButton offline = new JButton("Go Offline");
JButton status = new JButton("Status");
JButton reboot = new JButton("Reboot");
JButton account = new JButton("Account");
JButton amount = new JButton("Amount");
JButton reset = new JButton("Reset");
JButton approvordecl = new JButton("Approve / Decline");
JButton test = new JButton("Test Button #1");
JButton testing = new JButton("Test Button #2");
JRadioButton button = new JRadioButton("Radio Button");
JRadioButton button2 = new JRadioButton("Radio Button");
JCheckBox checkbox = new JCheckBox("Check Box");
JCheckBox checkbox2 = new JCheckBox("Check Box");
JPanel newButtonPanel = new JPanel();
newButtonPanel.add(online);
newButtonPanel.add(offline);
newButtonPanel.add(status);
newButtonPanel.add(reboot);
newButtonPanel.add(account);
newButtonPanel.add(amount);
newButtonPanel.add(reset);
newButtonPanel.add(approvordecl);
JPanel testPanel = new JPanel();
testPanel.add(button);
testPanel.add(button2);
testPanel.add(checkbox2);
JPanel posPanel = new JPanel();
posPanel.add(test);
posPanel.add(testing);
posPanel.add(checkbox);
JPanel llpPanel = new JPanel();
llpPanel.setLayout(new BorderLayout());
llpPanel.add(newButtonPanel);
llpPanel.add(logbox, BorderLayout.PAGE_END);
JPanel buttonPanel = new JPanel();
buttonPanel.add(initialize);
buttonPanel.add(connect);
buttonPanel.add(disconnect);
buttonPanel.add(shutdown);
buttonPanel.add(portsettings);
frame.add(buttonPanel);
frame.add(buttonPanel, BorderLayout.NORTH);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("LLP", null, llpPanel, "Low Level Protocol");
tabbedPane.addTab("POS",null, posPanel, "Point Of Sale");
tabbedPane.addTab("Test", null, testPanel, "Test");
JPanel tabsPanel = new JPanel(new BorderLayout());
tabsPanel.add(tabbedPane);
frame.add(tabsPanel, BorderLayout.CENTER);
frame.pack();
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
JPanels use FlowLayout by default so applying BorderLayout constraints such as PAGE_END will have no effect. You need to set the layout of the panel:
llpPanel.setLayout(new BorderLayout());
Then you will encounter the problem of components displacing themselves in the BorderLayout.CENTER position. The solution is to create another JPanel as a container for the components other than logbox on llpPanel.
JPanel newButtonPanel = new JPanel();
newButtonPanel.add(online);
...
llpPanel.add(newButtonPanel);
JScrollPane scrollPane = new JScrollPane(logbox) {
#Override
public java.awt.Dimension getPreferredSize() {
return new Dimension(500, 500);
};
};
llpPanel.add(scrollPane, BorderLayout.PAGE_END);
Use a JScrollPane rather than adding the JTextArea directly to the container.
Set the component's preferred size property rather than its size, and add it to BorderLayout.SOUTH. For BorderLayout layouts, the container will try to use preferred sizes for the edges (north,south,east and west) and resize the center accordingly.
A short snipped example to illustrate. The view is a panel, which will have the text area at the bottom that is 50 high. This is done by adding the JTextArea component at BorderLayout.SOUTH and set the preferred size property at Dimension(0,50). The rest of the view is filled with a panel. This panel is placed at the BorderLayout.CENTER and will be resized by the layout manager.
JPanel view = new JPanel( );
view.setSize( 800, 600 );
view.setLayout( new BorderLayout( ) );
JPanel topArea = new JPanel( );
JTextArea textArea = new JTextArea( );
textArea.setPreferredSize( new Dimension( 0, 50 ) );
view.add( topArea, BorderLayout.CENTER );
view.add( textArea, BorderLayout.SOUTH );

How to program this GUI in Java Swing

I'm currently developing a small utility with the following GUI:
Right now i have a container (JPanel) with the BorderLayout layout that holds everything in place. The i have another 2 JPanels placed on BorderLayout.NORTH and BorderLayout.SOUTH respectively, each whith the GridLayout (2 columns by 1 row). The table is on the main container placed at the CENTER of it.
Do you think this is the best approach? I'm having a rough time dealing with spacing between the components and the borders of the frame.
Right now i have this code:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
public class GUI extends JFrame {
private JButton loadFileBtn = new JButton("Load File");
private JButton generateReportBtn = new JButton("Generate Report");
private JButton exitBtn = new JButton("Exit");
private JLabel fileNameLbl = new JLabel("File Name Here");
private JMenuBar menuBar = new JMenuBar();
private JMenu fileMI = new JMenu("File");
private JMenuItem openFileMenu = new JMenuItem("Open File");
private JSeparator separator = new JSeparator();
private JMenuItem exitMenu = new JMenuItem("Exit");
private JMenu reportMI = new JMenu("Report");
private JMenuItem generateReportMenu = new JMenuItem("Generate Report");
private JMenu helpMI = new JMenu("Help");
private JMenuItem aboutMenu = new JMenuItem("About");
private JTable table = new JTable(5, 2);
private JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
private JPanel panel1 = new JPanel(new BorderLayout());
private JPanel panel2 = new JPanel(new GridLayout(1, 2));
private JPanel panel3 = new JPanel(new GridLayout(1, 2));
public GUI() {
super("Sample GUI");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(new Dimension(300, 300));
setResizable(false);
setLayout(new BorderLayout(10, 10));
fileMI.add(openFileMenu);
fileMI.add(separator);
fileMI.add(exitMenu);
reportMI.add(generateReportMenu);
helpMI.add(aboutMenu);
menuBar.add(fileMI);
menuBar.add(reportMI);
menuBar.add(helpMI);
setJMenuBar(menuBar);
panel1.add(table, BorderLayout.CENTER);
panel2.add(fileNameLbl);
panel2.add(loadFileBtn);
panel3.add(generateReportBtn);
panel3.add(exitBtn);
mainPanel.add(panel2, BorderLayout.NORTH);
mainPanel.add(panel1, BorderLayout.CENTER);
mainPanel.add(panel3, BorderLayout.SOUTH);
add(mainPanel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
GUI app = new GUI();
app.setVisible(true);
}
});
}
}
What do you think would be the best approach to do this?
Any help would be appreciated. Thanks.
UPDATE:
Right now, i have the following GUI
I want the components to space away from the borders evenly, like in the mockup.
2 things you can use to make this happen:
Use BorderFactory.createEmptyBorder(int, int, int, int)
Use the 4-args constructor of GridLayout
There are other LayoutManager's which can bring the same functionality (like GridBagLayout, or using nested BorderLayout), but if you feel comfortable with the current LayoutManager's, there is no imperious need to change to those. The way you did is also acceptable.
You might consider wrapping the table in a JScrollPane to make it nicer, with headers and scrollbars if ever needed.
Small example code:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
public class GUI extends JFrame {
private JButton loadFileBtn = new JButton("Load File");
private JButton generateReportBtn = new JButton("Generate Report");
private JButton exitBtn = new JButton("Exit");
private JLabel fileNameLbl = new JLabel("File Name Here");
private JMenuBar menuBar = new JMenuBar();
private JMenu fileMI = new JMenu("File");
private JMenuItem openFileMenu = new JMenuItem("Open File");
private JSeparator separator = new JSeparator();
private JMenuItem exitMenu = new JMenuItem("Exit");
private JMenu reportMI = new JMenu("Report");
private JMenuItem generateReportMenu = new JMenuItem("Generate Report");
private JMenu helpMI = new JMenu("Help");
private JMenuItem aboutMenu = new JMenuItem("About");
private JTable table = new JTable(5, 2);
private JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
private JPanel panel1 = new JPanel(new BorderLayout());
private JPanel panel2 = new JPanel(new GridLayout(1, 2, 10, 10));
private JPanel panel3 = new JPanel(new GridLayout(1, 2, 10, 10));
public GUI() {
super("Sample GUI");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(new Dimension(300, 300));
setResizable(false);
setLayout(new BorderLayout(10, 10));
fileMI.add(openFileMenu);
fileMI.add(separator);
fileMI.add(exitMenu);
reportMI.add(generateReportMenu);
helpMI.add(aboutMenu);
menuBar.add(fileMI);
menuBar.add(reportMI);
menuBar.add(helpMI);
setJMenuBar(menuBar);
panel1.add(table, BorderLayout.CENTER);
panel2.add(fileNameLbl);
panel2.add(loadFileBtn);
panel3.add(generateReportBtn);
panel3.add(exitBtn);
mainPanel.add(panel2, BorderLayout.NORTH);
mainPanel.add(panel1, BorderLayout.CENTER);
mainPanel.add(panel3, BorderLayout.SOUTH);
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
add(mainPanel);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
GUI app = new GUI();
app.setVisible(true);
}
});
}
}
In the past, I have found that using MigLayout, solves all my problems
Here's how I would arrange your GUI. This is just one way. It's not the only way.
The JTable goes inside of a JScrollPane.
Button2 and Button3 go inside of a button JPanel with a FlowLayout.
Label and Button1 go inside of a label JPanel with a FlowLayout.
File, Report, and Help are JMenuItems on a JMenuBar.
The main JPanel has a BoxLayout with a Y_AXIS orientation.
Add the label JPanel, the JScrollPane, and the button JPanel to the main JPanel.
The best way is to create a GUI is to code in a way you and others will understand . Take a look at this Guide to Layout Managers. You can use different layout managers for different components. This will help you setting correct spacing.
If your problem is just the spacing around the components, set its Insets.

Categories