adding images in JFrame, image when clicked - java

I want to make a "simple" program. it consists of three buttons and when you click on one of them i want a picture to show up, but i don't know how to add the image properly.
If anyone has played pokemon i want to make the start where you select your starter pokemon.
Here is my code.
public LayoutLek(){
super("Starter");
panel=new JPanel();
panel.setLayout(new GridLayout(2,1));
top_p=new JPanel();
label1=new JLabel("Make a choice");
label1.setFont(new Font("Arial", Font.BOLD, 30));
label1.setForeground(Color.black);
ImageIcon green = new ImageIcon("Bilder/bulbasaur.jpg"); //Dont know if it is correct but...
JLabel label2 = new JLabel(green);
top_p.setBackground(Color.yellow);
top_p.add(label1);
bottom_p=new JPanel();
bottom_p.setLayout(new GridLayout(1,3));
panel.add(top_p);
panel.add(bottom_p);
button1=new JButton("Button 1");
button1.setBackground(Color.green);
button1.setForeground(Color.black);
button1.setFont(new Font("Arial", Font.BOLD, 24));
button2=new JButton("Button 2");
button2.setBackground(Color.red);
button2.setForeground(Color.black);
button2.setFont(new Font("Arial", Font.BOLD, 24));
button3=new JButton("Button 3");
button3.setBackground(Color.blue);
button3.setForeground(Color.black);
button3.setFont(new Font("Arial", Font.BOLD, 24));
bottom_p.add(button1);
bottom_p.add(button2);
bottom_p.add(button3);
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
this.add(panel);
//this.setSize(350, 300);
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setAlwaysOnTop(true);
}
public static void main(String[] args) {
new LayoutLek();
}
public void actionPerformed(ActionEvent e) {
System.out.println("Clicked"); //Just to test
Object src = e.getSource();
if(src==button1){
//Here should the image show up
}
else if(src==button2){
}
else if(src==button3){
}
}
If anyone can help i would be thankful!

Images that are embedded into your program should be loaded from the class path, not the file system. When you pass a String to the ImageIcon your telling the program to look in the file system. To load from the class path, use
new ImageIcon(getClass().getResource("/Bilder/bulbasaur.jpg");
where Bilder need to be in the src
Your JLabel label2 is locally scoped within the constructor, so you can't access it from outside the constructor, i.e. the actionPerformed. You need to declare it outside the constructor, as class members, as you seem to have done with your other objects.
Have all three ImageIcons already initialized As class members also.
Just use label2.setIcon(oneOfTheImageIcons); in the actionPerformed to change the icon of the JLabel
Swing apps should be run from the Event Dispatch Thread. You can do so by wrapping your new LayoutLek(); in a SwingUtilities.invokeLater... See Initial Threads for complete details.
You never add your label2 to a visible conainter.
After fixing all the above mentioned points, here is a runnable refactor. You just need to change your file paths accordingly.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class LayoutLek extends JFrame implements ActionListener {
JPanel panel;
JPanel top_p;
JLabel label1;
JPanel bottom_p;
JButton button1;
JButton button2;
JButton button3;
ImageIcon green;
ImageIcon blue;
ImageIcon red;
JLabel label2;
public LayoutLek() {
super("Starter");
green = new ImageIcon(getClass().getResource("/path/to/imgage"));
blue = new ImageIcon(getClass().getResource("/path/to/imgage"));
red = new ImageIcon(getClass().getResource("/path/to/imgage"));
label2 = new JLabel(green);
panel = new JPanel();
panel.setLayout(new GridLayout(2, 1));
top_p = new JPanel();
label1 = new JLabel("Make a choice");
label1.setFont(new Font("Arial", Font.BOLD, 30));
label1.setForeground(Color.black);
top_p.setBackground(Color.yellow);
top_p.add(label1);
bottom_p = new JPanel();
bottom_p.setLayout(new GridLayout(1, 3));
panel.add(top_p);
panel.add(bottom_p);
button1 = new JButton("Button 1");
button1.setBackground(Color.green);
button1.setForeground(Color.black);
button1.setFont(new Font("Arial", Font.BOLD, 24));
button2 = new JButton("Button 2");
button2.setBackground(Color.red);
button2.setForeground(Color.black);
button2.setFont(new Font("Arial", Font.BOLD, 24));
button3 = new JButton("Button 3");
button3.setBackground(Color.blue);
button3.setForeground(Color.black);
button3.setFont(new Font("Arial", Font.BOLD, 24));
bottom_p.add(button1);
bottom_p.add(button2);
bottom_p.add(button3);
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
this.add(panel);
this.add(label2, BorderLayout.PAGE_START);
//this.setSize(350, 300);
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setAlwaysOnTop(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new LayoutLek();
}
});
}
public void actionPerformed(ActionEvent e) {
System.out.println("Clicked"); //Just to test
Object src = e.getSource();
if (src == button1) {
label2.setIcon(green);
} else if (src == button2) {
label2.setIcon(blue);
} else if (src == button3) {
label2.setIcon(red);
}
}
}

