How to align JLabels and JPanels to the left inside BoxLayout? - java

I want to align Labels and a Panel (containing Buttons) to the left inside a vertical BoxLayout.
As long as I don't add the panel to the BoxLayout everything is aligned to the left perfectly, but adding it screws everything up.
import javax.swing.*;
import java.awt.*;
public class BoxLayoutDemo{
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JPanel five = new JPanel();
JButton plus = new JButton("+");
JButton minus = new JButton("-");
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
Font testFont = new Font("Arial", Font.BOLD, 20);
JLabel label1 = new JLabel("Label1");
label1.setFont(testFont);
JLabel label2 = new JLabel("Label2");
label2.setFont(testFont);
five.setLayout(new BoxLayout(five, BoxLayout.X_AXIS));
plus.setMinimumSize(new Dimension(30, 30));
plus.setMaximumSize(new Dimension(30, 30));
minus.setMinimumSize(new Dimension(30, 30));
minus.setMaximumSize(new Dimension(30, 30));
five.add(plus);
five.add(minus);
panel.add(label1);
panel.add(five);
panel.add(label2);
panel.setOpaque(true);
panel.setBackground(Color.red);
frame.setMinimumSize(new Dimension(200, 200));
frame.getContentPane().add(panel, BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}

Your components need to have the same "x alignment":
label1.setAlignmentX(Component.LEFT_ALIGNMENT);
label2.setAlignmentX(Component.LEFT_ALIGNMENT);
five.setAlignmentX(Component.LEFT_ALIGNMENT);
Read the section from the Swing tutorial on Fixing Alignment Problems for more information.

You can use invisible components as fillers.
private static Box leftAlignedInHorizontalBox(Component component) {
Box box = Box.createHorizontalBox();
box.add(component);
box.add(Box.createHorizontalGlue());
return box;
}
and then:
panel.add(leftAlignedInHorizontalBox(label1));

Related

How do I specifically position JLabels within a JPanel

I made a JPanel, which has 6 string JLabels, and one image JLabel. What I need is to be able to position the Jlabel strings somewhere inside of my image JLabel's bounds. I'm pretty sure my problem would be solved if I knew how to resize JLabels.
Some Code:
import javax.swing.*;
import java.awt.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setTitle("rainbow seizure");
frame.setResizable(false);
frame.setSize(500, 500);
frame.setVisible(true);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout());
frame.add(panel, BorderLayout.SOUTH);
JButton newCardButton = new JButton("New Card");
newCardButton.addActionListener(actionEvent -> {
JPanel panel2 = new JPanel();
panel2.setLayout(new OverlayLayout(panel2));
JLabel jImage = new JLabel(new ImageIcon("C:\\Users\\unkno\\java\\Card1.PNG"));
Dimension dimension = jImage.getPreferredSize(); // dimensions for me are 72x122
System.out.println(dimension.width);
System.out.println(dimension.height);
JLabel label1 = new JLabel("name");
label1.setBounds(new Rectangle(dimension.width, dimension.height)); // doesn't do anything :(
label1.setAlignmentX(Component.LEFT_ALIGNMENT);
label1.setAlignmentY(Component.TOP_ALIGNMENT);
JLabel label2 = new JLabel("cost");
JLabel label3 = new JLabel ("atk");
JLabel label4 = new JLabel("type");
JLabel label5 = new JLabel ("hp");
JLabel label6 = new JLabel("disc");
panel2.add(label1);
panel2.add(label2);
panel2.add(label3);
panel2.add(label4);
panel2.add(label5);
panel2.add(label6);
panel2.add(jImage);
panel.add(panel2);
frame.revalidate();
});
frame.add(newCardButton, BorderLayout.NORTH);
}
}

How is it possible to add a container for border layout?

