How to set size of swing components - java

I want to customize the height and width of the JTextField objects. I have tried with the setSize method, passing width and height as dimensions and as int as well. But none of them seems to work. Am I missing something, like some mandatory method call on the panel or something so that the size customization would be effective? Please help. Thanks in advance.
EDIT: Here is a bit of the code:
public class WestPanel extends JPanel{
private JLabel dateL;
private JTextField date;
public WestPanel(){
setBackground(Color.white);
setLayout(new GridLayout(1,2,0,0));
dateL=new JLabel("Date: ");
date=new JTextField("dd/mm/yyyy");
date.setSize(60,10);
add(dateL);
add(date);
//....remaining code....//

Let the layout manager take care of the dimensions of your Swing components, but if you absolutely must, use setPreferredSize in combination with a layout manager that respects that property.

I'm not sure this answers the original poster's questions, but hopefully it will be helpful to other Swing developers.
Most people want the labels and components to line up, like in the following dialog I created.
I use the Swing layout manager GridBagLayout to create this type of layout. Rather than lots of explanation, here's the code that created this dialog.
package com.ggl.business.planner.view;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import com.ggl.business.planner.model.BusinessPlannerModel;
import com.ggl.business.planner.view.extended.EscapeDialog;
import com.ggl.business.planner.view.extended.JFontChooser;
public class OptionsDialog {
protected static final Insets entryInsets = new Insets(0, 10, 4, 10);
protected static final Insets spaceInsets = new Insets(10, 10, 4, 10);
protected static final Insets noInsets = new Insets(0, 0, 0, 0);
protected static final Insets iconInsets = new Insets(0, 4, 0, 0);
protected BusinessPlannerFrame frame;
protected BusinessPlannerModel model;
protected EscapeDialog dialog;
protected JButton activityTextFontButton;
protected JButton connectorTextFontButton;
protected JSpinner borderSizeSpinner;
protected SpinnerNumberModel spinnerNumberModel;
protected boolean okPressed;
public OptionsDialog(BusinessPlannerModel model, BusinessPlannerFrame frame) {
this.model = model;
this.frame = frame;
createPartControl();
}
protected void createPartControl() {
dialog = new EscapeDialog();
dialog.setTitle("Business Planner Options");
dialog.setLayout(new GridBagLayout());
int gridy = 0;
gridy = createBorderFields(gridy);
gridy = createFontFields(gridy);
gridy = createButtonFields(gridy);
dialog.pack();
dialog.setBounds(dialogBounds());
dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
dialog.setVisible(true);
}
protected int createBorderFields(int gridy) {
JLabel borderSizeLabel = new JLabel("Border size:");
borderSizeLabel.setHorizontalAlignment(SwingConstants.LEFT);
addComponent(dialog, borderSizeLabel, 0, gridy, 1, 1, spaceInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
spinnerNumberModel = new SpinnerNumberModel(model.getActivityBorder(), 1, 5, 1);
borderSizeSpinner = new JSpinner(spinnerNumberModel);
addComponent(dialog, borderSizeSpinner, 1, gridy++, 4, 1, spaceInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
return gridy;
}
protected int createFontFields(int gridy) {
JLabel boxtextFontLabel = new JLabel("Activity text font:");
boxtextFontLabel.setHorizontalAlignment(SwingConstants.LEFT);
addComponent(dialog, boxtextFontLabel, 0, gridy, 1, 1, spaceInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
Font font = model.getActivityFont();
activityTextFontButton = new JButton(getFontText(font));
activityTextFontButton.setFont(font);
activityTextFontButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
JFontChooser fontChooser = new JFontChooser();
fontChooser.setSelectedFont(model.getActivityFont());
int result = fontChooser.showDialog(dialog);
if (result == JFontChooser.OK_OPTION) {
Font font = fontChooser.getSelectedFont();
String text = getFontText(font);
model.setActivityFont(font);
activityTextFontButton.setText(text);
activityTextFontButton.setFont(font);
JButton dummy = new JButton(text);
setButtonSizes(activityTextFontButton,
connectorTextFontButton, dummy);
dialog.validate();
dialog.pack();
}
}
});
addComponent(dialog, activityTextFontButton, 1, gridy++, 4, 1, spaceInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JLabel connectortextFontLabel = new JLabel("Connector text font:");
connectortextFontLabel.setHorizontalAlignment(SwingConstants.LEFT);
addComponent(dialog, connectortextFontLabel, 0, gridy, 1, 1, spaceInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
font = model.getConnectorFont();
connectorTextFontButton = new JButton(getFontText(font));
connectorTextFontButton.setFont(font);
connectorTextFontButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
JFontChooser fontChooser = new JFontChooser();
fontChooser.setSelectedFont(model.getConnectorFont());
int result = fontChooser.showDialog(dialog);
if (result == JFontChooser.OK_OPTION) {
Font font = fontChooser.getSelectedFont();
String text = getFontText(font);
model.setConnectorFont(font);
connectorTextFontButton.setText(text);
connectorTextFontButton.setFont(font);
JButton dummy = new JButton(text);
setButtonSizes(activityTextFontButton,
connectorTextFontButton, dummy);
dialog.validate();
dialog.pack();
}
}
});
addComponent(dialog, connectorTextFontButton, 1, gridy++, 4, 1, spaceInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
setButtonSizes(activityTextFontButton, connectorTextFontButton);
return gridy;
}
protected String getFontText(Font font) {
StringBuilder builder = new StringBuilder();
builder.append(font.getName());
builder.append(", ");
builder.append(font.getSize());
builder.append(" points, ");
if (font.isPlain()) {
builder.append("plain");
} else if (font.isBold()) {
builder.append("bold ");
} else if (font.isItalic()) {
builder.append("italic");
}
return builder.toString();
}
protected int createButtonFields(int gridy) {
JPanel buttondrawingPanel = new JPanel();
buttondrawingPanel.setLayout(new FlowLayout());
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
//TODO Add edits to make sure fields are filled correctly
setModel();
okPressed = true;
dialog.setVisible(false);
}
});
dialog.setOkButton(okButton);
buttondrawingPanel.add(okButton);
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
okPressed = false;
dialog.setVisible(false);
}
});
buttondrawingPanel.add(cancelButton);
setButtonSizes(okButton, cancelButton);
addComponent(dialog, buttondrawingPanel, 0, gridy++, 5, 1, spaceInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
return gridy;
}
protected void addComponent(Container container, Component component,
int gridx, int gridy, int gridwidth, int gridheight,
Insets insets, int anchor, int fill) {
GridBagConstraints gbc = new GridBagConstraints(gridx, gridy,
gridwidth, gridheight, 1.0D, 1.0D, anchor, fill, insets, 0, 0);
container.add(component, gbc);
}
protected void setButtonSizes(JButton ... buttons) {
Dimension preferredSize = new Dimension();
for (JButton button : buttons) {
Dimension d = button.getPreferredSize();
preferredSize = setLarger(preferredSize, d);
}
for (JButton button : buttons) {
button.setPreferredSize(preferredSize);
}
}
protected Dimension setLarger(Dimension a, Dimension b) {
Dimension d = new Dimension();
d.height = Math.max(a.height, b.height);
d.width = Math.max(a.width, b.width);
return d;
}
protected void setModel() {
model.setActivityBorder(spinnerNumberModel.getNumber().intValue());
}
protected Rectangle dialogBounds() {
int margin = 200;
Rectangle bounds = dialog.getBounds();
Rectangle f = frame.getFrame().getBounds();
bounds.x = f.x + margin;
bounds.y = f.y + margin;
return bounds;
}
public boolean isOkPressed() {
return okPressed;
}
}
The EscapeDialog class I extend just lets me use the Esc key to close the dialog, as if I left clicked on the Cancel button.
There are two things I'll make note of. The first is the addComponent method, which simplifies adding components to a GridBagLayout.
The second is the setButtonSizes method, which makes all of the button sizes uniform. Even though they are JButton components, and not JTextField components, you can do something similar if you want to make JTextField components the same size.

