Java - JLabel with icon not aligned (going to the right) - java

I'm trying to make a deck manager for a card game (Yu-Gi-Oh :D), and for now I only have a table with available cards and a panel that shows the card the user selected in a bigger size and with the card's description.
MVCE:
import java.awt.*;
import javax.swing.*;
public class SelectedCardPanel extends JPanel{
private final JLabel cardArea;
private final JTextArea cardInfo;
public static void main(String args[]){
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Yu-Gi-Oh!");
frame.add(new SelectedCardPanel());
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
public SelectedCardPanel(){
super();
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setPreferredSize(new Dimension(200, 400));
cardArea = new JLabel(" ");
cardArea.setOpaque(true);
cardArea.setBackground(Color.white);
cardArea.setPreferredSize(new Dimension(200, 300));
cardArea.setSize(cardArea.getPreferredSize());
cardArea.setBorder(BorderFactory.createLineBorder(Color.black));
cardInfo = new JTextArea();
cardInfo.setEditable(false);
cardInfo.setWrapStyleWord(true);
cardInfo.setLineWrap(true);
cardInfo.setPreferredSize(new Dimension(200, 100));
cardInfo.setBorder(BorderFactory.createLineBorder(Color.black));
add(cardArea);
add(cardInfo);
}
public final void setImage(ImageIcon icon){
cardArea.setIcon(icon);
}
}
But that's what happens:
In the MVCE:
The cardArea gets to the right, and I don't understand why.
The card I select in the Table goes without problems to the selected card panel.
Why is the JLabel getting to the right?

The problem is with the BoxLayout. I would instead recommend using a BorderLayout And get rid of all the set[Preferred]Sizes. As for the text area, use the constructor JTextArea(rows, cols). For the columns you can leave at 0, and with BorderLayout, it will stretch to match the width of the image
import java.awt.*;
import javax.swing.*;
public class SelectCardPanel extends JPanel{
private final JLabel cardArea;
private final JTextArea cardInfo;
public static void main(String args[]){
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Yu-Gi-Oh!");
SelectCardPanel panel = new SelectCardPanel();
panel.setImage(new ImageIcon(SelectCardPanel.class.getResource("images.jpg")));
frame.add(panel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
public SelectCardPanel(){
super();
setLayout(new BorderLayout());
//setPreferredSize(new Dimension(200, 400));
cardArea = new JLabel();
cardArea.setOpaque(true);
cardArea.setBackground(Color.white);
//cardArea.setPreferredSize(new Dimension(200, 300));
//cardArea.setSize(cardArea.getPreferredSize());
cardArea.setBorder(BorderFactory.createLineBorder(Color.black));
cardInfo = new JTextArea(5, 0);
cardInfo.setEditable(false);
cardInfo.setWrapStyleWord(true);
cardInfo.setLineWrap(true);
//cardInfo.setPreferredSize(new Dimension(200, 100));
cardInfo.setBorder(BorderFactory.createLineBorder(Color.black));
add(cardArea);
add(cardInfo, BorderLayout.PAGE_END);
}
public final void setImage(ImageIcon icon){
cardArea.setIcon(icon);
}
}

Related

Java GUI - buttons will not add to panel

Hello I am having a problem adding buttons to my GUI, I try to use BorderLayout to add the buttons but it does not show when I run. Since using BorderLayout my choice of background color reverts to white as well. Can anyone please help?
import javax.swing.*;
import java.awt.*;
public class BlackjackGUI{
private JFrame frame;
private JPanel panel;
private JButton newGameBtn, dealBtn, hitBtn, standBtn;
private JLabel playerMoneyLbl;
private JLabel playerCard1Lbl, playerCard2Lbl, playerCard3Lbl,
playerCard4Lbl, playerCard5Lbl, playerCard6Lbl, playerCard7Lbl;
private JLabel dealerCard1Lbl, dealerCard2Lbl, dealerCard3Lbl, dealerCard4Lbl,
dealerCard5Lbl, dealerCard6Lbl, dealerCard7Lbl;
private JLabel playerCardValueLbl, dealerCardValueLbl;
private JTextField betInputBox;
public BlackjackGUI(){
createForm();
addButtons();
frame.add(panel);
frame.setVisible(true);
}
public void createForm() {
JFrame frame = new JFrame("Blackjack");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1200,800);
frame.setVisible(true);
JPanel panel = new JPanel();
Color c = new Color(0, 100, 0);
panel.setBackground(c);
panel.setLayout(new BorderLayout());
}
public void addButtons() {
newGameBtn = new JButton("New Game");
panel.add(newGameBtn, BorderLayout.NORTH);
}
public static void main(String[] args) {
new BlackjackGUI();
}
}

How can I remove the background behind the JtabbedPane, or change its colour

Hi, I have a JTabbedPane as above. I want to remove, or change the colour of the background, behind the tab "Select Tab." I've been searching for a long time and cannot find any info on it
Behind the tab means.. outer container. Use setBackground(Color) method on outer container.
See below code.
import javax.swing.*;
import java.awt.*;
public class TabbedPaneTabColor extends JPanel {
public TabbedPaneTabColor() {
initializeUI();
}
private void initializeUI() {
this.setLayout(new BorderLayout());
this.setPreferredSize(new Dimension(400, 200));
JTabbedPane pane = new JTabbedPane();
setBackground(Color.BLACK);// This line sets the JPANEL(container) color to black
pane.addTab("A Tab", new JPanel());
pane.addTab("B Tab", new JPanel());
pane.addTab("C Tab", new JPanel());
pane.addTab("D Tab", new JPanel());
pane.setForeground(Color.BLACK);
pane.setBackgroundAt(0, Color.RED);
pane.setBackgroundAt(1, Color.GREEN);
pane.setBackgroundAt(2, Color.YELLOW);
pane.setBackgroundAt(3, Color.ORANGE);
this.add(pane, BorderLayout.CENTER);
}
public static void showFrame() {
JPanel panel = new TabbedPaneTabColor();
panel.setOpaque(true);
JFrame frame = new JFrame("JTabbedPane Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TabbedPaneTabColor.showFrame();
}
});
}
}