Firstly, src.equals(button1). It's better practise to use the object-based equals method, == is better applied to primitive comparison (i.e. int, long, boolean, etc).
Secondly, you can do a couple of things.
Add the image to a container, then remove it and add another each time a button is clicked.
Add all three images to a container, set them all to invisible (setVisible(false)) and then in src.equals(button1/2/3) you set the appropriate image to visible. Container may need to be repainted.
Hope this helps!

Related

COMPOUND BORDER : Get a outline border with title outside the Jpanel in java Swing

My only problem is that I don't know how to put my border outside the panel. I've tried compound and some other border code but so far I am unable to put it outside. It either disappears or it doesn't change at all.
The output that I want:
The output that I'm getting :
I'm a newbie at swing and I have been searching and found out about compound border but I am still not so familiar on how it works with adding the buttons into the panel. (I've removed the code of me trying to do compound border because it was just a mess full of errors)
THE CODE :
package activityswing;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.Border;
public class swing {
public static void main (String args []) {
JFrame pa= new JFrame("Swing Activity");
//boarder
pa.setLayout(new BorderLayout());
//panels
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
//buttons
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
JButton button3 = new JButton("Button 3");
JButton button4 = new JButton("Button 4");
JButton button5 = new JButton("Button 5");
JButton button6 = new JButton("Button 6");
//label
JLabel lb1= new JLabel("Panel 1");
JLabel lb2= new JLabel("Panel 2");
//adding label to panel
lb1.add(panel1);
lb1.add(panel2);
//panel1
Border line1 = BorderFactory.createLineBorder(Color.blue);
panel1.setBorder(line1);
panel1.add(button1);
panel1.add(button2);
panel1.add(button3);
panel1.setBorder(BorderFactory.createTitledBorder("Panel 1"));
panel1.setBackground(Color.BLUE);
panel1.setPreferredSize(new Dimension(270,40));
//panel2
Font font2 = new Font("Verdana",Font.ITALIC,12);
Border line2 = BorderFactory.createLineBorder(Color.blue);
lb2.setFont(font2);
panel2.setBorder(line2);
LayoutManager layout = new FlowLayout();
panel2.setLayout(layout);
panel2.add(button4);
panel2.add(button5);
panel2.add(button6);
panel2.add(lb2);
panel2.setBorder(BorderFactory.createTitledBorder("Panel 2"));
panel2.setBackground(Color.GREEN);
panel2.setPreferredSize(new Dimension(270,40));
//FRAME
FlowLayout flow = new FlowLayout(FlowLayout.CENTER, 50,50);
pa.setLayout(flow);
pa.pack();
pa.add(panel1);
pa.add(panel2);
pa.setSize(700,200);
pa.setResizable(false);
pa.setVisible(true);
pa.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pa.setLocationRelativeTo(null);
}
}
Don't add component to labels
lb1.add(panel1);
lb1.add(panel2);
Labels calculate their preferred size based the label properties (text/icon/font/etc) and not the child components.
Don't mess with the preferredSize of the components unless you are absolutely certain you willing to take over all the responsibility to calculate the components size.
The simple solution would be to create a instance of TitledBorder yourself, for example...
Font font2 = new Font("Verdana", Font.ITALIC, 12);
TitledBorder border = new TitledBorder("Panel 1");
border.setTitleFont(font2);
I'd kind of tempted to create a factory method to make this easier, but you get the general idea
To get the border "separated" from the component, I would use a compound component approach, where the outer panel contains the title and then add the inner panel into it.
If needed, you could use CompoundBorder and use a EmptyBorder on the side of the outer panel
Have a look at:
JavaDocs for TitledBorder
How to Use Borders
... for more details
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.LayoutManager;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
public class Test {
public static void main(String args[]) {
JFrame pa = new JFrame("Swing Activity");
//boarder
pa.setLayout(new BorderLayout());
//panels
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
//buttons
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
JButton button3 = new JButton("Button 3");
JButton button4 = new JButton("Button 4");
JButton button5 = new JButton("Button 5");
JButton button6 = new JButton("Button 6");
Font font2 = new Font("Verdana", Font.ITALIC, 12);
TitledBorder border1 = new TitledBorder("Panel 1");
border1.setTitleFont(font2);
JPanel outter1 = new JPanel(new BorderLayout());
outter1.setBorder(border1);
panel1.add(button1);
panel1.add(button2);
panel1.add(button3);
panel1.setBackground(Color.BLUE);
outter1.add(panel1);
//panel2
LayoutManager layout = new FlowLayout();
TitledBorder border2 = new TitledBorder("Panel 2");
JPanel outter2 = new JPanel(new BorderLayout());
outter2.setBorder(border2);
panel2.setLayout(layout);
panel2.add(button4);
panel2.add(button5);
panel2.add(button6);
panel2.setBackground(Color.GREEN);
outter2.add(panel2);
//FRAME
FlowLayout flow = new FlowLayout(FlowLayout.CENTER, 50, 50);
pa.setLayout(flow);
pa.add(outter1);
pa.add(outter2);
pa.pack();
pa.setLocationRelativeTo(null);
pa.setVisible(true);
pa.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pa.setLocationRelativeTo(null);
}
}
You can nest JPanels. That is how I implemented the output you want.
The below code is not a correction of your code, it is an example of how to achieve the output you want. Since the two JPanels in your code are quite similar, the below code only displays a single JPanel. I assume you can make the appropriate changes.
package activityswing;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
public class Swing2 {
private JPanel createInner() {
JPanel inner = new JPanel();
inner.setBackground(Color.GREEN);
JButton button1 = new JButton("Button 1");
inner.add(button1);
JButton button2 = new JButton("Button 2");
inner.add(button2);
JButton button3 = new JButton("Button 3");
inner.add(button3);
return inner;
}
private JPanel createOuter() {
JPanel outer = new JPanel();
TitledBorder titledBorder = new TitledBorder(new LineBorder(Color.blue), "Panel 1");
Font font2 = new Font("Verdana", Font.BOLD + Font.ITALIC, 12);
titledBorder.setTitleFont(font2);
EmptyBorder emptyBorder = new EmptyBorder(10, 10, 10, 10);
CompoundBorder compoundBorder = new CompoundBorder(titledBorder, emptyBorder);
outer.setBorder(compoundBorder);
outer.add(createInner());
return outer;
}
private void showGui() {
JFrame frame = new JFrame("Swing2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createOuter());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new Swing2().showGui());
}
}
Running the above code displays the following window.

Can I use a for loop to create objects in java?

Can I initialize multiple objects in a single loop?
Here's what a snippet of my code looks like. As you can see, it becomes hard to look at from a glance and takes up too much space.
I'd like to be able to create the buttons in one for loop and then modify in another for loop.
public class MyFrame extends JFrame {
MyFrame() {
JButton button1 = new JButton();
JButton button2 = new JButton();
JButton button3 = new JButton();
JButton button4 = new JButton();
JButton button5 = new JButton();
JButton button6 = new JButton();
JButton button7 = new JButton();
JButton button8 = new JButton();
JButton button9 = new JButton();
JButton button0 = new JButton();
button1.setBounds(60, 60, 50, 50);
button2.setBounds(120,60,50,50);
button3.setBounds(180,60,50,50);
button4.setBounds(60,120,50,50);
button5.setBounds(120,120,50,50);
button6.setBounds(180,120,50,50);
button7.setBounds(60,180,50,50);
button8.setBounds(120,180,50,50);
button9.setBounds(180,180,50,50);
button0.setBounds(120,240,50,50);
}
}
Yes, you can use a for loop to create the buttons.
Here's a GUI I created.
It's not a good idea to use absolute positioning (setBounds) when creating a GUI. You should use the Swing layout managers.
I used a GridLayout to position the buttons.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TenButtonGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new TenButtonGUI());
}
#Override
public void run() {
JFrame frame = new JFrame("Ten Button GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new GridLayout(0, 3, 5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
for (int i = 0; i < 11; i++) {
if (i == 9) {
JLabel label = new JLabel(" ");
panel.add(label);
} else {
JButton button = new JButton();
button.setPreferredSize(new Dimension(50, 50));
panel.add(button);
}
}
return panel;
}
}
You could do something like this:
List<JButton> buttons = new ArrayList<>();
int[][] bounds = {{60, 60, 50, 50}, {120,60,50,50}}; //add more bound quadruplets
// iterating over the values in the bounds array
Arrays.asList(bounds).forEach(v -> {
JButton button = new JButton();
button.setBounds(v[0], v[1], v[2], v[3]);
buttons.add(button);
});
In the end you will find your buttons in the buttons List.