The setSize() method only works when setting the layout manager to null.

As suggested in comments, use size hints in the text field constructor, and an appropriate layout manager.
import java.awt.*;
import javax.swing.*;
public class WestPanel extends JPanel {
private JLabel dateL;
private JTextField date;
public WestPanel(){
setBackground(Color.white);
setLayout(new FlowLayout());
dateL=new JLabel("Date: ");
date=new JTextField("dd/mm/yyyy",6);
add(dateL);
add(date);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
JPanel gui = new JPanel(new BorderLayout());
gui.add(new WestPanel(), BorderLayout.LINE_START);
gui.setBackground(Color.ORANGE);
JOptionPane.showMessageDialog(null, gui);
}
};
SwingUtilities.invokeLater(r);
}
}

Size of your components in Swing will depend on the type of layout manager you are using. If you want full control of UI, you can use a Freeflow layout.
Read the full story here:
http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html

JTextField can not be set size, infact, you should use a JTextArea instead.

Related

Create Legend in Java

I am trying to make a design to my java app and I want to make 2 groups I have already done creating 2 groups using JPanel but I am trying to make a legend design type. Now here is my question is there a way to make the overflow of the JPanel visible?
Take a look at the white space in the border of the jpanel there is a jlabel there but its content are out of bound of the panel I want to show them.
here is my code:
package myproject;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI extends JFrame {
private static final long serialVersionUID = 1L;
private JLabel jlabel1, jlabel2, lbtitle1, lbtitle2;
private JTextArea lbresult;
private JPanel layout, group1, group2;
private JButton btnlogin;
private JTextField jtxemail, jtxpass;
public GUI() {
// TODO Auto-generated constructor stub
super("This is my interface");
setSize(500,420);
setLayout(new BorderLayout(0, 0));
doDrawing();
add(layout, BorderLayout.CENTER);
}
private void doDrawing() {
// TODO Auto-generated method stub
layout = new JPanel();
layout.setLayout(null);
layout.setBackground(Color.WHITE);
layout.setSize(this.getWidth(), this.getHeight());
group1 = createGroup(group1, 0, 15, layout.getWidth() * 50/100, 50);
lbtitle1 = new JLabel("Email");
lbtitle1.setBounds(10, -15, 100, 30);
lbtitle1.setOpaque(true);
lbtitle1.setBackground(Color.WHITE);
//create label1:
jlabel1 = new JLabel("Email: ");
jlabel1.setBounds(10, 10, 100, 30);
//create textfield1:
jtxemail = new JTextField();
jtxemail.setBounds(120, 10, 100, 30);
//add objects for the group:
group1.add(lbtitle1);
group1.add(jlabel1);
group1.add(jtxemail);
layout.add(group1);
}
private JPanel createGroup(JPanel group, int x, int y, int width, int height) {
group = new JPanel();
group.setLayout(null);
group.setBounds(x, y, 0, 0);
group.setSize(width, height);
group.setBackground(new Color(0,0,0,0));
group.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1, false));
return group;
}
}
You could do something like this using a combination of layouts. For instance if you wanted a single column of data for input, then the overall layout could be a GridLayout(0, 1), creating a grid of one column and variable number of rows. Then the rows themselves would be made of a JPanel that uses, say GridBagLayout. Something like so:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
public class GUI2 extends JPanel {
private static final String[][] LABELS = {
{"E-Mail", "E-Mail Address"},
{"Phone", "Phone Number"},
{"Address", "Street Address"},
{"City", "City"},
{"State", "State"} };
private static final int TXT_FIELD_COLS = 15;
private Map<String, JTextField> labelFieldMap = new HashMap<>();
public GUI2() {
setLayout(new GridLayout(0, 1));
for (String[] label : LABELS) {
add(createLegend(label));
}
}
private JPanel createLegend(String[] label) {
JLabel jLabel = new JLabel(label[1]);
JTextField txtField = new JTextField(TXT_FIELD_COLS);
labelFieldMap.put(label[0], txtField);
JPanel legendPanel = new JPanel();
legendPanel.setBorder(BorderFactory.createTitledBorder(label[0]));
legendPanel.setLayout(new GridBagLayout());
int anchor = GridBagConstraints.WEST;
int fill = GridBagConstraints.HORIZONTAL;
int ins = 3;
Insets insets = new Insets(ins, ins, ins, 3* ins);
GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, anchor, fill, insets, 0, 0);
legendPanel.add(jLabel, gbc);
gbc.gridx = 1;
gbc.weightx = 0.0;
gbc.anchor = GridBagConstraints.EAST;
legendPanel.add(txtField, gbc);
return legendPanel;
}
private static void createAndShowGui() {
GUI2 mainPanel = new GUI2();
JFrame frame = new JFrame("GUI2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

Moving JPasswordField to absolute position

I have this code:
import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class DialogExample extends JPanel {
private static final int COLUMN_COUNT = 10;
private static final int I_GAP = 3;
public static final String BKG_IMG_PATH = "http://upload.wikimedia.org/wikipedia/commons/"
+ "thumb/9/92/Camels_in_Jordan_valley_%284568207363%29.jpg/800px-Camels_in_Jordan_valley_"
+ "%284568207363%29.jpg";
private BufferedImage backgrndImage;
private JTextField userNameField = new JTextField();
private JPasswordField passwordField = new JPasswordField();
private JPanel mainPanel = new JPanel(new GridBagLayout());
private JButton okButton = new JButton("OK");
private JButton cancelButton = new JButton("Cancel");
public DialogExample(BufferedImage backgrndImage) {
this.backgrndImage = backgrndImage;
userNameField.setColumns(COLUMN_COUNT);
passwordField.setColumns(COLUMN_COUNT);
JPanel btnPanel = new JPanel(new GridLayout(1, 0, 5, 5));
btnPanel.setOpaque(false);
btnPanel.add(okButton);
btnPanel.add(cancelButton);
GridBagConstraints gbc = getGbc(0, 0, GridBagConstraints.BOTH);
mainPanel.add(createLabel("User Name", Color.white), gbc);
gbc = getGbc(1, 0, GridBagConstraints.HORIZONTAL);
mainPanel.add(userNameField, gbc);
gbc = getGbc(0, 1, GridBagConstraints.BOTH);
mainPanel.add(createLabel("Password:", Color.white), gbc);
gbc = getGbc(1, 1, GridBagConstraints.HORIZONTAL);
mainPanel.add(passwordField, gbc);
gbc = getGbc(0, 2, GridBagConstraints.BOTH, 2, 1);
mainPanel.add(btnPanel, gbc);
mainPanel.setOpaque(false);
add(mainPanel);
}
private JLabel createLabel(String text, Color color) {
JLabel label = new JLabel(text);
label.setForeground(color);
return label;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (backgrndImage != null) {
g.drawImage(backgrndImage, 0, 0, this);
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet() || backgrndImage == null) {
return super.getPreferredSize();
}
int imgW = backgrndImage.getWidth();
int imgH = backgrndImage.getHeight();
return new Dimension(imgW, imgH);
}
public static GridBagConstraints getGbc(int x, int y, int fill) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = new Insets(I_GAP, I_GAP, I_GAP, I_GAP);
gbc.fill = fill;
return gbc;
}
public static GridBagConstraints getGbc(int x, int y, int fill, int width,
int height) {
GridBagConstraints gbc = getGbc(x, y, fill);
gbc.gridwidth = width;
gbc.gridheight = height;
return gbc;
}
private static void createAndShowGui() throws IOException {
final JFrame frame = new JFrame("Frame");
final JDialog dialog = new JDialog(frame, "User Sign-In", ModalityType.APPLICATION_MODAL);
URL imgUrl = new URL(BKG_IMG_PATH);
BufferedImage img = ImageIO.read(imgUrl);
final DialogExample dlgExample = new DialogExample(img);
dialog.add(dlgExample);
dialog.pack();
JPanel mainPanel = new JPanel();
mainPanel.add(new JButton(new AbstractAction("Please Press Me!") {
#Override
public void actionPerformed(ActionEvent e) {
dialog.setVisible(true);
}
}));
mainPanel.setPreferredSize(new Dimension(800, 650));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
createAndShowGui();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
Ho can I move the JPasswordField to a absolute position (X,Y)?? I've been trying different things like setPosition(int X, int Y) and nothing worked. I tryed playing too with the layout but not success either. I would like to have just a JPasswordField object and a button object on his right. that's it
Thank you
Start by creating a panel for the password field and button to reside on. Next, randomise a EmptyBorder and the Insets of a GridBagConstraints to define different locations within the parent container. Add the password/button panel to this container with these randomised constraints...
public class TestPane extends JPanel {
public TestPane() {
Random rnd = new Random();
JPanel panel = new JPanel();
JPasswordField pf = new JPasswordField(10);
JButton btn = new JButton("Login");
panel.add(pf);
panel.add(btn);
panel.setBorder(new EmptyBorder(rnd.nextInt(10), rnd.nextInt(10), rnd.nextInt(10), rnd.nextInt(10)));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(rnd.nextInt(100), rnd.nextInt(100), rnd.nextInt(100), rnd.nextInt(100));
add(panel, gbc);
}
}
The other choice would be to write your own custom layout manager...but if you can avoid it, the above example is MUCH simpler...
ps- You could randomise either the border OR the insets, maybe using a larger random range and get the same effect, I've simpler used both to demonstrate the point ;)
Updated with layout manager example
public class TestPane extends BackgroundImagePane {
public TestPane() throws IOException {
super(ImageIO.read(new File("Path/to/your/image")));
Random rnd = new Random();
JPanel panel = new JPanel();
panel.setOpaque(false);
JPasswordField pf = new JPasswordField(10);
JButton btn = new JButton("Login");
panel.add(pf);
panel.add(btn);
setLayout(new RandomLayoutManager());
Dimension size = getPreferredSize();
size.width -= panel.getPreferredSize().width;
size.height -= panel.getPreferredSize().height;
add(panel, new Point(rnd.nextInt(size.width), rnd.nextInt(size.height)));
}
}
public class RandomLayoutManager implements LayoutManager2 {
private Map<Component, Point> mapConstraints;
public RandomLayoutManager() {
mapConstraints = new WeakHashMap<>(25);
}
#Override
public void addLayoutComponent(String name, Component comp) {
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public void removeLayoutComponent(Component comp) {
mapConstraints.remove(comp);
}
#Override
public Dimension preferredLayoutSize(Container parent) {
Area area = new Area();
for (Component comp : mapConstraints.keySet()) {
Point p = mapConstraints.get(comp);
Rectangle bounds = new Rectangle(p, comp.getPreferredSize());
area.add(new Area(bounds));
}
Rectangle bounds = area.getBounds();
Dimension size = bounds.getSize();
size.width += bounds.x;
size.height += bounds.y;
return size;
}
#Override
public Dimension minimumLayoutSize(Container parent) {
return preferredLayoutSize(parent);
}
#Override
public void layoutContainer(Container parent) {
for (Component comp : mapConstraints.keySet()) {
Point p = mapConstraints.get(comp);
comp.setLocation(p);
comp.setSize(comp.getPreferredSize());
}
}
#Override
public void addLayoutComponent(Component comp, Object constraints) {
if (constraints instanceof Point) {
mapConstraints.put(comp, (Point) constraints);
} else {
throw new IllegalArgumentException("cannot add to layout: constraint must be a java.awt.Point");
}
}
#Override
public Dimension maximumLayoutSize(Container target) {
return preferredLayoutSize(target);
}
#Override
public float getLayoutAlignmentX(Container target) {
return 0.5f;
}
#Override
public float getLayoutAlignmentY(Container target) {
return 0.5f;
}
#Override
public void invalidateLayout(Container target) {
}
}
public class BackgroundImagePane extends JPanel {
private Image image;
public BackgroundImagePane(Image img) {
this.image = img;
}
#Override
public Dimension getPreferredSize() {
return image == null ? super.getPreferredSize() : new Dimension(image.getWidth(this), image.getHeight(this));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
int x = (getWidth() - image.getWidth(this)) / 2;
int y = (getHeight() - image.getHeight(this)) / 2;
g.drawImage(image, x, y, this);
}
}
}
The BackgroundImagePane is based on this example, allowing the background image panel to be the container for the field panel and you should be well on your way...
You could use a null layout, but that takes too long and it doesn't re-size with the frame.
Like this:
public class TestPane{
public static void main (String[] args) {
Random rnd = new Random();
JFrame frame = new JFrame();
JPasswordField pf = new JPasswordField();
JButton btn = new JButton("Login");
frame.setSize(500, 500);
frame.setLayout(null);
btn.setBounds(y, x, width, height);
pf.setBounds(y, x, width, height);
frame.add(btn);
frame.add(pf);
}
}
And that should work.
If you want to use a null layout.

Cleaning up a Nested J panel

Rebuilt the SCCE for you guys.
My goal is this
The general idea is that clicking on the title bars of the menus (right side) will collapsible (set visible to false) the content panes associated with them:
gender_panel_BG collapses gender_panel_body
race_panel_BG collapses race_panel_body
class_panel_BG collapses class_panel_body
base_stats_panel_BG collapses base_stats_panel_body
merits_panel_BG collapses merits_panel_body
You get the idea
Another thing that is bugging me is the huge space at the top of the body and it's content.
Gradient bar img source
background source source
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.*;
public class JaGCharCreation {
//set inital size of window
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int initalWidth = (int) screenSize.width - 50;
int initalHeight = (int) screenSize.height - 50;
JPanel gender_panel_body;
GridBagConstraints gbc;
JLabel viewdata_gender = new JLabel("gender");
ImageIcon BGicon = new ImageIcon("parchmentTall.jpg");
Image img1 = BGicon.getImage();
public static void main(String[] args) {
new JaGCharCreation ();
}
//set up thread safe invoking for GUI
public JaGCharCreation () {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
//frame.setLocationRelativeTo(null);
frame.setVisible(true);
// Give the frame an initial size.
frame.setSize(initalWidth, initalHeight);
}
});
}
//main panel to hold all others
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridLayout(0, 2));
add(createLeftPane());
add(createRightPane());
}//end of class for master frame
/////////////////////////////////Left Panel Nest Begin//////////////////////////////////////////////////////////////
protected JPanel createLeftPane() {
img1 = img1.getScaledInstance(initalWidth/2, initalHeight, java.awt.Image.SCALE_SMOOTH);
final ImageIcon BGiconSM = new ImageIcon(img1);
JPanel panel = new JPanel(new BorderLayout()) {
protected void paintComponent(Graphics g)
{
// Dispaly image at full size
g.drawImage(BGiconSM.getImage(), 0, 0, null);
super.paintComponent(g);
}
};
panel.setOpaque( false );
panel.setBorder(new EmptyBorder(35, 80, 35, 80));
//panel.setBackground(Color.RED);
return panel;
}//end left pane
/////////////////////////////////Left Panel Nest End//////////////////////////////////////////////////////////////
/////////////////////////////////Right Panel Nest Begin//////////////////////////////////////////////////////////////
protected JPanel createRightPane() {
img1 = img1.getScaledInstance(initalWidth/2, initalHeight, java.awt.Image.SCALE_SMOOTH);
final ImageIcon BGiconSM = new ImageIcon(img1);
JPanel content = new JPanel(new GridBagLayout());
content.setOpaque(false);
JPanel panel = new JPanel(new BorderLayout()) {
protected void paintComponent(Graphics g)
{
// Dispaly image at full size
g.drawImage(BGiconSM.getImage(), 0, 0, null);
super.paintComponent(g);
}
};
panel.setOpaque( false );
panel.setBorder(new EmptyBorder(35, 80, 35, 80));
//panel.setBackground(Color.BLUE);
//set up our image for the title bars
ImageIcon icon = new ImageIcon("GradientDetail.png");
Image img = icon.getImage();
img = img.getScaledInstance(initalWidth/2, 40, java.awt.Image.SCALE_SMOOTH);
final ImageIcon iconSM = new ImageIcon(img);
/////////////////////////////////Gender Panel Nest Begins//////////////////////////////////////////////////////////////
JPanel gender_panel_BG = new JPanel(new BorderLayout())
{
protected void paintComponent(Graphics g)
{
// Dispaly image at full size
g.drawImage(iconSM.getImage(), 0, 0, null);
super.paintComponent(g);
}
};
gender_panel_BG.setOpaque( false );
JLabel gender_panel_label = new JLabel("Gender");
gender_panel_label.setFont(new Font("Impact", Font.BOLD, 30));
gender_panel_label.setForeground(Color.white);
gender_panel_label.setOpaque(false);
gender_panel_body = new JPanel(new GridLayout(1, 3));
gender_panel_body.setBackground(Color.WHITE);
gender_panel_BG.add(gender_panel_label, BorderLayout.NORTH);
JPanel gender_panel = new JPanel(new GridLayout(2, 1));
//gender_panel.setBorder(new EmptyBorder(0, 10, 0, 10));
//gender_panel.setBackground(Color.GREEN);
gender_panel.setOpaque(false);
gender_panel.add(gender_panel_BG);
gender_panel.add(gender_panel_body);
MouseAdapter gender = new MouseAdapterMod(){
public void mousePressed(MouseEvent e) {
//System.out.println(e.getSource());
System.out.println("A mouse was pressed");
gender_panel_body.setVisible(!gender_panel_body.isVisible());
}//end of mousePressed(MouseEvent e)
};
// Create radio buttons and add them to content pane.
JRadioButton g1 = new JRadioButton("Male");
g1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
viewdata_gender.setText("Gender: Male");
}//action perfomed;
});//g1 add action listener
gender_panel_body.add(g1);
JRadioButton g2 = new JRadioButton("Female");
g2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
viewdata_gender.setText("Gender: Female");
}//action perfomed;
});//g2 add action listener
gender_panel_body.add(g2);
JRadioButton g3 = new JRadioButton("<Unknown>");
g3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
viewdata_gender.setText("Gender: <Unknown>");
}//action perfomed;
});//g3 add action listener
gender_panel_body.add(g3);
// Define a button group.
ButtonGroup genderButtons = new ButtonGroup();
genderButtons.add(g1);
genderButtons.add(g2);
genderButtons.add(g3);
gender_panel_BG.addMouseListener(gender);
content.add(gender_panel, gbc);
/////////////////////////////////Gender Panel Nest End//////////////////////////////////////////////////////////////
/////////////////////////////////Race Panel Nest Begins//////////////////////////////////////////////////////////////
JPanel race_panel_BG = new JPanel(new BorderLayout())
{
protected void paintComponent(Graphics g)
{
// Dispaly image at full size
g.drawImage(iconSM.getImage(), 0, 0, null);
super.paintComponent(g);
}
};
race_panel_BG.setOpaque( false );
JLabel race_panel_label = new JLabel("Race");
race_panel_label.setFont(new Font("Impact", Font.BOLD, 30));
race_panel_label.setForeground(Color.white);
race_panel_label.setOpaque(false);
JPanel race_panel_body = new JPanel(new GridLayout(5, 8));
race_panel_body.setBackground(Color.WHITE);
race_panel_BG.add(race_panel_label, BorderLayout.NORTH);
JPanel race_panel = new JPanel(new GridLayout(2, 1));
//race_panel.setBorder(new EmptyBorder(0, 10, 0, 10));
//race_panel.setBackground(Color.GREEN);
race_panel.setOpaque(false);
race_panel.add(race_panel_BG);
race_panel.add(race_panel_body);
for (int i=0; i <= 60; i++){
ImageIcon RCicon = new ImageIcon("headshot.jpg");
Image RCimg = RCicon.getImage();
RCimg = RCimg.getScaledInstance(40, 40, java.awt.Image.SCALE_SMOOTH);
final ImageIcon RCiconSM = new ImageIcon(RCimg);
JButton button = new JButton(RCiconSM);
button.setBorder(BorderFactory.createEmptyBorder());
button.setContentAreaFilled(false);
race_panel_body.add(button);
};//for loop
MouseAdapter race = new MouseAdapterMod();
race_panel_body.addMouseListener(race);
content.add(race_panel, gbc);
/////////////////////////////////Race Panel Nest End//////////////////////////////////////////////////////////////
/////////////////////////////////Class Panel Nest Begins//////////////////////////////////////////////////////////////
JPanel class_panel_BG = new JPanel(new BorderLayout())
{
protected void paintComponent(Graphics g)
{
// Dispaly image at full size
g.drawImage(iconSM.getImage(), 0, 0, null);
super.paintComponent(g);
}
};
class_panel_BG.setOpaque( false );
JLabel class_panel_label = new JLabel("Class");
class_panel_label.setFont(new Font("Impact", Font.BOLD, 30));
class_panel_label.setForeground(Color.white);
class_panel_label.setOpaque(false);
JPanel class_panel_body = new JPanel(new GridLayout(5, 8));
class_panel_body.setBackground(Color.WHITE);
class_panel_BG.add(class_panel_label, BorderLayout.NORTH);
JPanel class_panel = new JPanel(new GridLayout(2, 1));
//class_panel.setBorder(new EmptyBorder(0, 10, 0, 10));
//class_panel.setBackground(Color.GREEN);
class_panel.setOpaque(false);
class_panel.add(class_panel_BG);
class_panel.add(class_panel_body);
for (int g=0; g <= 50; g++){
ImageIcon CCicon = new ImageIcon("headshot.jpg");
Image CCimg = CCicon.getImage();
CCimg = CCimg.getScaledInstance(40, 40, java.awt.Image.SCALE_SMOOTH);
final ImageIcon CCiconSM = new ImageIcon(CCimg);
JButton cbutton = new JButton(CCiconSM);
cbutton.setBorder(BorderFactory.createEmptyBorder());
cbutton.setContentAreaFilled(false);
class_panel_body.add(cbutton);
};//for loop
MouseAdapter cclass = new MouseAdapterMod();
class_panel_body.addMouseListener(cclass);
content.add(class_panel, gbc);
/////////////////////////////////Class Panel Nest End//////////////////////////////////////////////////////////////
/////////////////////////////////Base Stats Panel Nest Begins//////////////////////////////////////////////////////////////
JPanel base_stats_panel_BG = new JPanel(new BorderLayout())
{
protected void paintComponent(Graphics g)
{
// Dispaly image at full size
g.drawImage(iconSM.getImage(), 0, 0, null);
super.paintComponent(g);
}
};
base_stats_panel_BG.setOpaque( false );
JLabel base_stats_panel_label = new JLabel("Base Attributes");
base_stats_panel_label.setFont(new Font("Impact", Font.BOLD, 30));
base_stats_panel_label.setForeground(Color.white);
base_stats_panel_label.setOpaque(false);
JPanel base_stats_panel_body = new JPanel(new GridLayout(1, 2));
base_stats_panel_body.setBackground(Color.WHITE);
base_stats_panel_BG.add(base_stats_panel_label, BorderLayout.NORTH);
JPanel base_stats_panel = new JPanel(new GridLayout(2, 1));
//base_stats_panel.setBorder(new EmptyBorder(0, 10, 0, 10));
//base_stats_panel.setBackground(Color.GREEN);
base_stats_panel.setOpaque(false);
base_stats_panel.add(base_stats_panel_BG);
base_stats_panel.add(base_stats_panel_body);
MouseAdapter base_stats = new MouseAdapterMod();
base_stats_panel_body.addMouseListener(base_stats);
content.add(base_stats_panel, gbc);
/////////////////////////////////Base Stats Panel Nest End//////////////////////////////////////////////////////////////
/////////////////////////////////Merits Panel Nest Begins//////////////////////////////////////////////////////////////
JPanel merits_panel_BG = new JPanel(new BorderLayout())
{
protected void paintComponent(Graphics g)
{
// Dispaly image at full size
g.drawImage(iconSM.getImage(), 0, 0, null);
super.paintComponent(g);
}
};
merits_panel_BG.setOpaque( false );
JLabel merits_panel_label = new JLabel("Advantages and Disadvantages");
merits_panel_label.setFont(new Font("Impact", Font.BOLD, 30));
merits_panel_label.setForeground(Color.white);
merits_panel_label.setOpaque(false);
JPanel merits_panel_body = new JPanel(new BorderLayout());
merits_panel_body.setBackground(Color.WHITE);
merits_panel_BG.add(merits_panel_label, BorderLayout.NORTH);
JPanel merits_panel = new JPanel(new GridLayout(2, 1));
//merits_panel.setBorder(new EmptyBorder(0, 10, 0, 10));
//merits_panel.setBackground(Color.GREEN);
merits_panel.setOpaque(false);
merits_panel.add(merits_panel_BG);
merits_panel.add(merits_panel_body);
MouseAdapter merits = new MouseAdapterMod();
merits_panel_body.addMouseListener(merits);
content.add(merits_panel, gbc);
/////////////////////////////////Merits Panel Nest End//////////////////////////////////////////////////////////////
/////////////////////////////////Group Panel Nest Begin//////////////////////////////////////////////////////////////
JPanel viewData = new JPanel(new GridLayout(5, 1));
viewData.add(gender_panel);
viewData.add(race_panel);
viewData.add(class_panel);
viewData.add(base_stats_panel);
viewData.add(merits_panel);
panel.add(new JScrollPane(viewData));
return panel;
/////////////////////////////////Group Panel Nest End//////////////////////////////////////////////////////////////
}//end right pane
/////////////////////////////////Right Panel Nest End//////////////////////////////////////////////////////////////
public class MouseAdapterMod extends MouseAdapter {
// usually better off with mousePressed rather than clicked
public void mousePressed(MouseEvent e) {
//System.out.println(e.getSource());
System.out.println("A mouse was pressed");
if (e.getSource() == "gender_panel_BG"){
gender_panel_body.setVisible(!gender_panel_body.isVisible());
}//end of if (e.getSource() == "gender")
}//end of mousePressed(MouseEvent e)
}//end of MouseAdapterMod extends MouseAdapter
}//end master panel set
}//end master class
Now I need to figure out how to select multiple JButtons. It's not quite a check box, as I want to have images instead of tick boxes.
JToggleButton, the parent of JCheckBox, works well for this, as each button knows its selected state. You can nest GridLayout instances in a vertical Box, as shown below.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToggleButton;
import javax.swing.UIManager;
import javax.swing.border.TitledBorder;
/** #see http://stackoverflow.com/a/16733710/230513 */
public class Test {
private static final int N = 4;
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Box b = new Box(BoxLayout.Y_AXIS);
b.add(createPanel());
b.add(createPanel());
f.add(new JScrollPane(b){
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 500);
}
});
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private JPanel createPanel() {
JPanel p = new JPanel(new GridLayout(N, N));
p.setBorder(new TitledBorder(String.valueOf(p.hashCode())));
for (int i = 0; i < N * N; i++) {
p.add(createButton());
}
return p;
}
private JToggleButton createButton() {
JToggleButton b = new JToggleButton(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
}
});
b.setIcon(UIManager.getIcon("html.pendingImage"));
b.setText(String.valueOf(b.hashCode()));
b.setHorizontalTextPosition(JToggleButton.CENTER);
b.setVerticalTextPosition(JToggleButton.BOTTOM);
return b;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Test().display();
}
});
}
}