How to refresh JFrame

I know there were similar questions but I have some different problem...
I'd like to remove all elements of JFrame after clicking a button:
It works:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
frame.getContentPane().removeAll();
frame.revalidate();
frame.repaint();
}
});
All elements disappeared. But after that I need to putelements on this JFrame... After these 3 lines above (below frame.repaint()) I call method initialize (method that I call when I create my window at the beginning):
private void initialize()
{
frame = new JFrame();
frame.setBounds(100, 100, 1454, 860);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnNewSubject = new JButton("New subject");
btnNewSubject.setBounds(647, 788, 137, 23);
frame.getContentPane().add(btnNewSubject);
JButton btnRefresh = new JButton("Refresh");
btnRefresh.setBounds(1339, 788, 89, 23);
frame.getContentPane().add(btnRefresh);
JLabel lblNewLabel = new JLabel("Subject");
lblNewLabel.setBounds(235, 11, 75, 14);
frame.getContentPane().add(lblNewLabel);
JLabel lblOwner = new JLabel("Owner");
lblOwner.setBounds(662, 11, 46, 14);
frame.getContentPane().add(lblOwner);
JLabel lblStatus = new JLabel("Status");
lblStatus.setBounds(883, 11, 46, 14);
frame.getContentPane().add(lblStatus);
JLabel lblDateOfAdded = new JLabel("Date of added");
lblDateOfAdded.setBounds(1104, 11, 116, 14);
frame.getContentPane().add(lblDateOfAdded);
}
Nothing happens. :( JFrame is still empty. Even if I call revalidate and repaint().
What is wrong?
You are creating a completely new JFrame in your method here
frame = new JFrame();
and you never display it, you never call setVisible(true) on it, and so it will remain invisible. It almost sounds as if you're creating two JFrames without realizing it, that you are adding components to the second non-displayed JFrame, but are leaving displaying just the first one, the one without new components.
More importantly, you will want to use a CardLayout to help you swap your JPanel views as this situation is exactly what it's built for. Also, Your program uses null layout and setBounds(...) something that results in a rigid GUI that may look good on one system but will usually look poor on any other system or screen resolution. Programs created this way are very hard to debug, maintain and upgrade. Instead use the layout managers as this is what they excel at: at creating complex flexible GUI's that can be enhanced and changed easily.
Note that your removeAll() call does not remove the root pane as Ludovic is stating because you're calling this on the contentPane not the JFrame, and the contentPane does not contain the root pane.
Edit
For example,
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class CardLayoutEg extends JPanel {
private CardLayout cardlayout = new CardLayout();
private TitlePanel titlePanel = new TitlePanel(this);
private SubjectPanel subjectPanel = new SubjectPanel(this);
public CardLayoutEg() {
setLayout(cardlayout);
add(titlePanel, titlePanel.getName());
add(subjectPanel, subjectPanel.getName());
}
public void nextCard() {
cardlayout.next(this);
}
public void showCard(String key) {
cardlayout.show(this, key);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("CardLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new CardLayoutEg());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class TitlePanel extends JPanel {
public static final String TITLE_PANEL = "title panel";
private static final int PREF_W = 900;
private static final int PREF_H = 750;
private static final String TITLE = "My Application Title";
private static final float POINTS = 46f;
private CardLayoutEg cardLayoutEg;
public TitlePanel(CardLayoutEg cardLayoutEg) {
setName(TITLE_PANEL);
this.cardLayoutEg = cardLayoutEg;
JLabel titleLabel = new JLabel(TITLE, SwingConstants.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, POINTS));
JButton subjectButton = new JButton(new SubjectAction("Subjects"));
JPanel buttonPanel = new JPanel();
buttonPanel.add(subjectButton);
setLayout(new BorderLayout());
add(titleLabel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.PAGE_END);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class SubjectAction extends AbstractAction {
public SubjectAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
cardLayoutEg.showCard(SubjectPanel.SUBJECT_PANEL);
}
}
}
class SubjectPanel extends JPanel {
public static final String SUBJECT_PANEL = "subject panel";
private static final String[] COLUMN_NAMES = {"Subject", "Owner", "Status", "Date Added"};
DefaultTableModel tableModel = new DefaultTableModel(COLUMN_NAMES, 10);
private JTable table = new JTable(tableModel);
private CardLayoutEg cardLayoutEg;
public SubjectPanel(CardLayoutEg cardLayoutEg) {
setBorder(BorderFactory.createTitledBorder("Subject Panel"));
setName(SUBJECT_PANEL);
this.cardLayoutEg = cardLayoutEg;
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1, 0, 10, 0));
buttonPanel.add(new JButton("New Subject"));
buttonPanel.add(new JButton("Refresh"));
buttonPanel.add(new JButton(new TitleAction("Title")));
buttonPanel.add(new JButton(new ExitAction("Exit")));
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));
bottomPanel.add(Box.createHorizontalGlue());
bottomPanel.add(buttonPanel);
setLayout(new BorderLayout());
add(new JScrollPane(table), BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
private class TitleAction extends AbstractAction {
public TitleAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
cardLayoutEg.showCard(TitlePanel.TITLE_PANEL);
}
}
private class ExitAction extends AbstractAction {
public ExitAction(String name) {
super(name);
int mnemonic = KeyEvent.VK_X;
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
Component component = (Component) e.getSource();
Window win = SwingUtilities.getWindowAncestor(component);
win.dispose();
}
}
}

