write a string on a jpanel centered - java

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

Related

Java GUI Frame creation compilation error?

I'm working on simple Java GUI Frame creation with buttons, it should show the frame with two buttons "OK" and "Clear" respectively. And two lines for writing the First Name and Last Name. I'm using VS Code editor. Following code gives compilation error, any help would be appreciated:
import java.awt.*;
import javax.swing.*;
import javafx.event.ActionEvent;
public class MainFrame extends JFrame{
final private Font mainFont = new Font("Segoe print", Font.BOLD, 18);
JTextField tfFirstName, tfLastName;
JLabel lbWelcome;
public void initialize(){
/********** Form Panel ***************/
JLabel lbFirstName = new JLabel("First Name");
lbFirstName.setFont(mainFont);
tfFirstName = new JTextField();
tfFirstName.setFont(mainFont);
JLabel lbLastName = new JLabel("Last Name");
lbLastName.setFont(mainFont);
tfLastName = new JTextField();
tfLastName.setFont(mainFont);
JPanel formPanel = new JPanel();
formPanel.setLayout(new GridLayout(4, 1, 5, 5));
formPanel.add(lbFirstName);
formPanel.add(tfFirstName);
formPanel.add(lbLastName);
formPanel.add(tfLastName);
/********** Welcome Label ***************/
lbWelcome = new JLabel();
lbWelcome.setFont(mainFont);
/********** Button Panel ***************/
JButton btnOK = new JButton("OK");
btnOK.setFont(mainFont);
btnOK.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
// TODO Auto-generated method stub
String firstName = tfFirstName.getText();
String lastName = tfLastName.getText();
lbWelcome.setText("Hello " + firstName + " " + lastName);
}
});
JButton btnClear = new JButton("Clear");
btnClear.setFont(mainFont);
btnClear.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
tfFirstName.setText("");
tfLastName.setText("");
lbWelcome.setText("");
}
});
JPanel buttonsPanel = new JPanel();
buttonsPanel.setLayout(new BorderLayout());
mainPanel.setBackground(new Color(128, 128, 255));
mainPanel.add(formPanel, BorderLayout.NORTH);
mainPanel.add(lbWelcome, BorderLayout.CENTER);
mainPanel.add(buttonsPanel, BorderLayout.SOUTH);
add(mainPanel);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.setBackground(new Color(128, 128, 255));
mainPanel.add(formPanel, BorderLayout.NORTH);
mainPanel.add(lbWelcome, BorderLayout.CENTER);
setTitle("Welcome");
setSize(500, 600);
setMinimumSize(new Dimension(300, 400));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
MainFrame myFrame = new MainFrame();
myFrame.initialize();
}
}
Compilation error message:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at JavaProjectTest.src.MainFrame.main(MainFrame.java:83)
Output result after fix:
There are two main problems:
(1) import javafx.event.ActionEvent; should be changed to import java.awt.event.ActionEvent; import java.awt.event.ActionListener;
(2) The order of JPanel mainPanel = new JPanel(); should be before using mainPanel.setBackground(new Color(128, 128, 255));.
import javax.swing.*;
import java.awt.*;
//REMOVE THIS
//import javafx.event.ActionEvent;
//ADD THIS
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainFrame extends JFrame {
final private Font mainFont = new Font("Segoe print", Font.BOLD, 18);
JTexThere are two main problems, (1) `import javafx.event.ActionEvent;` should be changed to `import java.awt.event.ActionEvent;
import jThere are two main problems, (1) `import javafx.event.ActionEvent;` should be changed to `import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;` (2) The order of `JPanel mainPanel = new JPanel();` should be before using `mainPanel.setBackground(new Color(128, 128, 255));`.ava.awt.event.ActionListener;` (2) The order of `JPanel mainPanel = new JPanel();` should be before using `mainPanel.setBackground(new Color(128, 128, 255));`.There are two main problems, (1) `import javafx.event.ActionEvent;` should be changed to `import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;` (2) The order of `JPanel mainPanel = new JPanel();` should be before using `mainPanel.setBackground(new Color(128, 128, 255));`.There are two main problems, (1) `import javafx.event.ActionEvent;` should be changed to `import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;` (2) The order of `JPanel mainPanel = new JPanel();` should be before using `mainPanel.setBackground(new Color(128, 128, 255));`.tField tfFirstName, tfLastName;
JLabel lbWelcome;
public void initialize(){
/********** Form Panel ***************/
JLabel lbFirstName = new JLabel("First Name");
lbFirstName.setFont(mainFont);
There are two main problems, (1) `import javafx.event.ActionEvent;` should be changed to `import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;` (2) The order of `JPanel mainPanel = new JPanel();` should be before using `mainPanel.setBackground(new Color(128, 128, 255));`.There are two main problems, (1) `import javafx.event.ActionEvent;` should be changed to `import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;` (2) The order of `JPanel mainPanel = new JPanel();` should be before using `mainPanel.setBackground(new Color(128, 128, 255));`.tfFirstName = new JTextField();
tfFirstName.setFont(mainFont);
JLabel lbLastName = new JLabel("Last Name");
lbLastName.setFont(mainFont);
tfLastName = new JTextField();
tfLastName.setFont(mainFont);
JPanel formPanel = new JPanel();
formPanel.setLayout(new GridLayout(4, 1, 5, 5));
formPanel.add(lbFirstName);
formPanel.add(tfFirstName);
formPanel.add(lbLastName);
formPanel.add(tfLastName);
/********** Welcome Label ***************/
lbWelcome = new JLabel();
lbWelcome.setFont(mainFont);
/********** Button Panel ***************/
JButton btnOK = new JButton("OK");
btnOK.setFont(mainFont);
btnOK.addActionListener(new ActionListener(){
#Overrideimport javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainFrame extends JFrame {
final private Font mainFont = new Font("Segoe print", Font.BOLD, 18);
JTextField tfFirstName, tfLastName;
JLabel lbWelcome;
public void initialize(){
/********** Form Panel ***************/
JLabel lbFirstName = new JLabel("First Name");
lbFirstName.setFont(mainFont);
tfFirstName = new JTextField();
tfFirstName.setFont(mainFont);
JLabel lbLastName = new JLabel("Last Name");
lbLastName.setFont(mainFont);
tfLastName = new JTextField();
tfLastName.setFont(mainFont);
JPanel formPanel = new JPanel();
formPanel.setLayout(new GridLayout(4, 1, 5, 5));
formPanel.add(lbFirstName);
formPanel.add(tfFirstName);
formPanel.add(lbLastName);
formPanel.add(tfLastName);
/********** Welcome Label ***************/
lbWelcome = new JLabel();
lbWelcome.setFont(mainFont);
/********** Button Panel ***************/
JButton btnOK = new JButton("OK");
btnOK.setFont(mainFont);
btnOK.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
// TODO Auto-generated method stub
String firstName = tfFirstName.getText();
String lastName = tfLastName.getText();
lbWelcome.setText("Hello " + firstName + " " + lastName);
}
});
JButton btnClear = new JButton("Clear");
btnClear.setFont(mainFont);
btnClear.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
tfFirstName.setText("");
tfLastName.setText("");
lbWelcome.setText("");
}
});
JPanel buttonsPanel = new JPanel();
buttonsPanel.setLayout(new BorderLayout());
//MOVE SEQUENCE JPanel mainPanel = new JPanel();
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.setBackground(new Color(128, 128, 255));
mainPanel.add(formPanel, BorderLayout.NORTH);
mainPanel.add(lbWelcome, BorderLayout.CENTER);
mainPanel.setBackground(new Color(128, 128, 255));
mainPanel.add(formPanel, BorderLayout.NORTH);
mainPanel.add(lbWelcome, BorderLayout.CENTER);
mainPanel.add(buttonsPanel, BorderLayout.SOUTH);
add(mainPanel);
setTitle("Welcome");
setSize(500, 600);
setMinimumSize(new Dimension(300, 400));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
MainFrame myFrame = new MainFrame();
myFrame.initialize();
}
}
public void actionPerformed(ActionEvent e){
// TODO Auto-generated method stub
String firstName = tfFirstName.getText();
String lastName = tfLastName.getText();
lbWelcome.setText("Hello " + firstName + " " + lastName);
}
});
JButton btnClear = new JButton("Clear");
btnClear.setFont(mainFont);
btnClear.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
tfFirstName.setText("");
tfLastName.setText("");
lbWelcome.setText("");
}
});
JPanel buttonsPanel = new JPanel();
buttonsPanel.setLayout(new BorderLayout());
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.setBackground(new Color(128, 128, 255));
mainPanel.add(formPanel, BorderLayout.NORTH);
mainPanel.add(lbWelcome, BorderLayout.CENTER);
mainPanel.setBackground(new Color(128, 128, 255));
mainPanel.add(formPanel, BorderLayout.NORTH);
mainPanel.add(lbWelcome, BorderLayout.CENTER);
mainPanel.add(buttonsPanel, BorderLayout.SOUTH);
add(mainPanel);
setTitle("Welcome");
setSize(500, 600);
setMinimumSize(new Dimension(300, 400));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
MainFrame myFrame = new MainFrame();
myFrame.initialize();
}
}

