Why isn't my JScrollPane working? - java

I'm trying to make my JPanel scrollable but it's not working. I made a JPanel, added components to it, then added my JPanel to a JScrollPane. This is what you're supposed to do, right? What am I doing wrong?
import java.awt.Dimension;
import java.awt.Font;
import java.awt.SystemColor;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ScrollPaneLayout;
import javax.swing.SwingConstants;
public class RegisterPane extends JPanel {
private JTextField txtJohnDoe;
private JTextField txtExampledomaincom;
private JPasswordField passwordField;
private JPasswordField passwordField_1;
/**
* Create the panel.
*/
public RegisterPane() {
setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(6, 36, 300, 450);
panel.setLayout(null);
JLabel lblFirstName = new JLabel("First Name");
lblFirstName.setBounds(28, 6, 92, 16);
panel.add(lblFirstName);
txtJohnDoe = new JTextField();
txtJohnDoe.setText("John Doe");
txtJohnDoe.setBounds(124, 0, 251, 28);
panel.add(txtJohnDoe);
txtJohnDoe.setColumns(10);
txtExampledomaincom = new JTextField();
txtExampledomaincom.setText("Example#domain.com");
txtExampledomaincom.setColumns(10);
txtExampledomaincom.setBounds(124, 40, 251, 28);
panel.add(txtExampledomaincom);
JLabel lblEmail = new JLabel("Email");
lblEmail.setBounds(28, 46, 92, 16);
panel.add(lblEmail);
JLabel lblGender = new JLabel("Gender");
lblGender.setBounds(28, 89, 55, 16);
panel.add(lblGender);
JRadioButton rdbtnMale = new JRadioButton("Male");
rdbtnMale.setBounds(124, 85, 92, 23);
panel.add(rdbtnMale);
JRadioButton rdbtnFemale = new JRadioButton("Female");
rdbtnFemale.setBounds(283, 85, 92, 23);
panel.add(rdbtnFemale);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(28, 157, 55, 16);
panel.add(lblPassword);
JLabel passDirections = new JLabel();
passDirections.setHorizontalAlignment(SwingConstants.CENTER);
passDirections.setFont(new Font("Lucida Grande", Font.PLAIN, 10));
passDirections.setBackground(SystemColor.window);
passDirections.setText("Password's Must be at Least 6 characters long and contain 1 non letter character");
passDirections.setBounds(29, 117, 346, 28);
panel.add(passDirections);
passwordField = new JPasswordField();
passwordField.setBounds(124, 151, 251, 28);
panel.add(passwordField);
passwordField_1 = new JPasswordField();
passwordField_1.setBounds(124, 195, 251, 28);
panel.add(passwordField_1);
JLabel lblRetypePassword = new JLabel("Password Again");
lblRetypePassword.setBounds(28, 201, 92, 16);
panel.add(lblRetypePassword);
JCheckBox chckbxSubscribeToNews = new JCheckBox("Subscribe to News Letter");
chckbxSubscribeToNews.setSelected(true);
chckbxSubscribeToNews.setHorizontalAlignment(SwingConstants.CENTER);
chckbxSubscribeToNews.setBounds(29, 244, 346, 23);
panel.add(chckbxSubscribeToNews);
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setBounds(28, 280, 55, 16);
panel.add(lblNewLabel);
JScrollPane scroll = new JScrollPane(panel);
scroll.setSize(new Dimension(450,300));
panel.setAutoscrolls(true);
add(scroll);
}
}
Here's my JFrame class
import java.awt.BorderLayout;
public class MainFrame extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(0, 0));
setResizable(false);
setContentPane(new RegisterPane());
//RegisterPane isn't scrolling ^
}
}
Thanks in Advance for your help!

I'm seeing setLayout(null) alot in your code.
The JViewport uses the component's/view's preferred size as a bases for determining if the view expands beyond the visible bounds of the JScrollPane, because you've seen fit to ignore this feature, the components have begun to break down.
Swing is designed to work layout managers and it makes it much easier to develop complex user interfaces that can work across a multitude of platforms and environments

