Java Swing GUI with text and picture pane [duplicate] - java

This is for Tetris. The glass (blue) is left, and the controls (red panel) are situated in the right. In other words, now I would like just to have a frame divided into two parts: left (wider) part is blue, right part is red. Nothing more. But I seem to fail to do this.
So, my logic is: let the frame have FlowLayout. Then I add two panels which means that they are expected to be put in a row.
I prepared this:
public class GlassView extends JFrame{
public GlassView(){
this.setSize(600, 750);
this.setVisible(true);
this.setLayout(new FlowLayout());
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel glass = new JPanel();
glass.setLayout(new BoxLayout(glass, BoxLayout.Y_AXIS));
glass.setSize(450, 750);
glass.setBackground(Color.BLUE);
glass.setVisible(true);
this.add(glass);
JPanel controls = new JPanel();
controls.setLayout(new BoxLayout(controls, BoxLayout.Y_AXIS));
controls.setSize(150, 750);
controls.setBackground(Color.RED);
controls.setVisible(true);
this.add(controls);
}
}
But only a gray frame is visible on the screen. Could you help me understand why?

As Amir said you want to use a JSplitPane for this. I have added this in your code. Have a look at this.
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
GlassView view = new GlassView();
}
private static class GlassView extends JFrame {
private int width = 600;
private int height = 750;
public GlassView() {
this.setSize(width, height);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel glass = new JPanel();
glass.setSize(450, 750);
glass.setBackground(Color.BLUE);
glass.setVisible(true);
JPanel controls = new JPanel();
controls.setSize(150, 750);
controls.setBackground(Color.RED);
controls.setVisible(true);
JSplitPane splitPane = new JSplitPane();
splitPane.setSize(width, height);
splitPane.setDividerSize(0);
splitPane.setDividerLocation(150);
splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
splitPane.setLeftComponent(controls);
splitPane.setRightComponent(glass);
this.add(splitPane);
}
}

How to divide a frame into two parts
...
I would like just to have a frame divided into two parts: left (wider) part is blue, right part is red.
You want to use is a SplitPane.

Related

How do I put offsets between the JPanels and the JFrame?

