I am currently working on the user interface for a quiz game. It currently looks like this:
I would like it to look like this:
However, I'm not sure about how to structure the screen accordingly, particularly the following things:
Splitting the screen into s several ones (header, where the the timer is... positioned to to the right), ensuring timer is on the right hand side
Creating a sidebar for scores
Creating a main area for questions
Centering all the elements slightly so that there is some padding around it
Not losing the elements drawn in paintComponent
Which type of layouts would work best from the outset?
My code is as follows (note that the bulk of the work is done in createWindow and paintComponent is how I draw the responses on screen):
final class Gui extends JFrame {
static String message;
static String answer;
private String alertMessage;
private String guesses;
private Display display;
private JTextArea textArea;
private JButton startButton;
private JLabel timerLabel;
private JButton nextButton;
private int badGuesses;
private boolean gameOver;
private Timer timer;
private ArrayList<JButton> alphabetButtons = new ArrayList<>();
Gui() {
createWindow();
}
public enum GuiText {
START("Start"),
QUIT("Quit"),
SUBMIT("Submit"),
RESET("Reset"),
SEND("Send"),
NEXT(">"),
PREVIOUS("<"),
PAUSE("Pause");
private String guiText;
GuiText(String guiText) {
this.guiText = guiText;
}
#Override
public String toString() {
return guiText;
}
}
/**
* This class defines the panel that occupies the large central area in the
* main panel. The paintComponent() method in this class is responsible for
* drawing the content of that panel. It shows everything that that the user
* is supposed to see, based on the current values of all the instance variables.
*/
private class Display extends JPanel {
Display() {
setPreferredSize(new Dimension(1000, 250));
setBackground(new Color(0x00bcda));
setFont(new Font("Tahoma", Font.BOLD, 20));
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
((Graphics2D) g).setStroke(new BasicStroke(3));
if (message != null) {
g.setColor(Color.DARK_GRAY);
g.drawString(message, 30, 120);
}
if (alertMessage != null) {
g.setColor(Color.DARK_GRAY);
g.drawString(alertMessage, 30, 150);
}
if (gameOver) {
alertMessage = "Click on \"Next\" to play again.";
} else {
g.drawString("Guesses remaining: " + (3 - badGuesses), 770, 40);
}
g.setColor(Color.DARK_GRAY);
if (answer != null) {
for (int i = 0; i < answer.length(); i++) {
if (String.valueOf(answer.charAt(i)).trim().length() > 0) {
g.drawLine(30 + i * 70, 210, 70 + i * 70, 210);
if (guesses.indexOf(answer.charAt(i)) >= 0) {
g.drawString(String.valueOf(answer.charAt(i)), 45 + i * 70, 195);
}
}
}
}
}
}
/**
* The constructor that creates the main panel, which is represented
* by this class. It makes all the buttons and subpanels and adds
* them to the main panel.
*/
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);
// Add timer panel
JPanel timerPanel = new JPanel();
timerPanel.setBorder(new EmptyBorder(0, 0, 0, 0));
timerPanel.setBackground(new Color(0x00bcda));
add(timerPanel, BorderLayout.PAGE_START);
// Add timer label
timerLabel = new JLabel("01:00", SwingConstants.RIGHT);
timerLabel.setFont(new Font("Arial", Font.BOLD, 20));
timerLabel.setHorizontalAlignment(JLabel.RIGHT);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.gridy = 0;
timerLabel.setForeground(Color.black);
timerPanel.add(timerLabel, c);
// Add left panel
JPanel leftPanel = new JPanel(new GridBagLayout());
c = new GridBagConstraints();
leftPanel.setBorder(new EmptyBorder(25, 25, 25, 5));
leftPanel.setBackground(new Color(0x00bcda));
add(leftPanel, BorderLayout.WEST);
// Add previous button
JButton previousButton = new JButton(String.valueOf(GuiText.PREVIOUS));
previousButton.setFont(new Font("Arial", Font.PLAIN, 60));
previousButton.addActionListener(buttonHandler);
c.gridx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.weighty = 0;
c.gridy = 0;
leftPanel.add(previousButton, c);
// Add right panel
JPanel rightPanel = new JPanel(new GridBagLayout());
c = new GridBagConstraints();
c.fill = GridBagConstraints.VERTICAL;
rightPanel.setBorder(new EmptyBorder(25, 25, 25, 25));
rightPanel.setBackground(new Color(0x00bcda));
add(rightPanel, BorderLayout.EAST);
// Add next button
nextButton = new JButton(String.valueOf(GuiText.NEXT));
nextButton.setFont(new Font("Arial", Font.PLAIN, 60));
nextButton.addActionListener(buttonHandler);
c.gridx = 1;
c.gridy = 0;
rightPanel.add(nextButton, c);
// Add actual timer
initialiseTimer();
// Add bottom panel
JPanel bottomPanel = new JPanel(new GridBagLayout());
GridBagConstraints bottomPanelConstraints = new GridBagConstraints();
bottomPanelConstraints.fill = GridBagConstraints.HORIZONTAL;
add(bottomPanel, BorderLayout.PAGE_END);
setBackground(new Color(100, 0, 0));
// Add primary button panel to bottom panel
JPanel primaryButtonPanel = new JPanel();
primaryButtonPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
primaryButtonPanel.setBackground(new Color(0xFFFFFF));
c.gridx = 0;
c.gridy = 3;
c.fill = GridBagConstraints.HORIZONTAL;
bottomPanel.add(primaryButtonPanel, c);
// Add text area
textArea = new JTextArea(1, 10);
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.HORIZONTAL;
textArea.setFont(new Font("Arial", Font.PLAIN, 24));
textArea.setBackground(new Color(0xCCCCCC));
textArea.setEditable(false);
primaryButtonPanel.add(textArea, c);
// Add buttons
JButton sendButton = new JButton(String.valueOf(GuiText.SEND));
sendButton.addActionListener(buttonHandler);
sendButton.setFont(new Font("Arial", Font.PLAIN, 24));
primaryButtonPanel.add(sendButton);
// Add secondary button panel
JPanel secondaryButtonPanel = new JPanel();
secondaryButtonPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
secondaryButtonPanel.setBackground(new Color(0xFFFFFF));
c.gridx = 0;
c.gridy = 4;
c.fill = GridBagConstraints.HORIZONTAL;
bottomPanel.add(secondaryButtonPanel, c);
// Add secondary buttons
startButton = new JButton(GuiText.START.toString());
startButton.addActionListener(buttonHandler);
startButton.setFont(new Font("Arial", Font.PLAIN, 24));
secondaryButtonPanel.add(startButton);
JButton pauseButton = new JButton(GuiText.PAUSE.toString());
pauseButton.setFont(new Font("Arial", Font.PLAIN, 24));
pauseButton.addActionListener(buttonHandler);
secondaryButtonPanel.add(pauseButton);
JButton quitButton = new JButton(GuiText.QUIT.toString());
quitButton.setFont(new Font("Arial", Font.PLAIN, 24));
quitButton.addActionListener(buttonHandler);
secondaryButtonPanel.add(quitButton);
JButton submitButton = new JButton(GuiText.SUBMIT.toString());
submitButton.setFont(new Font("Arial", Font.PLAIN, 24));
submitButton.addActionListener(buttonHandler);
secondaryButtonPanel.add(submitButton);
// Add keyboard panel
JPanel keyboardPanel = new JPanel();
keyboardPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
keyboardPanel.setBackground(new Color(0xFFFFFF));
c.gridx = 0;
c.gridy = 5;
c.fill = GridBagConstraints.HORIZONTAL;
bottomPanel.add(keyboardPanel, c);
keyboardPanel.setLayout(new GridLayout(3, 10, 5, 5));
for (char alphabet = 'a'; alphabet <= 'z'; alphabet++) {
JButton button = new JButton(String.valueOf(alphabet));
button.addActionListener(buttonHandler);
button.setFont(new Font("Arial", Font.PLAIN, 20));
keyboardPanel.add(button);
alphabetButtons.add(button);
}
}
For this particular set of requirements, a SpringLayout (https://docs.oracle.com/javase/tutorial/uiswing/layout/spring.html) is perfect, though it requires a lot of lines of code, and is hard to read. However it it is one of the most flexibility 'out of the box' layout managers.
SpringLayout works by applying constraints to elements, bringing them in relative position to each other (including relative to the container). This is flexible, because you are able to achieve almost all configurations where the main focus is the relative position of elements (including some padding and thelike).
Incidentally, you should also be able to achieve what you need with a GridBagLayout (https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html), but that might restrict you later on.
Related
Why GridLayot not working in Swing Java?
I need to place element at concrete cell, but they placing wrong (picture)
How to place elements to concrete cell in Java Swing with grid layout?
My code:
package com.KvaksManYT;
import javax.swing.*;
import java.awt.*;
public class GUI extends JFrame {
public GUI() {
super("Test");
setBounds(100, 100, 250, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container container = this.getContentPane();
container.setLayout(new GridLayout(3, 2, 2, 2));
container.add(but1, onPosition(1, 2));
container.add(but2, onPosition(2, 2));
container.add(but3, onPosition(1, 1));
container.add(but4, onPosition(2, 1));
}
private JButton but1 = new JButton("Press 1");
private JButton but2 = new JButton("Press 2");
private JButton but3 = new JButton("Press 3");
private JButton but4 = new JButton("Press 4");
private GridBagConstraints onPosition(int x, int y) {
GridBagConstraints layConstraints = new GridBagConstraints();
layConstraints.fill = GridBagConstraints.BOTH;
layConstraints.gridx = x;
layConstraints.gridy = y;
return layConstraints;
}
}
The GridBagConstraints is used for Grid Bag Layout, rather than Grid Layout.
You have to start counting at 0 too:
public class GUI extends JFrame {
public GUI() {
super("Test");
setBounds(100, 100, 250, 100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagConstraints layConstraints = new GridBagConstraints();
layConstraints.fill = GridBagConstraints.NONE;
layConstraints.insets = new Insets(3, 2, 2, 2);
Container container = this.getContentPane();
container.setLayout(new GridBagLayout());
container.add(but1, onPosition(0, 1, layConstraints));
container.add(but2, onPosition(1, 1, layConstraints));
container.add(but3, onPosition(0, 0, layConstraints));
container.add(but4, onPosition(1, 0, layConstraints));
}
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);
}
}
}
How can I add JButton on JTextArea?
I have such a code, when I print name of country in JTextField some information using REST displays on JTextArea. But I want to use for this purpose JButton. When user click JButton information will be start searching and then display.
public class Client extends JPanel implements ActionListener{
protected JTextField textField;
protected JTextArea textArea;
protected static JButton search;
public Client() {
super(new GridBagLayout());
search = new JButton("Search");
search.setBounds(100,190,60,30);
textField = new JTextField(20);
textField.addActionListener(this);
textArea = new JTextArea(10, 20);
textArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(textArea);
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
add(textField, c);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
add(scrollPane, c);
}
My program show such a window, I want to place my button on the bottom of the window (on the picture).
I don't know what are you expecting exactly, but I wrote this code, I'm not use your code, cause I can't run it, but I think this is that you want.
JFrame gui = new JFrame("Button on bottom.");
JPanel panel = new JPanel(new BorderLayout());
JTextField textfield = new JTextField();
textfield.setText("Australia");
JTextArea textarea = new JTextArea();
textarea.setText("Australia, -27, 133. AUD");
JButton button = new JButton("Button on bottom.");
button.setFont(new java.awt.Font("Dialog", 0, 15));
button.setBorderPainted(false);
button.setFocusable(false);
button.setForeground(new java.awt.Color(255, 255, 255));
button.setBackground(new java.awt.Color(0, 140, 255));
panel.add(textfield, BorderLayout.PAGE_START);
panel.add(textarea);
panel.add(button, BorderLayout.PAGE_END);
gui.setDefaultCloseOperation(gui.EXIT_ON_CLOSE);
gui.setSize(300, 300);
gui.setLocationRelativeTo(null);
gui.add(panel);
gui.setVisible(true);}}
I am in the process of creating a calendar component in Swing, and am running into some trouble.
I want the component to be able to be able to change amount of columns for different views, but that seems simple enough with GridBagLayout.
The problem is getting GBL to show a grid with row and columns that could be empty. I have tried, but can't get it to do that. What is a way to do this, or another simple method to end up being able to place panels on certain places on a grid, such as this:
I have a class called PanelCalendarWeek that extends JPanel. Some of the code is omitted for brevity. The code is below, and the following link is a picture of its output.
public PanelCalendarWeek() {
/* This panel holds the date */
innerPanel = new JPanel();
innerPanel.setBackground(Color.BLACK);
innerPanel.setBounds(0, 0, 700, 700);
innerPanel.setPreferredSize(new Dimension(700, 700));
innerPanel.setLayout(new GridBagLayout());
/* Create Grid bag containts for the BLACK area */
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.PAGE_END;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 0;
/* Add example panels that would be dates */
JPanel panel1 = new JPanel();
panel1.setBorder(BorderFactory.createLineBorder(Color.WHITE, 2));
panel1.setPreferredSize(new Dimension(1, 200));
panel1.setBackground(Color.BLUE);
innerPanel.add(panel1, c);
/* Create more components in the manner above for example reasons */
this.addComponentListener(new ComponentListener() {
#Override
public void componentResized(ComponentEvent e) {
innerPanel.setBounds(0, 0, columnView.getWidth(), 1000);
innerPanel.setPreferredSize(new Dimension(columnView.getWidth(), 1000));
} // more code omitted for brevitu
});
scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.getViewport().setLayout(null);
scrollPane.setViewportView(innerPanel);
scrollPane.setBounds(0, 0, 400, 400);
columnView = new JPanel();
columnView.setBackground(Color.RED);
columnView.setBounds(0, 0, 200, 50);
columnView.setPreferredSize(new Dimension(200, 50));
scrollPane.setColumnHeaderView(columnView);
rowView = new JPanel(); /* omitted, same process as above */
this.setLayout(new BorderLayout());
this.add(scrollPane, BorderLayout.CENTER);
}
I am trying to get familiar with CardLayout so I am making a mock game menu. This menu should have three buttons, but that layout part is easy.
So, what I want to do is start it with a menu with three buttons. The single player button should change what the user sees to a single button, which can change it back to the original menu.
I followed an example online and then applied the same methods to this. However, the menu itself is a card and it's where the command to change cards will come from, not a separate container.
Whenever I run this i get an error:
public class GameMenuCards extends JFrame{
private int currentCard = 1;
private JPanel cardPanel;
private CardLayout cl;
private GridBagConstraints gbc;
public GameMenuCards(){
initUI();
}
public void initUI(){
//set the properties for the window
setTitle("Game Menu With Cards");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setExtendedState(MAXIMIZED_BOTH);
cardPanel = new JPanel();
cl = new CardLayout();
JPanel game = new JPanel();
game.setBackground(Color.BLACK);
//the menu panel
JPanel menu = new JPanel();
menu.setLayout(new GridBagLayout());
menu.setBackground(Color.BLACK);
cardPanel.add(menu, "1");
cardPanel.add(game, "2");
//set up the buttons for the menu
JButton single = new JButton("Single Player");
single.setPreferredSize(new Dimension(300, 30));
single.setBackground(Color.GRAY);
single.setForeground(Color.CYAN);
single.setBorder(BorderFactory.createLineBorder(Color.CYAN, 3));
JButton multi = new JButton("Multi Player");
multi.setPreferredSize(new Dimension(300, 30));
multi.setBackground(Color.GRAY);
multi.setForeground(Color.CYAN);
multi.setBorder(BorderFactory.createLineBorder(Color.CYAN, 3));
JButton score = new JButton("High Scores");
score.setPreferredSize(new Dimension(300, 30));
score.setBackground(Color.GRAY);
score.setForeground(Color.CYAN);
score.setBorder(BorderFactory.createLineBorder(Color.CYAN, 3));
gbc = new GridBagContraints();
//add everything to the menu
gbc.insets = new Insets(35, 50, 0, 50);
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.gridx = 1;
gbc.gridy = 1;
menu.add(single, gbc);
gbc.gridx = 1;
gbc.gridy = 2;
label(menu);
gbc.gridx = 1;
gbc.gridy = 3;
menu.add(multi, gbc);
gbc.gridx = 1;
gbc.gridy = 4;
label(menu);
gbc.gridx = 1;
gbc.gridy = 5;
gbc.insets = new Insets(35, 50, 35, 50);
menu.add(score, gbc);
single.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
currentCard = 2;
cl.show(cardPanel, "" + (currentCard));
}
});
JButton returnBut = new JButton("Back To Menu");
returnBut.setPreferredSize(new Dimension(300, 30));
returnBut.setBackground(Color.GRAY);
returnBut.setForeground(Color.CYAN);
returnBut.setBorder(BorderFactory.createLineBorder(Color.CYAN, 3));
returnBut.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
currentCard = 1;
cl.show(cardPanel, "" + (currentCard));
}
});
game.add(returnBut);
getContentPane().add(cardPanel);
}
public void label(Container c){
JLabel j1 = new JLabel();
j1.setPreferredSize(new Dimension(300, 40));
j1.setBackground(Color.BLACK);
c.add(j1, gbc);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
GameMenuCards gm = new GameMenuCards();
gm.setVisible(true);
}
});
}
}
I know that i could have done a similar thing with the buttons to the labels but i only had the thought two buttons in, so at that stage it would have taken longer.
Am I going about this the right way? Can you correct any mistakes I've made in the code?
Whenever I run this i get an error
Your application is throwing an NPE here
gbc.insets = new Insets(35, 50, 0, 50);
as you haven't initialized your GridBagConstraints gbc.
Also, the reason that you see both panels side-by-side is that, even though you created a CardLayout, you neglect to use it for your cardPanel. Therefore you are still using the default FlowLayout of the JPanel. You could do:
cardPanel = new JPanel(cl);