Related

GUI goes blank when i try to define the public void actionPerformed(ActionEvent arg0)

When I try to add some function to get data from jtext field under public void actionPerformed(ActionEvent arg0) My GUI goes blank I have attached the images below I can't figure out what's wrong with it.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Register extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
private JTextField textField_4;
private JLabel lblNewLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Register frame = new Register();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Register() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblName = new JLabel("Name");
lblName.setBounds(56, 56, 56, 16);
contentPane.add(lblName);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(56, 85, 77, 16);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(56, 114, 56, 16);
contentPane.add(lblPassword);
JLabel lblAge = new JLabel("Age");
lblAge.setBounds(56, 143, 56, 16);
contentPane.add(lblAge);
JLabel lblGender = new JLabel("Gender");
lblGender.setBounds(56, 172, 56, 16);
contentPane.add(lblGender);
textField = new JTextField();
textField.setBounds(130, 53, 116, 19);
contentPane.add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(130, 82, 116, 22);
contentPane.add(textField_1);
textField_1.setColumns(10);
textField_2 = new JTextField();
textField_2.setBounds(130, 111, 116, 22);
contentPane.add(textField_2);
textField_2.setColumns(10);
textField_3 = new JTextField();
textField_3.setBounds(130, 140, 116, 22);
contentPane.add(textField_3);
textField_3.setColumns(10);
textField_4 = new JTextField();
textField_4.setBounds(130, 169, 116, 22);
contentPane.add(textField_4);
textField_4.setColumns(10);
JButton btnSubmit = new JButton("Submit");
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnSubmit.setBounds(169, 215, 97, 25);
contentPane.add(btnSubmit);
lblNewLabel = new JLabel("New label");
lblNewLabel.setBounds(330, 56, 56, 16);
contentPane.add(lblNewLabel);
}
}
EDIT 1: Added String name to action just to get name.
JButton btnSubmit = new JButton("Submit");
btnSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String Name;
}
});
and This happened
GUI went blank:
You're using an absolute layout. Since you can't pack() the window, you need to at least validate() its contents.
Register frame = new Register();
frame.validate();
frame.setVisible(true);
Now you can see the real problem: you picked bounds for lblPassword and lblNewLabel that cut off the text on my computer. You really need to use a layout, maybe like this.

JDialog shows empty

