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;
}
}
}
Related
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.
I am new to working with GUI's in Java and I am having a problem moving my text and buttons around. No matter what coordinates I give my button or any of the other JLabel it doesn't move, I was wondering how I could fix it this in such a way that I can place my components where ever I want on the JPanel
public class IntroPage extends JFrame {
public static void main(String[] args) {
IntroPage main = new IntroPage();
main.setVisible(true);
}
private JPanel contentPane;
public IntroPage (){
//make sure the program exits when the frame closes
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Welcome");
contentPane = new JPanel();
setSize(400,700);
//This will center the JFrame in the middle of the screen
setLocationRelativeTo(null);
//Welcome Page stuff :D
JLabel ApplauseLabel = new JLabel("Welcome to U.X.Dot.X");
ApplauseLabel.setFont(new Font("Gill Sans MT", Font.PLAIN, 30));
ApplauseLabel.setLocation(100, 50);
contentPane.add(ApplauseLabel);
JLabel slogan = new JLabel("Register below");
slogan.setFont(new Font("Gill Sans MT", Font.PLAIN, 15));
slogan.setLocation(100, 400);
contentPane.add(slogan);
//FacebookSignUp.
JButton FBbutton = new JButton("Login With FaceBook");
FBbutton.setBackground(Color.BLUE);
FBbutton.setSize(50,50);
FBbutton.setLocation(20, 40);
FBbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Add JPanel to go to FB API. Much later
}
});
contentPane.add(FBbutton);
add(contentPane);
//make sure the JFrame is visible
setVisible(true);
}
}
You're ignoring the layout managers of your contentPane JPanel. Understand that it uses FlowLayout by default, and will ignore your setLocation and setBounds statements. Ror the JPanel to accept absolute positioning, you would have to give it a null layout via contentPane.setLayout(null).
Having said that, I do not advise you to do this! While null layouts, setLocation(...) and setBounds(...) might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
For example the following GUI
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import javax.swing.*;
public class IntroPage2 extends JPanel {
public static final String TITLE = "Welcome to U.X.Dot.X";
private JLabel welcomeLabel = new JLabel(TITLE, SwingConstants.CENTER);
private JButton fbButton = new JButton("Login With Facebook");
public IntroPage2() {
fbButton.setBackground(Color.BLUE);
fbButton.setForeground(Color.CYAN);
welcomeLabel.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 30));
int wlGap = 20;
welcomeLabel.setBorder(BorderFactory.createEmptyBorder(wlGap, wlGap, wlGap, wlGap));
JLabel registerBelowLabel = new JLabel("Register Below");
registerBelowLabel.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
JPanel centralPanel = new JPanel(new GridBagLayout());
centralPanel.setPreferredSize(new Dimension(300, 600));
centralPanel.add(registerBelowLabel);
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.add(fbButton, BorderLayout.LINE_START);
topPanel.add(welcomeLabel, BorderLayout.CENTER);
setLayout(new BorderLayout());
int ebGap = 8;
setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
add(topPanel, BorderLayout.PAGE_START);
add(centralPanel, BorderLayout.CENTER);
}
private static void createAndShowGui() {
IntroPage2 mainPanel = new IntroPage2();
JFrame frame = new JFrame("Welcome");
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());
}
}
would create something like:
When I compile and run my program I would like to be able to re-size it and keep the components with the same scale factor. This would mean that when the frame is expanded the components will also expand, keeping the size and the spacing scale as the original was.
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.lang.*;
public class ResizeTst
{
JFrame myMainWindow = new JFrame("This is my title");
JPanel firstPanel = new JPanel();
//Components
JButton CompAth = new JButton();
JButton ViewAth = new JButton();
JButton UpdateRD = new JButton();
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String []fontFamilies = ge.getAvailableFontFamilyNames();
Font FontT5 = new Font("SansSerif", Font.BOLD, 50);
///////////
public void runGUI()
{
myMainWindow.setBounds(10, 10, 1296, 756);
myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myMainWindow.setLayout(new GridLayout(1,1));
createFirstPanel();
myMainWindow.getContentPane().add(firstPanel);
myMainWindow.setVisible(true);
}
public void createFirstPanel()
{
firstPanel.setLayout(null);
CompAth.setLocation(500,250);
CompAth.setSize(320,300);
CompAth.setText("<html><CENTER>Compare<br>Athletes</CENTER></html>");
CompAth.setFont(FontT5);
firstPanel.add(CompAth);
ViewAth.setLocation(100,250);
ViewAth.setSize(320,300);
ViewAth.setText("<html><CENTER>View<br>Athletes</CENTER></html>");
ViewAth.setFont(FontT5);
firstPanel.add(ViewAth);
UpdateRD.setLocation(900,250);
UpdateRD.setSize(320,300);
UpdateRD.setText("<html><CENTER>Update<br>Running<br>Details</CENTER></html>");
UpdateRD.setFont(FontT5);
firstPanel.add(UpdateRD);
}
public static void main(String[] args)
{
ResizeTst rt = new ResizeTst();
rt.runGUI();
}
}
So that if I implemented this code it would allow me to run it on any system in full size automatically, without the size of the components changing in scale factor to what they were originally. Allowing for my program to run without it looking bad on larger or smaller screens in full screen.
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.lang.*;
public class ResizeTst
{
JFrame myMainWindow = new JFrame("This is my title");
JPanel firstPanel = new JPanel();
//Components
JButton CompAth = new JButton();
JButton ViewAth = new JButton();
JButton UpdateRD = new JButton();
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String []fontFamilies = ge.getAvailableFontFamilyNames();
Font FontT5 = new Font("SansSerif", Font.BOLD, 50);
///////////
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
public void runGUI()
{
myMainWindow.setExtendedState(JFrame.MAXIMIZED_BOTH);
myMainWindow.setSize(screenSize);
myMainWindow.setVisible(true);
myMainWindow.setResizable(true);
myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myMainWindow.setLayout(new GridLayout(1,1));
createFirstPanel();
myMainWindow.getContentPane().add(firstPanel);
myMainWindow.setVisible(true);
}
I have been told I should use a layout on the panel which would allow me to do this, but I am unaware of which layout to use and how to apply it to this program correctly. Any solutions or suggestions on how to do this would be greatly appreciated.
Start with something along these lines. It uses a GridLayout that will stretch components to size. The buttons are made a little larger using setMargin(Insets). The font size is reduced for the screenshot, adjust all numbers to need.
import javax.swing.*;
import java.awt.*;
import javax.swing.border.EmptyBorder;
public class ResizeTst {
JFrame myMainWindow = new JFrame("This is my title");
JPanel firstPanel = new JPanel();
//Components
JButton compAth = new JButton();
JButton viewAth = new JButton();
JButton updateRD = new JButton();
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontFamilies = ge.getAvailableFontFamilyNames();
Font fontT5 = new Font(Font.SANS_SERIF, Font.BOLD, 25);
///////////
public void runGUI() {
myMainWindow.setBounds(10, 10, 1296, 756); // don't guess the size (1)
myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myMainWindow.setLayout(new GridLayout(1, 1));
createFirstPanel();
myMainWindow.getContentPane().add(firstPanel);
myMainWindow.pack(); // 1) Make it mininum size needed
myMainWindow.setMinimumSize(myMainWindow.getSize());
myMainWindow.setVisible(true);
}
public void createFirstPanel() {
//firstPanel.setLayout(null);
firstPanel.setLayout(new GridLayout(1,0,50,50));
firstPanel.setBorder(new EmptyBorder(50,50,50,50));
Insets buttonMargin = new Insets(20, 20, 20, 20);
compAth.setText("<html><CENTER>Compare<br>Athletes</CENTER></html>");
compAth.setMargin(buttonMargin);
compAth.setFont(fontT5);
firstPanel.add(compAth);
viewAth.setMargin(buttonMargin);
viewAth.setText("<html><CENTER>View<br>Athletes</CENTER></html>");
viewAth.setFont(fontT5);
firstPanel.add(viewAth);
updateRD.setMargin(buttonMargin);
updateRD.setText("<html><CENTER>Update<br>Running<br>Details</CENTER></html>");
updateRD.setFont(fontT5);
firstPanel.add(updateRD);
}
public static void main(String[] args) {
// should be on the EDT!
ResizeTst rt = new ResizeTst();
rt.runGUI();
}
}
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();
}
});
}
}
I would write on a JPanel a String much bigger respect than other element.which could be the way to paint a string in terms of simply?There is a method to do this?
You could add the text as a JLabel component and change its font size.
public static void main(String[] args) {
NewJFrame1 frame = new NewJFrame1();
frame.setLayout(new GridBagLayout());
JPanel panel = new JPanel();
JLabel jlabel = new JLabel("This is a label");
jlabel.setFont(new Font("Verdana",1,20));
panel.add(jlabel);
panel.setBorder(new LineBorder(Color.BLACK)); // make it easy to see
frame.add(panel, new GridBagConstraints());
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(NewJFrame1.EXIT_ON_CLOSE);
frame.setVisible(true);
}
The code will run and look like this :
see also Java layout manager vertical center for more info
JLabel supports HTML 3.2 formating, so you can use header tags if you don't want to mess with fonts.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class HtmlHeadersSample extends JFrame {
public HtmlHeadersSample() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300,200);
setLocation(100, 100);
JLabel label1 = new JLabel();
label1.setText("simple text");
label1.setBounds(0, 0, 200, 50);
JLabel label2 = new JLabel();
label2.setText("<html><h1>header1 text</h1></html>");
label2.setBounds(0, 20, 200, 50);
JLabel label3 = new JLabel();
label3.setText("<html><h2>header2 text</h2></html>");
label3.setBounds(0, 40, 200, 50);
JLabel label4 = new JLabel();
label4.setText("<html><h3>header3 text</h3></html>");
label4.setBounds(0, 60, 200, 50);
add(label1);
add(label2);
add(label3);
add(label4);
setVisible(true);
}
public static void main(String[] args) {
new HtmlHeadersSample();
}
}
Here's how it looks like:
Just set the size of your font
JLabel bigLabel = new JLabel("Bigger text");
bigLabel.setFont(new Font("Arial", 0, 30));