Drawline not working with JPanel or JFrame

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

Why after I added a JComboBox into one of the JPanels, all JPanels were not rendered

When the JComboBox, cmbox was not added to a JPanel, two panels, p1 & p2 could be rendered. You may comment out the combo box portion to see the result. But after I added the combo box into one of the panels, all panels were not rendered.
My code is like the following:
import java.awt.*;
import javax.swing.*;
public class TestCombo {
public static void main(String[] args) {
JFrame frame = new JFrame("康樂彩歌");
frame.setVisible(true);
frame.setBounds(0, 0, 1368, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p1 = new JPanel();
p1.setBackground(Color.CYAN);
JRadioButton rb1 = new JRadioButton("加簡譜", false);
rb1.setFont(new Font("新細明體", Font.PLAIN, 20));
JRadioButton rb2 = new JRadioButton("加人聲", false);
rb2.setFont(new Font("新細明體", Font.PLAIN, 20));
rb1.setBounds(450, 180, 50, 50);
rb2.setBounds(500, 180, 50, 50);
JButton btPlay = new JButton("PLAY");
btPlay.setFont(new Font(Font.DIALOG_INPUT, Font.BOLD, 25));
btPlay.setBounds(100, 20, 100, 20);//x axis, y axis, width, height
JButton btStop = new JButton("STOP");
btStop.setFont(new Font(Font.DIALOG_INPUT, Font.BOLD, 25));
btStop.setBounds(140, 20, 100, 20);//x axis, y axis, width, height
//p1.add(cmbox);
p1.add(rb1);
p1.add(rb2);
p1.add(btPlay);
p1.add(btStop);
p1.setBorder(BorderFactory.createLineBorder(Color.black));
JPanel p2 = new JPanel();
p2.setBackground(Color.PINK);
p2.setBorder(BorderFactory.createLineBorder(Color.red));
JComboBox cmbox = new JComboBox(); //The JComboBox to be added to a JPanel
cmbox.setFont(new Font("新細明體", Font.PLAIN, 20));
cmbox.addItem("紫竹調");
cmbox.addItem("走一同去郊遊");
cmbox.addItem("大野狼");
cmbox.addItem("歸來吧蘇連多");
cmbox.addItem("追尋");
cmbox.addItem("三輪車");
cmbox.addItem("我家門前有小河");
cmbox.addItem("漁家樂");
cmbox.addItem("嚕啦啦");
cmbox.addItem("踏雪尋梅");
p2.add(cmbox);
frame.add(p1, BorderLayout.PAGE_START);
frame.add(p2, BorderLayout.CENTER);
}
}
Implementing the changes as detailed below the code, solves the problem.
import java.awt.*;
import javax.swing.*;
public class TestCombo {
public static void main(String[] args) {
JFrame frame = new JFrame("康樂彩歌");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p1 = new JPanel();
p1.setBackground(Color.CYAN);
JRadioButton rb1 = new JRadioButton("加簡譜", false);
rb1.setFont(new Font("新細明體", Font.PLAIN, 20));
JRadioButton rb2 = new JRadioButton("加人聲", false);
rb2.setFont(new Font("新細明體", Font.PLAIN, 20));
JButton btPlay = new JButton("PLAY");
btPlay.setFont(new Font(Font.DIALOG_INPUT, Font.BOLD, 25));
JButton btStop = new JButton("STOP");
btStop.setFont(new Font(Font.DIALOG_INPUT, Font.BOLD, 25));
p1.add(rb1);
p1.add(rb2);
p1.add(btPlay);
p1.add(btStop);
p1.setBorder(BorderFactory.createLineBorder(Color.black));
JPanel p2 = new JPanel();
p2.setBackground(Color.PINK);
p2.setBorder(BorderFactory.createLineBorder(Color.red));
JComboBox cmbox = new JComboBox(); //The JComboBox to be added to a JPanel
cmbox.setFont(new Font("新細明體", Font.PLAIN, 20));
cmbox.addItem("紫竹調");
cmbox.addItem("走一同去郊遊");
cmbox.addItem("大野狼");
cmbox.addItem("歸來吧蘇連多");
cmbox.addItem("追尋");
cmbox.addItem("三輪車");
cmbox.addItem("我家門前有小河");
cmbox.addItem("漁家樂");
cmbox.addItem("嚕啦啦");
cmbox.addItem("踏雪尋梅");
p2.add(cmbox);
frame.add(p1, BorderLayout.PAGE_START);
frame.add(p2, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
btPlay.setBounds(100, 20, 100, 20); Do not set the bounds of components. Let the layouts (padding and borders) do their job.
frame.setBounds(0, 0, 1368, 500); That's just a guess, and if it's the right guess on one OS, it will be the wrong guess on others. Instead pack() the window after components are added.
Sidebar: GUIs should be started on the EDT. (Not implemented above: 'batteries not included'.)

Java - Unable to open a new frame from ActionListener

I am currently designing a login screen, but I ran into a strange issue. I already designed my GUI with the help of swing, and it was time to make functional buttons. I wanted to test my login button and if it would take me to the frame I want, but it is unable to. I can set a JOptionPane.showMessageDialog for example, which works just fine, but I am unable to open another frame from the button. I tried with New JFrameName().setVisible(true), and also JFrameName test = new JFrameName(); test.setVisible(true);, but the methods show up in red. Here is my code.
package com.edu4java.swing.tutrial3;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginView {
public static void main(String[] args) {
JFrame frame = new JFrame("Bus Tour Booking System");
frame.setSize(300, 200);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
}
private static void placeComponents(JPanel panel) {
panel.setLayout(null);
JLabel titleLabel = new JLabel("Bus Tour Booking System");
titleLabel.setBounds(70,15,150,25);
panel.add(titleLabel);
JLabel userLabel = new JLabel("Username: ");
userLabel.setBounds(30, 50, 80, 25);
panel.add(userLabel);
JTextField userText = new JTextField(20);
userText.setBounds(120, 50, 130, 25);
panel.add(userText);
JLabel passwordLabel = new JLabel("Password: ");
passwordLabel.setBounds(30, 80, 80, 25);
panel.add(passwordLabel);
JPasswordField passwordText = new JPasswordField(20);
passwordText.setBounds(120, 80, 130, 25);
panel.add(passwordText);
JButton loginButton = new JButton("login");
loginButton.setBounds(100, 125, 80, 25);
panel.add(loginButton);
ActionListener myButtonListener = new MyButtonListener();
loginButton.addActionListener(myButtonListener);
}
private static class MyButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
//can't access a new frame from here :(
}
}
}
I would be very grateful if someone could help me out, I read a lot on Stackoverflow and Reddit, but just can't find the solution. I am also new to Java, so that doesn't help a lot either :D. Thanks in advance!
P.S. As far as the actual functionality for the login screen, I am going to do that in a later stage.
This is your login class. I put the JFrame frame in the global scope, so you can manipulate it from the ButtonListener method. I also created a SomeFrame class, just to demonstrate the new JFrame that would be created when you click the button. When an action is performed(the button is clicked) a new object of SomeFrame is created. Since SomeFrame extends JFrame we can use the method setVisible() to a SomeFrame object. The SomeFrame frame appears and the LoginView is no longer visible.
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginView {
public static JFrame frame = new JFrame("Bus Tour Booking System");
public static void main(String[] args) {
frame.setSize(300, 200);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
}
private static void placeComponents(JPanel panel) {
panel.setLayout(null);
JLabel titleLabel = new JLabel("Bus Tour Booking System");
titleLabel.setBounds(70,15,150,25);
panel.add(titleLabel);
JLabel userLabel = new JLabel("Username: ");
userLabel.setBounds(30, 50, 80, 25);
panel.add(userLabel);
JTextField userText = new JTextField(20);
userText.setBounds(120, 50, 130, 25);
panel.add(userText);
JLabel passwordLabel = new JLabel("Password: ");
passwordLabel.setBounds(30, 80, 80, 25);
panel.add(passwordLabel);
JPasswordField passwordText = new JPasswordField(20);
passwordText.setBounds(120, 80, 130, 25);
panel.add(passwordText);
JButton loginButton = new JButton("login");
loginButton.setBounds(100, 125, 80, 25);
panel.add(loginButton);
ActionListener myButtonListener = new MyButtonListener();
loginButton.addActionListener(myButtonListener);
}
private static class MyButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
SomeFrame newFrame = new SomeFrame();
newFrame.setVisible(true);
frame.setVisible(false);
}
}
}
This is the SomeFrame class.
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SomeFrame extends JFrame {
public SomeFrame(){
super("something");
this.setSize(300, 200);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
this.add(panel);
this.setVisible(true);
}
}

adding images in JFrame, image when clicked

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!

Categories