JScrollPane inside JPanel inside a JTabbedPane is not scrolling

I have this JPanel called CatalogPane, which is of size 800 by 600, which is inside a JTabbedPane inside a JFrame called BookFrame. So inside the CatalogPane, I created a JPanel called bookDisplay which displays a list of books and their details. I want it to be of size 780 by 900, leaving 20px for the scrollbar and taller than the frame so that it can scroll. Then I created a panel of size 800 by 400 because I need to leave some extra space at the bottom for other fields. I tried creating a JScrollPane for bookDisplay and then put it inside the other panel, but somehow the scrollbar appears but can't be used to scroll. I've experimented changing the sizes and scrollpane but I still can't get it to work.
What it looks like: http://prntscr.com/12j0d9
The scrollbar is there but can't work. I'm trying to get the scrollbar to work before I format the layout properly.
CatalogPane:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;
public class CatalogPane extends JPanel{
//private Order currOrder = new Order();
//ArrayList<Book> bookCatalog = new ArrayList();
GridBagConstraints gbc = new GridBagConstraints();
GridBagLayout gbl = new GridBagLayout();
JPanel bookDisplay = new JPanel();
public CatalogPane()
{
//loadBookCatalog();
this.setPreferredSize(new Dimension(800, 600));
bookDisplay.setPreferredSize(new Dimension(780, 900));
bookDisplay.setLayout(new GridLayout(6, 5));
//bookDisplay.setLayout(gbl);
//gbc.fill = GridBagConstraints.NONE;
//gbc.weightx = 1;
//gbc.weighty = 1;
JLabel bookL = new JLabel("Books");
JLabel hardL = new JLabel("Hardcopy");
JLabel hardQuantL = new JLabel("Quantity");
JLabel eL = new JLabel("EBook");
JLabel eQuantL = new JLabel("Quantity");
bookDisplay.add(bookL);
bookDisplay.add(hardL);
bookDisplay.add(hardQuantL);
bookDisplay.add(eL);
bookDisplay.add(eQuantL);
/*
addComponent(bookL, 0, 0, 1, 1);
addComponent(hardL, 0, 1, 1, 1);
addComponent(hardQuantL, 0, 2, 1, 1);
addComponent(eL, 0, 3, 1, 1);
addComponent(eQuantL, 0, 4, 1, 1);
*/
Iterator<Book> bci = bookCatalog.iterator();
int row = 1;
/*
while(bci.hasNext())
{
Book temp = bci.next();
ImageIcon book1 = new ImageIcon(temp.getImage());
JLabel image = new JLabel(temp.getTitle(), book1, JLabel.CENTER);
image.setVerticalTextPosition(JLabel.TOP);
image.setHorizontalTextPosition(JLabel.CENTER);
String[] quant = {"1", "2", "3", "4", "5"};
JLabel hardP = new JLabel("$" + temp.getHardPrice());
JLabel eP = new JLabel("$" + temp.getEPrice());
JComboBox jbc1 = new JComboBox(quant);
JComboBox jbc2 = new JComboBox(quant);
jbc1.setSelectedIndex(0);
jbc2.setSelectedIndex(0);
/*
addComponent(b1temp, row, 0, 1, 1);
addComponent(hardP, row, 1, 1, 1);
addComponent(jbc1, row, 2, 1, 1);
addComponent(eP, row, 3, 1, 1);
addComponent(jbc2, row, 4, 1, 1);
row++;
bookDisplay.add(image);
bookDisplay.add(new JLabel("$" + temp.getHardPrice()));
bookDisplay.add(jbc1);
bookDisplay.add(new JLabel("$" + temp.getEPrice()));
bookDisplay.add(jbc2);
*/
for(int i=0;i<5;i++)
{
String[] quant = {"1", "2", "3", "4", "5"};
JComboBox jbc1 = new JComboBox(quant);
JComboBox jbc2 = new JComboBox(quant);
jbc1.setSelectedIndex(0);
jbc2.setSelectedIndex(0);
JLabel image = new JLabel("image");
bookDisplay.add(image);
bookDisplay.add(new JLabel("$" + 20));
bookDisplay.add(jbc1);
bookDisplay.add(new JLabel("$" + 15));
bookDisplay.add(jbc2);
}
JScrollPane vertical = new JScrollPane(bookDisplay);
//JPanel testP = new JPanel();
//testP.setPreferredSize(new Dimension(800, 400));
//JScrollPane vertical = new JScrollPane(testP);
//testP.add(bookDisplay);
vertical.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JPanel testP = new JPanel();
testP.setPreferredSize(new Dimension(800, 400));
testP.add(vertical);
add(testP);
}
public void addComponent(Component c, int row, int col, int hei, int wid)
{
gbc.gridx = col;
gbc.gridy = row;
gbc.gridwidth = wid;
gbc.gridheight = hei;
gbl.setConstraints(c, gbc);
bookDisplay.add(c);
}
public Order getCurrOrder()
{
return currOrder;
}
private void loadBookCatalog()
{
try
{
String[] str = new String[8];
Scanner sc = new Scanner(new File("bookcat.txt"));
double temp1, temp2;
while(sc.hasNextLine())
{
str = sc.nextLine().split(";");
temp1 = Double.parseDouble(str[3]);
temp2 = Double.parseDouble(str[4]);
Book temp = new Book(temp1, temp2, str[0], str[1], str[2], str[5]);
bookCatalog.add(temp);
}
}
catch(IOException e)
{
System.out.println("File not found!");
}
}
}
BookFrame:
public class BookFrame extends JFrame{
JButton closeButton;
CatalogPane cp;
//IntroPane ip;
public BookFrame(String name)
{
super(name);
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e)
{
JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent(new IntroPane()),
"Thank you for visiting Groovy Book Company.", "Message",
JOptionPane.INFORMATION_MESSAGE, new ImageIcon("coffee.jpg"));
System.exit(0);
}
});
//ip = new IntroPane();
cp = new CatalogPane();
JTabbedPane jtp = new JTabbedPane();
jtp.setPreferredSize(new Dimension(800, 600));
//jtp.addTab("Intro", ip);
jtp.addTab("Catalog", cp);
add(jtp);
pack();
setVisible(true);
}
}
I'd look at JTable, which handles scrolling and rendering as shown here and below. This example shows how to render images and currency. Start by adding a third column for quantity of type Integer. This related example illustrates using a JComboBox editor.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.text.NumberFormat;
import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
/**
* #see https://stackoverflow.com/a/16264880/230513
*/
public class Test {
public static final Icon ICON = UIManager.getIcon("html.pendingImage");
private JPanel createPanel() {
JPanel panel = new JPanel();
DefaultTableModel model = new DefaultTableModel() {
#Override
public Class<?> getColumnClass(int col) {
if (col == 0) {
return Icon.class;
} else {
return Double.class;
}
}
};
model.setColumnIdentifiers(new Object[]{"Book", "Cost"});
for (int i = 0; i < 42; i++) {
model.addRow(new Object[]{ICON, Double.valueOf(i)});
}
JTable table = new JTable(model);
table.setDefaultRenderer(Double.class, new DefaultTableCellRenderer() {
#Override
protected void setValue(Object value) {
NumberFormat format = NumberFormat.getCurrencyInstance();
setText((value == null) ? "" : format.format(value));
}
});
table.setRowHeight(ICON.getIconHeight());
panel.add(new JScrollPane(table) {
#Override
public Dimension getPreferredSize() {
return new Dimension(320, 240);
}
});
return panel;
}
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("Test1", createPanel());
jtp.addTab("Test2", createPanel());
f.add(jtp);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Test().display();
}
});
}
}