I want to add labels and buttons above and below the border layout. How can I do that? Here is what I did:
import java.awt.*;
import javax.swing.*;
class homework{
public static void main(String[] args) {
JFrame frame= new JFrame("border layout");
frame.setVisible(true);
JLabel label=new JLabel("Container of BorderLayout");
JButton button1 = new JButton("NORTH");
JButton button2 = new JButton("SOUTH");
JButton button3 = new JButton("EAST");
JButton button5 = new JButton("CENTER");
JButton button4 = new JButton("WEST");
JPanel panel1=new JPanel();
JPanel panel2=new JPanel();
frame.add(panel2);
label.setLayout(new FlowLayout(0));
panel2.add(label);
panel1.setLayout(new BorderLayout());
panel1.add(button1,BorderLayout.NORTH);
panel1.add(button2,BorderLayout.SOUTH);
panel1.add(button3,BorderLayout.EAST);
panel1.add(button4,BorderLayout.WEST);
panel1.add(button5,BorderLayout.CENTER);
frame.add(panel1);
frame.pack();
}
}
Above and below of border layout, set new 2 containers (for example JPanel) and make them flow layout. enter image description here
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.NORTH);
JRadioButton rdbtnNewRadioButton = new JRadioButton("New radio button");
panel.add(rdbtnNewRadioButton);
JRadioButton rdbtnNewRadioButton_1 = new JRadioButton("New radio button");
panel.add(rdbtnNewRadioButton_1);
JPanel panel_1 = new JPanel();
frame.getContentPane().add(panel_1, BorderLayout.SOUTH);
JLabel lblNewLabel = new JLabel("New label");
panel_1.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("New label");
panel_1.add(lblNewLabel_1);
add something like that before frame.pack(); code.
Actually what do you mean by above and below? Do you mean north and south? If It is you should have something like this enter image description here
and you should write code this way
import java.awt.*;
class homework{
public static void main(String[] args) {
JFrame frame= new JFrame("border layout");
frame.setVisible(true);
JLabel label=new JLabel("Container of BorderLayout");
JButton button3 = new JButton("EAST");
JButton button5 = new JButton("CENTER");
JButton button4 = new JButton("WEST");
JPanel panel1=new JPanel();
JPanel panel2=new JPanel();
frame.getContentPane().add(panel2);
label.setLayout(new FlowLayout(0));
panel2.add(label);
panel1.setLayout(new BorderLayout());
panel1.add(button3,BorderLayout.EAST);
panel1.add(button4,BorderLayout.WEST);
panel1.add(button5,BorderLayout.CENTER);
frame.getContentPane().add(panel1);
JPanel panel = new JPanel();
panel1.add(panel, BorderLayout.NORTH);
JLabel lblNewLabel = new JLabel("New label");
panel.add(lblNewLabel);
JRadioButton rdbtnNewRadioButton = new JRadioButton("New radio button");
panel.add(rdbtnNewRadioButton);
JPanel panel_1 = new JPanel();
panel1.add(panel_1, BorderLayout.SOUTH);
JLabel lblNewLabel_1 = new JLabel("New label");
panel_1.add(lblNewLabel_1);
JRadioButton rdbtnNewRadioButton_1 = new JRadioButton("New radio button");
panel_1.add(rdbtnNewRadioButton_1);
frame.pack();
}
}
In two conditions, you should add two containers into your code and make them flow layout.

Resizing JFrame while shrinking a scrollpane acordingly

