Java Swing: manage multiple SpringLayout - java

I would like to manage a complex structure of containers as a combination of SpringLayouts (a series of stand-alone SpringLayout one inside other)
In particular, a JFrame managed by a main SpringLayout that contains JPanels: every JPanel should be managed by its own SpringLayout.
Unfortunalely, if i try to apply two different SpringLayout, nothing appears on the frame
I made this simple code to show you the problem. The code contains:
A JFrame and its SprilgLayout
A JPanel and its SpringLayout
a simple JButton inside the JPanel
Here the code:
import java.awt.Container;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SpringLayout;
public class SpringLayout_cobination {
// THE OBJECTS
static JFrame frame;// The frame
static JPanel panel; // The container
static JButton Button; // Object
// THE LayOuts
static SpringLayout LayOut_Frame;
static SpringLayout LayOut_panel;
static Container contentPane;
public static void main(String[] args) {
// Start frame and componets
frame=new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(830, 420);
panel=new JPanel();
Button=new JButton("ok");
panel.add(Button);
panel.setSize(new Dimension(100,100));
frame.add(panel);
// Set the layouts
LayOut_Frame=new SpringLayout(); // Frame LayOut
frame.setLayout(LayOut_Frame);
contentPane=frame.getContentPane(); // Main Container of the frame
LayOut_panel=new SpringLayout();
panel.setLayout(LayOut_panel);
LayOut_Frame.putConstraint(SpringLayout.NORTH, panel,30,SpringLayout.NORTH, contentPane);
LayOut_Frame.putConstraint(SpringLayout.WEST, panel,30,SpringLayout.WEST , contentPane);
LayOut_panel.putConstraint(SpringLayout.NORTH, contentPane,30,SpringLayout.NORTH, Button);
LayOut_panel.putConstraint(SpringLayout.WEST, contentPane,30,SpringLayout.WEST , Button);
frame.setVisible(true);
}
}

apply two different SpringLayout
If I understand your requirement, I think it is possible to combine SpringLayouts as below:
import java.awt.*;
import javax.swing.*;
public class SpringLayoutCobinationTest {
private static Component makeSubPanel() {
JButton button = new JButton("ok");
SpringLayout layout = new SpringLayout();
JPanel pnl = new JPanel(layout);
layout.putConstraint(SpringLayout.NORTH, button, 10, SpringLayout.NORTH, pnl);
layout.putConstraint(SpringLayout.WEST, button, 10, SpringLayout.WEST, pnl);
pnl.add(button);
pnl.setBorder(BorderFactory.createLineBorder(Color.RED));
return pnl;
}
public Component makeUI() {
Component sub = makeSubPanel();
SpringLayout layout = new SpringLayout();
SpringLayout.Constraints c = layout.getConstraints(sub);
c.setWidth(Spring.constant(100));
c.setHeight(Spring.constant(100));
JPanel panel = new JPanel(layout);
layout.putConstraint(SpringLayout.NORTH, sub, 30, SpringLayout.NORTH, panel);
layout.putConstraint(SpringLayout.WEST, sub, 30, SpringLayout.WEST, panel);
panel.add(sub);
return panel;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.add(new SpringLayoutCobinationTest().makeUI());
f.setSize(420, 420);
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}

The part of code i forgot was:
SpringLayout.Constraints c = LayOut_Frame.getConstraints(panel);
c.setWidth(Spring.constant(200));
c.setHeight(Spring.constant(100));
It seems that you must impose a Constraints dimension every time you import a component in the main frame
in my example, when I import the
The final code is:
import java.awt.Container;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Spring;
import javax.swing.SpringLayout;
public class SpringLayout_cobination {
// THE OBJECTS
static JFrame frame;// The frame
static JPanel panel; // The container
static JButton Button; // Object
// THE LayOuts
static SpringLayout LayOut_Frame;
static SpringLayout LayOut_panel;
static Container contentPane;
public static void main(String[] args) {
// Start frame and componets
frame=new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(830, 420);
panel=new JPanel();
Button=new JButton("ok");
panel.add(Button);
panel.setSize(new Dimension(100,100));
frame.add(panel);
// Set the layouts
LayOut_Frame=new SpringLayout(); // Frame LayOut
frame.setLayout(LayOut_Frame);
contentPane=frame.getContentPane(); // Main Container of the frame
LayOut_panel=new SpringLayout();
panel.setLayout(LayOut_panel);
LayOut_panel.putConstraint(SpringLayout.NORTH, contentPane,30,SpringLayout.NORTH, Button);
LayOut_panel.putConstraint(SpringLayout.WEST, contentPane,30,SpringLayout.WEST , Button);
SpringLayout.Constraints c = LayOut_Frame.getConstraints(panel);
c.setWidth(Spring.constant(200));
c.setHeight(Spring.constant(100));
LayOut_Frame.putConstraint(SpringLayout.NORTH, panel,30,SpringLayout.NORTH, contentPane);
LayOut_Frame.putConstraint(SpringLayout.WEST, panel,30,SpringLayout.WEST , contentPane);
frame.setVisible(true);
}
}

Related

How can I add a scroll bar to a text area?

Please, anyone, tell me how to add the scrollbar to a JTextArea. I tried out many things. but still not able to get it. I copied some codes related to the text area.
public class main extends JPanel {
private JTextArea jcomp1;
public main() {
jcomp1 = new JTextArea(5, 5);
setPreferredSize(new Dimension(944, 574));
// setPreferredSize (new Dimension (1024, 1080));
setLayout(null);
//add components
add(jcomp1);
jcomp1.setBounds(110, 165, 330, 300);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Paraphrasing Tool");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new main());
frame.pack();
frame.setVisible(true);
}
}
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Netbeans section.
As Andrew said, you have to place the JTextArea inside of a JScrollPane, then place the JScrollPane inside of a JPanel with a Swing layout. I used a BorderLayout.
Here's the GUI after I typed some lines.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class JTextAreaExample extends JPanel {
private static final long serialVersionUID = 1L;
private JTextArea jcomp1;
public JTextAreaExample() {
this.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
this.setLayout(new BorderLayout());
jcomp1 = new JTextArea(5, 30);
jcomp1.setMargin(new Insets(5, 5, 5, 5));
JScrollPane scrollPane = new JScrollPane(jcomp1);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
add(scrollPane);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Paraphrasing Tool");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JTextAreaExample(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
}
}
Add the text area to (the viewport of) a JScrollPane. The easiest way is to add it in the constructor. Then add the scroll pane to a panel with a layout (in a GUI that uses layouts).