Why is my Java swing application misbehaving?

When I try to maximize the window, the orinigal window rendering remains while another maximized window appears making it messy.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.*;
import javax.swing.table.TableColumnModel;
/**
* #author ad *
*/
public class Blotter {
private JFrame topFrame;
private JPanel mainContentPanel;
private JList unsubscribedFields;
private JList subscribedFields;
private JButton butSubscribe;
private JButton butUnsubscribe;
private JButton butApply;
private JButton butOk;
private JButton butCancel;
private JPanel panConfirm;
private JPanel panToggle;
private JPanel panBottom;
private JPanel panLeftList;
private JPanel panRightList;
private JPanel panSubcribe;
private JPanel panUnsubscribe;
/**
* #param args
*/
public Blotter(){
topFrame = new JFrame("Subscription Fields");
mainContentPanel = new JPanel(new BorderLayout());
/*
butSubscribe = new JButton("-->");
butUnsubscribe= new JButton("<--");
butApply = new JButton("Apply");
butOk = new JButton("OK");
butCancel = new JButton("Cancel");*/
createAndBuildGui();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Blotter b = new Blotter();
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}
b.createAndBuildGui();
b.fillGUI();
}
private void fillGUI() {
String[] someRow = {"S110","200","100","42","32"};
}
public void createAndBuildGui()
{
panConfirm = new JPanel(new GridLayout(1,3,5,5));
panToggle = new JPanel(new GridBagLayout());
panBottom = new JPanel(new FlowLayout());
butApply = new JButton("Apply");
butOk = new JButton("OK");
butCancel = new JButton("Cancel");
unsubscribedFields = new JList();
subscribedFields = new JList();
butSubscribe = new JButton(">>>");
butUnsubscribe = new JButton("<<<");
panSubcribe = new JPanel(new BorderLayout());
panUnsubscribe = new JPanel(new BorderLayout());
panLeftList = new JPanel(new BorderLayout());
panRightList = new JPanel(new BorderLayout());
// GridBagConstraints(int gridx, int gridy, int gridwidth,
// int gridheight, double weightx, double weighty,
// int anchor, int fill, Insets insets, int ipadx, int ipady)
panLeftList.add(unsubscribedFields, BorderLayout.CENTER);
panRightList.add(subscribedFields, BorderLayout.CENTER);
panSubcribe.add(butSubscribe, BorderLayout.SOUTH);
panUnsubscribe.add(butUnsubscribe, BorderLayout.NORTH);
panToggle.add(panLeftList,
new GridBagConstraints(0, 0, 1, 2, 0.5, 1, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
panToggle.add(panRightList,
new GridBagConstraints(2, 0, 1, 2, 0.5, 1, GridBagConstraints.CENTER,
GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
panToggle.add(panSubcribe,
new GridBagConstraints(1, 0, 1, 1, 0, 0.5, GridBagConstraints.SOUTH,
GridBagConstraints.NONE, new Insets(0, 2, 4, 4), 0, 0));
panToggle.add(panUnsubscribe,
new GridBagConstraints(1, 1, 1, 1, 0, 0.5, GridBagConstraints.NORTH,
GridBagConstraints.NONE, new Insets(0, 2, 4, 4), 0, 0));
// Building bottom OK Apply Cancel panel.
panConfirm.add(butApply, 0);
panConfirm.add(butOk, 1);
panConfirm.add(butCancel, 2);
panBottom = new JPanel(new FlowLayout(FlowLayout.RIGHT));
panBottom.add(panConfirm, BorderLayout.EAST);
// building main content panel
mainContentPanel.add(panToggle,BorderLayout.CENTER);
mainContentPanel.add(panBottom, BorderLayout.SOUTH);
topFrame.add(mainContentPanel);
topFrame.pack();
topFrame.setVisible(true);
topFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
protected void createPriceTable() {
// More fields : "Quantity Done","Quantity Open","PInst","State","Cancel State","Executing System","WaveID","Source System","TraderID","Average Price","LastExecutionPrice","ClientOrderTag","OldQuantityDone"
String[] columnNames = {"OrderId","Account","Symbol","Side","Quantity",};
Object[][] o = new Object[0][columnNames.length];
}
}
You're calling createAndBuildGui() twice: once in main and once in the constructor.
public Blotter(){
topFrame = new JFrame("Subscription Fields");
mainContentPanel = new JPanel(new BorderLayout());
// ...
createAndBuildGui(); <--------
}
public static void main(String[] args) {
Blotter b = new Blotter();
// ...
b.createAndBuildGui(); <--------
b.fillGUI();
}
If you remove one of them, it works just fine.
It depends on layout manager you are using. For example BorderLayout knows to re-render elements when frame size is changed. Unfortunately you did not mention which window works for you and which does not but I saw GridBagLayout in your code. Probably this layout (better to say usage of this layout) prevents similar behavior.

Categories