How to add spacing between JPanel and JFrame's contentPane? - java

This is the picture I am trying to replicate
This is what I have (didn't add icon images yet)
I can't seem to find a solution, been staring at it for quite some time.
I am trying to replicate the following picture, using GridLayout for the buttons and the figure out the rest on my own using Java Swing. Furthermore, I've added my buttons into a JPanel and now I'm trying to add spacing between the panel and the pane.
This is what I have, how can I go about it?
super(title);
this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.PAGE_AXIS));
Container pane = this.getContentPane();
JButton b1 = new JButton();
b1.setBackground(Color.white);
JButton b2 = new JButton();
b2.setBackground(Color.white);
JButton b3 = new JButton();
b3.setBackground(Color.white);
JButton b4 = new JButton();
b4.setBackground(Color.white);
JButton b5 = new JButton();
b5.setBackground(Color.white);
JButton b6 = new JButton();
b6.setBackground(Color.white);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2,3,10,10));
panel.setBackground(Color.black);
panel.add(b1);
panel.add(b2);
panel.add(b3);
panel.add(b4);
panel.add(b5);
panel.add(b6);
pane.add(panel);
this.setSize(500,500);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);

The easiest way to do it would be to add an empty border to your JPanel (see this post on empty borders):
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2, 10, 10));
// ...
panel.setBorder(new EmptyBorder(50, 50, 50, 50));
Another good approach (depending always on your application needs), if you have the JButton preferred size set, would be to have the main JPanel's grid layout set to have two columns and one row, with another JPanel inside each column. Adding to the interior JPanels a BoxLayout in Y_AXIS mode and aligning the buttons with setAlignmentX() would work great too (note this approach wouldn't center the JButtons vertically) (see How to use BoxLayout):
public class MyFrame extends JFrame {
private String title = "Title";
public MyFrame(){
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(1,2,10,10));
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));
mainPanel.add(leftPanel);
mainPanel.add(rightPanel);
JButton b1 = new JButton();
b1.setBackground(Color.white);
//b1.setIcon(new ImageIcon(img1));
b1.setAlignmentX(Component.RIGHT_ALIGNMENT);
leftPanel.add(b1);
JButton b2 = new JButton();
b2.setBackground(Color.white);
//b2.setIcon(new ImageIcon(img2));
b2.setAlignmentX(Component.RIGHT_ALIGNMENT);
leftPanel.add(b2);
JButton b3 = new JButton();
b3.setBackground(Color.white);
//b3.setIcon(new ImageIcon(img3));
b3.setAlignmentX(Component.RIGHT_ALIGNMENT);
leftPanel.add(b3);
JButton b4 = new JButton();
b4.setBackground(Color.white);
//b4.setIcon(new ImageIcon(img4));
b4.setAlignmentX(Component.LEFT_ALIGNMENT);
rightPanel.add(b4);
JButton b5 = new JButton();
b5.setBackground(Color.white);
//b5.setIcon(new ImageIcon(img5));
b5.setAlignmentX(Component.LEFT_ALIGNMENT);
rightPanel.add(b5);
JButton b6 = new JButton();
b6.setBackground(Color.white);
//b6.setIcon(new ImageIcon(img6));
b6.setAlignmentX(Component.LEFT_ALIGNMENT);
rightPanel.add(b6);
add(mainPanel); //Adding our mainPanel to the contentPane of the JFrame
this.setSize(500,500); //or pack();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setTitle(title);
this.setVisible(true);
}
}