How can I make the JMenuBar strape dissapear after the buttons?

How can I make the JMenuBar streak dissapear after the menuitems? I want to put a 2nd menu in the middle of the frame, and it looks weird with this streak.
I tried to set the background to Panel.background but it doesn't work.
import java.awt.*;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class SwingMenuDemo extends JPanel {
public SwingMenuDemo(){
setLayout(null);
JMenuBar menuBar = new JMenuBar();
menuBar.setBackground(UIManager.getColor("Panel.background"));
menuBar.setBounds(0, 0, 450, 25);
add(menuBar);
JButton btn1 = new JButton("Menu1");
menuBar.add(btn1);
JButton btn2 = new JButton("Menu2");
menuBar.add(btn2);
JButton btn3 = new JButton("Menu3");
menuBar.add(btn3);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("SwingMenuDemo");
frame.setPreferredSize(new Dimension(400,400));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),BoxLayout.PAGE_AXIS));
frame.getContentPane().add(new SwingMenuDemo());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
If you want to create your own "menu" of several JButtons, then don't use JMenu and don't use null layout and setBounds(...) (you should avoid the latter just as a general rule). Instead nest JPanels, each using its own layout manager to allow for simple creation of complex GUI's.
For instance you could create a JPanel to hold the buttons, say called menuPanel, give it a new GridLayout(1, 0) layout, meaning it will hold a grid of components in 1 row, and a variable number of columns (that's what the 0 means). Then put your buttons in that.
Then place that JPanel into another JPanel that uses say FlowLayout.LEADING, 0, 0) as its layout -- it will push all its components to the left.
Then make the main GUI use a BorderLayout and add the above panel to it's top in the BorderLayout.PAGE_START position. For example:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class SwingMenuDemo2 extends JPanel {
private static final String[] MENU_TEXTS = {"Menu 1", "Menu 2", "Menu 3"};
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
public SwingMenuDemo2() {
JPanel menuPanel = new JPanel(new GridLayout(1, 0));
for (String menuText : MENU_TEXTS) {
menuPanel.add(new JButton(menuText));
}
JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0));
topPanel.add(menuPanel);
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
SwingMenuDemo2 mainPanel = new SwingMenuDemo2();
JFrame frame = new JFrame("Swing Menu Demo 2");
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(() -> createAndShowGui());
}
}
You can do that with
menuBar.setBorderPainted(false);

Access and change size of Components placed on a JDialog

