here is piece of my code:
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));
JPanel a = new JPanel();
a.setAlignmentX(Component.CENTER_ALIGNMENT);
a.setPreferredSize(new Dimension(100, 100));
a.setBorder(BorderFactory.createTitledBorder("aa"));
JPanel b = new JPanel();
b.setAlignmentX(Component.CENTER_ALIGNMENT);
b.setPreferredSize(new Dimension(50, 50));
b.setBorder(BorderFactory.createTitledBorder("bb"));
pane.add(a);
pane.add(b);
problem is with the width of second panel as you can see in image:
How can I fix it ?
because in flow layout it looks like I want:
As mentioned before, BoxLayout pays attention to a component's
requested minimum, preferred, and maximum sizes. While you are
fine-tuning the layout, you might need to adjust these sizes.¹
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class BoxLayoutDemo {
private static void createAndShowGUI(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
JPanel a = new JPanel();
a.setAlignmentX(Component.CENTER_ALIGNMENT);
a.setPreferredSize(new Dimension(100, 100));
a.setMaximumSize(new Dimension(100, 100)); // set max = pref
a.setBorder(BorderFactory.createTitledBorder("aa"));
JPanel b = new JPanel();
b.setAlignmentX(Component.CENTER_ALIGNMENT);
b.setPreferredSize(new Dimension(50, 50));
b.setMaximumSize(new Dimension(50, 50)); // set max = pref
b.setBorder(BorderFactory.createTitledBorder("bb"));
frame.getContentPane().add(a);
frame.getContentPane().add(b);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
createAndShowGUI();
}
});
}
}
¹ How to Use BoxLayout: Specifying Component Sizes .
Related
I tried create some window application. I have container which consist a JFrame and two JPanel (white square and red square. The last square inside white square).
I want change position red square ( any place on my work window( for example, left or right side)). I tried do it, but i didn't have success.
Could you help me?
It's my code)
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class main_window extends JFrame {
public static void main(String\[\] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.black);
frame.getContentPane().setLayout(new GridLayout(1, 1));
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
frame.getContentPane().add(panel);
JPanel panel_1 = new JPanel();
panel_1.setPreferredSize(new Dimension(200, 200));
panel_1.setBackground(Color.red);
panel.add(panel_1);
frame.setSize(800,800);
frame.setVisible(true);
}
}
GridBagLayout will give you the greatest amount of control over the layout itself.
For example...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setBackground(Color.WHITE);
setLayout(new GridBagLayout());
JPanel pane = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(50, 50);
}
};
pane.setBackground(Color.RED);
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.weighty = 1;
// Left
//gbc.anchor = GridBagConstraints.WEST;
// Right
//gbc.anchor = GridBagConstraints.EAST;
// Top
//gbc.anchor = GridBagConstraints.NORTH;
// Bottom
//gbc.anchor = GridBagConstraints.SOUTH;
// Top/left
//gbc.anchor = GridBagConstraints.NORTHWEST;
// Top/Right
//gbc.anchor = GridBagConstraints.NORTHEAST;
// Bottom/left
//gbc.anchor = GridBagConstraints.SOUTHHWEST;
// Bottom/Right
//gbc.anchor = GridBagConstraints.SOUTHEAST;
// Middle
gbc.anchor = GridBagConstraints.CENTER;
add(pane, gbc);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
}
}
It's also the most complex layout manager, so it might take some time and experimentation to get it just right.
Start by having a look at How to Use GridBagLayout
You can use FlowLayout to control the position of the red square.I have set layout to the outer panel with white background to control the position of the inside panel panel_1 which is the red square.Check my answer.
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.black);
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
frame.getContentPane().add(panel);
JPanel panel_1 = new JPanel();
panel_1.setPreferredSize(new Dimension(200, 200));
panel_1.setBackground(Color.red);
panel.add(panel_1);
//FlowLayout.RIGHT, LEFT, CENTER
panel.setLayout(new FlowLayout(FlowLayout.RIGHT));
frame.setSize(800,800);
frame.setVisible(true);
You need to perform some action in order to move the square e.g. I have added a button in my code which when clicked, will cause the square to move. For the button to perform some action, you need to implement ActionListener. As you can see in the actionPerformed method, I am generating random x and y coordinates of the top left corner of the rectangle and setting new coordinates by using the method, setBounds. Note that I have maintained the same width and height of the rectangle when it is moved to new coordinates.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainWindow extends JFrame implements ActionListener {
JPanel panel, panel_1;
JButton btnMoveSquare;
Random random;
MainWindow() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setBackground(Color.black);
getContentPane().setLayout(new GridLayout(1, 1));
panel = new JPanel();
panel.setBackground(Color.WHITE);
getContentPane().add(panel);
panel_1 = new JPanel();
panel_1.setPreferredSize(new Dimension(200, 200));
panel_1.setBackground(Color.red);
panel.add(panel_1);
btnMoveSquare = new JButton("Move Square");
btnMoveSquare.addActionListener(this);
panel.add(btnMoveSquare);
setSize(800, 800);
random = new Random();
}
#Override
public void actionPerformed(ActionEvent e) {
int x = random.nextInt(800);
int y = random.nextInt(800);
panel_1.setBounds(x, y, panel_1.getWidth(), panel_1.getHeight());
}
public static void main(String[] args) {
new MainWindow().setVisible(true);
}
}
Feel free to comment if you have any doubt with the code.
I want to place a JPanel with 300,200 size at 100,50 location in a JFrame, but the following code makes the whole JFrame to be filled with the JPanel, where am I wrong?
Code:
public class Class1 {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.setSize(700, 500);
panel.setSize(300, 200);
panel.setBackground(Color.green);
panel.setCursor(new Cursor(java.awt.Cursor.HAND_CURSOR));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(panel, BorderLayout.CENTER);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}
If I change BorderLayout.SOUTH or NORTH, the JPanel looks like a thin line at the bottom or top of the JFrame. Also I tried to use preferred size but its still the same result.
You need to understand the basics of Layout Managers before you can attempt anything with Swing.
Study the tutorial here https://docs.oracle.com/javase/tutorial/uiswing/layout/howLayoutWorks.html
If you are trying to construct a form with various Swing controls, never use absolute coordinates to position them. Resizing the window should dynamically reposition your controls according to the type of layout you want to use. If you are using your panel as a drawing canvas (which is what I think you are after), look at my example below.
Try to master a couple of fundamental layouts first such as BorderLayout and GridLayout. Once mastered you can use very few to achieve just about any kind of layout you desire by nesting them together. Also learn the basics of ScrollPane to make efficient use of screen real-estate
As for your original question, I created an example of how BorderLayout works and how to draw to a specific region on a panel. I also added some code so you can set your cursor differently depending on whether you are in the smaller region within a given panel.
Try this:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class FrameDemo extends JFrame {
private static final long serialVersionUID = 1L;
public FrameDemo() {
super("Frame Demo");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
getContentPane().add(new CustomPanel(Color.RED), BorderLayout.NORTH);
getContentPane().add(new CustomPanel(Color.GREEN), BorderLayout.SOUTH);
getContentPane().add(new CustomPanel(Color.BLUE), BorderLayout.EAST);
getContentPane().add(new CustomPanel(Color.YELLOW), BorderLayout.WEST);
getContentPane().add(new JScrollPane(new CustomPanel(Color.BLACK)), BorderLayout.CENTER);
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new FrameDemo();
frame.setVisible(true);
}
});
}
}
class CustomPanel extends JPanel implements MouseMotionListener {
private static final long serialVersionUID = 1L;
private static final Dimension PANEL_SIZE = new Dimension(200, 100);
private static final int HAND_CURSOR_INDEX = 1;
private static final int DEFAULT_CURSOR_INDEX = 0;
private static final Cursor[] _cursors = new Cursor[] {
Cursor.getDefaultCursor(),
Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)
};
// I want to place a JPanel with 300,200 size at 100,50 location in a JFrame
private static final Rectangle _rectangle = new Rectangle(50, 10, 40, 50);
public CustomPanel(Color color) {
setBackground(color);
addMouseMotionListener(this);
}
public Dimension getPreferredSize() {
return PANEL_SIZE;
}
public Dimension getMinimumSize() {
return PANEL_SIZE;
}
public Dimension getMaximumSize() {
return PANEL_SIZE;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillRect(
(int)_rectangle.getX(),
(int)_rectangle.getY(),
(int)_rectangle.getWidth(),
(int)_rectangle.getHeight());
}
#Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseMoved(MouseEvent e) {
int cursorIndex = _rectangle.contains(e.getPoint()) ?
HAND_CURSOR_INDEX :
DEFAULT_CURSOR_INDEX;
setCursor(_cursors[cursorIndex]);
}
}
If you want the panel to occupy part of the JFrame (contentpane) you can use other layout managers. He is an example using GroupLayout:
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class Class1 {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.getContentPane().setPreferredSize(new Dimension(700, 500) );
panel.setPreferredSize(new Dimension(300, 200));
panel.setBackground(Color.green);
panel.setCursor(new Cursor(java.awt.Cursor.HAND_CURSOR));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
GroupLayout groupLayout = new GroupLayout(frame.getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(104)
.addComponent(panel, GroupLayout.PREFERRED_SIZE, 493, GroupLayout.PREFERRED_SIZE)
.addContainerGap(103, Short.MAX_VALUE))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(100)
.addComponent(panel, GroupLayout.PREFERRED_SIZE, 301, GroupLayout.PREFERRED_SIZE)
.addContainerGap(99, Short.MAX_VALUE))
);
frame.getContentPane().setLayout(groupLayout);
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}
output:
Another example using BorderLayout with 4 additional "place holder" or feeler panels :
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import java.awt.BorderLayout;
public class Class1 {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout(0, 0));
JPanel centerPanel = new JPanel();
centerPanel.setPreferredSize(new Dimension(300, 200));
centerPanel.setBackground(Color.green);
centerPanel.setCursor(new Cursor(java.awt.Cursor.HAND_CURSOR));
frame.getContentPane().add(centerPanel);
JPanel northPanel = new JPanel();
northPanel.setBackground(Color.RED);
northPanel.setForeground(Color.BLACK);
northPanel.setPreferredSize(new Dimension(0, 150));
frame.getContentPane().add(northPanel, BorderLayout.NORTH);
JPanel westPanel = new JPanel();
westPanel.setBackground(Color.MAGENTA);
westPanel.setPreferredSize(new Dimension(200, 0));
frame.getContentPane().add(westPanel, BorderLayout.WEST);
JPanel southPanel = new JPanel();
southPanel.setBackground(Color.YELLOW);
southPanel.setPreferredSize(new Dimension(0, 150));
frame.getContentPane().add(southPanel, BorderLayout.SOUTH);
JPanel eastPanel = new JPanel();
eastPanel.setBackground(Color.BLUE);
eastPanel.setPreferredSize(new Dimension(200, 0));
frame.getContentPane().add(eastPanel, BorderLayout.EAST);
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}
output :
import javax.swing.*;
import java.awt.*;
public class Class1 {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JPanel another = new JPanel();
JPanel emptyPanel = new JPanel();
emptyPanel.setPreferredSize(new Dimension(700, 50));
frame.setSize(700, 500);
panel.setMaximumSize(new Dimension(300, 200));
panel.setMinimumSize(new Dimension(300, 200));
panel.setPreferredSize(new Dimension(300, 200));
panel.setBackground(Color.green);
panel.setCursor(new Cursor(java.awt.Cursor.HAND_CURSOR));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
another.add(emptyPanel, BorderLayout.NORTH);
another.add(panel, BorderLayout.CENTER);
frame.add(another);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}
The created image looks like below
It looks to me that immediate child container of the JFrame is resized to the size of the JFrame, the top level container, itself.
Studying BoxLayout and GUI in general. I want to place a panel on a frame. Later I'll add an identical panel and will test BoxLaoyout. But I can't understand why this code produces not a panel sized 200x400 but just a red point in the middle of the left side of the frame (with coordinates about (300,0)).
public class View extends JFrame {
public View(){
this.setPreferredSize(new Dimension(600, 600));
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.pack();
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
Border border = BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.RED, Color.BLACK);
JPanel p1 = new JPanel();
p1.setSize(200, 400);
p1.setBorder(border);
p1.setLayout(new BoxLayout(p1, BoxLayout.Y_AXIS));
panel.add(p1);
this.add(panel);
this.setVisible(true);
}
}
The layout manager (BoxLayout) is using the preferred size of the components of the container it is managing. By default, the preferred size of a empty JPanel is 0x0, adding in the border has produced a preferred size closer to 2x2
When using layout managers, calling setSize is meaningless, as the layout manager will override anything you specify when the container is revalidate
Updated
It would appear that the combination of both BoxLayouts seems to be playing against you. If I remove the second BoxLayout from p1, it seems to work okay.
Also, BoxLayout seems to want to work with the maximum size of the component...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.WindowConstants;
import javax.swing.border.BevelBorder;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
public class View extends JFrame {
public View() {
this.setPreferredSize(new Dimension(600, 600));
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.pack();
JPanel panel = new JPanel();
panel.setBorder(new LineBorder(Color.BLUE));
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
Border border = BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.RED, Color.BLACK);
JPanel p1 = new JPanel() {
public Dimension getMaximumSize() {
return new Dimension(200, 400);
}
};
p1.setBorder(border);
p1.setLayout(new BoxLayout(p1, BoxLayout.Y_AXIS));
panel.add(p1);
this.add(panel);
this.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new View();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
I'm making a small game and at the beginning i want to have JCheckBox for choosing the language(after that they are few more of them for setting the game) and above that a jlabel with picture with name of the game OR draw an image there, the problem is that i dont know any other way how to center the panel with checkboxes then to use GridBagLayout and when i use this, i cannot draw anything to the frame, id like to also remove those grey lines around the checkboxes if its possible, appreciate any help, thanks.
This is my second question here and i cant add images yet so here is a link to the picture :
here is code for the frame
private GamePlan plan;
private JFrame frame;
private String language;
private JPanel panel;
private JCheckBox englishBox;
private JCheckBox germanBox;
public Settings(GamePlan plan){
this.plan = plan;
frame = new JFrame();
frame.setSize(600, 500);
frame.setLocation(200, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.setResizable(false);
frame.setVisible(true);
panel = new JPanel(new GridLayout(2, 1));
englishBox = new JCheckBox("English", false);
germanBox = new JCheckBox("German", false);
englishBox.addActionListener(new EnglishLanguage());
germanBox.addActionListener(new GermanLanguage());
panel.add(englishBox);
panel.add(germanBox);
englishBox.setOpaque(false);
germanBox.setOpaque(false);
panel.setOpaque(false);
frame.add(panel);
frame.getContentPane().setBackground(new Color(216,252,202));
}
" the problem is that i dont know any other way how to center the panel with checkboxes then to use GridBagLayout and when i use this, i cannot draw anything to the frame"
I can't really tell what you're doing wrong without a complete example. I don't even see where you're trying to add the image. But don't try and draw on the frame. Draw on a JPanel instead.
Here is an example you may be able to gain some insight from.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.TitledBorder;
public class ImageByDrawing {
public ImageByDrawing() {
ImagePanel imagePanel = new ImagePanel();
imagePanel.setBorder(new TitledBorder("Drawn Image onto JPanel"));
JCheckBox germanBox = new JCheckBox("German");
germanBox.setOpaque(false);
JCheckBox englishBox = new JCheckBox("English");
englishBox.setOpaque(false);
JPanel boxPanel = new JPanel();
boxPanel.setBorder(new TitledBorder("JPanel with default FlowLayout"));
boxPanel.setOpaque(false);
boxPanel.add(germanBox);
boxPanel.add(englishBox);
JPanel centerPanel = new JPanel(new BorderLayout());
centerPanel.add(imagePanel, BorderLayout.CENTER);
centerPanel.add(boxPanel, BorderLayout.SOUTH);
centerPanel.setBorder(new TitledBorder("JPanel with BorderLayout"));
centerPanel.setOpaque(false);
JPanel mainPanel = new JPanel(new GridBagLayout());
mainPanel.add(centerPanel);
mainPanel.setBorder(new TitledBorder("JPanel with GridBagLayout"));
mainPanel.setBackground(new Color(216,252,202));
JFrame frame = new JFrame();
frame.add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public class ImagePanel extends JPanel {
BufferedImage img;
int dWidth;
int dHeight;
public ImagePanel() {
try {
img = ImageIO.read(getClass().getResource("/resources/stackblack.jpg"));
dWidth = img.getWidth();
dHeight = img.getHeight();
} catch (IOException ex) {
Logger.getLogger(ImageByDrawing.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, img.getWidth(), img.getHeight(), this);
}
#Override
public Dimension getPreferredSize() {
return (img == null) ? new Dimension(300, 300) : new Dimension(dWidth, dHeight);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new ImageByDrawing();
}
});
}
}
Also I don't know why you prefer to draw the image. The same can be easily done with a JLabel and ImageIcon
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagLayout;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.TitledBorder;
public class ImageByDrawing {
public ImageByDrawing() {
ImageIcon icon = new ImageIcon(getClass().getResource("/resources/stackblack.jpg"));
JLabel label = new JLabel(icon);
label.setBorder(new TitledBorder("JLabel with ImageIcon"));
JCheckBox germanBox = new JCheckBox("German");
germanBox.setOpaque(false);
JCheckBox englishBox = new JCheckBox("English");
englishBox.setOpaque(false);
JPanel boxPanel = new JPanel();
boxPanel.setBorder(new TitledBorder("JPanel with default FlowLayout"));
boxPanel.setOpaque(false);
boxPanel.add(germanBox);
boxPanel.add(englishBox);
JPanel centerPanel = new JPanel(new BorderLayout());
centerPanel.add(label, BorderLayout.CENTER);
centerPanel.add(boxPanel, BorderLayout.SOUTH);
centerPanel.setBorder(new TitledBorder("JPanel with BorderLayout"));
centerPanel.setOpaque(false);
JPanel mainPanel = new JPanel(new GridBagLayout());
mainPanel.add(centerPanel);
mainPanel.setBorder(new TitledBorder("JPanel with GridBagLayout"));
mainPanel.setBackground(new Color(216, 252, 202));
JFrame frame = new JFrame();
frame.add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ImageByDrawing();
}
});
}
}
The last part of your question, as #Jere pointed out you can use setFocusPainted for the check box germanBox.setFocusPainted(false);
I have JPanel with a border, the problem is that when I add the panel on the JFrame it takes the panel size although I set the preferred size for the panel using setPreferredSize. The layout of the frame is 'BoxLayout' and here's the code:
public class ActionForm extends JFrame {
JPanel namePanel;
JPanel descPanel;
JLabel actionName;
JLabel nameLabel;
JTextField nameTextField, descTextField;
FlowLayout toolBarLayout = new FlowLayout();
public ActionForm() {
this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));
TitledBorder nameBorder= BorderFactory.createTitledBorder(
"Change Description");
nameBorder.setTitleJustification(TitledBorder.LEFT);
namePanel = new JPanel(toolBarLayout);
namePanel.setPreferredSize(new Dimension(150, 150));
nameLabel = new JLabel("ButtonName");
nameTextField = new JTextField("Action's Name", 50);
namePanel.add(nameLabel);
namePanel.add(nameTextField);
namePanel.setBorder(nameBorder);
namePanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
this.add(namePanel);
}
public static void main(String[] args) {
ActionForm form = new ActionForm();
form.setVisible(true);
form.setSize(970, 500);
form.setResizable(false);
}
}
Why the size of the panel doesn't change?
BoxLayout accepting Min/Max/preferredSize that came from JComponents layed by this LayoutManager
(I'm don't want to comment something, because my answer will be so long) please to compare your code with this code example, there are implemented all good (required and important) Swing rulles
for example
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.TitledBorder;
public class ActionForm {
private static final long serialVersionUID = 1L;
private JFrame frame;
private JPanel namePanel;
private JLabel nameLabel;
private JTextField nameTextField;
private FlowLayout toolBarLayout = new FlowLayout();
public ActionForm() {
TitledBorder nameBorder = BorderFactory.createTitledBorder(
"Change Description");
nameBorder.setTitleJustification(TitledBorder.LEFT);
namePanel = new JPanel(toolBarLayout);
namePanel.setPreferredSize(new Dimension(150, 150));// hardCoded sizing
namePanel.setMaximumSize(new Dimension(250, 150)); // hardCoded sizing
namePanel.setMinimumSize(new Dimension(150, 150)); // hardCoded sizing
nameLabel = new JLabel("ButtonName");
nameTextField = new JTextField("Action's Name", 10);
namePanel.add(nameLabel);
namePanel.add(nameTextField);
namePanel.setBorder(nameBorder);
namePanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
frame = new JFrame("Mix / Max / PreferredSize for BoxLayout");
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),
BoxLayout.Y_AXIS)); // otherwise nice exceptions java.awt.AWTError:
// BoxLayout can't be shared
frame.add(namePanel);
frame.setPreferredSize(new Dimension(970, 500));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ActionForm form = new ActionForm();
}
});
}
}