Here's a little demonstration I whipped up.
All Swing applications must start with a call to the SwingUtilities invokeLater method. This method ensures that all Swing components are created and executed on the Event Dispatch Thread.
You don't set the size of the JFrame and try and make the Swing components fit. You let the JFrame pack with all the Swing components.
You create a GridLayout JPanel inside of a FlowLayout JPanel. The FlowLayout JPanel uses an empty border of the appropriate size.
I used the image the OP provided to get the icons.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class EmptySpaceDemo implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new EmptySpaceDemo());
}
private Image[] images;
public EmptySpaceDemo() {
this.images = createImages();
}
private Image[] createImages() {
BufferedImage image = readImage();
Image[] images = new Image[6];
images[0] = image.getSubimage(155, 113, 110, 90);
images[1] = image.getSubimage(276, 113, 110, 90);
images[2] = image.getSubimage(155, 217, 110, 90);
images[3] = image.getSubimage(276, 217, 110, 90);
images[4] = image.getSubimage(155, 321, 110, 90);
images[5] = image.getSubimage(276, 321, 110, 90);
return images;
}
#Override
public void run() {
JFrame frame = new JFrame("Empty Space Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBackground(Color.BLACK);
panel.setBorder(BorderFactory.createEmptyBorder(40, 100, 40, 100));
JPanel innerPanel = new JPanel(new GridLayout(0, 2, 10, 10));
innerPanel.setBackground(Color.BLACK);
for (int i = 0; i < images.length; i++) {
JButton button = new JButton(new ImageIcon(images[i]));
innerPanel.add(button);
}
panel.add(innerPanel);
return panel;
}
private BufferedImage readImage() {
try {
return ImageIO.read(getClass().getResourceAsStream("/icons.png"));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}

Related

BorderLayout combined with FlowLayout: JTextArea ruins GUI (Java Swing)

I use a BorderLayout combined with a FlowLayout, which works perfectly when I set up the BorderLayout.NORTH. However, in the CENTER area I would like to add a JTextArea (to print out console), but when I create a panel, add JTextArea, after adding a panel to BorderLayout.CENTER nothing appears and became grey. I have tried several combinations and tricks, also I have checked several forum posts without luck. Here is my very simplified code (should run flawlessly, I have commented the problematic part if you remove the comment the bug present):
public static void main(String[] args) {
blogGUI();
}
public static void blogGUI() {
JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setVisible(true);
frame.setSize(700, 500);
frame.setLayout(new BorderLayout()); //a frame BorderLayout elrendezésü
JPanel panel1 = new JPanel();
//panel.setBounds(0,0,700,500);
panel1.setBackground(new java.awt.Color(255,255,255));
panel1.setVisible(true);
panel1.setSize(new Dimension(140, 30));
JPanel panel2 = new JPanel();
//panel.setBounds(0,0,700,500);
panel2.setBackground(new java.awt.Color(255,255,255));
panel2.setVisible(true);
panel2.setSize(new Dimension(140, 30));
JButton btNewEntry = new JButton("New Post");
JButton btModifyEntry = new JButton("Modify");
JButton btDeleteEntry = new JButton("Delete");
JButton btShowEntries = new JButton("List");
JButton btExit = new JButton("Exit");
JLabel lbFile = new JLabel("Open Blog:");
JLabel lbFilePath = new JLabel("Nothing selected...");
JButton btFileOpen = new JButton("Open");
btNewEntry.setPreferredSize(new Dimension(100,30));
btModifyEntry.setPreferredSize(new Dimension(100,30));
btDeleteEntry.setPreferredSize(new Dimension(100,30));
btShowEntries.setPreferredSize(new Dimension(100,30));
btExit.setPreferredSize(new Dimension(100,30));
lbFile.setPreferredSize(new Dimension(100,30));
lbFilePath.setPreferredSize(new Dimension(310,30));
btFileOpen.setPreferredSize(new Dimension(100,30));
panel1.add(btNewEntry);
panel1.add(btModifyEntry);
panel1.add(btDeleteEntry);
panel1.add(btShowEntries);
panel1.add(btExit);
panel2.add(lbFile);
panel2.add(btFileOpen);
panel2.add(lbFilePath);
JPanel cpanelNorth = new JPanel();
cpanelNorth.setBackground(new java.awt.Color(135,206,250));
cpanelNorth.setLayout(new FlowLayout());
cpanelNorth.setPreferredSize(new Dimension(500, 95));
cpanelNorth.add(panel1);
cpanelNorth.add(panel2);
frame.add(cpanelNorth, BorderLayout.NORTH);
/*Something wrong here! From this point, if this uncommented ruins the gui.*/
JPanel panel3 = new JPanel();
panel3.setLayout(new FlowLayout());
//panel.setBounds(0,0,700,500);
panel3.setBackground(new java.awt.Color(255,255,255));
//panel3.setVisible(true);
//panel3.setPreferredSize(new Dimension(30, 30));
JTextArea textArea = new JTextArea("Welcome to...!");
//textArea.setPreferredSize(new Dimension(50,50));
textArea.setBackground(new java.awt.Color(255,0,0));
panel3.add(textArea);
frame.add(panel3, BorderLayout.CENTER);
Hi Andrew Thompson and user16320675, Thanks for the quick help, this solved my issue. How can I further improve the quality the code? I had to put only one setPrefferedSize() at the JTextArea, all other places I removed (without this the window shrinks to zero)
I reduced my code
image: https://ibb.co/Xj7tYKf
I have removed allsetPrefferedSize()
I put frame.setVisible(true) at the end, and also frame.pack() at the end
Here is my code:
package bloggui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class Start {
public static void main(String[] args) {
blogGUI();
}
public static void blogGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel panel1 = new JPanel();
panel1.setBackground(new java.awt.Color(255,255,255));
JPanel panel2 = new JPanel();
panel2.setBackground(new java.awt.Color(255,255,255));
JButton btNewEntry = new JButton("New Post");
JButton btModifyEntry = new JButton("Modify");
JButton btDeleteEntry = new JButton("Delete");
JButton btShowEntries = new JButton("List");
JButton btExit = new JButton("Exit");
JLabel lbFile = new JLabel("Open Blog:");
JLabel lbFilePath = new JLabel("Nothing selected...");
JButton btFileOpen = new JButton("Open");
panel1.add(btNewEntry);
panel1.add(btModifyEntry);
panel1.add(btDeleteEntry);
panel1.add(btShowEntries);
panel1.add(btExit);
panel2.add(lbFile);
panel2.add(btFileOpen);
panel2.add(lbFilePath);
JPanel cpanelNorth = new JPanel();
cpanelNorth.setBackground(new java.awt.Color(135,206,250));
cpanelNorth.setLayout(new FlowLayout());
cpanelNorth.add(panel1);
cpanelNorth.add(panel2);
frame.add(cpanelNorth, BorderLayout.NORTH);
frame.pack();
JPanel panel3 = new JPanel();
panel3.setLayout(new FlowLayout());
panel3.setBackground(new java.awt.Color(135,206,250));
JTextArea textArea = new JTextArea("Welcome to...!");
textArea.setBackground(new java.awt.Color(255,255,255));
textArea.setPreferredSize(new Dimension(620, 400)); //Must not use setPreferredSize() [I must use it only once here!]
panel3.add(textArea);
frame.add(panel3, BorderLayout.CENTER);
frame.pack(); //Must be at the end
frame.setVisible(true); //Must be at the end
}
}

Java JFrame: Windows Layout & Embed

I need to define a layout for a Jframe Window, as in the picture above.
Below is my approach.
A Picture from my resources folder (/resources/...jpg) embed inside the middle(main).
Top, Bottom, Left and Right divided in four parts, whereas their content is a labeled button stretched, so I can map some methods on it later, that change the picture inside the main container.
I tried to display the picture, but I get the result you see in my screenshot. I can't see it inside my main container and I receive no error message.
I don't know if this is because of my wrong approach of using JFrame.
Below you can see my code, I'd be happy if you could help me solving my wrong design layout pattern too.
MyFrame.java
package ms0.gui;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class MyFrame extends JFrame {
public MyFrame () {
setTitle("This is an example title");
setSize(600,600);
setLocation(750,640);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//Main Container
Container mainContainer = this.getContentPane();
mainContainer.setLayout(new BorderLayout(8,6));
mainContainer.setBackground(Color.BLUE);
this.getRootPane().setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.green));
//JButton Positions
JButton topButton = new JButton("Oben");
JButton bottomButton = new JButton("Unten");
JButton leftButton = new JButton("Links");
JButton rightButton = new JButton("Rechts");
//Panel Top
JPanel topPanel = new JPanel();
topPanel.setBorder(new LineBorder(Color.BLACK, 3));
topPanel.setBackground(Color.ORANGE);
topPanel.setLayout(new FlowLayout(5));
topPanel.add(topButton);
mainContainer.add(topPanel, BorderLayout.NORTH);
//Panel Middle
JPanel middlePanel = new JPanel();
middlePanel.setBorder(new LineBorder(Color.black, 3));
middlePanel.setLayout(new FlowLayout(4,4,4));
middlePanel.setBackground(Color.cyan);
//Grid Panel Right
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new FlowLayout(4,4,4));
rightPanel.setBorder(new LineBorder(Color.black, 3));
rightPanel.setBackground(Color.GREEN);
rightPanel.add(rightButton);
//Grid Panel Left
JPanel gridPanel = new JPanel();
gridPanel.setLayout(new GridLayout(4,1,5,5));
gridPanel.setBorder(new LineBorder(Color.black, 3));
gridPanel.setBackground(Color.red);
gridPanel.add(leftButton);
//Center Box
JLabel label = new JLabel("Center Box", SwingConstants.CENTER);
label.setOpaque(true);
label.setBorder(new LineBorder(Color.black,3));
middlePanel.add(gridPanel);
mainContainer.add(label);
mainContainer.add(middlePanel, BorderLayout.WEST);
mainContainer.add(rightPanel, BorderLayout.EAST);
//Panel Bottom
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new FlowLayout(3));
bottomPanel.add(bottomButton);
bottomPanel.setBackground(Color.magenta);
bottomPanel.setBorder(new LineBorder(Color.BLUE, 3));
mainContainer.add(bottomPanel, BorderLayout.SOUTH);
//Siegel
String filepath = "/resources/siegel.jpg";
int picWidth = 150;
int picHeight = 150;
ImageIcon image1 = new ImageIcon(getClass().getResource(filepath));
//Image scaledImage = img.getScaledInstance(picWidth, picHeight, Image.SCALE_DEFAULT);
//ImageIcon icon = new ImageIcon(scaledImage);
mainContainer.add(new JButton(image1));
}
}
So, as a very basic example, nothing but BorderLayout
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
public class MyFrame extends JFrame {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MyFrame frame = new MyFrame();
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public MyFrame() {
setTitle("This is an example title");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
add(new JButton("Top button (stretched)"), BorderLayout.NORTH);
add(new JButton("Left button (stretched)"), BorderLayout.WEST);
add(new JButton("Right button (stretched)"), BorderLayout.EAST);
add(new JButton("Bottom button (stretched)"), BorderLayout.SOUTH);
JLabel label = new JLabel("Picture");
label.setBorder(new EmptyBorder(100, 100, 100, 100));
add(label);
}
}
Remember, simple is often best.
Now, if you absolutely, positively must have the label/picture in another container, you can simply make use of GridBagLayout, as it will centre the child component(s) by default, for example...
JLabel label = new JLabel("Picture");
label.setBorder(new EmptyBorder(100, 100, 100, 100));
// Automatic center position
JPanel mainPane = new JPanel(new GridBagLayout());
mainPane.add(label);
add(mainPane);
And you don't have to use EmptyBorder. GridBagLayout will allow to supply insets which will do the same thing

