Components size not adjustable in JFrame - java

I'm trying to make a JFrame with a JProgressbar and a JButton inside, for the user to be see how far the process is and able to abort the process.
The only issue I seem to encounter, the progressbar and button components to always adjust to the JFrame size, and not the size I set them to. See picture one; Picture 1
The goal is to make it look like this example; Picture 2
Does anyone have some suggestions?
See my code below;
JFrame f = new JFrame("Retrieve Datalog");
JButton b = new JButton("Abort");
JProgressBar progressBar = new JProgressBar();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setIconImage(ICONBAR.getImage());
f.setResizable(false);
f.setSize(300, 100);
f.setLocationRelativeTo(getFrame());
b.setSize(50, 10);
progressBar.setSize(f.getWidth() - 100, f.getHeight() - 50);
progressBar.setValue(50);
progressBar.setStringPainted(true);
f.add(progressBar, BorderLayout.NORTH);
f.add(b, BorderLayout.CENTER);
f.setVisible(true);
PS:
I'm using NetBeans 8.1 IDE, JDK v8u91

I try some code. You can use Grid bag layout. There is the code and snapshot
Snapshot
import java.awt.*;
import javax.swing.*;
/**
* JFrame with a progress bar and button. With the size of their own.
*
* #author Tadesse
*/
public class Test extends JFrame {
JButton button = new JButton("Cancel");
JProgressBar progressBar = new JProgressBar();
public Test() {
GridBagConstraints g = new GridBagConstraints();
setLayout(new GridBagLayout());
set(g, 0, 0, GridBagConstraints.CENTER);
add(progressBar, g);
set(g, 0, 1, GridBagConstraints.CENTER);
add(button, g);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(200, 100);
setVisible(true);
}
public void set(GridBagConstraints c, int x, int y, int anchor) {
c.gridx = x;
c.gridy = y;
c.anchor = anchor;
}
public static void main(String[] args) {
new Test();
}
}

Related

Why oh why, does my scrollPane not scroll to anywhere?