I would like to make a design like the following,
I'm trying to put the offesets between the JPanels and the Jframe and I get something similar to this,
I have the code as following where I out the 2 JPanels inside a JFrame.
private static void createAndShowGUI() {
JFrame frame = new JFrame("My App");
GridLayout myLayout = new GridLayout(1,2);
myLayout.setHgap(10);
frame.setLayout(myLayout);
JPanel jLeftPanel = new JPanel();
JPanel jRightPanel = new JPanel();
jLeftPanel.setBackground(Color.DARK_GRAY);
jLeftPanel.setSize(275, 250);
jRightPanel.setBackground(Color.DARK_GRAY);
jRightPanel.setSize(275, 250);
frame.add(jLeftPanel);
frame.add(jRightPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// frame.pack();
frame.setSize(600, 550);
frame.setVisible(true);
}
How do I improve the design ?
A JComponent can have a border. There is a BorderFactory which can produce appropriate borders. For instance:
int top=10;
int left=10;
int bottom=10;
int right=10;
jLeftPanel.setBorder(BorderFactory.createEmptyBorder(top,left,bottom,right));
This would create an empty (i.e. non-opaque) border. You could have a border with a specific color, too:
int thickness=10;
jLeftPanel.setBorder(BorderFactory.createLineBorder(Color.GRAY,thickness));
Check out the other BorderFactory.create... methods, and if you need anything more complicated, you can create your own implementations of the javax.swing.border.Border interface.

Which Layout Manager Should I use to achieve the following?

I have a JFrame and three JPanels. On the frame I used BorderLayout. At the CENTER of the frame I have put outerPanel. On my outerPanel I have used MigLayout. The two other panels are added on to the outerPanel. These two panels are of equal size and their widths add up to the width of the outerPanel - I wanted the outerPanel to be divided into two halves. Below is the code for this:
public class ControlPanel extends JFrame {
// components
public JPanel outerPanel;
public JPanel innerPanel1;
public JPanel innerPanel2;
public ControlPanel() {
this.createUI();
}
public void createUI() {
// form properties
this.setSize(new java.awt.Dimension(300, 300));
this.setVisible(true);
this.setLayout(new java.awt.BorderLayout());
this.outerPanel = new JPanel();
this.outerPanel.setPreferredSize(new java.awt.Dimension(260, 250));
this.outerPanel.setLayout(new net.miginfocom.swing.MigLayout());
this.outerPanel.setBorder(BorderFactory.createEtchedBorder());
this.add(new javax.swing.JLabel("North"), BorderLayout.NORTH);
this.add(this.outerPanel, BorderLayout.CENTER);
this.innerPanel1 = new JPanel();
this.innerPanel1.setPreferredSize(new java.awt.Dimension(130, 150));
this.innerPanel1.setLayout(new net.miginfocom.swing.MigLayout());
this.innerPanel1.setBorder(BorderFactory.createTitledBorder("Panel1"));
this.innerPanel2 = new JPanel();
this.innerPanel2.setPreferredSize(new java.awt.Dimension(130, 150));
this.innerPanel2.setLayout(new net.miginfocom.swing.MigLayout());
this.innerPanel2.setBorder(BorderFactory.createTitledBorder("Panel2"));
this.outerPanel.add(this.innerPanel1);
this.outerPanel.add(this.innerPanel2);
this.pack();
}
public static void main(String[] args) {
ControlPanel cp = new ControlPanel();
}
}
Problem: When I run my program, the GUI that appears before I resize the window is fine; but when I resize the window -enlarging it, innerPane1 and innerPanel2 remains of the same size without resizing to occupy the space available.
Question: How do we make the two panels , innerPannel1 and innerPanel2, resize at the same time with the window so that they can share equally the available space? Any particular Layout Manager that can be used to divide a panel into two equal halves that can resize at the same time with the window?
Images Showing the output.
Before resizing - the GUI looks well and the panels have correct size.
After resizing -the GUI is distorted and the panels doesn't change size.
I suggest you use new GridLayout(1, 2). This will split the panel in 1 row and 2 (equally sized) columns.
So, simply changing
this.outerPanel = new JPanel();
to
this.outerPanel = new JPanel(new GridLayout(1, 2));
should do.

How to remove the padding between in the JPanel still using a flow layout?

Here's the portion of my java application GUI that I have a question about.
What this GUI consists is a blue JPanel(container) with default FlowLayout as LayoutManager that contains a Box which contains two JPanels(to remove the horizontal spacing or i could have used setHgaps to zero for that matter instead of a Box) that each contains a JLabel.
Here's my code for creating that part of the GUI.
private void setupSouth() {
final JPanel southPanel = new JPanel();
southPanel.setBackground(Color.BLUE);
final JPanel innerPanel1 = new JPanel();
innerPanel1.setBackground(Color.ORANGE);
innerPanel1.setPreferredSize(new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT));
innerPanel1.add(new JLabel("Good"));
final JPanel innerPanel2 = new JPanel();
innerPanel2.setBackground(Color.RED);
innerPanel2.setPreferredSize(new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT));
innerPanel2.add(new JLabel("Luck!"));
final Box southBox = new Box(BoxLayout.LINE_AXIS);
southBox.add(innerPanel1);
southBox.add(innerPanel2);
myFrame.add(southPanel, BorderLayout.SOUTH);
}
My question is how would i get rid the vertical padding between the outer JPanel(the blue one) and the Box?
I know this is padding because i read on Difference between margin and padding? that "padding = space around (inside) the element from text to border."
This wouldn't work because this has to due with gaps(space) between components.- How to remove JPanel padding in MigLayout?
I tried this but it didn't work either. JPanel Padding in Java
You can just set the gaps in the FlowLayout, i.e.
FlowLayout layout = (FlowLayout)southPanel.getLayout();
layout.setVgap(0);
The default FlowLayout has a 5-unit horizontal and vertical gap. Horizontal doesn't matter in this case as the BorderLayout is stretching the panel horizontally.
Or simple initialize the panel with a new FlowLayout. It'll be the same result.
new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
Edit:
"I tried that, didn't work.."
Works for me...
Setting the gap ↑ Not setting the gap ↑
import java.awt.*;
import javax.swing.*;
public class Test {
public void init() {
final JPanel southPanel = new JPanel();
FlowLayout layout = (FlowLayout)southPanel.getLayout();
layout.setVgap(0);
southPanel.setBackground(Color.BLUE);
final JPanel innerPanel1 = new JPanel();
innerPanel1.setBackground(Color.ORANGE);
innerPanel1.add(new JLabel("Good"));
final JPanel innerPanel2 = new JPanel();
innerPanel2.setBackground(Color.RED);
innerPanel2.add(new JLabel("Luck!"));
final Box southBox = new Box(BoxLayout.LINE_AXIS);
southBox.add(innerPanel1);
southBox.add(innerPanel2);
southPanel.add(southBox); // <=== You're also missing this
JFrame myFrame = new JFrame();
JPanel center = new JPanel();
center.setBackground(Color.yellow);
myFrame.add(center);
myFrame.add(southPanel, BorderLayout.SOUTH);
myFrame.setSize(150, 100);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setLocationByPlatform(true);
myFrame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new Test().init();
}
});
}
}
Note: Always post a runnable example (as I have done) for better help. You say it doesn't work, but it always works for me, so how would we know what you're doing wrong without some code that will run and demonstrate the problem?