I was trying to replace the use of JOptionPane by a new custom dialog here is what I did:
package pk;
import java.util.Enumeration;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JTextArea;
import java.awt.SystemColor;
import javax.swing.JPanel;
import java.awt.Color;
import javax.swing.border.LineBorder;
public class SIMessage extends JDialog implements ActionListener{
private static final long serialVersionUID = 1L;
public JButton oui=new JButton("Oui"),btnClose=new JButton(new ImageIcon("images\\logo\\delete.gif")),
non=new JButton("Non"),annuler=new JButton("Annuler"),ok=new JButton("OK");
public JLabel lblImgErr=new JLabel(new ImageIcon("images\\logo\\msgErreur.png")),
lblImgConf=new JLabel(new ImageIcon("images\\logo\\msgQuestion.png")),
lblImgWarning=new JLabel(new ImageIcon("images\\logo\\msgWarning.png")),
lblImgInfo=new JLabel(new ImageIcon("images\\logo\\msgInformation.png")),
lblImgQuestion=new JLabel(new ImageIcon("images\\logo\\msgQuestion.png")),
lblImgIconApp=new JLabel(new ImageIcon("images\\logo\\clntIco.ico"));
public JLabel title=new JLabel(),message=new JLabel();
public enum TypeMessage{
ERROR_MESSAGE,
CONFIRMATION_MESSAGE,
WARNING_MESSAGE,
INFORMATION_MESSAGE,
VALIDATION_MESSAGE
}
public SIMessage(JFrame parent,String title,TypeMessage type,String message) {
super(parent,true);
setUndecorated(true);
getContentPane().setLayout(new GridLayout(1, 1));
JPanel mainDgPanel = new JPanel();
mainDgPanel.setBorder(new LineBorder(new Color(255, 255, 255), 3, true));
mainDgPanel.setBounds(0, 0, 444, 156);
getContentPane().add(mainDgPanel);
mainDgPanel.setLayout(null);
mainDgPanel.setBackground(Color.decode(EcranPrincipal.blueThemeCP));
JTextArea txtrTextarea = new JTextArea(message);
txtrTextarea.setRows(2);
txtrTextarea.setBounds(123, 62, 340, 80);
txtrTextarea.setFont(new Font("Iskoola Pota", Font.PLAIN, 18));
txtrTextarea.setEditable(false);
txtrTextarea.setFocusable(false);
txtrTextarea.setOpaque(false);
txtrTextarea.setBorder(null);
txtrTextarea.setWrapStyleWord(true);
txtrTextarea.setLineWrap(true);
txtrTextarea.setForeground(Color.decode(EcranPrincipal.blueThemeBT));
mainDgPanel.add(txtrTextarea);
JPanel panelButtons = new JPanel();
panelButtons.setBounds(47, 115, 344, 30);
mainDgPanel.add(panelButtons);
switch(type)
{
case ERROR_MESSAGE:
{
JLabel lblNewLabel =lblImgErr;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOk = ok;
panelButtons.add(btnOk);
break;
}
case CONFIRMATION_MESSAGE:
{
JLabel lblNewLabel =lblImgConf;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOui = oui;
panelButtons.add(btnOui);
break;
}
case WARNING_MESSAGE:
{
JLabel lblNewLabel =lblImgWarning;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOk = ok;
panelButtons.add(btnOk);
break;
}
case INFORMATION_MESSAGE:
{
JLabel lblNewLabel =lblImgInfo;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOk = ok;
panelButtons.add(btnOk);
break;
}
case VALIDATION_MESSAGE:
{
JLabel lblNewLabel =lblImgConf;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOui = oui;
panelButtons.add(btnOui);
JButton btnNon = non;
panelButtons.add(btnNon);
JButton btnAnnuler = annuler;
panelButtons.add(btnAnnuler);
break;
}
default:
}
ok.addActionListener(this);
oui.addActionListener(this);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 444, 27);
mainDgPanel.add(panel);
panel.setBackground(Color.WHITE);
panel.setLayout(null);
JButton btnCloseDf = btnClose;
btnCloseDf.setBounds(411, 0, 39, 23);
panel.add(btnCloseDf);
JLabel lblIconApp =lblImgIconApp;
lblIconApp.setBounds(10, 4, 77, 14);
panel.add(lblIconApp);
JLabel lblTitle = new JLabel(title);
lblTitle.setBounds(190, 4, 46, 14);
panel.add(lblTitle);
this.pack();
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Object source=e.getSource();
if(source==oui||source==ok)
{
this.dispose();
}
}
Then I call:
SIMessage sm=new SIMessage(this, "Attention", SIMessage.TypeMessage.WARNING_MESSAGE,"You need to change ...");
callMethode2();
The problem is that it executes the call to Methode2 before showing any dialog while it is supposed to force the user to respond before continuing.
I see an empty window side by side with the window generated by callMethod2!, so what is wrong?
You should set the modality for Dialog.
A modal window is a graphical control element subordinate to an application's main window. It creates a mode that disables the main window but keeps it visible with the modal window as a child window in front of it. Users must interact with the modal window before they can return to the parent application.
So, Set the modal flag of the dialog when initializing it.
setModal(True)
edit:
I don't know what you exactly changed in your code, but the code below works fine for me:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Emad
*/
import java.awt.BorderLayout;
import java.util.Enumeration;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JTextArea;
import java.awt.SystemColor;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import javafx.event.ActionEvent;
import javax.swing.border.LineBorder;
public class SIMessage extends JDialog implements ActionListener {
private static final long serialVersionUID = 1L;
public JButton oui = new JButton("Oui"), btnClose = new JButton(new ImageIcon("images\\logo\\delete.gif")),
non = new JButton("Non"), annuler = new JButton("Annuler"), ok = new JButton("OK");
public JLabel lblImgErr = new JLabel(new ImageIcon("images\\logo\\msgErreur.png")),
lblImgConf = new JLabel(new ImageIcon("images\\logo\\msgQuestion.png")),
lblImgWarning = new JLabel(new ImageIcon("images\\logo\\msgWarning.png")),
lblImgInfo = new JLabel(new ImageIcon("images\\logo\\msgInformation.png")),
lblImgQuestion = new JLabel(new ImageIcon("images\\logo\\msgQuestion.png")),
lblImgIconApp = new JLabel(new ImageIcon("images\\logo\\clntIco.ico"));
public JLabel title = new JLabel(), message = new JLabel();
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
// TODO Auto-generated method stub
Object source = e.getSource();
if (source == oui || source == ok) {
this.dispose();
}
}
public enum TypeMessage {
ERROR_MESSAGE,
CONFIRMATION_MESSAGE,
WARNING_MESSAGE,
INFORMATION_MESSAGE,
VALIDATION_MESSAGE
}
public SIMessage(JFrame parent, String title, TypeMessage type, String message) {
super(parent, true);
setUndecorated(true);
getContentPane().setLayout(new GridLayout(1, 1));
JPanel mainDgPanel = new JPanel();
mainDgPanel.setBorder(new LineBorder(new Color(255, 255, 255), 3, true));
mainDgPanel.setBounds(0, 0, 444, 156);
getContentPane().add(mainDgPanel);
// mainDgPanel.setBackground(Color.decode(EcranPrincipal.blueThemeCP));
JTextArea txtrTextarea = new JTextArea(message);
txtrTextarea.setRows(2);
txtrTextarea.setBounds(123, 62, 340, 80);
txtrTextarea.setFont(new Font("Iskoola Pota", Font.PLAIN, 18));
txtrTextarea.setEditable(false);
txtrTextarea.setFocusable(false);
txtrTextarea.setOpaque(false);
txtrTextarea.setBorder(null);
txtrTextarea.setWrapStyleWord(true);
txtrTextarea.setLineWrap(true);
// txtrTextarea.setForeground(Color.decode(EcranPrincipal.blueThemeBT));
mainDgPanel.add(txtrTextarea);
JPanel panelButtons = new JPanel();
panelButtons.setBounds(47, 115, 344, 30);
mainDgPanel.add(panelButtons);
switch (type) {
case ERROR_MESSAGE: {
JLabel lblNewLabel = lblImgErr;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOk = ok;
panelButtons.add(btnOk);
break;
}
case CONFIRMATION_MESSAGE: {
JLabel lblNewLabel = lblImgConf;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOui = oui;
panelButtons.add(btnOui);
break;
}
case WARNING_MESSAGE: {
JLabel lblNewLabel = lblImgWarning;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOk = ok;
panelButtons.add(btnOk);
break;
}
case INFORMATION_MESSAGE: {
JLabel lblNewLabel = lblImgInfo;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOk = ok;
panelButtons.add(btnOk);
break;
}
case VALIDATION_MESSAGE: {
JLabel lblNewLabel = lblImgConf;
lblNewLabel.setBounds(10, 69, 79, 14);
mainDgPanel.add(lblNewLabel);
JButton btnOui = oui;
panelButtons.add(btnOui);
JButton btnNon = non;
panelButtons.add(btnNon);
JButton btnAnnuler = annuler;
panelButtons.add(btnAnnuler);
break;
}
default:
}
ok.addActionListener(this);
oui.addActionListener(this);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 444, 27);
mainDgPanel.add(panel);
panel.setBackground(Color.WHITE);
panel.setLayout(null);
JButton btnCloseDf = btnClose;
btnCloseDf.setBounds(411, 0, 39, 23);
panel.add(btnCloseDf);
JLabel lblIconApp = lblImgIconApp;
lblIconApp.setBounds(10, 4, 77, 14);
panel.add(lblIconApp);
JLabel lblTitle = new JLabel(title);
lblTitle.setBounds(190, 4, 46, 14);
panel.add(lblTitle);
this.pack();
this.setVisible(true);
}
public static void main(String[] args)
{
SIMessage sm=new SIMessage(null, "Attention", SIMessage.TypeMessage.WARNING_MESSAGE,"You need to change ...");
System.out.println("hello");
}
}