I currently have a JFrame to start fullscreen, inside this jframe i have a jpanel, this jpanel includes a vertical scrollpane. Now if i resize my jframe vertically it just kinda removes the bottom part of the jpanel. Is there any way to just shrink the jscrollpane.
im currently using flowlayout for the jframe,
Scrollbar appear automatically when the preferred size of the components added to the scroll pane area greater than the size of the scroll pane.
The FlowLayout will wrap components to a new row, but it always gives the preferred size as the size required to fit the components on a single row, so the preferred height will never change.
To solve this problem you can use the Wrap Layout which simple extend FlowLayout to recalculate the preferred size when wrapping occurs.
The JPanel consists of 3 other panels, a top panel, a scrollpane in the middle and a botpanel. The top and bot panel are just button and checkboxes and stuff
private void initPane() {
createFolderCompPanel();
createBotPanel();
createTopPanel();
createScrollPane();
createTotalPanel();
add(totalPanel);
}
private void createFolderCompPanel() {
//Create folderCompPanel
folderCompPanel = new JPanel();
folderCompPanel.setLayout(new BoxLayout(folderCompPanel, BoxLayout.Y_AXIS));
folderCompPanel.add(Box.createVerticalGlue());
}
private void createTotalPanel() {
//Create TotalPanel
totalPanel = new JPanel();
totalPanel.setLayout(new BoxLayout(totalPanel, BoxLayout.Y_AXIS));
totalPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
totalPanel.add(topPanel);
totalPanel.add(scrollPane);
totalPanel.add(botPanel);
}
private void createScrollPane() {
//Create ScrollPane
scrollPane = new JScrollPane();
scrollPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setViewportBorder(BorderFactory.createEtchedBorder());
scrollPane.getVerticalScrollBar().setUnitIncrement(6);
}
private void createBotPanel() {
//Create BotPanel
botPanel = new JPanel();
botPanel.setLayout(new BoxLayout(botPanel, BoxLayout.X_AXIS));
//AddButton
addButton = new JButton("Add");
addButton.setEnabled(false);
addButton.addActionListener(this);
//SaveButton
saveButton = new JButton("Save");
saveButton.setEnabled(false);
saveButton.addActionListener(this);
//CancelButton
cancelButton = new JButton("Cancel");
cancelButton.setEnabled(false);
cancelButton.addActionListener(this);
lblTotalLength = new JLabel("Total Length: " + totalLength);
botPanel.add(Box.createRigidArea(new Dimension(10, 0)));
botPanel.add(addButton);
botPanel.add(Box.createRigidArea(new Dimension(10, 0)));
botPanel.add(lblTotalLength);
botPanel.add(Box.createHorizontalGlue());
botPanel.add(saveButton);
botPanel.add(Box.createRigidArea(new Dimension(10, 0)));
botPanel.add(cancelButton);
botPanel.add(Box.createRigidArea(new Dimension(10, 0)));
}
private void createTopPanel() {
//Create TopPanel
topPanel = new JPanel();
topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.X_AXIS));
//create deletedisplay button
deleteDisplayButton = new JButton("Delete Display");
deleteDisplayButton.addActionListener(this);
deleteDisplayButton.setEnabled(false);
//create displaybox
displayBox = new JComboBox();
displayBox.addActionListener(this);
displayBox.addItem("<None>");
for (String s : connect.getAllDisplays()) {
displayBox.addItem(s);
}
displayBox.setMaximumSize(displayBox.getPreferredSize());
//create newdisplay button
newDisplayButton = new JButton("New Display");
newDisplayButton.addActionListener(this);
topPanel.add(Box.createRigidArea(new Dimension(10, 0)));
topPanel.add(displayBox);
topPanel.add(Box.createHorizontalGlue());
topPanel.add(newDisplayButton);
topPanel.add(Box.createRigidArea(new Dimension(5, 0)));
topPanel.add(deleteDisplayButton);
topPanel.add(Box.createRigidArea(new Dimension(10, 0)));
}
this is the panel i add to the jframe
public GuiConstructor(){
super(APPLICATION_NAME);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setMinimumSize(new Dimension(630, 600));
setLayout(new FlowLayout(FlowLayout.LEFT));
LoopControlWindow folderSearch = new LoopControlWindow(connect, this);
add(folderSearch);
pack();
setLocationRelativeTo(null);
setResizable(true);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

Setting background image

How can I get rid of that gray box?
This is what I'm talking about:
i would really appreciate if you could help me out
Full code here: http://pastebin.com/nrpCTjvV
public final void initUI() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(new EmptyBorder(new Insets(90, 155, 40, 60)));
JButton NewGame = new JButton ("New Game!");
JButton Highscore = new JButton("Highscore");
JButton Credits = new JButton ("Credits");
JButton Website = new JButton ("Website");
JButton Exit = new JButton ("Exit");
panel.add(NewGame);
panel.add(Box.createRigidArea(new Dimension(0, 5)));
panel.add(Highscore);
panel.add(Box.createRigidArea(new Dimension(0, 5)));
panel.add(Credits);
panel.add(Box.createRigidArea(new Dimension(0, 5)));
panel.add(Website);
panel.add(Box.createRigidArea(new Dimension(0, 5)));
panel.add(Exit);
final ButtonGroup entreeGroup = new ButtonGroup();
JRadioButton radioButton;
panel.add(radioButton = new JRadioButton("Music1"));
radioButton.setActionCommand("Music1");
entreeGroup.add(radioButton);
panel.add(radioButton = new JRadioButton("Music2"));
radioButton.setActionCommand("Music2");
entreeGroup.add(radioButton);
panel.add(radioButton = new JRadioButton("No Music", true));
radioButton.setActionCommand("No Music");
entreeGroup.add(radioButton);
add(panel);
pack();
setTitle("Title");
JLabel background = new JLabel(new ImageIcon("background.png"));
add(background);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setSize(400, 400);
}
add(panel);
pack();
setTitle("Title");
JLabel background = new JLabel(new ImageIcon("background.png"));
add(background);
The default layout manager for a JFrame is a BorderLayout. When you add a component without specifying a constraint the component is added to the CENTER. You can't add multiple components to a single location.
Instead you need to use a different component as the background. Then you add your panel to this component. Check out Background Panel. Then code would be something like:
Background background = new BackgroundPanel(...);
background.add(panel);
add(background);
setResizable(false);
pack();
...