JButton turns non-transparent when hovered over

I'm trying to make a small game (just for fun because i get bored) and at the current time i have a few panels, buttons, frames, images and whatnot already in it working well, but i'm come to a problem that i couldn't figure out for the past few days so i thought i'd ask here
The problem i have is i want to set a JButton transparent so that all you see is the image that is placed onto it (left and right arrows), and it works....except for when you hover your mouse over the transparent button, a different part of the screen becomes the background/foreground of the JButton instead of it still being transparent
(The White Spots are where my mouse is at the time, i do not click or anything, it just changes when you interact with the JButton, look specifically at the larger left arrow)
Image Without Mouse on JButton - http://i.imgur.com/xWWE5E0.png
Image With Mouse on JButton - http://i.imgur.com/8PosnwP.png
As you can see the previously transparent JButton has not got a background/foreground and most definitely not transparent anymore
The code for the JFrame is like this (i tried to make a smaller demo but it works properly in a plain, new frame so here's my actual code(feel free to give tips on improving it by PM))
package com.Braxeo.Games;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class CharacterNew
{
static ImageIcon LArrow = new ImageIcon("Materials/LeftArrow.png");
static ImageIcon RArrow = new ImageIcon("Materials/RightArrow.png");
static ImageIcon bg = new ImageIcon("Materials/CharacterNewBackground.jpg");
public static JPanel CreateNewCharacter()
{
JPanel contentPane = new JPanel();
JPanel BackGround = new JPanel();
JLabel background = new JLabel();
JLabel shipshape = new JLabel();
JButton shapeleft = new JButton();
JButton shaperight = new JButton();
JLabel shapetext = new JLabel();
JPanel ShapeText = new JPanel();
JPanel ShipShape = new JPanel();
JPanel Shape = new JPanel();
JLabel shipcolor = new JLabel();
JButton colorleft = new JButton();
JButton colorright = new JButton();
JLabel colortext = new JLabel();
JPanel ShipColor = new JPanel();
JPanel ShipText = new JPanel();
JPanel SColor = new JPanel();
JLabel chartext = new JLabel();
JLabel charicon = new JLabel();
JButton iconleft = new JButton();
JButton iconright = new JButton();
JPanel iconpane = new JPanel();
JPanel icontext = new JPanel();
JPanel icon = new JPanel();
JButton back = new JButton();
JPanel backtext = new JPanel();
JButton continu = new JButton();
JPanel cont = new JPanel();
JLabel charname = new JLabel();
JTextField typename = new JTextField();
JPanel charnamePane = new JPanel();
// Shape
ShapeText.setLayout(new GridLayout(1,1));
ShipShape.setLayout(new GridLayout(1,3));
Shape.setLayout(new BorderLayout());
shipshape = new JLabel("ADD SSHIPS");
shapeleft = new JButton(LArrow);
shaperight = new JButton(RArrow);
shapeleft.setContentAreaFilled(false);
shapeleft.setOpaque(false);
shapeleft.setBackground(new Color(0,0,0,0));
shapetext = new JLabel("Choose Shape of Ship");
ShipShape.setBackground(new Color(0,0,0,0));
Shape.setBackground(new Color(0,0,0,0));
Shape.setBounds(600, 100, 500, 400);
ShipShape.add(shapeleft);
ShipShape.add(shipshape);
ShipShape.add(shaperight);
ShapeText.add(shapetext);
Shape.add(ShapeText, BorderLayout.PAGE_START);
Shape.add(ShipShape);
contentPane.add(Shape);
// Color
ShipColor.setLayout(new GridLayout(1, 3));
ShipText.setLayout(new GridLayout(1,1));
SColor.setLayout(new BorderLayout());
colortext = new JLabel(" Choose Color of your Ship");
shipcolor = new JLabel("ADD IMAGES");
colorleft = new JButton("ADD LEFT ARROW");
colorright = new JButton("ADD RIGHT ARROW");
colortext.setFont(new Font("Serif", Font.BOLD, 32));
ShipText.setBackground(new Color(0,0,0,0));
colortext.setForeground(Color.red);
SColor.setBackground(new Color(0,0,0,0));
ShipText.setOpaque(true);
ShipText.add(colortext);
ShipColor.add(colorleft);
ShipColor.add(shipcolor);
ShipColor.add(colorright);
SColor.setBounds(Main.x - 750,400,380,145);
SColor.add(ShipText, BorderLayout.PAGE_START);
SColor.add(ShipColor);
contentPane.add(SColor);
// Icon
iconpane.setLayout(new GridLayout(1,3));
icontext.setLayout(new GridLayout(1,1));
icon.setLayout(new BorderLayout());
chartext = new JLabel(" Pick Your Desired Icon");
charicon = new JLabel("PLACE IMAGE");
iconleft = new JButton("PLACE LEFT ICON");
iconright = new JButton("PLACE right ICON");
chartext.setFont(new Font("Serif", Font.BOLD, 32));
icontext.setBackground(new Color(0,0,0,0));
icon.setBackground(new Color(0,0,0,0));
chartext.setForeground(Color.red);
icontext.setOpaque(true);
icontext.add(chartext);
iconpane.add(iconleft);
iconpane.add(charicon);
iconpane.add(iconright);
icon.setBounds(Main.x - 750,550,380,145);
icon.add(icontext, BorderLayout.PAGE_START);
icon.add(iconpane);
contentPane.add(icon);
// back
backtext.setLayout(new BorderLayout());
back = new JButton("Back");
backtext.setBounds(50, Main.y-150, 252,76);
back.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Main.defaultframe.getContentPane().removeAll();
Main.defaultframe.getContentPane().revalidate();
Main.defaultframe.setContentPane(CharacterSelect.CreateLoadCharacter());
Main.defaultframe.setVisible(true);
}
});
backtext.add(back);
contentPane.add(backtext);
// continue
cont.setLayout(new BorderLayout());
continu = new JButton("Continue");
cont.setBounds(Main.x-302, Main.y-150, 252,76);
cont.add(continu);
contentPane.add(cont);
// Name
charnamePane.setLayout(new GridLayout( 2,1));
charname = new JLabel(" Enter Your Name Below");
charname.setFont(new Font("Impact", Font.BOLD, 32));
typename.setSize(252, 76);
typename.setFont(new Font("Razer Text Regular", Font.BOLD, 22));
typename.setBackground(Color.LIGHT_GRAY);
typename.setHorizontalAlignment(JLabel.CENTER);
charnamePane.setBounds(100,200,400,100);
charnamePane.setOpaque(true);
charnamePane.setBackground(new Color(0,0,0,0));
charname.setBackground(new Color(0,0,0,0));
charname.setForeground(Color.white);
charnamePane.add(charname);
charnamePane.add(typename, BorderLayout.PAGE_START);
contentPane.add(charnamePane);
// Background
background = new JLabel(bg);
BackGround.setLayout(new BorderLayout());
BackGround.setBounds(0, 0, Main.x, Main.y);
BackGround.add(background);
contentPane.add(BackGround);
contentPane.setLayout(new BorderLayout());
return contentPane;
}
}
The code that works out the Transparent JButton is
JButton shapeleft = new JButton();
JPanel ShapeText = new JPanel();
JPanel Shape = new JPanel();
shapeleft = new JButton(LArrow);
shapeleft.setContentAreaFilled(false);
shapeleft.setOpaque(false);
shapeleft.setBackground(new Color(0,0,0,0));
ShipShape.setBackground(new Color(0,0,0,0));
Shape.setBackground(new Color(0,0,0,0));
Shape.setBounds(600, 100, 500, 400);
ShipShape.add(shapeleft);
Shape.add(ShipShape);
contentPane.add(Shape);
If anyone could please help me figure out why its playing up like it is that would be a massive help, and i'm still a beginner so all help is good help :) thanks :)
ShipShape.setBackground(new Color(0,0,0,0));
Check out Background With Transparency for the probable problem and a couple of solutions.
Basically you need to make sure the parent component gets painted before you paint your components background.