I can't figure out why this code doesn't make scrollbars appear. I'm a complete beginner at Swing so the scrollpanes are very confusing and I don't understand some of the solutions I have seen online. The annoying thing is this code briefly worked but I destroyed the successful part before backing it up when trying to add a component. Any help would be appreciated!
import javax.swing.*;
import java.awt.*;
public class Test extends JFrame
{
private JPanel leftPanel;
private JButton myButton;
private JPanel scrollPanel;
private JScrollPane scrollPane;
public static void main(String[] args)
{
System.setProperty("swing.defaultlaf", "com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run() {
new Test();
}
});
}
/**
* Constructor for objects of class Backup
*/
public Test()
{
this.setTitle("testy");
this.setSize(new Dimension(1280,622));
leftPanel = new JPanel();
leftPanel.setBackground(new Color(255,0,0));
leftPanel.setBounds(0, 100, 640, 558);
leftPanel.setEnabled(true);
this.add(leftPanel);
scrollPanel = new JPanel(null);
scrollPanel.setBackground(new Color(100,100,100));
scrollPanel.setPreferredSize(new Dimension(640, 550));
scrollPanel.setEnabled(true);
JScrollPane scrollPane = new JScrollPane(scrollPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setBounds(0, 0, 642, 550);
scrollPane.setEnabled(true);
leftPanel.add(scrollPane);
for (int i = 1; i < 30; i++)
{
scrollPanel.setLayout(new GridLayout(30, 1, 0, 1));
myButton = new JButton("AAAAAAAAAAAAAAAAAAAAA " + i);
myButton.setPreferredSize(new Dimension(630, 70));
scrollPanel.add(myButton);
}
this.setBackground(new Color(0,0,0));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
}
I think I've massively improved it since then thanks to camickr
Here is the current version:
import javax.swing.*;
import java.awt.*;
public class Test extends JFrame
{
private JPanel leftPanel;
private JButton myButton;
private JPanel scrollPanel;
private JScrollPane scrollPane;
public static void main(String[] args)
{
System.setProperty("swing.defaultlaf",
"com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run() {
new Test();
}
});
}
public Test()
{
this.setTitle("testy");
this.setSize(new Dimension(1280,622));
leftPanel = new JPanel();
leftPanel.setBackground(new Color(255,0,0));
leftPanel.setBounds(0, 100, 640, 558);
this.add(leftPanel);
scrollPanel = new JPanel();
scrollPanel.setLayout(new GridLayout(70, 1, 0, 1));
//scrollPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20,
20));
scrollPanel.setBackground(new Color(100,100,100));
//scrollPanel.setPreferredSize(new Dimension(640, 550));
//JScrollPane scrollPane = new JScrollPane(scrollPanel);
JScrollPane scrollPane = new JScrollPane(scrollPanel,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
//scrollPane.setLayout(new GridLayout(30, 1, 0, 1));
//scrollPane.setBounds(0, 0, 642, 550);
scrollPane.setEnabled(true);
//scrollPanel.add(scrollPane);
leftPanel.add(scrollPanel);
for (int i = 1; i < 71; i++)
{
myButton = new JButton("AAAAAAAAAAAAAAAAAAAAA " + i);
//myButton.setPreferredSize(new Dimension(640, 80));
scrollPanel.add(myButton);
}
this.setBackground(new Color(0,0,0));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}}
Don't use a null layout.
Don't use setBounds().
Don't use setPreferredSize().
Each Swing component is responsible for determining its own preferred size. The layout manager will then set the size/location of each components added to the panel and it will then (dynamically) calculated the preferred size of the panel. The scroll bars will appear when the preferred size of the panel is greater than the size of the scroll pane.
scrollPanel = new JPanel(null);
scrollPanel.setBackground(new Color(100,100,100));
// scrollPanel.setPreferredSize(new Dimension(640, 550)); // delete
//scrollPanel.setEnabled(true); // not needed
...
for (int i = 1; i < 30; i++)
{
//scrollPanel.setLayout(new GridLayout(30, 1, 0, 1)); // set layout when panel created.
//myButton.setPreferredSize(new Dimension(630, 70)); // not needed.
The layout manager should be set outside the loop, when you create the panel. It should NOT be null.
Don't hard code the preferred size. It will not dynamically adjust as components are added.
Swing components are enabled by default to setEnabled is not needed.
Don't use the "leftPanel". Just add the scroll pane directly to the frame. This will allow the scrollpane to resize dynamically as the frame is resized. Then the scroll bars will appear when requirement.
Don't set the preferreid size of the button. The size will be determined based on the text and the Font of the button.

How to fix error in GridLayout/GridBagConstraints?

Why GridLayot not working in Swing Java?
I need to place element at concrete cell, but they placing wrong (picture)
How to place elements to concrete cell in Java Swing with grid layout?
My code:
package com.KvaksManYT;
import javax.swing.*;
import java.awt.*;
public class GUI extends JFrame {
public GUI() {
super("Test");
setBounds(100, 100, 250, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container container = this.getContentPane();
container.setLayout(new GridLayout(3, 2, 2, 2));
container.add(but1, onPosition(1, 2));
container.add(but2, onPosition(2, 2));
container.add(but3, onPosition(1, 1));
container.add(but4, onPosition(2, 1));
}
private JButton but1 = new JButton("Press 1");
private JButton but2 = new JButton("Press 2");
private JButton but3 = new JButton("Press 3");
private JButton but4 = new JButton("Press 4");
private GridBagConstraints onPosition(int x, int y) {
GridBagConstraints layConstraints = new GridBagConstraints();
layConstraints.fill = GridBagConstraints.BOTH;
layConstraints.gridx = x;
layConstraints.gridy = y;
return layConstraints;
}
}
The GridBagConstraints is used for Grid Bag Layout, rather than Grid Layout.
You have to start counting at 0 too:
public class GUI extends JFrame {
public GUI() {
super("Test");
setBounds(100, 100, 250, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagConstraints layConstraints = new GridBagConstraints();
layConstraints.fill = GridBagConstraints.NONE;
layConstraints.insets = new Insets(3, 2, 2, 2);
Container container = this.getContentPane();
container.setLayout(new GridBagLayout());
container.add(but1, onPosition(0, 1, layConstraints));
container.add(but2, onPosition(1, 1, layConstraints));
container.add(but3, onPosition(0, 0, layConstraints));
container.add(but4, onPosition(1, 0, layConstraints));
}

JButton does not appear on the GUI

when I compile and run my code everything seems to work fine except the JButton does not appear. I'm adding it to a JPanel that is on the frame. I'm new so I might not know what to lookout for here. Thanks!
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
public class TemperatureConverter extends JFrame{
//declarations
private JLabel celJLabel, farJLabel;
private JTextField celJTextField, farJTextField;
private JSlider sliderJSlider;
private JButton closeButton;
private TitledBorder border;
private JPanel topPanel, bottomPanel;
double celsiusDegrees, farenheitDegrees, sliderValue;
DecimalFormat decimalFormat = new DecimalFormat("#.0");
public TemperatureConverter()
{
createUserInterface();
}
public void createUserInterface()
{
//create the JFrame
Container frame = getContentPane();
frame.setBackground(Color.white);
frame.setLayout(null);
border = new TitledBorder("Convert between C & F");
border.setTitleColor(Color.black);
border.setTitleFont(new Font("Default", Font.ITALIC, 12));
border.setTitleJustification(TitledBorder.LEFT);
border.setTitlePosition(TitledBorder.TOP);
topPanel = new JPanel();
topPanel.setBounds(20,10,360,300);
topPanel.setForeground(Color.black);
topPanel.setBackground(Color.white);
topPanel.setLayout(null);
topPanel.setBorder(border);
frame.add(topPanel);
bottomPanel = new JPanel();
bottomPanel.setBounds(20,310,360,50);
bottomPanel.setForeground(Color.black);
bottomPanel.setBackground(Color.white);
bottomPanel.setLayout(null);
frame.add(bottomPanel);
celJLabel = new JLabel();
celJLabel.setBounds(120, 200, 60, 20);
celJLabel.setBackground(Color.white);
celJLabel.setFont(new Font("Default", Font.PLAIN, 12));
celJLabel.setText("Celcius");
celJLabel.setHorizontalAlignment(JLabel.LEFT);
topPanel.add(celJLabel);
farJLabel = new JLabel();
farJLabel.setBounds(120, 220, 60, 20);
farJLabel.setBackground(Color.white);
farJLabel.setFont(new Font("Default", Font.PLAIN, 12));
farJLabel.setText("Faranheit");
farJLabel.setHorizontalAlignment(JLabel.LEFT);
topPanel.add(farJLabel);
celJTextField = new JTextField();
celJTextField.setBounds(195,200, 50, 15);
celJTextField.setFont(new Font("Default", Font.PLAIN, 12));
celJTextField.setHorizontalAlignment(JTextField.CENTER);
celJTextField.setForeground(Color.black);
celJTextField.setBackground(Color.white);
topPanel.add(celJTextField);
farJTextField = new JTextField();
farJTextField.setBounds(195,225, 50, 15);
farJTextField.setFont(new Font("Default", Font.PLAIN, 12));
farJTextField.setHorizontalAlignment(JTextField.CENTER);
farJTextField.setForeground(Color.black);
farJTextField.setBackground(Color.white);
topPanel.add(farJTextField);
sliderJSlider = new JSlider(JSlider.HORIZONTAL, 0,100,0);
sliderJSlider.setBounds(20, 20, 310, 120);
sliderJSlider.setMajorTickSpacing(10);
sliderJSlider.setMinorTickSpacing(5);
sliderJSlider.setPaintTicks(true);
sliderJSlider.setPaintLabels(true);
sliderJSlider.setForeground(Color.black);
sliderJSlider.setBackground(Color.white);
topPanel.add(sliderJSlider);
sliderJSlider.addChangeListener(
new ChangeListener()
{
public void stateChanged(ChangeEvent event)
{
sliderStateChanged(event);
}
}
);
closeButton = new JButton();
closeButton.setBounds(140, 250, 75, 20);
closeButton.setFont(new Font("Default", Font.PLAIN,12));
closeButton.setText("Close");
closeButton.setForeground(Color.black);
closeButton.setBackground(Color.white);
bottomPanel.add(closeButton);
closeButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
closeActionPerformed(event);
}
}
);
setTitle("Temperature Converter");
setSize(400,400);
setVisible(true);
}
public static void main(String[] args)
{
TemperatureConverter application = new TemperatureConverter();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void sliderStateChanged(ChangeEvent event)
{
farenheitDegrees = sliderJSlider.getValue();
calculateCelsiusTemperature();
}
public void calculateCelsiusTemperature()
{
celsiusDegrees = (farenheitDegrees - 32)*5.0/9.0;
outputTemps();
}
public void outputTemps()
{
celJTextField.setText(decimalFormat.format(celsiusDegrees));
farJTextField.setText(decimalFormat.format(farenheitDegrees));
}
public void closeActionPerformed(ActionEvent event)
{
TemperatureConverter.this.dispose();
}
}
I'd follow the advice from the comments, use a proper layout manager.
The actual fault, is the placement of the close button within the bottom panel.
closeButton.setBounds(140, 250, 75, 20);
This might be a typo or a misunderstanding of the coordinate system, each new panel has its own private system where (0,0) is the top left of at component. The button is at (140, 250), however bottomPanel is only 360 x 50, so it is outside the visible bounds..
Try changing to
closeButton.setBounds(0, 0, 75, 20);
Your first and major mistake is this: topPanel.setLayout(null);. While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
The solution is simple: learn about and how to use the layout managers, and then use them. You can find links to the Swing tutorials including those for the layout managers and other Swing resources here: Swing Info
e.g.,
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.*;
public class TempConverter extends JPanel {
private static final int PREF_W = 400;
private static final int GAP = 5;
private JTextField celJTextField = new JTextField(10);
private JTextField farJTextField = new JTextField(10);
private JSlider sliderJSlider = new JSlider(0, 100, 0);
private JButton closeButton = new JButton("Close");
public TempConverter() {
sliderJSlider.setMajorTickSpacing(10);
sliderJSlider.setMinorTickSpacing(5);
sliderJSlider.setPaintTicks(true);
sliderJSlider.setPaintLabels(true);
JPanel textFieldPanel = new JPanel(new GridBagLayout());
textFieldPanel.add(new JLabel("Celcius:"), createGbc(0, 0));
textFieldPanel.add(celJTextField, createGbc(1, 0));
textFieldPanel.add(new JLabel("Faranheit:"), createGbc(0, 1));
textFieldPanel.add(farJTextField, createGbc(1, 1));
JPanel textFieldWrapperPanel = new JPanel(new GridBagLayout());
textFieldWrapperPanel.add(textFieldPanel);
JPanel conversionPanel = new JPanel(new BorderLayout());
conversionPanel.setBorder(BorderFactory.createTitledBorder("Foo"));
conversionPanel.setLayout(new BorderLayout());
conversionPanel.add(sliderJSlider, BorderLayout.PAGE_START);
conversionPanel.add(textFieldWrapperPanel, BorderLayout.CENTER);
JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
bottomPanel.add(closeButton);
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new BorderLayout());
add(conversionPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(GAP, GAP, GAP, GAP);
return gbc;
}
#Override
public Dimension getPreferredSize() {
Dimension superSize = super.getPreferredSize();
;
if (isPreferredSizeSet()) {
super.getPreferredSize();
}
int prefW = Math.max(PREF_W, superSize.width);
return new Dimension(prefW, superSize.height);
}
private static void createAndShowGui() {
TempConverter mainPanel = new TempConverter();
JFrame frame = new JFrame("TempConverter");
frame.setDefaultCloseOperation(JFrame.DISPOSE_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();
}
});
}
}
Now you might say that this looks more complicated, and perhaps it is, but what happens when you want to add another JTextField and JLabel to represent the Kelvin temperature scale? For your GUI, you'll need to resize the GUI and recalculate the position of any component that may be effected by adding the new components. For my GUI, you just need to add a few new lines, and the chance of the changes causing a bug in my code is much smaller than that of your changes. e.g. please note the changes below just require 3 lines of code. Everything else remains the same:
public class TempConverter extends JPanel {
private static final int PREF_W = 400;
private static final int GAP = 5;
private JTextField celJTextField = new JTextField(10);
private JTextField farJTextField = new JTextField(10);
private JTextField KelvinJTextField = new JTextField(10); // !!! Added
private JSlider sliderJSlider = new JSlider(0, 100, 0);
private JButton closeButton = new JButton("Close");
public TempConverter() {
sliderJSlider.setMajorTickSpacing(10);
sliderJSlider.setMinorTickSpacing(5);
sliderJSlider.setPaintTicks(true);
sliderJSlider.setPaintLabels(true);
JPanel textFieldPanel = new JPanel(new GridBagLayout());
textFieldPanel.add(new JLabel("Celcius:"), createGbc(0, 0));
textFieldPanel.add(celJTextField, createGbc(1, 0));
textFieldPanel.add(new JLabel("Faranheit:"), createGbc(0, 1));
textFieldPanel.add(farJTextField, createGbc(1, 1));
// !!! added
textFieldPanel.add(new JLabel("Kelvin:"), createGbc(0, 2));
textFieldPanel.add(KelvinJTextField, createGbc(1, 2));

how to center position progressbar in java

i want my progressbar at the center of the sreen. i already tried...
setLocationRelativeTo(null);
but when i run the program it didnt work. somehow it is not in the middle of the screen. Please help me. See image.
HERE ARE MY CODES
public class progressbar extends JFrame {
private JProgressBar jp;
private Timer t;
int i = 0;
public progressbar() {
setTitle("Loading...");
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().setLayout(new GridBagLayout());
setLocationRelativeTo(null);
setUndecorated(true);
setVisible(true);
jp = new JProgressBar();
// Paint the percent complete on progress bar
jp.setStringPainted(true);
jp.setPreferredSize(new Dimension(500, 30));
jp.setMinimum(0);
jp.setMaximum(1000);
getContentPane().add(jp);
pack();
// Create a timer that executes for every 2 millisec
t = new Timer(2, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
jp.setValue(i++);
if (i == 1000) {
t.stop();
setVisible(false);
loginInterface l = new loginInterface();
l.txtUser.requestFocus();
}
}
});
// Start the timer
t.start();
}
The GridBagConstraints
Anchor is Center, Grid Height 1, Grid Width 1, Grid X -1, Grid Y - 1
You need to create GridBagConstraints and define anchor (among others like x_weight) to center in GridBagLayout
Then add the component to the layout like this
GridBagLayout layout = new GridBagLayout();
GridBagConstraints cons = new GridBagConstraints();
//set the constraints properties
layout.addLayoutComponent(JProgressBar, cons);
then
setLayout(layout)

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