Making a second frame in Java swing

I have made a simple digital business card in Java swing using Eclipse, I am brand new to Java and programming in general so please bear with me. Basically what I want to do is add a button that says "Our Work" or "Portfolio" for example, which when clicked will open a new window where I can then add pictures or links or false reviews etc.
I know this is probably quite simple, but I struggle to understand a lot of tutorials when it is based on other peoples code.
package dbuscard;
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import java.awt.Font;
import javax.swing.JSeparator;
public class card {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
card window = new card();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public card() {
initialize();
}
/**
* Initialise the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(new Color(153, 204, 255));
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblLogo = new JLabel("");
lblLogo.setBounds(127, 11, 219, 104);
frame.getContentPane().add(lblLogo);
lblLogo.setIcon(new ImageIcon("Images\\zlogoimg.png"));
JLabel lblNewLabel = new JLabel("t: 01254 777494");
lblNewLabel.setFont(new Font("Source Code Pro Light", Font.PLAIN, 11));
lblNewLabel.setBounds(20, 187, 126, 14);
frame.getContentPane().add(lblNewLabel);
JLabel lblEApexuxdesigngmailcom = new JLabel("e: apexuxdesign#gmail.com");
lblEApexuxdesigngmailcom.setFont(new Font("Source Code Pro Light", Font.PLAIN, 11));
lblEApexuxdesigngmailcom.setBounds(20, 204, 200, 14);
frame.getContentPane().add(lblEApexuxdesigngmailcom);
JLabel lblVisitWebsite = new JLabel("visit website");
lblVisitWebsite.setFont(new Font("Source Code Pro Light", Font.BOLD, 11));
lblVisitWebsite.setBounds(10, 237, 117, 14);
frame.getContentPane().add(lblVisitWebsite);
JLabel facebook = new JLabel("");
facebook.setBounds(282, 204, 64, 47);
frame.getContentPane().add(facebook);
facebook.setIcon(new ImageIcon("Images\\facebook.png"));
JLabel twitter = new JLabel("");
twitter.setBounds(320, 204, 72, 47);
frame.getContentPane().add(twitter);
twitter.setIcon(new ImageIcon("Images\\twitter.png"));
JLabel youtube = new JLabel("");
youtube.setBounds(356, 204, 68, 47);
frame.getContentPane().add(youtube);
youtube.setIcon(new ImageIcon("Images\\youtube.png"));
JLabel lblSeanHutchinson = new JLabel("Sean Hutchinson");
lblSeanHutchinson.setFont(new Font("Source Code Pro Light", Font.PLAIN, 11));
lblSeanHutchinson.setBounds(20, 128, 126, 14);
frame.getContentPane().add(lblSeanHutchinson);
JLabel lblUxDesigner = new JLabel("UX Designer");
lblUxDesigner.setFont(new Font("Source Code Pro Light", Font.PLAIN, 11));
lblUxDesigner.setBounds(20, 145, 107, 14);
frame.getContentPane().add(lblUxDesigner);
JLabel lblNewLabel_1 = new JLabel("CEO - Apex UX Design");
lblNewLabel_1.setFont(new Font("Source Code Pro Light", Font.PLAIN, 11));
lblNewLabel_1.setBounds(20, 162, 158, 14);
frame.getContentPane().add(lblNewLabel_1);
}
}
Simple. Add an action listener which uses the method setVisible(true); on a seperate JFrame. Example code:
package com.nonsense;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class del {
private JFrame frame, frame2;
/**
* Launch the application.
*/
public static void main(String[] args) {
del window = new del();
window.frame.setVisible(true);
}
/**
* Create the application.
*/
public del() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame2 = new JFrame();
frame2.setBounds(100, 100, 450, 300);
frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame2.getContentPane().setLayout(null);
JButton btnOpenWindow = new JButton("Open Window");
btnOpenWindow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame2.setVisible(true);
}
});
btnOpenWindow.setBounds(167, 118, 120, 23);
frame.getContentPane().add(btnOpenWindow);
}
}
I use "DISPOSE_ON_CLOSE" so that the second window does not terminate the program when the X button is pressed.