Can't get JPanel to size properly in Swing

I'm just learning Swing, and built a sample GUI for myself as practice. Very basic, it has three panels on the West, Center, and East sides of the JFrame. In the last panel, there is another panel and a button. The panel is my extension of JPanel, DrawPanel. It draws a random Rectangle every time the button beneath it Repaint is clicked. This is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Tester
{
public static DrawPanel panelEastDrawPanelCenter;
public static void main()
{
Tester gui = new Tester();
gui.go();
}
public void go()
{
JFrame frame = new JFrame("This is the title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create all the Western Panel components
JPanel panelWest = new JPanel();
// panelWest.setLayout(new BorderLayout());
JButton panelWestButtonWest = new JButton("Western-most West Button");
JButton panelWestButtonCenter = new JButton("Western-most Center Button");
JButton panelWestButtonEast = new JButton("Western-most East Button");
// Create all Center Panel components
JPanel panelCenter = new JPanel();
panelCenter.setBackground(Color.darkGray);
JButton panelCenterButtonCenter = new JButton("Center Button");
// Create all East Panel components
JPanel panelEast = new JPanel();
panelEastDrawPanelCenter = new DrawPanel();
panelEastDrawPanelCenter.setSize(50,50);
JButton panelEastButtonSouth = new JButton("Repaint");
panelEastButtonSouth.addActionListener(new panelEastButtonSouthListener());
// Add everything to the GUI
// West Panel
frame.getContentPane().add(BorderLayout.WEST, panelWest);
panelWest.add(BorderLayout.WEST, panelWestButtonWest);
panelWest.add(BorderLayout.CENTER, panelWestButtonCenter);
panelWest.add(BorderLayout.EAST, panelWestButtonEast);
// Center Panel
frame.getContentPane().add(BorderLayout.CENTER, panelCenter);
panelCenter.add(BorderLayout.CENTER, panelCenterButtonCenter);
// East Panel
frame.getContentPane().add(BorderLayout.EAST, panelEast);
panelEast.add(panelEastDrawPanelCenter);
panelEast.add(panelEastButtonSouth);
frame.pack();
//frame.setSize(frame.getWidth(), 500);
frame.setVisible(true);
}
class panelEastButtonSouthListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
panelEastDrawPanelCenter.repaint();
}
}
class DrawPanel extends JPanel // JPanel that displays a rectangle upon clicking the button "Repaint"
{
public void paintComponent(Graphics g)
{
g.setColor(Color.WHITE); // Removes previous rectangle
g.fillRect(0,0, this.getWidth(),this.getHeight());
g.setColor(randColor()); // Puts a new rectangle on screen, rand size and color
int height = (int)(Math.random() * this.getHeight());
int width = (int)(Math.random() * this.getHeight());
int x = (int)(Math.random() * 20);
int y = (int)(Math.random() * 20);
g.fillRect(x,y, height,width);
}
public Color randColor()
{
int r = (int)(Math.random() * 255);
int g = (int)(Math.random() * 255);
int b = (int)(Math.random() * 255);
return new Color(r, g, b);
}
}
}
The problem I am encountering is that although I explicitly setSize() for the DrawPanel object (panelEastDrawPanelCenter) to 50×50, when I run the program it (DrawPanel) is still a small panel next to the button, and panelEast (the container for DrawPanel and the button) is still the same width (and will never get wider). I realize that I can say
frame.pack();
frame.setSize(frame.getWidth(), 500);
if I set the east panel to use a layout of either BorderLayout or BoxLayout, and this will make the DrawPanel display bigger.
But I do not understand why setting the size of the DrawPanel object does not actually change its size, and why it remains small regardless of me doing setSize(50,50);
How would I get the middle panel to stop resizing so huge, so that the East panel can resize to be wider? Or how do I resize the East panel?
The BorderLayout respects the preferred width of its west and east components. And it respects the preferred width and height of its center component. So, your DrawPanel should override getPreferredSize() and return the appropriate preferred size.
Since it's placed at the center of a BorderLayout which also has a south component, the preferred width of the east panel will be the max of the preferred width of the draw panel and of the button.
Have you tried using panel.setPerferredSize(Dimension size);
Try the setPreferredSize(Dimension) method instead of setSize(int, int) and call a pack() after that.