Vertical alignement in Java Swing

How can I make buttons like this?
JPanel jp = new JPanel();
JPanel jpB1 = new JPanel();
JPanel jpB2 = new JPanel();
JPanel jpB3 = new JPanel();
JButton jb1 = new JButton("button1");
JButton jb2 = new JButton("button2");
JButton jb3 = new JButton("button3");
...
JLabel jl = new JLabel("label");
...
jp.setLayout(new BorderLayout());
...
jpB1.add(jb1);
jpB2.add(jb2);
jpB3.add(jb3);
...
jp.add(jpB1, BorderLayout.NORTH);
jp.add(jpB2, BorderLayout.CENTER);
jp.add(jpB3, BorderLayout.SOUTH);
...
I tried this code on creating 3 panels and add them to the main panel. It shows two buttons on north and one button on south! Can someone help me?
Note, the default layout of JPanel is FlowLayout; a GridBagLayout with default constraints is centered in the frame's BorderLayout.CENTER. Also, pack() the enclosing Window and display it last. Using Initial Threads left as an exercise.
Addendum: A useful trick for solving layout problems is setting the background color of an enclosing container to a contrasting color, for example
jpB2.setBackground(Color.blue);
import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Bouton2 {
public static void main(String[] args) {
final int LARGEUR = 400;
final int HAUTEUR = 300;
JFrame jf = new JFrame();
JPanel jp = new JPanel();
JPanel jpB1 = new JPanel();
JPanel jpB2 = new JPanel(new GridBagLayout());
JPanel jpB3 = new JPanel();
JButton jb1 = new JButton("Cliquez ici");
JButton jb2 = new JButton("Je compte");
JButton jb3 = new JButton("J'agrandis");
JLabel jl = new JLabel("0 clic");
jp.setLayout(new BorderLayout());
jpB1.add(jb1);
jpB2.add(jb2);
jpB3.add(jb3);
jp.add(jpB1, BorderLayout.NORTH);
jp.add(jpB2, BorderLayout.CENTER);
jp.add(jpB3, BorderLayout.SOUTH);
jf.setTitle("Fenêtre Bouton2");
jf.setContentPane(jp);
jf.pack();
jf.setSize(LARGEUR, HAUTEUR);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setLocationRelativeTo(null);
jf.setVisible(true);
}
}