ActionListener continues to throw errors

I don't know a whole lot about programming so excuse my messy code, but I'm working on a little choice-based game and my action listeners are throwing a nasty NullPointerException. Let me know what the issue might be.
the error is
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
with a continued list of (Unknown Source) based lines
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class finalproj extends JFrame implements ActionListener
{
private static final int WIDTH = 800, HEIGHT = 800;
private static final Font STANDARD_FONT = new Font("Arial", Font.BOLD, 32);
private JButton startgame, next, endgame;
private JLabel startmenu, question;
private int chanceofdeath = 0;
private JRadioButton q1A, q1B, q1C, q2A, q2B, q2C, q3A, q3B, q3C, q4A, q4B, q4C,
q5A, q5B, q5C, q6A, q6B, q6C, q7A, q7B, q8C, q9A, q9B, q9C, q10A, q10B, q10C, q11A,
q11B, q11C, q12A, q12B, q12C, q13A, q13B, q13C, q14A, q14B, q14C, q15A, q15B, q15C;
public static void main(String[] args)
{
new finalproj();
}
public finalproj()
{
setLayout(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(WIDTH, HEIGHT);
setTitle("The Wild, Wild West");
getContentPane().setBackground(Color.BLACK);
setLocationRelativeTo(null);
setResizable(false);
JLabel startmenu = new JLabel("");
startmenu.setSize(800, 100);
startmenu.setLocation(35, 100);
startmenu.setFont(STANDARD_FONT);
startmenu.setText("Howdy Pardner! Ready to enter the Wild West?!");
startmenu.setOpaque(true);
startmenu.setBackground(Color.BLACK);
startmenu.setForeground(Color.WHITE);
startmenu.setVisible(true);
JButton startgame = new JButton("press me");
startgame.setFont(new Font("Arial", Font.BOLD, 28));
startgame.setForeground(Color.BLACK);
startgame.setSize(600, 100);
startgame.setLocation(100, 300);
startgame.setVisible(true);
JButton next = new JButton("Continue");
next.setFont(new Font("Arial", Font.BOLD, 28));
next.setForeground(Color.BLACK);
next.setSize(600, 100);
next.setLocation(100, 300);
next.setFocusable(false);
next.setVisible(false);
JLabel question = new JLabel();
question.setFont(new Font("Arial", Font.BOLD, 28));
question.setForeground(Color.BLACK);
question.setSize(600, 100);
question.setLocation(100, 300);
question.setFocusable(false);
question.setVisible(false);
question.setText("AAAAA");
startgame.addActionListener(this);
add(startmenu);
add(startgame);
add(question);
add(next);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("press me"))
{
startmenu.setVisible(false);
}
You are using local variable with the name 'startmenu', while the field 'startmenu' is never assigned.
You should initialize it like this
startmenu = new JLabel("");
instead of
JLabel startmenu = new JLabel("");
The same thing should be done with other fields.
Let me advice you to use IDE highlighting, it will show you what field or variable you are looking at.
First of you declare a variable name with
private JLabel startmenu, question;
in your constructor, you are creating an object using
JLabel startmenu = new JLabel("");
this object scoope only in constructor, not outside the constructor.
so you need to insitalize value of startmenu using above statement.
this.startmenu = new JLabel("");
what to do. replace
JLabel startmenu = new JLabel("");
to
this.startmenu = new JLabel("");

JPanel layout - adding text box and rearranging components

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.

write a string on a jpanel centered

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));

Categories