I can use getActionCommand to change the label content, but I can't use it to change the color?

So with the help of others here I finally managed to code a button that alternates the label "Hello World!" to "Hello Universe!" and back again. I used the code below, and used the same way to try and change the color, but it didn't work as expected. I've been searching for hours on this, but with no avail. Thank you for reading, anything helps!
Code:
package game;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Javagame extends JPanel implements ActionListener{
protected JButton changetext;
protected JButton red;
protected JButton green;
private JLabel label;
public Javagame() {
add(changetext = new JButton("Button!"));
changetext.setPreferredSize(new Dimension(50, 50));
changetext.setActionCommand("change");
add(red = new JButton("Red"));
red.setPreferredSize(new Dimension(50, 50));
red.setActionCommand("changecolorRed");
add(green = new JButton("Green"));
green.setPreferredSize(new Dimension(50, 50));
green.setActionCommand("changecolorGreen");
changetext.addActionListener(this);
label = new JLabel("Hello World!", SwingConstants.CENTER);
label.setFont(new Font("Arial", Font.BOLD, 20));
label.setForeground(new Color(0x009900));
setLayout(new BorderLayout());
add(label, BorderLayout.CENTER);
add(changetext, BorderLayout.NORTH);
add(red, BorderLayout.WEST);
add(green, BorderLayout.EAST);
}
public void actionPerformed(ActionEvent e) {
if ("change".equals(e.getActionCommand())) {
label.setText("Hello Universe!");
changetext.setActionCommand("changeBack");
}
if ("changeBack".equals(e.getActionCommand())) {
label.setText("Hello World!");
changetext.setActionCommand("change");
}
if ("changecolorRed".equals(e.getActionCommand())) {
label.setForeground(new Color(0xFF0000));
}
if ("changecolorGreen".equals(e.getActionCommand())) {
label.setForeground(new Color(0x009900));
}
}
private static void createWindow(){
JFrame frame = new JFrame("Javagame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(500,500));
JPanel panel = new JPanel(new BorderLayout());
Javagame newContentPane = new Javagame();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
createWindow();
}
}
You need to add ActionListeners to buttons for them to work.
This is usually done via a simple method call: red.addActionListener(someListener);
Also:
get rid of your setPreferredsize(...) method calls, and instead let components set their own size. At the most you can override getPreferredSize() if need be, but try to limit that.
Avoid having your GUI code implement your listener interfaces as that leads to confusing and difficult to manage code. Better to use anonymous inner listeners or private inner classes or stand alone listener classes.
For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class JavaGame2 extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = 400;
private static final Font LABEL_FONT = new Font("Arial", Font.BOLD, 20);
private static final Color[] FOREGROUNDS = { new Color(0x009900),
new Color(0x990000), new Color(0x000099), new Color(0x999900),
new Color(0x990099), new Color(0x009999) };
private static final String[] LABEL_TEXTS = { "Hello World!",
"Goodbye World!", "Hola Todo el Mundo!", "Hasta la Vista Baby!",
"Whatever!!" };
private JButton changetextButton;
private JButton changeColorButton;
private JLabel label;
private int labelTextIndex = 0;
private int foregroundIndex = 0;
public JavaGame2() {
label = new JLabel(LABEL_TEXTS[labelTextIndex], SwingConstants.CENTER);
label.setFont(LABEL_FONT);
label.setForeground(FOREGROUNDS[foregroundIndex]);
// example of anonymous inner ActionListener:
changetextButton = new JButton("Change Text");
changetextButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
labelTextIndex++;
labelTextIndex %= LABEL_TEXTS.length;
label.setText(LABEL_TEXTS[labelTextIndex]);
}
});
// example of use of an anonymous AbstractAction:
changeColorButton = new JButton(new AbstractAction("Change Color") {
#Override
public void actionPerformed(ActionEvent e) {
foregroundIndex++;
foregroundIndex %= FOREGROUNDS.length;
label.setForeground(FOREGROUNDS[foregroundIndex]);
}
});
setLayout(new BorderLayout());
add(changetextButton, BorderLayout.NORTH);
add(changeColorButton, BorderLayout.SOUTH);
add(label, BorderLayout.CENTER);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
JavaGame2 mainPanel = new JavaGame2();
JFrame frame = new JFrame("Java Game 2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

How can I properly center a JPanel ( FIXED SIZE ) inside a JFrame?

Hi all!
I'm trying to solve an -apparently- simple problem, but I cannot fix it.
I'm working on a sample application with Java/Swing libraries;
I have a JFrame and a JPanel.
I just want to achieve the following objectives:
JPanel MUST be centered inside the JFrame.
JPanel MUST have ALWAYS the size that is specified with
setPreferredSize() method. It MUST NOT be resized under this size.
I tried by using a GridBagLayout: it's the ONLY way I can do it.
See the sample below:
/* file StackSample01.java */
import java.awt.*;
import javax.swing.*;
public class StackSample01 {
public static void main(String [] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(100, 100));
panel.setBackground(Color.RED);
frame.setLayout(new GridBagLayout());
frame.add(panel, new GridBagConstraints());
frame.setSize(new Dimension(200, 200));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Here a screenshot:
I would not use a GridBagLayout to do a thing too simple.
I tried a simplest solution, by using a Box, but this does not work:
Sample code:
/* file StackSample02.java */
import java.awt.*;
import javax.swing.*;
public class StackSample02 {
public static void main(String [] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(100, 100));
panel.setBackground(Color.RED); // for debug
panel.setAlignmentX(JComponent.CENTER_ALIGNMENT); // have no effect
Box box = new Box(BoxLayout.Y_AXIS);
box.add(Box.createVerticalGlue());
box.add(panel);
box.add(Box.createVerticalGlue()); // causes a deformation
frame.add(box);
frame.setSize(new Dimension(200, 200));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Here a screenshot,
Any ideas? Thanks to all :-)
BoxLayout can pretty to hold your setXxxSize(), then just add panel.setMaximumSize(new Dimension(100, 100));
and your output would be
Removed by setMinimumSize(notice if Container has greater size as ... )
import java.awt.*;
import javax.swing.*;
public class CustomComponent12 extends JFrame {
private static final long serialVersionUID = 1L;
public CustomComponent12() {
Box box = new Box(BoxLayout.Y_AXIS);
box.setAlignmentX(JComponent.CENTER_ALIGNMENT);
box.add(Box.createVerticalGlue());
box.add(new CustomComponents12());
box.add(Box.createVerticalGlue());
add(box);
pack();
setTitle("Custom Component Test / BoxLayout");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setMaximumSize(getMinimumSize());
setMinimumSize(getMinimumSize());
setPreferredSize(getPreferredSize());
setLocation(150, 150);
setVisible(true);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
CustomComponent12 main = new CustomComponent12();
}
};
javax.swing.SwingUtilities.invokeLater(r);
}
}
class CustomComponents12 extends JPanel {
private static final long serialVersionUID = 1L;
#Override
public Dimension getMinimumSize() {
return new Dimension(100, 100);
}
#Override
public Dimension getMaximumSize() {
return new Dimension(100, 100);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
#Override
public void paintComponent(Graphics g) {
int margin = 10;
Dimension dim = getSize();
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
}
}
First of all, thanks to all.
I reply another time to my own question, to show everyone the choice I have made.
See the sample code below;
As you can see, I have included only minimal steps which are absolutely necessary to achieve the goal.
/* file StackResponse.java */
import java.awt.*;
import javax.swing.*;
public class StackResponse {
public static void main(String [] args) {
JPanel panel = new JPanel();
Dimension expectedDimension = new Dimension(100, 100);
panel.setPreferredSize(expectedDimension);
panel.setMaximumSize(expectedDimension);
panel.setMinimumSize(expectedDimension);
panel.setBackground(Color.RED); // for debug only
Box box = new Box(BoxLayout.Y_AXIS);
box.add(Box.createVerticalGlue());
box.add(panel);
box.add(Box.createVerticalGlue());
JFrame frame = new JFrame();
frame.add(box);
frame.setSize(new Dimension(200, 200));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setMinimumSize(frame.getMinimumSize()); // cannot be resized-
frame.setVisible(true);
}
}
Here you can see a screenshot.
Problem solved.
Many thanks again to all.
IT
create a panel by name "FixedPanel" with GridBagLayout and set preferred size to frame size
then add your frame into FixedPanel.
Frame = new JFrame("CenterFrame");
Frame.setLocation(0, 0);
Frame.setSize(new Dimension(400,400));//dim
JPanel FixedPanel = new JPanel(new GridBagLayout());
FixedPanel.setPreferredSize(Frame.getSize());
JPanel myPanel = new JPanel();
myPanel.setPreferredSize(new Dimension(100,100));
myPanel.setBackground(Color.BLACK);
FixedPanel.add(myPanel);
Frame.add(FixedPanel);
Frame.setVisible(true);
You can do this. I had to make a chess game, and I wanted the chess piece piece to always go in the center of a cell which was a JlayeredPane:
private void formMouseReleased(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
if (jl != null)
{
jl.setLocation(evt.getX()+10, evt.getY()+10);
Component com = findComponentAt(evt.getPoint());
if (com instanceof JPanel)
{
// System.out.println("Yes, it's a jpanel");
((JPanel)com).add(jl);
((JPanel)com).validate();
}
}
}
Its Just Having
jPanel.setBounds(x, y, 1046, 503);
Where x is space for right side and y is space for left side.
you have to calculate the space from both side according to screen height and width
use
panel.setMaximumSize(new Dimension(200,200));
panel.setResizable(false)
instead?

Categories

Resources