I created a modal JDialog (to be correct, a children of JDialog) and set it visible when the user clicks on a JButton on a JFrame. To make sure the content on the JDialog is vertically centered I've overridden the setVisible() method and do some operations before calling super.setVisible(true). The problem here is that no component, that's placed on the dialog, does have an other size than 0 before calling setVisible(true) if the dialog is set to be modal. Also setVisible() does block the execution.
Any suggestions/tips how to bypass/fix this issue?
Sample code:
public class SampleDialog extends JDialog {
protected JPanel contentPane;
public SampleDialog() {
super();
setLayout(new BorderLayout());
setDefaultCloseOperation(HIDE_ON_CLOSE);
setModal(true);
JPanel headerPane = new JPanel();
headerPane.setBackground(Color.GREEN);
add(headerPane, BorderLayout.NORTH);
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
add(contentPane, BorderLayout.CENTER);
JPanel footerPane = new JPanel();
footerPane.setBackground(Color.YELLOW);
add(footerPane, BorderLayout.SOUTH);
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
contentPane.add(new JLabel("Code"));
contentPane.add(new JTextField());
contentPane.add(new JLabel("Password"));
contentPane.add(new JPasswordField());
contentPane.add(new JButton("Login"));
}
#Override
public void setVisible(boolean b) {
/*
* Get total height of all components added to 'contentPane'
* Place Box.createVerticalStrut() before and after the 'contentPane' components,
* so the input fields look like they are centered vertically
* !!! Cannot determine size of any component because it is not rendered
*/
super.setVisible(b);
}
}
to make sure the content on the JDialog is vertically centered i've overriden the setVisible()
You should NOT be overriding setVisible() for this.
To center the component use an appropriate layout manager.
For example to center components vertically and horizontally you can just use a GridBagLayout:
JDialog dialog = new JDialog();
dialog.setLayout( new GrigBagLayout() );
JPanel panel = new JPanel(...);
panel.add(...);
dialog.add(panel, new GridBagConstraints());
You can use MigLayout manager to easily create your intended layout:
package com.zetcode;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;
/*
* Centering components on screen.
* Author Jan Bodnar
* Website zetcode.com
*/
class MyDialog extends JDialog {
public MyDialog() {
initDialog();
}
private void initDialog() {
JLabel lbl1 = new JLabel("Code");
JTextField field1 = new JTextField(15);
JLabel lbl2 = new JLabel("Password");
JPasswordField field2 = new JPasswordField(15);
JButton btn = new JButton("Login");
createLayout(lbl1, field1, lbl2, field2, btn);
setTitle("Login");
setLocationRelativeTo(null);
setDefaultCloseOperation(HIDE_ON_CLOSE);
setModal(true);
}
private void createLayout(JComponent... arg) {
setLayout(new MigLayout("wrap, align 50% 50%", "[center]"));
add(arg[0]);
add(arg[1]);
add(arg[2]);
add(arg[3]);
add(arg[4]);
pack();
}
}
public class MigLayoutCenterEx extends JFrame {
public MigLayoutCenterEx() {
initUI();
}
private void initUI() {
JPanel pnl = new JPanel();
JButton btn = new JButton("Show dialog");
btn.addActionListener((ActionEvent e) -> {
JDialog dialog = new MyDialog();
dialog.setVisible(true);
});
pnl.add(btn);
add(pnl);
setSize(400, 300);
setTitle("MigLayout example");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MigLayoutCenterEx ex = new MigLayoutCenterEx();
ex.setVisible(true);
});
}
}
Screenshot:

JPanel fill the whole JFrame

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.

Creating a class and Going into the Frame

I am trying to create this Panel into a class but it is not working, trying to make it go into the Frame as well. I am getting the "It is not a class error"
Please explain to me what I am doing wrong. Programming is fun until you are stuck for hours on one problem.
Panel:
import java.awt.Button;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TopPanel extends JPanel {
public TopPanel{
JPanel panel = new JPanel();
JFrame frame = new JFrame("Create a frame");
frame.getContentPane().add(panel);
Button button = new Button("111");
JLabel Crse = new JLabel("Course Info");
Crse.setFont(new Font("Serif", Font.PLAIN, 14));
panel.add(Crse);
panel.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setVisible(true);
}
}
Frame:
import javax.swing.*;
import java.awt.*;
public class CourseGUI extends JFrame {
public CourseGUI()
{
super("CourseGUI Frame");
JPanel topPanel = new JPanel();
topPanel.setBackground(java.awt.Color.WHITE);
Dimension d = new Dimension(800,600);
topPanel.setPreferredSize(d);
this.setLayout(new BorderLayout());
this.add(topPanel, BorderLayout.NORTH);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800,600);
TopPanel.setLayout(new BorderLayout());
TopPanel.add(Crse, BorderLayout.NORTH);
this.setVisible(true);
}
public static void main(String[] args)
{
new CourseGUI();
}
}
Thanks in advanced.
I changed the TopPanel:
import javax.swing.*;
import java.awt.*;
public class TopPanel extends JPanel {
public TopPanel(){
JPanel panel = new JPanel();
JLabel Crse = new JLabel("Course Info");
Crse.setFont(new Font("Serif", Font.PLAIN, 14));
panel.add(Crse);
panel.add(button);
}
}
TopPanel is your class name, topPanel is your JPanel instance. (Java is case sensitive).
Lines like
TopPanel.setLayout(new BorderLayout());
TopPanel.add(Crse, BorderLayout.NORTH);
Are trying to use the class which is not what you intended...
Your are also missing () on the line public TopPanel { (the one inside the class, not the one defining the class)
Crse is a local variable in the TopPanel creator, so you can't use it inside CourseGUI()
TopPanel is creating a frame to put itself into which is weird...

Categories