I am having some issues with my Swing GUI.
It currently looks like this:
But I would like to move a couple things around.
Firstly I want the buttons underneath the keyboard
I want to add a text field on top of the keyboard with the submit button on the right hand side.
How can I accomplish this? I've tried to create a GridLayout and slot things by row,column coordinate but it doesn't seem to work.
private class Display extends JPanel {
Display() {
setPreferredSize(new Dimension(620, 420));
setBackground(new Color(250, 230, 180));
setFont(new Font("Serif", Font.BOLD, 20));
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
((Graphics2D) g).setStroke(new BasicStroke(3));
if (message != null) {
g.setColor(Color.RED);
g.drawString(message, 30, 40);
g.drawString("00:00", 30, 410);
}
}
}
private void createWindow() {
setJMenuBar(menuBarCreator());
// The ActionListener that will respond to button clicks.
ButtonHandler buttonHandler = new ButtonHandler();
// Create the subpanels and add them to the main panel.
display = new Display();
setLayout(new BorderLayout(3, 3));
add(display, BorderLayout.CENTER);
JPanel bottom = new JPanel();
bottom.setLayout(new GridLayout(1,1));
add(bottom, BorderLayout.NORTH);
// Add keyboard
JPanel keyboard = new JPanel();
JPanel keyboardHolder = new JPanel();
keyboard.setLayout(new GridLayout(2, 13));
keyboardHolder.setLayout(new GridLayout(1, 2));
for (char alphabet = 'a'; alphabet <= 'z'; alphabet++) {
JButton button = new JButton(String.valueOf(alphabet));
button.addActionListener(buttonHandler);
keyboard.add(button);
alphabetButtons.add(button);
}
keyboardHolder.add(keyboard, 0,0);
add(keyboardHolder, BorderLayout.SOUTH);
// Create three buttons, register the ActionListener to respond to clicks on the
// buttons, and add them to the bottom panel.
JButton submitButton = new JButton("Submit");
submitButton.addActionListener(buttonHandler);
keyboard.add(submitButton);
JButton startButton = new JButton(GuiText.START.toString());
startButton.addActionListener(buttonHandler);
bottom.add(startButton);
JButton nextButton = new JButton(GuiText.NEXT.toString());
nextButton.addActionListener(buttonHandler);
bottom.add(nextButton);
JButton skipButton = new JButton(GuiText.SKIP.toString());
skipButton.addActionListener(buttonHandler);
bottom.add(skipButton);
JButton quit = new JButton(GuiText.QUIT.toString());
quit.addActionListener(buttonHandler);
bottom.add(quit);
setBackground(new Color(100, 0, 0));
nextButton.setEnabled(false);
skipButton.setEnabled(false);
}
Below is a concrete example of what camickr wrote in his comment to the original question. Note that this is not the only possibility. There are many layout managers. I recommend visiting Laying Out Components Within a Container
The purpose of the code is only to show you how to achieve your desired layout.
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class GuesGame implements Runnable {
private JFrame frame;
public void run() {
showGui();
}
private JPanel createBottomPanel() {
JPanel bottomPanel = new JPanel(new GridLayout(3, 1));
bottomPanel.add(createSubmitPanel());
bottomPanel.add(createKeyboardPanel());
bottomPanel.add(createButtonsPanel());
return bottomPanel;
}
private JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel();
JButton startButton = new JButton("Start");
buttonsPanel.add(startButton);
JButton nextButton = new JButton("Next");
buttonsPanel.add(nextButton);
JButton skipButton = new JButton("Skip");
buttonsPanel.add(skipButton);
JButton quitButton = new JButton("Quit");
buttonsPanel.add(quitButton);
return buttonsPanel;
}
private JPanel createKeyboardPanel() {
JPanel keyboardPanel = new JPanel(new GridLayout(2, 13));
for (char c = 'a'; c <= 'z'; c++) {
JButton button = new JButton(String.valueOf(c));
keyboardPanel.add(button);
}
return keyboardPanel;
}
private JPanel createSubmitPanel() {
JPanel submitPanel = new JPanel();
JTextField txtFld = new JTextField(20);
submitPanel.add(txtFld);
JButton submitButton = new JButton("Submit");
submitPanel.add(submitButton);
return submitPanel;
}
private void showGui() {
frame = new JFrame("Guess Game");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(new Display(), BorderLayout.CENTER);
frame.add(createBottomPanel(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new GuesGame());
}
}
class Display extends JPanel {
private String message;
Display() {
message = "Starting game";
setPreferredSize(new Dimension(620, 420));
setBackground(new Color(250, 230, 180));
setFont(new Font("Serif", Font.BOLD, 20));
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
((Graphics2D) g).setStroke(new BasicStroke(3));
if (message != null) {
g.setColor(Color.RED);
g.drawString(message, 30, 40);
g.drawString("00:00", 30, 410);
}
}
}
You want three "rows" below the Display panel as follows
Text field and "submit" button.
Keyboard
Other buttons.
Hence the "bottom" panel contains three panels laid out one above the other.
The first panel is the text field and "submit" panel.
Underneath that is the "keyboard".
And underneath the keyboard are the other buttons.
Note that the default layout manager for JPanel is java.awt.FlowLayout and this layout manager is suitable for the panel containing the "submit" button and also suitable for the panel containing the other buttons.
Here is a screen capture of the running app.
Related
I cant seem to get the line to appear. I have a Background color and a few pictures. If I have frame.setSize(x, y); and frame.setVisible(true);
then the outcome is as expected but without the line there. If I change the code and remove frame. from these two lines, leaving setSize(x,y); and setVisible(true);. I have tried using extends JPanel and extends JFrame but neither work. I have tried adding and removing #Override, paintComponent and g2d.drawLine.
It either one or the other, how do I get both to work?
import javax.swing.*;
import java.awt.*;
import javax.imageio.*;
import java.io.*;
public class CodeBreaker extends JPanel
{
JFrame frame = new JFrame("Code Breaker!");
Picture picture = new Picture("Empty.png");
JLabel label = new JLabel(picture);
JLabel label2 = new JLabel(picture);
JLabel label3 = new JLabel(picture);
JLabel label4 = new JLabel(picture);
JLabel label5 = new JLabel(picture);
JLabel label6 = new JLabel(picture);
JLabel label7 = new JLabel(picture);
JLabel label8 = new JLabel(picture);
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
public CodeBreaker()
{
frame.setSize(600, 900);
frame.setContentPane(panel);
frame.add(panel2);
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(new Color(141, 100, 21));
panel.add(label);
panel.add(label2);
panel.add(label3);
panel.add(label4);
panel2.add(label5);
panel2.add(label6);
panel2.add(label7);
panel2.add(label8);
panel2.setOpaque(false);
frame.setVisible(true);
}
/*
void drawLines(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
g2d.drawLine(120, 50, 360, 50);
}
*/
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.white);
g.drawLine(120, 50, 360, 50);
}
}
And this is my main:
public class CodeBreakerDriver
{
public static void main(String[] args)
{
CodeBreaker cb = new CodeBreaker();
}
}
Introduction
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section.
Since the code you posted isn't executable, I went ahead and created the following GUI.
You can see a black line in the lower right of the GUI.
Explanation
All Swing applications must start with a call to the SwingUtilities invokeLater method. This method ensures that the Swing components are created and executed on the Event Dispatch Thread.
Create the JFrame and JPanels in separate methods. This makes the code much easier to read and understand.
Use Swing layout managers. The JFrame has a default BorderLayout. I used a FlowLayout for both JPanels.
Code
Here's the complete runnable code. I made the Picture class an inner class so I could post the code as one block.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class CodeBreakerGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new CodeBreakerGUI());
}
private final Picture picture;
public CodeBreakerGUI() {
this.picture = new Picture();
}
#Override
public void run() {
JFrame frame = new JFrame("Code Breaker!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTopPanel(), BorderLayout.NORTH);
frame.add(createBottomPanel(), BorderLayout.SOUTH);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public JPanel createTopPanel() {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 25, 25));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JLabel label = new JLabel(new ImageIcon(picture.getEmptyImage()));
panel.add(label);
JLabel label2 = new JLabel(new ImageIcon(picture.getEmptyImage()));
panel.add(label2);
JLabel label3 = new JLabel(new ImageIcon(picture.getEmptyImage()));
panel.add(label3);
JLabel label4 = new JLabel(new ImageIcon(picture.getEmptyImage()));
panel.add(label4);
return panel;
}
public JPanel createBottomPanel() {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 25, 25)) {
private static final long serialVersionUID = 1L;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.drawLine(120, 50, 360, 50);
}
};
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JLabel label5 = new JLabel(new ImageIcon(picture.getEmptyImage()));
panel.add(label5);
JLabel label6 = new JLabel(new ImageIcon(picture.getEmptyImage()));
panel.add(label6);
JLabel label7 = new JLabel(new ImageIcon(picture.getEmptyImage()));
panel.add(label7);
JLabel label8 = new JLabel(new ImageIcon(picture.getEmptyImage()));
panel.add(label8);
return panel;
}
public class Picture {
private final BufferedImage emptyImage;
public Picture() {
this.emptyImage = new BufferedImage(64, 64, BufferedImage.TYPE_INT_RGB);
}
public BufferedImage getEmptyImage() {
return emptyImage;
}
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Button extends JButton{
Button(){}
Button(String text,ImageIcon icon,Dimension dm,Point point){
this.setText(text);
this.setIcon(icon);
this.setSize(dm);
this.setBorder(BorderFactory.createLineBorder(Color.WHITE));
this.setHorizontalTextPosition(SwingConstants.RIGHT);
this.setIconTextGap(50);
this.setFont(new Font(null, Font.PLAIN, 14));
this.setFocusable(false);
this.setLocation(point);
this.setBackground(null);
}
}
class MenuPanel extends JPanel implements ActionListener{
public MenuPanel(int width,int height,Color color){
bDimension = new Dimension(196,40);
addIcon =new ImageIcon(getClass().getResource("addUser.png"));
editIcon =new ImageIcon(getClass().getResource("editUser.png"));
this.setLayout(null);
this.setPreferredSize(new Dimension(width,height));
this.setBackground(color);
//THE LOGO
this.add(new LogoPanel(new Dimension(196, 150), this.getBackground(),new Point(2, 2)));
//THE ADD BUTTON
btnAdd =new Button("Add User",addIcon,bDimension,new Point(2,this.getComponent(0).getHeight()+4));
btnAdd.addActionListener`enter code here`(this);
this.add(btnAdd);
//THE EDIT BUTTON
btnEdit =new Button("Edit User",editIcon,bDimension,new Point(2,this.getComponent(0).getHeight()+this.getComponent(1).getHeight()+8));
btnEdit.addActionListener(this);
this.add(btnEdit);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnAdd) {
JPanel addUser =new JPanel();
addUser.setBackground(Color.BLUE);
addUser.setPreferredSize(new Dimension(400,100));
addUser.add(new JButton("Button"));
//NOT SURE WHAT I'M DOING HERE. DOESN'T WORK
this.getParent().add(addUser,BorderLayout.CENTER);
}else if(e.getSource()==btnEdit) {
JPanel editUser =new JPanel();
editUser.setBackground(Color.RED);
editUser.setPreferredSize(new Dimension(400,100));
editUser.add(new JButton("Button"));
//NOT SURE WHAT I'M DOING HERE. DOESN'T WORK
this.getParent().add(editUser,BorderLayout.CENTER);
}
}
private Button btnAdd;
private Button btnEdit;
private ImageIcon addIcon;
private ImageIcon editIcon;
private Dimension bDimension;
}
class LogoPanel extends JPanel{
public LogoPanel(Dimension dimension,Color color,Point point){
btnLogo =new JLabel();
btnLogo.setText("Your Name");
btnLogo.setIcon(new ImageIcon(getClass().getResource("user.png")));
btnLogo.setOpaque(true);
btnLogo.setIconTextGap(10);
btnLogo.setHorizontalTextPosition(0);
btnLogo.setVerticalTextPosition(3);
btnLogo.setHorizontalAlignment(0);
btnLogo.setVerticalAlignment(0);
this.setLayout(new BorderLayout());
this.setBorder(BorderFactory.createLineBorder(Color.WHITE));
this.setSize(dimension);
this.setBackground(color);
this.add(btnLogo,BorderLayout.CENTER);
this.getComponent(0).setFont(new Font(null, Font.PLAIN, 14));
this.getComponent(0).setFocusable(false);
this.setLocation(point);
}
JLabel btnLogo;
}
public class Window extends JFrame {
public Window(){
this.setTitle(null);
this.setIconImage(null);
this.setLayout(new BorderLayout(0,2));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setPreferredSize(new Dimension(new Dimension(960,500)));
this.setMinimumSize(new Dimension(960,500));
this.getContentPane().setBackground(new Color(250, 250, 250));
//ADD PANELS
this.add(new MenuPanel(200, 0, new Color(238, 238, 238)),BorderLayout.WEST);
this.setLocationRelativeTo(null);
}
}
The code above creates a jframe with a borderlayout and a menu panel aligned west. The menu panel has
two jbuttons.
What i want to achive is, click either of the buttons and thereby inserting a panel to the other side of the jframe.
Could you somebody please help/teach me how to achieve this. I am very new to programming and particularly in java.
I have a array of JButtons that do not want to be visible unless I add another JButton before the loop for the array of buttons.
Window class:
import javax.swing.*;
import java.awt.*;
public class Window extends JFrame {
private Container mContainer = new Container();
public Window()
{
super();
this.setTitle("Calculator");
this.setSize(200, 300);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mContainer.setBorder(null);
mContainer.setBackground(Color.GRAY);
mContainer.setOpaque(true);
this.setContentPane(mContainer);
//Panels
JPanel panel = new JPanel();
JPanel center = new JPanel();
center.setBackground(Color.GRAY);
center.setBorder(null);
JPanel displayOutput = new JPanel();
displayOutput.setBackground(Color.GRAY);
this.getContentPane().add(panel);
//TextArea
JTextArea textArea = new JTextArea(1, 20);
textArea.setForeground(Color.WHITE);
textArea.setBackground(Color.GRAY);
textArea.setPreferredSize(new Dimension(200, 60));
//Panel Layouts
panel.setLayout(new BorderLayout());
center.setLayout(new GridLayout(5, 4, 2, 2));
//Add other panel elements
displayOutput.add(textArea);
panel.add(displayOutput, BorderLayout.NORTH);
panel.add(center, BorderLayout.CENTER);
//For some reason adding this makes the array of buttons appear
JButton btnNewButton = new JButton("1");
center.add(btnNewButton);
//Create buttons
for(int i = 0; i < 20; i++){
CalcButtons cButtons[] = new CalcButtons[20];
cButtons[i] = new CalcButtons();
//Add buttons to center box below output
center.add(cButtons[i]);
//Sets fourth column of buttons in cyan.
if(((i + 1) % 4) == 0){
cButtons[i].setBackground(Color.CYAN);
}
}
//Add panel to window
getContentPane().add(panel);
this.setVisible(true);
}
}
Container Class:
import java.awt.Graphics;
import javax.swing.JPanel;
public class Container extends JPanel {
public Container() {
super();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
}
}
Button Class:
import javax.swing.*;
import java.awt.Color;
public class CalcButtons extends JButton
{
public CalcButtons()
{
this.setBackground(Color.WHITE);
this.setBorder(null);
}
}
This code then produced this:
However if I remove this:
//For some reason adding this makes the array of buttons appear
JButton btnNewButton = new JButton("1");
center.add(btnNewButton);
It produces this:
The problem is the size of your buttons are 0. You have set the border to null and there is no icon or text set. So when GridLayout calls getPreferredSize() on your buttons they return a size of 0,0 (width, height). When you add the JButton with a 1 in it then all of sudden one component has size. Since Gridlayout makes all components the same size you now can see your buttons. If you want your buttons to be blank but also be drawn set your border to an empty border with a size of 1 or greater on each edge.
This question already has an answer here:
Java aligning components in panels
(1 answer)
Closed 6 years ago.
I add a JTextField to my game in the bottom left corner using a nested BorderLayout inside my main panel's BorderLayout.SOUTH. This works fine, but then when I add a button to go right next to it, my JTextField dissapears. Can someone please help?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class BlackjackGUI{
private JFrame frame;
private JPanel panel, panelLeft, panelBottom;
private JButton newGameBtn, dealBtn, hitBtn, standBtn;
private JLabel placeBetLbl, playerMoneyLbl;
private JLabel playerCard1Lbl, playerCard2Lbl, playerCard3Lbl,
playerCard4Lbl, playerCard5Lbl, playerCard6Lbl, playerCard7Lbl;
private JLabel dealerCard1Lbl, dealerCard2Lbl, dealerCard3Lbl, dealerCard4Lbl,
dealerCard5Lbl, dealerCard6Lbl, dealerCard7Lbl;
private JLabel playerCardValueLbl, dealerCardValueLbl;
private JLabel spacer1, spacer2;
private JTextField betInputBox;
public BlackjackGUI(){
createForm();
addTextField();
addButtons();
addLabels();
frame.add(panel);
frame.setVisible(true);
}
public void createForm() {
frame = new JFrame("Blackjack");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1200,800);
panel = new JPanel();
panel.setLayout(new BorderLayout());
Color c = new Color(0, 100, 0);
panel.setBackground(c);
panelLeft = new JPanel();
Color panelLeftBG = new Color (23, 25, 100);
panelLeft.setBackground(panelLeftBG);
panel.add(panelLeft, BorderLayout.WEST);
panelBottom = new JPanel();
Color panelBottomBG = new Color (56, 12, 10);
panelBottom.setBackground(panelBottomBG);
panelBottom.setLayout(new BorderLayout());
panel.add(panelBottom, BorderLayout.SOUTH);
}
public void addButtons() {
newGameBtn = new JButton("New Game");
panelLeft.add(newGameBtn, BorderLayout.WEST);
newGameBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
dealBtn = new JButton("Deal");
dealBtn.setPreferredSize(new Dimension (100, 50));
panelBottom.add(dealBtn, BorderLayout.WEST);
newGameBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
System.exit(0);
}
});
}
public void addTextField() {
betInputBox = new JTextField("£25.00");
betInputBox.setFont(new Font("Gill Sans MT", Font.PLAIN, 35));
betInputBox.setHorizontalAlignment(SwingConstants.RIGHT);
betInputBox.setPreferredSize(new Dimension(175,50));
panelBottom.add(betInputBox, BorderLayout.WEST);
}
public void addLabels() {
placeBetLbl = new JLabel("Place your bets!");
placeBetLbl.setFont(new Font("Gill Sans MT", Font.PLAIN, 35));
panelBottom.add(placeBetLbl);
playerMoneyLbl = new JLabel("£2,500");
playerMoneyLbl.setFont(new Font("Gill Sans MT", Font.PLAIN, 35));
panelBottom.add(playerMoneyLbl, BorderLayout.EAST);
}
public static void main(String[] args) {
new BlackjackGUI();
}
}
Excerpt from the BorderLayout javadoc:
Each region may contain no more than one component, and is identified
by a corresponding constant: NORTH, SOUTH, EAST, WEST, and
CENTER.
Your are first adding the text field and then the button to the same region (WEST), thus button just replaces the text field.
To solve the issue you can use FlowLayout for the panelBottom:
panelBottom.setLayout(new FlowLayout(FlowLayout.LEFT));
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();
}
});
}
}