Add to JLabel method?

Is there a method that will add a string to JLabel without editing what was already there? I know about the setText method but in my program, a calculator, I want to add the button clicked to the JLabel with out overriding what is already there. Im I doing this right? Here's my code (if you need it):
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.border.EmptyBorder;
public class calc extends JFrame implements ActionListener {
private JPanel contentPane;
public JLabel results;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
calc frame = new calc();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public calc() {
setTitle("Calculator");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 255, 179);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JPanel panel = new JPanel();
panel.setToolTipText("Numbers will appear here once clicked!");
panel.setBackground(Color.WHITE);
contentPane.add(panel, BorderLayout.NORTH);
results = new JLabel("");
panel.add(results);
JPanel panel_1 = new JPanel();
contentPane.add(panel_1, BorderLayout.CENTER);
panel_1.setLayout(null);
JButton one = new JButton("1");
one.addActionListener(this);
one.setBounds(6, 19, 61, 29);
panel_1.add(one);
JButton two = new JButton("2");
two.addActionListener(this);
two.setBounds(67, 19, 61, 29);
panel_1.add(two);
JButton three = new JButton("3");
three.addActionListener(this);
three.setBounds(127, 19, 61, 29);
panel_1.add(three);
JButton four = new JButton("4");
four.addActionListener(this);
four.setBounds(6, 48, 61, 29);
panel_1.add(four);
JButton five = new JButton("5");
five.addActionListener(this);
five.setBounds(67, 48, 61, 29);
panel_1.add(five);
JButton six = new JButton("6");
six.addActionListener(this);
six.setBounds(127, 48, 61, 29);
panel_1.add(six);
JButton seven = new JButton("7");
seven.addActionListener(this);
seven.setBounds(6, 75, 61, 29);
panel_1.add(seven);
JButton eight = new JButton("8");
eight.addActionListener(this);
eight.setBounds(67, 75, 61, 29);
panel_1.add(eight);
JButton nine = new JButton("9");
nine.addActionListener(this);
nine.setBounds(127, 75, 61, 29);
panel_1.add(nine);
JButton zero = new JButton("0");
zero.addActionListener(this);
zero.setBounds(6, 102, 122, 29);
panel_1.add(zero);
JButton decimal = new JButton(".");
decimal.addActionListener(this);
decimal.setBounds(127, 102, 61, 29);
panel_1.add(decimal);
JButton add = new JButton("+");
add.addActionListener(this);
add.setBounds(184, 19, 61, 29);
panel_1.add(add);
JButton sub = new JButton("-");
sub.addActionListener(this);
sub.setBounds(184, 48, 61, 29);
panel_1.add(sub);
JButton times = new JButton("x");
times.addActionListener(this);
times.setBounds(184, 75, 61, 29);
panel_1.add(times);
JButton div = new JButton("\u00F7");
div.addActionListener(this);
div.setBounds(184, 102, 61, 29);
panel_1.add(div);
JSeparator separator = new JSeparator();
separator.setBounds(6, 6, 239, 12);
panel_1.add(separator);
}
public void actionPerformed(ActionEvent al) {
String name = al.getActionCommand();
}
}
Just get the orginal text, add "blah" (or anything else), and set it back.
results.setText(results.getText() + "blah");
Don't use a JLabel which is really designed to just display text. Instead you can use a non-editable JTextField which is designed to be updated. Then you can just use:
String name = al.getActionCommand();
textField.replaceSelection(name);
and the character will be appended to the end of the text field.
Also, don't use a null layout and the setBounds() method. Swing was designed to be used with layout managers.

