Regarding to my question I have before How to stop .next() and .previous() from looping It seems that whenever I cancel/finish/close my jframe I can't make my original program run again like when I run it for the first time.
I made the code below in netbeans while my original code is in eclipse. There shouldn't be difference where I run my program, right? But then.. I have that code in my original program in eclipse and it only execute .setEnable and .setText only once when I run my program. Even though both of the platforms have the same code I get different outcomes. Is this natural or not? My code below works perfectly fine but then in my original code it isn't. Is there something I'm doing wrong here? Should I post a snippet of codes from my original code for comparison?
This is my sample code though its not that short...
main class:
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
*
* #author lenovo
*/
public class main {
JFrame Card = new JFrame();
public main(){
Card.setVisible(true);
Card.setSize(605,333);
Card.setTitle("Tank Delivery");
Card.setResizable(false);
final Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x=(int)((dimension.getWidth() - Card.getWidth())/2);
int y=(int)((dimension.getHeight() - Card.getHeight())/2);
Card.setLocation(x, y);
Card.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel();
JButton a = new JButton("OPEN");
a.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
gridbaglayoutdemo g = new gridbaglayoutdemo();
}
});
panel.add(a);
Card.add(panel);
}
public static void main(String[] args){
//Use the event dispatch thread for Swing components
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new main();
}
});
}
}
my other class:
package cardlayoutalignment;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
public class gridbaglayoutdemo {
JFrame Card = new JFrame();
FlowLayout flow = new FlowLayout(FlowLayout.RIGHT,2,2);
Border etch = BorderFactory.createEtchedBorder(Color.white,Color.gray);
Border margin = new EmptyBorder(10,10,10,10);
public static GridBagLayout grid = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
final static boolean shouldFill = true;
JPanel container;
JPanel divider = new JPanel();
JPanel bodypanel = new JPanel();
final JPanel buttonpanel = new JPanel();
JPanel panel_1 = new JPanel();
JPanel panel_2 = new JPanel();
JPanel panel_3 = new JPanel();
CardLayout cl = new CardLayout();
JTextArea text_2;
JTextArea text_3;
String change = "Finish";
final JButton btnNext;
final JButton btnBack;
int currentCard = 0;
int cardflag = 0;
AbstractAction backAction;
AbstractAction nextAction;
public gridbaglayoutdemo(){
Card.setVisible(true);
Card.setSize(605,333);
Card.setTitle("Tank Delivery");
Card.setResizable(false);
final Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x=(int)((dimension.getWidth() - Card.getWidth())/2);
int y=(int)((dimension.getHeight() - Card.getHeight())/2);
Card.setLocation(x, y);
Card.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
bodypanel.setLayout(new BorderLayout());
divider.setLayout(new BorderLayout());
container = new JPanel(cl);
container.setLayout(cl);
cl.show(container, "1");
panel_1.setLayout(grid);
JLabel label_1 = new JLabel("Enter 1:");
label_1.setFont(new Font("Arial", Font.PLAIN, 18));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0;
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(10,10,0,0);
panel_1.add(label_1, c);
JComboBox box_1 = new JComboBox();
box_1.setPreferredSize(new Dimension(200,30));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0;
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(10,10,0,0);
panel_1.add(box_1,c);
JLabel label = new JLabel("");
label.setFont(new Font("Arial", Font.PLAIN, 18));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 1;
c.gridx = 0;
c.gridy = 2;
c.insets = new Insets(10,0,0,0);
panel_1.add(label, c);
panel_2.setLayout(grid);
JLabel label_2 = new JLabel("Enter 2:");
label_2.setFont(new Font("Arial", Font.PLAIN, 18));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0;
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(10,10,0,0);
panel_2.add(label_2,c);
text_2 = new JTextArea();
text_2.setPreferredSize(new Dimension(200,30));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0;
c.gridx = 0;
c.gridy = 20;
c.insets = new Insets(10,10,0,0);
panel_2.add(text_2,c);
JLabel label_22 = new JLabel("");
label_22.setFont(new Font("Arial", Font.PLAIN, 18));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 1;
c.gridx = 0;
c.gridy = 30;
c.insets = new Insets(10,0,0,0);
panel_2.add(label_22, c);
panel_3.setLayout(grid);
JLabel label_3 = new JLabel("Enter 3:");
label_3.setFont(new Font("Arial", Font.PLAIN, 18));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0;
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(10,10,0,0);
panel_3.add(label_3,c);
text_3 = new JTextArea();
text_3.setPreferredSize(new Dimension(200,30));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0;
c.gridx = 0;
c.gridy = 20;
c.insets = new Insets(10,10,0,0);
panel_3.add(text_3,c);
JLabel label_33 = new JLabel("");
label_33.setFont(new Font("Arial", Font.PLAIN, 18));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 1;
c.gridx = 0;
c.gridy = 30;
c.insets = new Insets(10,0,0,0);
panel_3.add(label_33, c);
buttonpanel.setLayout(new FlowLayout(SwingConstants.RIGHT));
buttonpanel.setBorder(new EmptyBorder(0,10,0,0));
buttonpanel.setLayout(new FlowLayout(SwingConstants.RIGHT));
buttonpanel.setBorder(new EmptyBorder(0,0,0,0));
btnBack = new JButton("< Back");
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl.previous(container);
buttonpanel.repaint();
cardflag--;
if (cardflag==0)
{btnBack.setEnabled(false);}
if(cardflag<3)
{btnNext.setText("Next >");}
}
});
btnBack.setEnabled(false);
btnBack.setFont(new Font("Arial", Font.PLAIN, 20));
btnBack.setBorder(new BevelBorder(BevelBorder.RAISED, Color.BLACK, null, null, null));
btnBack.setPreferredSize(new Dimension(110, 40));
btnBack.setBackground(new Color(224,223,227));
buttonpanel.add(btnBack);
btnNext = new JButton("Next >");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl.next(container);
buttonpanel.repaint();
cardflag++;
if(cardflag<3)
{btnBack.setEnabled(true);}
if(cardflag==2)
{btnNext.setText(change);}
if (cardflag==3)
{cl.show(container, "3");
JOptionPane.showMessageDialog(null, "DONE");
Window dialog = SwingUtilities.windowForComponent( btnNext );
dialog.dispose();
cardflag=0;
btnNext.setText("Next >");
}
validateText();
}
});
btnNext.setFont(new Font("Arial", Font.PLAIN, 20));
btnNext.setBorder(new BevelBorder(BevelBorder.RAISED, Color.BLACK, null, null, null));
btnNext.setPreferredSize(new Dimension(110, 40));
btnNext.setBackground(new Color(224,223,227));
btnNext.setVisible(true);
buttonpanel.add(btnNext);
final JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cardflag=0;
Window dialog = SwingUtilities.windowForComponent( btnCancel );
dialog.dispose();
}
});
btnCancel.setFont(new Font("Arial", Font.PLAIN, 20));
btnCancel.setFocusable(false);
btnCancel.setFocusTraversalKeysEnabled(false);
btnCancel.setFocusPainted(false);
btnCancel.setBorder(new BevelBorder(BevelBorder.RAISED, Color.BLACK, null, null, null));
btnCancel.setPreferredSize(new Dimension(110, 40));
btnCancel.setBackground(new Color(224,223,227));
buttonpanel.add(btnCancel);
JPanel numberpanel = new JPanel();
numberpanel.setPreferredSize(new Dimension(221,0));
numberpanel.setBorder(new EmptyBorder(10,0,0,10));
numberpanel.setBorder(BorderFactory.createEtchedBorder(Color.white,Color.gray));
numberpanel.setLayout(flow);
JButton button_7 = new JButton("7");
button_7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonaction(e);
}
});
button_7.setActionCommand("7");
button_7.setFont(new Font("Arial", Font.PLAIN, 30));
button_7.setFocusable(false);
button_7.setFocusTraversalKeysEnabled(false);
button_7.setFocusPainted(false);
button_7.setBorder(new BevelBorder(BevelBorder.RAISED, Color.BLACK, null, null, null));
button_7.setPreferredSize(new Dimension(70, 70));
button_7.setBackground(new Color(224,223,227));
numberpanel.add(button_7);
JButton button_8 = new JButton("8");
button_8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonaction(e);
}
});
button_8.setActionCommand("8");
button_8.setFont(new Font("Arial", Font.PLAIN, 30));
button_8.setFocusable(false);
button_8.setFocusTraversalKeysEnabled(false);
button_8.setFocusPainted(false);
button_8.setBorder(new BevelBorder(BevelBorder.RAISED, Color.BLACK, null, null, null));
button_8.setPreferredSize(new Dimension(70, 70));
button_8.setBackground(new Color(224,223,227));
numberpanel.add(button_8);
JButton button_9 = new JButton("9");
button_9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonaction(e);
}
});
button_9.setActionCommand("9");
button_9.setFont(new Font("Arial", Font.PLAIN, 30));
button_9.setFocusable(false);
button_9.setFocusTraversalKeysEnabled(false);
button_9.setFocusPainted(false);
button_9.setBorder(new BevelBorder(BevelBorder.RAISED, Color.BLACK, null, null, null));
button_9.setPreferredSize(new Dimension(70, 70));
button_9.setBackground(new Color(224,223,227));
numberpanel.add(button_9);
Card.add(bodypanel);
bodypanel.add(divider, BorderLayout.WEST);
divider.add(container, BorderLayout.NORTH);
container.add(panel_1, "1");
container.add(panel_2, "2");
container.add(panel_3, "3");
divider.add(buttonpanel, BorderLayout.SOUTH);
bodypanel.add(numberpanel, BorderLayout.EAST);
}
private void buttonaction(ActionEvent e){
try{
if(cardflag==1)
{text_2.append("" + e.getActionCommand());}
if(cardflag==2)
{text_3.append("" + e.getActionCommand());}
}catch(Exception e1){}
}
private void validateText(){
if(cardflag==2)
{String text = text_2.getText();
if (text.isEmpty()==true)
{JOptionPane.showMessageDialog(null, "Text 2 is empty!");
cl.show(container, "2");
btnNext.setText("Next >");
cardflag--;
}
}
}
}
Related
I'm working on a character creation panel for a role-playing game. It has a JPanel using GridBagLayout and within it a JPanel using FlowLayout.
Originally, when I didn't use FlowLayout it looked like this:
I needed to add another component on the x-axis. The weightx value would increase and become an even value. It would make all my titles off-centre and I didn't like that. I was thinking I could put some of my components inside a JPanel using FlowLayout, maybe wrap it in a JScrollPane or something nice:
Unfortunately the JPanel using FlowLayout is not being anchored by the JPanel using GridBagLayout. It went to the side of the display despite being set to anchor GridBagConstraints.BASELINE.
My Code:
public class TheLifeOfErnestRhodes extends JFrame {
private static JFrame frame = new JFrame("The Life of Ernest Rhodes");
private static Color black = new Color(40,40,40);
private static Color gold = new Color(255,223,0);
private static Color sienna = new Color(255,82,45);
private static Color stone = new Color(119,136,153);
private static Font titleFont = new Font("Serif", Font.BOLD + Font.ITALIC, 48);
private static Font textFont = new Font("Serif", Font.PLAIN, 20);
private static Font buttonFont = new Font("Serif", Font.BOLD + Font.ITALIC, 20);
private static void setFrame() {
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setResizable(false);
Container pane = frame.getContentPane();
JPanel backPanel = new JPanel();
backPanel.setBackground(black);
backPanel.setVisible(true);
pane.add(backPanel);
pane.add(charScreen());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
setFrame();
}
});
}
private static JPanel charScreen() {
GridBagLayout layout = new GridBagLayout();
JPanel charScreen = new JPanel(layout);
charScreen.setBackground(black);
charScreen.setVisible(true);
//Static labels for the two headings/titles on this screen.
GridBagConstraints c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 0;
c.anchor = GridBagConstraints.NORTH;
c.insets = new Insets(80,0,20,0);
JLabel heading = new JLabel("THE LIFE OF ERNEST RHODES");
heading.setForeground(gold);
heading.setFont(titleFont);
charScreen.add(heading, c);
c.gridy++;
c.anchor = GridBagConstraints.BASELINE;
c.insets = new Insets(0,0,10,0);
JLabel title = new JLabel("CHARACTER CREATION");
title.setForeground(stone);
title.setFont(titleFont);
charScreen.add(title, c);
c.gridy++;
c.insets = new Insets (10, 20, 10, 20);
JPanel namePanel = new JPanel(new FlowLayout());
namePanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
JLabel labelName = new JLabel("FULL NAME:");
labelName.setForeground(stone);
labelName.setFont(textFont);
labelName.setVisible(true);
namePanel.add(labelName, c);
JTextField firstName = new JTextField("Taylor", 20);
firstName.setMinimumSize(firstName.getPreferredSize());
firstName.setBackground(black.darker());
firstName.setForeground(stone);
firstName.setFont(textFont);
firstName.setHorizontalAlignment(JTextField.CENTER);
firstName.setBorder(null);
firstName.setVisible(true);
namePanel.add(firstName);
JTextField lastName = new JTextField("Woodhouse", 20);
lastName.setMinimumSize(lastName.getPreferredSize());
lastName.setBackground(black.darker());
lastName.setForeground(stone);
lastName.setFont(textFont);
lastName.setHorizontalAlignment(JTextField.CENTER);
lastName.setBorder(null);
lastName.setVisible(true);
namePanel.add(lastName);
JLabel displayName = new JLabel("TYPE A NAME & PRESS 'ENTER'");
displayName.setForeground(stone);
displayName.setFont(textFont);
displayName.setVisible(true);
namePanel.add(displayName, c);
charScreen.add(namePanel);
c.gridx = 0;
c.gridy++;
c.fill = GridBagConstraints.NONE;
JLabel availablePts = new JLabel("AVAILABLE POINTS: 5");
availablePts.setForeground(stone);
availablePts.setFont(textFont);
availablePts.setVisible(true);
charScreen.add(availablePts, c);
c.gridx++;
JLabel allocatedPts = new JLabel("ALLOCATED POINTS:");
allocatedPts.setForeground(stone);
allocatedPts.setFont(textFont);
allocatedPts.setVisible(true);
charScreen.add(allocatedPts, c);
c.gridx++;
JLabel selectTrait = new JLabel("SELECT TRAITS:");
selectTrait.setForeground(stone);
selectTrait.setFont(textFont);
selectTrait.setVisible(true);
charScreen.add(selectTrait, c);
c.gridx = 0;
c.gridy++;
JLabel labelInv = new JLabel("Investigation");
labelInv.setForeground(gold);
labelInv.setFont(textFont);
labelInv.setVisible(true);
charScreen.add(labelInv, c);
c.gridy++;
JLabel labelPers = new JLabel("Persuasion");
labelPers.setForeground(gold);
labelPers.setFont(textFont);
labelPers.setVisible(true);
charScreen.add(labelPers, c);
c.gridy++;
JLabel LabelStl = new JLabel("Stealth");
LabelStl.setForeground(gold);
LabelStl.setFont(textFont);
LabelStl.setVisible(true);
charScreen.add(LabelStl, c);
c.gridx++;
c.gridy = 4;
JLabel allocatedInt = new JLabel("0");
allocatedInt.setForeground(stone);
allocatedInt.setFont(textFont);
allocatedInt.setVisible(true);
charScreen.add(allocatedInt, c);
c.gridy++;
JLabel allocatedPers = new JLabel("0");
allocatedPers.setForeground(stone);
allocatedPers.setFont(textFont);
allocatedPers.setVisible(true);
charScreen.add(allocatedPers, c);
c.gridy++;
JLabel allocatedAth = new JLabel("0");
allocatedAth.setForeground(stone);
allocatedAth.setFont(textFont);
allocatedAth.setVisible(true);
charScreen.add(allocatedAth, c);
c.gridx++;
c.gridy = 4;
JLabel keenEye = new JLabel("Keen Eye");
keenEye.setForeground(sienna);
keenEye.setFont(textFont);
keenEye.setVisible(true);
charScreen.add(keenEye, c);
c.gridy++;
JLabel interrogator = new JLabel("Interrogator");
interrogator.setForeground(gold);
interrogator.setFont(textFont);
interrogator.setVisible(true);
charScreen.add(interrogator, c);
c.gridy++;
JLabel sleuth = new JLabel("Sleuth");
sleuth.setForeground(gold);
sleuth.setFont(textFont);
sleuth.setVisible(true);
charScreen.add(sleuth, c);
c.gridx = 1;
c.gridy++;
JLabel reset = new JLabel("Reset Stats");
reset.setForeground(gold);
reset.setFont(textFont);
reset.setVisible(true);
charScreen.add(reset, c);
c.gridy++;
JLabel gender = new JLabel("GENDER:");
gender.setForeground(stone);
gender.setFont(textFont);
gender.setVisible(true);
charScreen.add(gender, c);
c.gridx = 0;
c.gridy++;
JLabel male = new JLabel("Male");
male.setForeground(gold);
male.setFont(textFont);
male.setVisible(true);
charScreen.add(male, c);
c.gridx++;
JLabel female = new JLabel("Female");
female.setForeground(gold);
female.setFont(textFont);
female.setVisible(true);
charScreen.add(female, c);
c.gridx++;
JLabel other = new JLabel("Other");
other.setForeground(sienna);
other.setFont(textFont);
other.setVisible(true);
charScreen.add(other, c);
c.gridx = 1;
c.gridy++;
c.anchor = GridBagConstraints.PAGE_END;
JLabel clickNext = new JLabel("Continue");
clickNext.setForeground(stone);
clickNext.setFont(titleFont);
clickNext.setVisible(true);
charScreen.add(clickNext, c);
}
}
Miscellaneous:
I tried doing the SSCCE thing. I couldn't bear the thought of someone running my code without the colors and fonts!
There are coloured JLabels used as 'buttons'. The Mac's button icons are really ugly so I went rogue. The above code is modified to only show the concerned components. In my program the JLabels have MouseListeners added to them.
If you're wondering about the game, it's a murder mystery and the player is the investigator! Obviously, they're investigating the life and death of 'Ernest Rhodes'.
Thank you all in advance!
Cheers,
Aadi
namePanel.add(labelName, c); is pointless, as namePanel is using a FlowLayout, passing it a GridBagLayoutConstraint is pointless as it's meaningless to FlowLayout
charScreen.add(namePanel); is effectively passing the "default" GridBagLayoutConstraint, meaning it will be laid out at the discretion of GridBagLayout, which isn't going to help you.
Maybe you meant charScreen.add(namePanel, c);, where c is the constraints you passed to namePanel
For example...
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class TheLifeOfErnestRhodes extends JFrame {
private static JFrame frame = new JFrame("The Life of Ernest Rhodes");
private static Color black = new Color(40, 40, 40);
private static Color gold = new Color(255, 223, 0);
private static Color sienna = new Color(255, 82, 45);
private static Color stone = new Color(119, 136, 153);
private static Font titleFont = new Font("Serif", Font.BOLD + Font.ITALIC, 48);
private static Font textFont = new Font("Serif", Font.PLAIN, 20);
private static Font buttonFont = new Font("Serif", Font.BOLD + Font.ITALIC, 20);
private void setFrame() {
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
// frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
// frame.setResizable(false);
Container pane = frame.getContentPane();
JPanel backPanel = new JPanel();
backPanel.setBackground(black);
backPanel.setVisible(true);
pane.add(backPanel);
pane.add(charScreen());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TheLifeOfErnestRhodes().setFrame();
}
});
}
private JPanel charScreen() {
GridBagLayout layout = new GridBagLayout();
JPanel charScreen = new JPanel(layout);
charScreen.setBackground(black);
charScreen.setVisible(true);
//Static labels for the two headings/titles on this screen.
GridBagConstraints c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 0;
c.anchor = GridBagConstraints.NORTH;
c.insets = new Insets(80, 0, 20, 0);
JLabel heading = new JLabel("THE LIFE OF ERNEST RHODES");
heading.setForeground(gold);
heading.setFont(titleFont);
charScreen.add(heading, c);
c.gridy++;
c.anchor = GridBagConstraints.BASELINE;
c.insets = new Insets(0, 0, 10, 0);
JLabel title = new JLabel("CHARACTER CREATION");
title.setForeground(stone);
title.setFont(titleFont);
charScreen.add(title, c);
c.gridy++;
c.insets = new Insets(10, 20, 10, 20);
// JPanel namePanel = new JPanel(new FlowLayout());
charScreen.add(new NamePane(), c);
c.gridx = 0;
c.gridy++;
c.fill = GridBagConstraints.NONE;
JLabel availablePts = new JLabel("AVAILABLE POINTS: 5");
availablePts.setForeground(stone);
availablePts.setFont(textFont);
availablePts.setVisible(true);
charScreen.add(availablePts, c);
c.gridx++;
JLabel allocatedPts = new JLabel("ALLOCATED POINTS:");
allocatedPts.setForeground(stone);
allocatedPts.setFont(textFont);
allocatedPts.setVisible(true);
charScreen.add(allocatedPts, c);
c.gridx++;
JLabel selectTrait = new JLabel("SELECT TRAITS:");
selectTrait.setForeground(stone);
selectTrait.setFont(textFont);
selectTrait.setVisible(true);
charScreen.add(selectTrait, c);
c.gridx = 0;
c.gridy++;
JLabel labelInv = new JLabel("Investigation");
labelInv.setForeground(gold);
labelInv.setFont(textFont);
labelInv.setVisible(true);
charScreen.add(labelInv, c);
c.gridy++;
JLabel labelPers = new JLabel("Persuasion");
labelPers.setForeground(gold);
labelPers.setFont(textFont);
labelPers.setVisible(true);
charScreen.add(labelPers, c);
c.gridy++;
JLabel LabelStl = new JLabel("Stealth");
LabelStl.setForeground(gold);
LabelStl.setFont(textFont);
LabelStl.setVisible(true);
charScreen.add(LabelStl, c);
c.gridx++;
c.gridy = 4;
JLabel allocatedInt = new JLabel("0");
allocatedInt.setForeground(stone);
allocatedInt.setFont(textFont);
allocatedInt.setVisible(true);
charScreen.add(allocatedInt, c);
c.gridy++;
JLabel allocatedPers = new JLabel("0");
allocatedPers.setForeground(stone);
allocatedPers.setFont(textFont);
allocatedPers.setVisible(true);
charScreen.add(allocatedPers, c);
c.gridy++;
JLabel allocatedAth = new JLabel("0");
allocatedAth.setForeground(stone);
allocatedAth.setFont(textFont);
allocatedAth.setVisible(true);
charScreen.add(allocatedAth, c);
c.gridx++;
c.gridy = 4;
JLabel keenEye = new JLabel("Keen Eye");
keenEye.setForeground(sienna);
keenEye.setFont(textFont);
keenEye.setVisible(true);
charScreen.add(keenEye, c);
c.gridy++;
JLabel interrogator = new JLabel("Interrogator");
interrogator.setForeground(gold);
interrogator.setFont(textFont);
interrogator.setVisible(true);
charScreen.add(interrogator, c);
c.gridy++;
JLabel sleuth = new JLabel("Sleuth");
sleuth.setForeground(gold);
sleuth.setFont(textFont);
sleuth.setVisible(true);
charScreen.add(sleuth, c);
c.gridx = 1;
c.gridy++;
JLabel reset = new JLabel("Reset Stats");
reset.setForeground(gold);
reset.setFont(textFont);
reset.setVisible(true);
charScreen.add(reset, c);
c.gridy++;
JLabel gender = new JLabel("GENDER:");
gender.setForeground(stone);
gender.setFont(textFont);
gender.setVisible(true);
charScreen.add(gender, c);
c.gridx = 0;
c.gridy++;
JLabel male = new JLabel("Male");
male.setForeground(gold);
male.setFont(textFont);
male.setVisible(true);
charScreen.add(male, c);
c.gridx++;
JLabel female = new JLabel("Female");
female.setForeground(gold);
female.setFont(textFont);
female.setVisible(true);
charScreen.add(female, c);
c.gridx++;
JLabel other = new JLabel("Other");
other.setForeground(sienna);
other.setFont(textFont);
other.setVisible(true);
charScreen.add(other, c);
c.gridx = 1;
c.gridy++;
c.anchor = GridBagConstraints.PAGE_END;
JLabel clickNext = new JLabel("Continue");
clickNext.setForeground(stone);
clickNext.setFont(titleFont);
clickNext.setVisible(true);
charScreen.add(clickNext, c);
return charScreen;
}
public class NamePane extends JPanel {
public NamePane() {
JLabel labelName = new JLabel("FULL NAME:");
labelName.setForeground(stone);
labelName.setFont(textFont);
labelName.setVisible(true);
add(labelName);
JTextField firstName = new JTextField("Taylor", 20);
// firstName.setMinimumSize(firstName.getPreferredSize());
firstName.setBackground(black.darker());
firstName.setForeground(stone);
firstName.setFont(textFont);
firstName.setHorizontalAlignment(JTextField.CENTER);
firstName.setBorder(null);
firstName.setVisible(true);
add(firstName);
JTextField lastName = new JTextField("Woodhouse", 20);
// lastName.setMinimumSize(lastName.getPreferredSize());
lastName.setBackground(black.darker());
lastName.setForeground(stone);
lastName.setFont(textFont);
lastName.setHorizontalAlignment(JTextField.CENTER);
lastName.setBorder(null);
lastName.setVisible(true);
add(lastName);
JLabel displayName = new JLabel("TYPE A NAME & PRESS 'ENTER'");
displayName.setForeground(stone);
displayName.setFont(textFont);
displayName.setVisible(true);
add(displayName);
}
}
}
I am making a simple project. It has login window like this
When the user click on button log in - it should "repaint" the window(it should seem to be happened in the same window) and then the window looks like this.
The problem is - I can't "repaint" the window - the only thing I can - it's create a new frame, so there actually are 2 frames totally.
How to make the whole thing in one same frame.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.Border;
public class Client
{
private JFrame frame;
private JTextArea allMessagesArea;
private JTextArea inputArea;
private JButton buttonSend;
private JButton buttonExit;
private String login;
public void addComponentsToPane(Container pane)
{
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(10,10,10,10);
c.fill = GridBagConstraints.HORIZONTAL;
allMessagesArea = new JTextArea(25,50);
c.weighty = 0.6;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=0;
c.gridwidth=2;
pane.add(allMessagesArea, c);
inputArea = new JTextArea(12,50);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth=2;
c.weighty =0.3;
c.gridx =0;
c.gridy =1;
pane.add(inputArea, c);
buttonSend = new JButton("Send");
c.weightx=0.5;
c.weighty = 0.1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx =0;
c.gridy=2;
c.gridwidth =1;
pane.add(buttonSend, c);
buttonExit = new JButton("Exit");
c.weightx =0.5;
c.weighty = 0.1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx =1;
c.gridy=2;
c.gridwidth =1;
pane.add(buttonExit, c);
}
public Client()
{
frame = new JFrame("Simple Client");
frame.setSize(400,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
welcomePage();
frame.setVisible(true);
}
public void welcomePage()
{
JPanel panel = new JPanel();
JLabel label = new JLabel("Your login:");
panel.add(label);
JTextField textField = new JTextField(15);
panel.add(textField);
JButton loginButton = new JButton("log in");
panel.add(loginButton);
JButton exitButton = new JButton("exit");
panel.add(exitButton);
frame.add(panel, BorderLayout.CENTER);
loginButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if(textField.getText().isEmpty())
JOptionPane.showMessageDialog(frame.getContentPane(), "Please enter your login");
else
{
login = textField.getText();
System.out.println(login);
frame = null;
frame = new JFrame("Simple Client");
frame.setSize(400,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
}
});
exitButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
public static void main(String[] args)
{
Client frame = new Client();
}
}
Use CardLayout.
This layout allows developers to switch between panels. It works by creating a "deck" panel that'll contain all of panels that'll potentially be displayed:
CardLayout layout = new CardLayout();
JPanel deck = new JPanel();
deck.setLayout(layout);
JPanel firstCard = new JPanel();
JPanel secondCard = new JPanel();
deck.add(firstCard, "first");
deck.add(secondCard, "second");
When you click on a button, that button's ActionListener should call show(Container, String), next(Container) or previous(Container) on the CardLayout to switch which panel is being displayed:
public void actionPerformed(ActionEvent e) {
layout.show(deck, "second");
}
One of the solutions
You can create two panels (one for each view) and add the required components to them. First, you add first panel to the frame (using frame.add(panel1)). If you want to show the second panel in the same window, you can delete first panel (using frame.remove(panel1)) and add the second panel (using frame.add(panel2)). At the end you've to call frame.pack().
This's your code with above solution:
public class Client
{
private JFrame frame;
private JTextArea allMessagesArea;
private JTextArea inputArea;
private JButton buttonSend;
private JButton buttonExit;
private String login;
public void addComponentsToPanel2()
{
panel2.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(10,10,10,10);
c.fill = GridBagConstraints.HORIZONTAL;
allMessagesArea = new JTextArea(25,50);
c.weighty = 0.6;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx=0;
c.gridy=0;
c.gridwidth=2;
panel2.add(allMessagesArea, c);
inputArea = new JTextArea(12,50);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth=2;
c.weighty =0.3;
c.gridx =0;
c.gridy =1;
panel2.add(inputArea, c);
buttonSend = new JButton("Send");
c.weightx=0.5;
c.weighty = 0.1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx =0;
c.gridy=2;
c.gridwidth =1;
panel2.add(buttonSend, c);
buttonExit = new JButton("Exit");
c.weightx =0.5;
c.weighty = 0.1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx =1;
c.gridy=2;
c.gridwidth =1;
panel2.add(buttonExit, c);
}
public Client()
{
frame = new JFrame("Simple Client");
frame.setSize(400,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
welcomePage();
frame.setVisible(true);
}
public void welcomePage()
{
panel1 = new JPanel();
JLabel label = new JLabel("Your login:");
panel1.add(label);
JTextField textField = new JTextField(15);
panel1.add(textField);
JButton loginButton = new JButton("log in");
panel1.add(loginButton);
JButton exitButton = new JButton("exit");
panel1.add(exitButton);
frame.add(panel1, BorderLayout.CENTER);
loginButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
if(textField.getText().isEmpty())
JOptionPane.showMessageDialog(frame.getContentPane(), "Please enter your login");
else
{
login = textField.getText();
System.out.println(login);
panel2 = new JPanel();
addComponentsToPanel2();
frame.remove(panel1);
frame.add(panel2);
//frame.repaint();
frame.pack();
}
}
});
exitButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
public static void main(String[] args)
{
Client frame = new Client();
}
private JPanel panel1;
private JPanel panel2;
}
My code below is a working code and I'd like to apologize for my not so short code. I have a problem with my buttons as they execute their action only once. My problem is that when I click the next button I have a validateText() method to check whether the textarea is empty or not. Here comes my problem.. when the panel goes back to the empty textarea the buttons on the left side will not work anymore. But when you close the program and run it again the button will work unless you click the next button with the empty textarea. Is there anyone who can point out my mistake?
package cardlayoutalignment;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
public class gridbaglayoutdemo {
JFrame Card = new JFrame();
FlowLayout flow = new FlowLayout(FlowLayout.RIGHT,2,2);
Border etch = BorderFactory.createEtchedBorder(Color.white,Color.gray);
Border margin = new EmptyBorder(10,10,10,10);
public static GridBagLayout grid = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
final static boolean shouldFill = true;
JPanel container;
JPanel divider = new JPanel();
JPanel bodypanel = new JPanel();
final JPanel buttonpanel = new JPanel();
JPanel panel_1 = new JPanel();
JPanel panel_2 = new JPanel();
JPanel panel_3 = new JPanel();
CardLayout cl = new CardLayout();
JTextArea text_2;
JTextArea text_3;
String change = "Finish";
final JButton btnNext;
final JButton btnBack;
int currentCard = 0;
int cardflag = 0;
AbstractAction backAction;
AbstractAction nextAction;
public gridbaglayoutdemo(){
Card.setVisible(true);
Card.setSize(605,333);
Card.setTitle("Tank Delivery");
Card.setResizable(false);
final Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x=(int)((dimension.getWidth() - Card.getWidth())/2);
int y=(int)((dimension.getHeight() - Card.getHeight())/2);
Card.setLocation(x, y);
Card.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
bodypanel.setLayout(new BorderLayout());
divider.setLayout(new BorderLayout());
container = new JPanel(cl);
container.setLayout(cl);
cl.show(container, "1");
panel_1.setLayout(grid);
JLabel label_1 = new JLabel("Enter 1:");
label_1.setFont(new Font("Arial", Font.PLAIN, 18));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0;
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(10,10,0,0);
panel_1.add(label_1, c);
JComboBox box_1 = new JComboBox();
box_1.setPreferredSize(new Dimension(200,30));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0;
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(10,10,0,0);
panel_1.add(box_1,c);
JLabel label = new JLabel("");
label.setFont(new Font("Arial", Font.PLAIN, 18));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 1;
c.gridx = 0;
c.gridy = 2;
c.insets = new Insets(10,0,0,0);
panel_1.add(label, c);
panel_2.setLayout(grid);
JLabel label_2 = new JLabel("Enter 2:");
label_2.setFont(new Font("Arial", Font.PLAIN, 18));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0;
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(10,10,0,0);
panel_2.add(label_2,c);
text_2 = new JTextArea();
text_2.setPreferredSize(new Dimension(200,30));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0;
c.gridx = 0;
c.gridy = 20;
c.insets = new Insets(10,10,0,0);
panel_2.add(text_2,c);
JLabel label_22 = new JLabel("");
label_22.setFont(new Font("Arial", Font.PLAIN, 18));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 1;
c.gridx = 0;
c.gridy = 30;
c.insets = new Insets(10,0,0,0);
panel_2.add(label_22, c);
panel_3.setLayout(grid);
JLabel label_3 = new JLabel("Enter 3:");
label_3.setFont(new Font("Arial", Font.PLAIN, 18));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0;
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(10,10,0,0);
panel_3.add(label_3,c);
text_3 = new JTextArea();
text_3.setPreferredSize(new Dimension(200,30));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 0;
c.gridx = 0;
c.gridy = 20;
c.insets = new Insets(10,10,0,0);
panel_3.add(text_3,c);
JLabel label_33 = new JLabel("");
label_33.setFont(new Font("Arial", Font.PLAIN, 18));
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.weighty = 1;
c.gridx = 0;
c.gridy = 30;
c.insets = new Insets(10,0,0,0);
panel_3.add(label_33, c);
buttonpanel.setLayout(new FlowLayout(SwingConstants.RIGHT));
buttonpanel.setBorder(new EmptyBorder(0,10,0,0));
backAction = new AbstractAction("< Back") {
public void actionPerformed(ActionEvent e) {
currentCard--;
gridbaglayoutdemo.this.evaluateActions();
}
};
nextAction = new AbstractAction("Next >") {
public void actionPerformed(ActionEvent e) {
currentCard++;
gridbaglayoutdemo.this.evaluateActions();
}
};
buttonpanel.setLayout(new FlowLayout(SwingConstants.RIGHT));
buttonpanel.setBorder(new EmptyBorder(0,0,0,0));
btnBack = new JButton("< Back");
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl.previous(container);
buttonpanel.repaint();
cardflag--;
if (cardflag==0)
{btnBack.setEnabled(false);}
if(cardflag<3)
{btnNext.setText("Next >");}
}
});
btnBack.setEnabled(false);
btnBack.setFont(new Font("Arial", Font.PLAIN, 20));
btnBack.setBorder(new BevelBorder(BevelBorder.RAISED, Color.BLACK, null, null, null));
btnBack.setPreferredSize(new Dimension(110, 40));
btnBack.setBackground(new Color(224,223,227));
buttonpanel.add(btnBack);
btnNext = new JButton("Next >");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cl.next(container);
buttonpanel.repaint();
cardflag++;
if(cardflag<3)
{btnBack.setEnabled(true);}
if(cardflag==2)
{btnNext.setText(change);}
if (cardflag==3)
{cl.show(container, "3");
JOptionPane.showMessageDialog(null, "DONE");
Window dialog = SwingUtilities.windowForComponent( btnNext );
dialog.dispose();
cardflag=0;
btnNext.setText("Next >");
}
validateText();
}
});
btnNext.setFont(new Font("Arial", Font.PLAIN, 20));
btnNext.setBorder(new BevelBorder(BevelBorder.RAISED, Color.BLACK, null, null, null));
btnNext.setPreferredSize(new Dimension(110, 40));
btnNext.setBackground(new Color(224,223,227));
btnNext.setVisible(true);
buttonpanel.add(btnNext);
final JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Window dialog = SwingUtilities.windowForComponent( btnCancel );
dialog.dispose();
}
});
btnCancel.setFont(new Font("Arial", Font.PLAIN, 20));
btnCancel.setFocusable(false);
btnCancel.setFocusTraversalKeysEnabled(false);
btnCancel.setFocusPainted(false);
btnCancel.setBorder(new BevelBorder(BevelBorder.RAISED, Color.BLACK, null, null, null));
btnCancel.setPreferredSize(new Dimension(110, 40));
btnCancel.setBackground(new Color(224,223,227));
buttonpanel.add(btnCancel);
JPanel numberpanel = new JPanel();
numberpanel.setPreferredSize(new Dimension(221,0));
numberpanel.setBorder(new EmptyBorder(10,0,0,10));
numberpanel.setBorder(BorderFactory.createEtchedBorder(Color.white,Color.gray));
numberpanel.setLayout(flow);
JButton button_7 = new JButton("7");
button_7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonaction(e);
}
});
button_7.setActionCommand("7");
button_7.setFont(new Font("Arial", Font.PLAIN, 30));
button_7.setFocusable(false);
button_7.setFocusTraversalKeysEnabled(false);
button_7.setFocusPainted(false);
button_7.setBorder(new BevelBorder(BevelBorder.RAISED, Color.BLACK, null, null, null));
button_7.setPreferredSize(new Dimension(70, 70));
button_7.setBackground(new Color(224,223,227));
numberpanel.add(button_7);
JButton button_8 = new JButton("8");
button_8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonaction(e);
}
});
button_8.setActionCommand("8");
button_8.setFont(new Font("Arial", Font.PLAIN, 30));
button_8.setFocusable(false);
button_8.setFocusTraversalKeysEnabled(false);
button_8.setFocusPainted(false);
button_8.setBorder(new BevelBorder(BevelBorder.RAISED, Color.BLACK, null, null, null));
button_8.setPreferredSize(new Dimension(70, 70));
button_8.setBackground(new Color(224,223,227));
numberpanel.add(button_8);
JButton button_9 = new JButton("9");
button_9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonaction(e);
}
});
button_9.setActionCommand("9");
button_9.setFont(new Font("Arial", Font.PLAIN, 30));
button_9.setFocusable(false);
button_9.setFocusTraversalKeysEnabled(false);
button_9.setFocusPainted(false);
button_9.setBorder(new BevelBorder(BevelBorder.RAISED, Color.BLACK, null, null, null));
button_9.setPreferredSize(new Dimension(70, 70));
button_9.setBackground(new Color(224,223,227));
numberpanel.add(button_9);
Card.add(bodypanel);
bodypanel.add(divider, BorderLayout.WEST);
divider.add(container, BorderLayout.NORTH);
container.add(panel_1, "1");
container.add(panel_2, "2");
container.add(panel_3, "3");
//container.add(panel_4, "4");
//container.add(p5.panel_5, "5");
//container.add(p6.panel_6, "6");
divider.add(buttonpanel, BorderLayout.SOUTH);
bodypanel.add(numberpanel, BorderLayout.EAST);
}
private void evaluateActions() {
((javax.swing.Action) backAction).setEnabled(currentCard > 0);
((javax.swing.Action) nextAction).setEnabled(currentCard < container.getComponentCount() - 1);
}
private void buttonaction(ActionEvent e){
try{
if(cardflag==1)
{text_2.append("" + e.getActionCommand());}
if(cardflag==2)
{text_3.append("" + e.getActionCommand());}
}catch(Exception IOe){}
}
private void validateText(){
if(cardflag==2)
{String text = text_2.getText();
if (text.isEmpty()==true)
{JOptionPane.showMessageDialog(null, "Text 2 is empty!");
cl.show(container, "2");
}
}
}
public static void main(String[] args){
//Use the event dispatch thread for Swing components
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new gridbaglayoutdemo();
}
});
}
}
I don't know what are you doing but I just noticed one thing with the state of cardflag.
When the text field is empty and next button is clicked cardflag = 2 and now button is clicked then below action listener is called.
private void buttonaction(ActionEvent e) {
try {
if (cardflag == 1) {
text_2.append("" + e.getActionCommand());
}
if (cardflag == 2) {
text_3.append("" + e.getActionCommand());
^^^
//This should be text_2
}
} catch (Exception IOe) {
}
}
Well I figure it out now. Thanks to user3218114. Since I'm clicking the next button my cardflag is still adding up and because of that I needed to add -1 in my cardflag so that the number of my panel will stay the same and that I won't be needing any additional duplication of my code.
private void validateText(){
if(cardflag==2)
{String text = text_2.getText();
if (text.isEmpty()==true)
{JOptionPane.showMessageDialog(null, "Text 2 is empty!");
cl.show(container, "2");
cardflag--;
}
}
}
I want to make my components on my JFrame resize with the resizing of the window.
How can this be done.
Currently when I make the JFrame smaller the components remain in the same place and then disappear as the frame gets smaller.
Ideally I would like to set a minimum JFrame size which would not allow the form to go any smaller but when I make it larger that components should move with the JFrame.
Add: What if I want to use an absolute layout manager. This is the layout manager that my boss prefers.
Code:
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import java.awt.Font;
public class TestFrame extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JButton btnNewButton;
private JButton btnNewButton_1;
private JButton btnNewButton_2;
private JCheckBox chckbxNewCheckBox;
private JCheckBox chckbxNewCheckBox_1;
private JCheckBox chckbxNewCheckBox_2;
public static void main(String[] args) {
TestFrame frame = new TestFrame();
frame.setVisible(true);
}
public TestFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 629, 458);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(15, 15, 15, 15));
setContentPane(contentPane);
contentPane.setLayout(null);
btnNewButton = new JButton("Save");
btnNewButton.setFont(new Font("Sylfaen", Font.BOLD, 14));
btnNewButton.setBounds(514, 386, 89, 23);
contentPane.add(btnNewButton);
btnNewButton_1 = new JButton("Open");
btnNewButton_1.setBounds(514, 352, 89, 23);
contentPane.add(btnNewButton_1);
btnNewButton_2 = new JButton("Close");
btnNewButton_2.setBounds(514, 318, 89, 23);
contentPane.add(btnNewButton_2);
btnNewButton_2.setBackground(Color.YELLOW);
btnNewButton_2.setEnabled(false);
chckbxNewCheckBox = new JCheckBox("Employeed");
chckbxNewCheckBox.setBounds(506, 7, 97, 23);
contentPane.add(chckbxNewCheckBox);
chckbxNewCheckBox_1 = new JCheckBox("Not Employeed");
chckbxNewCheckBox_1.setBounds(506, 33, 97, 23);
contentPane.add(chckbxNewCheckBox_1);
chckbxNewCheckBox_2 = new JCheckBox("Self Employeed");
chckbxNewCheckBox_2.setBounds(506, 59, 97, 23);
contentPane.add(chckbxNewCheckBox_2);
}
}
An Example of GridBagLayout:
This is an an example of the GridBagLayout. The components resize correctly but I do not see a grow property. It must do that automatically.
import java.awt.*;
import javax.swing.JButton;
import javax.swing.JFrame;
public class GridBagLayoutDemo {
final static boolean shouldFill = true;
final static boolean shouldWeightX = true;
final static boolean RIGHT_TO_LEFT = false;
public static void addComponentsToPane(Container pane) {
JButton button;
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
button = new JButton("Button 1");
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
pane.add(button, c);
button = new JButton("Button 2");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 1;
c.gridy = 0;
pane.add(button, c);
button = new JButton("Button 3");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 2;
c.gridy = 0;
pane.add(button, c);
button = new JButton("Long-Named Button 4");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 40; //make this component tall
c.weightx = 0.0;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 1;
pane.add(button, c);
button = new JButton("5");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 0; //reset to default
c.weighty = 1.0; //request any extra vertical space
c.anchor = GridBagConstraints.PAGE_END; //bottom of space
c.insets = new Insets(10,0,0,0); //top padding
c.gridx = 1; //aligned with button 2
c.gridwidth = 2; //2 columns wide
c.gridy = 2; //third row
pane.add(button, c);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("GridBagLayout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponentsToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
createAndShowGUI();
}
}
Use a layout manager, like GridBagLayout, its have a property call "grow" for a column.
I want to make a JFrame to display a GUI like this: http://i.stack.imgur.com/2POFs.png
(im not allowed to embed pictures)
the blank spcaces are the same X and Y dimentions,
the buttons are the same X and Y dimentions,
JTextArea is half of the frame.
public static JFrame frame = new JFrame ("Launcher " + version);
public static GridBagConstraints c = new GridBagConstraints();
public static JTextArea news = new JTextArea();
public static JButton launchGame = new JButton("Launch Game");
public static JButton settings = new JButton("Settings");
public static JButton exitGame = new JButton("Exit");
public static void main(String[] args)
{
news.setEditable(false);
news.setBounds(0, 0, (screenSize.width - 500) / 2, screenSize.height - 400);
news.append(" NEWS:\n");
news.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.gray, Color.black));
frame.setLayout(new GridBagLayout());
frame.setBounds(300, 200, screenSize.width - 500, screenSize.height - 400);
c.fill = GridBagConstraints.VERTICAL;
c.weighty = 0.5;
c.gridx = 0;
c.gridy = 0;
c.gridheight = 3;
frame.add(news, c);
frame.setVisible(true);
c.fill = GridBagConstraints.EAST;
c.weightx = 0.5;
c.gridx = 1;
c.gridheight = 1;
frame.add(launchGame, c);
c.gridy = 1;
frame.add(settings, c);
c.gridy = 2;
frame.add(exitGame, c);
}
Is this what you want? I added/modified the following in your button constraints:
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(0, 10, 0, 10); // 10 is the marginal
And here is the full code:
public static void main(String[] args)
{
news.setEditable(false);
news.append(" NEWS:\n");
news.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.gray, Color.black));
frame.setLayout(new GridBagLayout());
c.fill = GridBagConstraints.VERTICAL;
c.weighty = 0.5;
c.gridx = 0;
c.gridy = 0;
c.gridheight = 3;
frame.add(news, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.insets = new Insets(10, 10, 10, 10); // 10 is the marginal
c.weightx = 0.5;
c.gridx = 1;
c.gridheight = 1;
frame.add(launchGame, c);
c.gridy = 1;
frame.add(settings, c);
c.gridy = 2;
frame.add(exitGame, c);
frame.pack();
frame.setVisible(true);
}
Here is a similar layout using BoxLayout instead (easier to work with I think):
private static JComponent buildButtons() {
for (JButton button : Arrays.asList(launchGame, settings, exitGame)) {
button.setMaximumSize(new Dimension(Short.MAX_VALUE, Short.MAX_VALUE));
}
Box b = Box.createVerticalBox();
b.add(Box.createVerticalStrut(10));
b.add(launchGame);
b.add(Box.createVerticalStrut(10));
b.add(settings);
b.add(Box.createVerticalStrut(10));
b.add(exitGame);
b.add(Box.createVerticalStrut(10));
return b;
}
static JComponent buildUI() {
Box b = Box.createHorizontalBox();
b.add(news);
b.add(Box.createHorizontalStrut(10));
b.add(buildButtons());
b.add(Box.createHorizontalStrut(10));
return b;
}
public static void main(String[] args)
{
news.setEditable(false);
news.append(" NEWS:\n");
news.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.gray, Color.black));
frame.add(buildUI());
frame.pack();
frame.setVisible(true);
}
First of all...
c.fill = GridBagConstraints.EAST;
Isn't what I think you want to do. I think the fill should be at least HORIZONTAL
Secondly...
You could use Insets to adjust the space between the components, something like
public class TestLayout {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new FormPane());
frame.setSize(500, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected static class FormPane extends JPanel {
private JTextArea news = new JTextArea();
private JButton launchGame = new JButton("Launch Game");
private JButton settings = new JButton("Settings");
private JButton exitGame = new JButton("Exit");
public FormPane() {
setLayout(new GridBagLayout());
news.setEditable(false);
news.append(" NEWS:\n");
news.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED, Color.gray, Color.black));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 1;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridheight = GridBagConstraints.REMAINDER;
gbc.weightx = 0.25;
add(news, gbc);
gbc.insets = new Insets(0, 50, 0, 50);
gbc.gridheight = 1;
gbc.gridx++;
add(launchGame, gbc);
gbc.gridy = 1;
add(settings, gbc);
gbc.gridy = 2;
add(exitGame, gbc);
}
}
}
I might also be inclined to to place the buttons in there own container (like a JPanel) and maybe use a GridLayout to lay them out, then use the above suggestion to lay the text area and button container.
This isolates the individual layout needs without further complicating the layout...