Not all components showing

When I run this program, the window blocks out the buttons in panel2 when I use setSize to determine window size.
In addition, if I use frame.pack() instead of setSize(), all components are on one horizontal line but I'm trying to get them so that panel1 components are on one line and panel2 components are on a line below them.
Could someone explain in detail the answers to both of these problems?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Exercise16_4 extends JFrame{
// FlowLayout components of top portion of calculator
private JLabel jlbNum1 = new JLabel("Number 1");
private JTextField jtfNum1 = new JTextField(4);
private JLabel jlNum2 = new JLabel("Number 2");
private JTextField jtfNum2 = new JTextField(4);
private JLabel jlbResult = new JLabel("Result");
private JTextField jtfResult = new JTextField(8);
// FlowLayout Components of bottom portion of calculator
private JButton jbtAdd = new JButton("Add");
private JButton jbtSubtract = new JButton("Subtract");
private JButton jbtMultiply = new JButton("Multiply");
private JButton jbtDivide = new JButton("Divide");
public Exercise16_4(){
JPanel panel1 = new JPanel();
panel1.setLayout(new FlowLayout(FlowLayout.CENTER, 3, 3));
panel1.add(jlbNum1);
panel1.add(jtfNum1);
panel1.add(jlNum2);
panel1.add(jtfNum2);
panel1.add(jlbResult);
panel1.add(jtfResult);
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout(FlowLayout.CENTER, 3, 10));
panel1.add(jbtAdd);
panel1.add(jbtSubtract);
panel1.add(jbtMultiply);
panel1.add(jbtDivide);
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.CENTER);
}
public static void main(String[] args){
Exercise16_4 frame = new Exercise16_4();
frame.setTitle("Caculator");
frame.setSize(400, 200);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setResizable(false);
frame.setVisible(true);
}
}
You're problem is likely a typographical error in that you're adding all components to panel1 and none to panel2:
// you create panel2 just fine
JPanel panel2 = new JPanel();
panel2.setLayout(new FlowLayout(FlowLayout.CENTER, 3, 10));
// but you don't use it! Change below to panel2.
panel1.add(jbtAdd);
panel1.add(jbtSubtract);
panel1.add(jbtMultiply);
panel1.add(jbtDivide);
Add the buttons to panel2, and then call pack() before setVisible(true). Do not set the size of the GUI.

Categories