How do I remove a component from a JPanel? and then redisplay the frame?

Some context for this code,
what I am trying to do is create a validation warning if the input containts "" as a value,
so if an error is displayed it displays the message.
If it is valid it does not display a message,
so how do I remove the message when the textField is valid?
The message is a JPanel that contains a JLabel with the text in it,
I add this this JPanel to the frame when it is not valid,
and I am trying to remove it when it is valid.
So what am I doing wrong here?
I am at a basic level with Swing.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Test {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test window = new Test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 401, 232);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 11, 330, 94);
frame.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblNewLabel = new JLabel("Firstname :");
lblNewLabel.setBounds(10, 11, 104, 14);
panel.add(lblNewLabel);
textField = new JTextField();
textField.setBounds(76, 8, 244, 20);
panel.add(textField);
textField.setColumns(10);
JLabel lblLastname = new JLabel("Lastname :");
lblLastname.setBounds(10, 42, 78, 14);
panel.add(lblLastname);
textField_1 = new JTextField();
textField_1.setBounds(76, 39, 244, 20);
panel.add(textField_1);
textField_1.setColumns(10);
JButton btnValidate = new JButton("Validate");
btnValidate.addMouseListener(new MouseAdapter() {
#SuppressWarnings("deprecation")
#Override
public void mousePressed(MouseEvent arg0) {
JPanel panel_1 = new JPanel();
JPanel panel_2 = new JPanel();
if(textField.getText().equals("")) {
panel_1.setBackground(new Color(30, 144, 255));
panel_1.setBounds(100, 116, 330, 26);
JLabel lblMessage = new JLabel("0 :");
lblMessage.setForeground(new Color(255, 255, 255));
lblMessage.setFont(new Font("Tahoma", Font.BOLD, 13));
panel_1.add(lblMessage);
frame.getContentPane().add(panel_1);
frame.revalidate();
frame.repaint(10);
frame.revalidate();
}
else if(textField_1.getText().equals("")) {
panel_2.setBackground(new Color(50, 200, 255));
panel_2.setBounds(10, 134, 330, 26);
JLabel lblMessage = new JLabel("1 :");
lblMessage.setBounds(50, 50, 50, 50);
lblMessage.setAlignmentX(50);
lblMessage.setForeground(new Color(255, 255, 255));
lblMessage.setFont(new Font("Tahoma", Font.BOLD, 13));
panel_2.add(lblMessage);
frame.getContentPane().add(panel_2);
frame.remove(panel_1);
frame.revalidate();
frame.repaint(10);
frame.revalidate();
}
}
});
btnValidate.setBounds(231, 71, 89, 23);
panel.add(btnValidate);
}
}
The easiest way is to simply adjust the visibility (JComponent#setVisible( false ) ).
If you really want to remove the component completely, you have to remove and revalidate, as documented in the Container#remove method
This method changes layout-related information, and therefore, invalidates the component hierarchy. If the container has already been displayed, the hierarchy must be validated thereafter in order to reflect the changes.
which results in code like
panel.remove( componentToRemove );
panel.revalidate();
panel.repaint();
As a side note: please replace the null layout and those setBounds call by a proper LayoutManager. You might want to take a look excellent 'Nested layout example' available on SO to see what is possible with layout managers. The Swing tag info on SO contains some extra useful links when starting to work with layout managers
yourpanel.setVisible(false); should hide your panel, where "yourPanel" is your JPanel instance

Categories

Resources