Java: Extra space in AbsoluteLayout

Is it possible to have some extra space around the edges of a JFrame that uses AbsoluteLayout? When I have a button as the downwardsmost component on the JFrame, it gets positioned right up against the bottom edge of the JFrame window, and it looks bad. I would like to know if there's a way to add a little extra space between components and the edge of the JFrame while using AbsoluteLayout.
Suggestions:
When you add a component to a JFrame, you're actually adding it to the JFrame's contentPane. To give the contentPane a "buffer" border, consider giving it an EmptyBorder(...) with the parameters being int constants for the amount of border desired around the component.
Avoid using "absolute" layouts for anything, and especially for placing components at easy to place locations for the layout managers, such as at the bottom of the GUI.
For example, note in the GUI created in the code below how the center and bottom JPanel's don't go out to the edge of the GUI because of the empty border:
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.*;
public class ButtonAtBottom {
private static void createAndShowGui() {
JPanel bottomPanel = new JPanel();
bottomPanel.add(new JButton("Bottom Button"));
bottomPanel.setBorder(BorderFactory.createTitledBorder("Bottom Panel"));
JPanel centerPanel = new JPanel();
centerPanel.setBorder(BorderFactory.createTitledBorder("Center Panel"));
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(centerPanel, BorderLayout.CENTER);
mainPanel.add(bottomPanel, BorderLayout.PAGE_END);
// **** here I add the border to the mainPanel which I'll
// make into the contentPane
int eb = 25;
mainPanel.setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
// don't set the preferredSize per Kleopatra, but am doing it
// here simply to make code shorter for this sscce
mainPanel.setPreferredSize(new Dimension(500, 400));
JFrame frame = new JFrame("ButtonAtBottom");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
You can use Box.createRigidArea(dimensions) to create an empty space that you can add below the button.
Set an empty border on your content panel where SIZE is the amount of padding you want.
JFrame frame = new JFrame();
JPanel panel = new JPanel(null);
panel.setBorder(BorderFactory.createEmptyBorder(SIZE,SIZE,SIZE,SIZE);
frame.setContentPane(panel);
//The rest
The arguments are for top, left, bottom and right padding so if you want different paddings on each edge, you can set it accordingly.

Categories

Resources