Resizable Swing layout with buttons arranged according to variable dimensions

I would like to make a layout using Java Swing which looks like the following drawing.
(source: braun-abstatt.de)
On the left is a JPanel which is drawn through paintComponent() in a way that the graphics automatically scale when the window is resized. (The question isn't about that panel. That one's already done.)
Now I need some buttons (the black boxes, added in Photoshop for the drawing) to the right of the JPanel mentioned before. The height of the reddish areas at the top and bottom, next to which there should be just empty space, is calculated along the lines of CONSTANT_FACTOR * getHeight(). Next to each compartment on the left, there should be a group of buttons, lined up to the center of the respective compartment (see the blue lines).
The JPanel containing the buttons knows about the CONSTANT_FACTOR and the number of compartments, so it should be possible to feed this information into a layout manager.
Which layout manager would I best use to achieve this layout? I've read about all the different layout managers, but I can't quite figure out which one or which combination of them best fits in this case.
For example, by use of a different LayoutManager, a very easy and simple container, takes no more than 15-20 minutes:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public class ThinLineFrame {
private JFrame frame = new JFrame();
private JScrollPane scrollPane;
private JPanel panel = new JPanel();
private JPanel panelNorth = new JPanel();
private JPanel panelCenter = new JPanel();
private JPanel panelCenterCh1 = new JPanel();
private JPanel panelCenterCh2 = new JPanel();
private JPanel panelCenterCh3 = new JPanel();
private JPanel panelCenterCh4 = new JPanel();
private JPanel panelCenterCh5 = new JPanel();
private JPanel panelSouth = new JPanel();
public ThinLineFrame() {
panelNorth.setBackground(Color.red.darker());
panelNorth.setPreferredSize(new Dimension(80, 30));
//
panelCenter.setBackground(Color.darkGray);
panelCenter.setLayout(new GridLayout(5, 1, 2, 2));
//
panelCenterCh1.setLayout(new BorderLayout());
JButton panelCenterCh1Button = new JButton();
panelCenterCh1.add(panelCenterCh1Button, BorderLayout.CENTER);
//
JButton panelCenterCh2Button1 = new JButton();
JButton panelCenterCh2Button2 = new JButton();
panelCenterCh2.setLayout(new GridLayout(2, 1, 2, 2));
panelCenterCh2.add(panelCenterCh2Button1);
panelCenterCh2.add(panelCenterCh2Button2);
//
JButton panelCenterCh3Button1 = new JButton();
JButton panelCenterCh3Button2 = new JButton();
panelCenterCh3.setLayout(new GridLayout(2, 1, 2, 2));
panelCenterCh3.add(panelCenterCh3Button1);
panelCenterCh3.add(panelCenterCh3Button2);
//
JButton panelCenterCh4Button1 = new JButton();
JButton panelCenterCh4Button2 = new JButton();
panelCenterCh4.setLayout(new GridLayout(2, 1, 2, 2));
panelCenterCh4.add(panelCenterCh4Button1);
panelCenterCh4.add(panelCenterCh4Button2);
//
panelCenterCh5.setLayout(new BorderLayout());
JButton panelCenterCh5Button = new JButton();
panelCenterCh5.add(panelCenterCh5Button, BorderLayout.CENTER);
//
panelCenter.add(panelCenterCh1);
panelCenter.add(panelCenterCh2);
panelCenter.add(panelCenterCh3);
panelCenter.add(panelCenterCh4);
panelCenter.add(panelCenterCh5);
//
panelSouth.setBackground(Color.red.darker());
panelSouth.setPreferredSize(new Dimension(80, 30));
//
panel.setLayout(new BorderLayout(2, 2));
panel.add(panelNorth, BorderLayout.NORTH);
panel.add(panelCenter, BorderLayout.CENTER);
panel.add(panelSouth, BorderLayout.SOUTH);
//
scrollPane = new JScrollPane(panel);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(80, 600));
frame.setLocation(100, 150);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ThinLineFrame dlg = new ThinLineFrame();
}
});
}
}
You should try looking at MigLayout. It's a super flexible LayoutManager that is also very simple.
The code would look something like:
MigLayout layout = new MigLayout("flowy");
panel.setLayoutManager(layout);
panel.add(button1);
panel.adD(button2);
etc..
Try adding debug, flowy to the constructor to get a visual idea of what is going on.
GBC without an anchor, just with plain vanilla GridBagConstraints and preferred size.
Centered JButton with fixed size:
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class MainWithFixSize {
public static void main(String[] argv) throws Exception {
JFrame frame = new JFrame();
Container container = frame.getContentPane();
GridBagLayout gbl = new GridBagLayout();
container.setLayout(gbl);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 1;
JButton component = new JButton();
component.setPreferredSize(new Dimension(25, 25));
gbl.setConstraints(component, gbc);
container.add(component);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(40, 90));
frame.pack();
frame.setVisible(true);
}
private MainWithFixSize() {
}
}

Categories

Resources