Java Swing JLabel not appearing - java

The JLabel nameLabel will not appear on the gui. Ive tried to use a SwingWorker so concurrency isnt an issue. When the Jlabel is added to the West section of the BorderLayout of the internal JPanel the panel makes room for the label but the label doesnt actually appear. If anyone has had this problem or knows how to fix it i would be very appreciative
thanks
public class Frame_2
{
JButton done = new JButton("Next Page");
JLabel topLabel = new JLabel("2. Contact Information");
JTextField nameInput = new JTextField();
JTextField mailingAddressInput = new JTextField();
JTextField cityStateInput = new JTextField();
JTextField telephoneInput = new JTextField();
JTextField faxInput = new JTextField();
JTextField eMailInput = new JTextField();
JLabel nameLabel = new JLabel("Name:");
JPanel internal = new JPanel();
JPanel northGrid = new JPanel();
int keepTrack = 0;
String name;
String mailingAddress;
String cityState;
String telephone;
String fax;
String eMail;
public void buildFrame_2(JFrame frame)
{
nameLabel.setText("Name:");
nameInput.setText("Name:");
mailingAddressInput.setText("Mailing Address:");
cityStateInput.setText("City, State, Zip Code:");
telephoneInput.setText("Telephone:");
faxInput.setText("Fax:");
eMailInput.setText("E-mail:");
internal.setLayout(new BorderLayout());
topLabel.setHorizontalAlignment(SwingConstants.CENTER);
frame.setLayout(new BorderLayout());
northGrid.setLayout(new GridLayout(12,2));
nameInput.addActionListener((new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
name = nameInput.getText();
System.out.println(name);
nameInput.setVisible(false);
keepTrack++;
if(keepTrack == 6)
{
askForSecondary(internal);
}
}
}));
mailingAddressInput.addActionListener((new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
mailingAddress = mailingAddressInput.getText();
System.out.println(mailingAddress);
mailingAddressInput.setVisible(false);
keepTrack++;
if(keepTrack == 6)
{
askForSecondary(internal);
}
}
}));
cityStateInput.addActionListener((new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
cityState = cityStateInput.getText();
System.out.println(cityState);
cityStateInput.setVisible(false);
keepTrack++;
if(keepTrack == 6)
{
askForSecondary(internal);
}
}
}));
telephoneInput.addActionListener((new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
telephone = telephoneInput.getText();
System.out.println(telephone);
telephoneInput.setVisible(false);
keepTrack++;
if(keepTrack == 6)
{
askForSecondary(internal);
}
}
}));
faxInput.addActionListener((new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
fax = faxInput.getText();
System.out.println(fax);
faxInput.setVisible(false);
keepTrack++;
if(keepTrack == 6)
{
askForSecondary(internal);
}
}
}));
eMailInput.addActionListener((new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
eMail = eMailInput.getText();
System.out.println(eMail);
eMailInput.setVisible(false);
keepTrack++;
if(keepTrack == 6)
{
askForSecondary(internal);
}
}
}));
northGrid.add(nameInput);
northGrid.add(mailingAddressInput);
northGrid.add(cityStateInput);
northGrid.add(telephoneInput);
northGrid.add(faxInput);
northGrid.add(eMailInput);
internal.add(nameLabel, BorderLayout.WEST);
//internal.add(northGrid, BorderLayout.CENTER);
frame.add(internal, BorderLayout.CENTER);
frame.add(done, BorderLayout.SOUTH);
frame.add(topLabel, BorderLayout.NORTH);
}

Using the below code, label shows up fine for me.
JFrame f = new JFrame();
Frame_2 f2 = new Frame_2();
f2.buildFrame_2(f);
f.pack();
f.setVisible(true);
However, if the pack() call is removed, the frame defaults to its minimum size so that contents cannot be seen.
My guess is that you just need to resize frame. However, you really ought to provide an SSCCE if you want more accurate answers.

Related

Java; Update second ComboBox after selection in first ComboBox

I've been trying to get te grips of Java (just because:)). At the moment I'm stuck on a 'calculator'. My intention is to select a overall subject through a ComboBox after which a second ComboBox shows which units can be calculated for said subject.
My problem is that the second ComboBox does not update and I'm having a hard time finding my oversight. Is anyone able to show my where I'm going wrong?
note: The terms for unitstring are placeholders for the time being:).
public class UserInterface implements Runnable{
String unitstring = "Select a subject";
#Override
public void run() {
JFrame frame = new JFrame("Radiation Calculator 2.0");
frame.setPreferredSize(new Dimension(350, 250));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
createComponents(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public void createComponents(Container container) {
GridLayout layout = new GridLayout(4, 2);
container.setLayout(layout);
JLabel subject = new JLabel("Select a subject");
String[] subjectStrings = {"Wavelenght", "Radioactive Decay", "Radiation Dose"};
JComboBox subjectsel = new JComboBox(subjectStrings);
subjectsel.addActionListener(this::actionPerformed);
JLabel unit = new JLabel("Select a unit");
String[] unitStrings = {unitstring};
JComboBox unitsel = new JComboBox(unitStrings);
JLabel input = new JLabel("Select a input");
JTextField userinput = new JTextField("");
JButton calculate = new JButton("Calculate");
JTextArea result = new JTextArea("");
container.add(subject);
container.add(subjectsel);
container.add(unit);
container.add(unitsel);
container.add(input);
container.add(userinput);
container.add(calculate);
container.add(result);
}
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
int print = cb.getSelectedIndex();
System.out.println(print);
unitArray(print);
}
public void unitArray(int x) {
if (x == 0) {
unitstring = "Lambda";
}
if (x == 1) {
unitstring = "Bequerel";
}
if (x == 2) {
unitstring = "Gray";
}
System.out.println(unitstring);
}
}

Adding ActionListeners to JPanel

This questions has been asked a few times but mine is a little different. I created a small application and in the view I added a few JPanels to a JFrame. I then try to add actionListeners in the controller which is where the problem happened.
The code below gives me the following error:
The method addActionListener(new ActionListener(){})
is undefined for the type JPanel
The view class
public class MainMenuGUI {
JTabbedPane tabbedPane = new JTabbedPane();
JPanel findUserPanel;
JPanel deleteUserPanel;
JPanel addUserPanel;
JFrame frame = new JFrame();
JPanel tabbedPanel = new JPanel();
//Controller class for tabbedPanel
ControllerTabbedPane listen = new ControllerTabbedPane(this);
//Controller class for findUserPanel
FindUserPanelController findUserController = new FindUserPanelController(findUserPanel);
public MainMenuGUI() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
findUserPanel = createFindUserPanel();
deleteUserPanel = createDeleteUserPanel();
addUserPanel = createAddUserPanel();
tabbedPane.addTab("Find User", findUserPanel);
tabbedPane.addTab("Delete User", deleteUserPanel);
tabbedPane.addTab("Add User", addUserPanel);
tabbedPanel.add(tabbedPane);
frame.add(tabbedPanel);
frame.pack();
// opens frame in the center of the screen
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
JPanel createFindUserPanel() {
findUserPanel = new JPanel();
findUserPanel.setPreferredSize(new Dimension(300, 300));
findUserPanel.setLayout(new GridLayout(5, 7));
JLabel firstlbl = new JLabel("First Name");
JLabel lastlbl = new JLabel("Last Name");
JLabel addresslbl = new JLabel("Address");
JLabel agelbl = new JLabel("Age");
JTextField firstNametxt = new JTextField(15);
JTextField lastNametxt = new JTextField(15);
JTextField addresstxt = new JTextField(30);
JTextField age = new JTextField(3);
JButton btn = new JButton("Submit");
JScrollPane window = new JScrollPane();
window.setViewportBorder(new LineBorder(Color.RED));
window.setPreferredSize(new Dimension(150, 150));
findUserPanel.add(firstlbl);
findUserPanel.add(firstNametxt);
findUserPanel.add(lastlbl);
findUserPanel.add(lastNametxt);
findUserPanel.add(addresslbl);
findUserPanel.add(addresstxt);
findUserPanel.add(agelbl);
findUserPanel.add(age);
findUserPanel.add(window, BorderLayout.CENTER);
findUserPanel.add(btn);
return findUserPanel;
}
Controller Class
public class ControllerTabbedPane {
MainMenuGUI mainMenuGUI;
int currentTabbedIndex = 0;
ControllerTabbedPane(MainMenuGUI mainMenuGUI){
this.mainMenuGUI = mainMenuGUI;
addTabbedPaneListeners();
}
private void addTabbedPaneListeners() {
mainMenuGUI.tabbedPane.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent ce) {
currentTabbedIndex = mainMenuGUI.tabbedPane.getSelectedIndex();
System.out.println("Current tab is:" + currentTabbedIndex);
}
});
}
/*ERROR saying The method addActionListener(new ActionListener(){})
is undefined for the type JPanel*/
private void findPanelListeners() {
mainMenuGUI.findUserPanel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
});
}
This is the way to achieve your request:
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JButton bt1 = new JButton();
JButton bt2 = new JButton();
panel1.add(bt1);
panel2.add(bt2);
bt1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Bt1 on panel1 pressed");
}
});
bt2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Bt2 on panel2 pressed");
}
});
You can modify variables or other objects into the listeners to store which panel was "pressed".
I think its not possible to add addActionListner() to JPanel
Instead
You can use,
JPanel p1=new JPanel();
p1.addMouseListener(this);
And override
public void mouseClicked(MouseEvent me)
{
int x=me.getX();
int y=me.getY();
System.out.println(x+","+y);
//By using x AND y you can identify the panel
}
NB: extends MouseAdapter

Java - Password Field character counter

I have an assignment question that requires me to create a JPasswordField. Two buttons are needed, one to show the actual password in another textfield, and the other just shows the character count in the textfield. Here's what I have to far, but I can't get it to compile because Method setText in class javax.swing.text.JTextComponent cannot be applied to given types.
The compiler stops under bt1 when I want it to read the password itself.
Can anyone help?
Thanks.
Code:
public class JavaPasswordCount {
public JavaPasswordCount() {
JFrame window = new JFrame("Password Character Count");
window.setSize(50, 50);
JButton bt1 = new JButton("Show Count");
JButton bt2 = new JButton("Show Password");
final JPasswordField pwd = new JPasswordField();
final JTextField tf = new JTextField();
final int counter;
JPanel panel = new JPanel();
bt1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tf.setText(pwd.getPassword());
}
});
bt2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
counter = pwd.length();
tf.setText(counter);
}
});
panel.setLayout(new FlowLayout()); // Add buttons and TextField to the panel
panel.add(tf);
panel.add(pwd);
panel.add(bt1);
panel.add(bt2);
window.getContentPane().add(panel, BorderLayout.CENTER);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.pack();
window.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {
}
JavaPasswordCount application = new JavaPasswordCount();
}
}
Change this lines:
counter = pwd.length();
tf.setText(counter);
to
int counter = pwd.getPassword().length;
tf.setText(String.valueOf((counter)));
and this
tf.setText(pwd.getPassword());
To
tf.setText(pwd.getPassword().toString());

frame 2 inside frame 1

I have 2 classes; Students and RegisterStudents, and hence 2 different main_panel(Class 1) and panel_1 (Class 2). What I am trying to do is, when a button on the Students Interface is pressed, the whole panel_1 should appear within main_panel. I have set both to same size already. is that possible?
The code i got so far is:
JButton btnNewButton = new JButton("Register Student");
btnNewButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
Students main_panel = new Students();
RegisterStudent panel_1 = new RegisterStudent();
main_panel.add(panel_1);
}
});
btnNewButton.setBounds(0, 162, 167, 37);
panel.add(btnNewButton);
This isnt doing anything though? its compiling, but panel_1 is not actually appearing inside the main_panel. Has anyone got any suggestions?
JButton btnNewButton = new JButton("Register Student");
btnNewButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
Students main_panel = new Students();
RegisterStudent panel_1 = new RegisterStudent();
main_panel.add(panel_1);
panel.add(main_panel); // ADD THIS LINE
}
});
btnNewButton.setBounds(0, 162, 167, 37);
panel.add(btnNewButton);
You were initializing the new main_panel, and new panel_1, and adding panel_1 to main_panel but then you weren't doing anything with the new main_panel.
Also, I highly suggest naming your variables otherwise - these names are very non-intuitive.
For such things I would suggest you to use CardLayout
When you add something to the container, you must call revalidate() and repaint() methods to realize the changes made to it at RunTime. Like in your case you adding main_panel.add(panel_1);now after this you must perform
main_panel.revalidate();
main_panel.repaint();
frame.getRootPane().revalidate(); // for Upto JDK 1.6.
frame.revalidate(); // for JDK 1.7+
frame.repaint();
so that changes can be seen. A small code snippet to help you understand what I mean.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MultiplePanels extends JFrame
{
private JPanel registrationPanel, loginPanel, searchPanel;
private JButton registerButton, loginButton, searchButton;
private ActionListener action;
public MultiplePanels()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
registrationPanel = new JPanel();
registrationPanel.setBackground(Color.WHITE);
loginPanel = new JPanel();
loginPanel.setBackground(Color.YELLOW);
searchPanel = new JPanel();
searchPanel.setBackground(Color.BLUE);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(0, 1));
buttonPanel.setBackground(Color.DARK_GRAY);
registerButton = new JButton("REGISTER");
loginButton = new JButton("LOGIN");
searchButton = new JButton("SEARCH");
buttonPanel.add(registerButton);
buttonPanel.add(loginButton);
buttonPanel.add(searchButton);
action = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
JButton button = (JButton) ae.getSource();
if (button == registerButton)
{
if (!(loginPanel.isShowing()) && !(searchPanel.isShowing()))
{
add(registrationPanel, BorderLayout.CENTER);
}
else
{
if (loginPanel.isShowing())
{
remove(loginPanel);
add(registrationPanel, BorderLayout.CENTER);
}
else if (searchPanel.isShowing())
{
remove(searchPanel);
add(registrationPanel, BorderLayout.CENTER);
}
}
}
else if (button == loginButton)
{
if (!(registrationPanel.isShowing()) && !(searchPanel.isShowing()))
{
add(loginPanel, BorderLayout.CENTER);
}
else
{
if (registrationPanel.isShowing())
{
remove(registrationPanel);
add(loginPanel, BorderLayout.CENTER);
}
else if (searchPanel.isShowing())
{
remove(searchPanel);
add(loginPanel, BorderLayout.CENTER);
}
}
}
else if (button == searchButton)
{
if (!(loginPanel.isShowing()) && !(registrationPanel.isShowing()))
{
add(searchPanel, BorderLayout.CENTER);
}
else
{
if (loginPanel.isShowing())
{
remove(loginPanel);
add(searchPanel, BorderLayout.CENTER);
}
else if (registrationPanel.isShowing())
{
remove(registrationPanel);
add(searchPanel, BorderLayout.CENTER);
}
}
}
// This is what we are doing here to realize the changes
// made to the GUI.
revalidate();
repaint();
}
};
registerButton.addActionListener(action);
loginButton.addActionListener(action);
searchButton.addActionListener(action);
add(buttonPanel, BorderLayout.LINE_START);
setSize(300, 300);
setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new MultiplePanels();
}
});
}
}

Set text colour of a disabled JSpinner (to make it easier to read)

JSpinner waitHr = new JSpinner();
waitHr.setEnabled(false);
I have a spinner and I need to prevent the user from editing it temporarily. The problem is, when the spinner is disabled, it's text colour makes it very hard to read, which is not acceptable in this case. I noticed that you can do this with JTextFields:
JTextField txtTest = new JTextField();
txtTest.setDisabledTextColor(Color.BLACK);
Is there anything similar that can be used for a JSpinner?
you can play with that as you want
import java.awt.*;
import javax.swing.*;
import javax.swing.border.LineBorder;
public class InactiveBackgroundTest {
public JComponent makeUI() {
JSpinner s0 = new JSpinner();
s0.setPreferredSize(new Dimension(100, 20));
s0.setEnabled(false);
UIManager.put("FormattedTextField.inactiveBackground", Color.RED);
JSpinner s1 = new JSpinner();
s1.setEnabled(false);
s1.setPreferredSize(new Dimension(100, 20));
JSpinner s2 = new JSpinner();
s2.setEnabled(false);
s2.setPreferredSize(new Dimension(100, 20));
JTextField field = ((JSpinner.NumberEditor) s2.getEditor()).getTextField();
field.setEditable(false);
field.setBackground(UIManager.getColor("FormattedTextField.background"));
JSpinner s3 = new JSpinner();
s3.setPreferredSize(new Dimension(100, 20));
s3.setEnabled(false);
s3.setBorder(null);
JTextField tf = ((JSpinner.DefaultEditor) s3.getEditor()).getTextField();
tf.setDisabledTextColor(Color.black);
tf.setBackground(Color.white);
tf.setBorder(new LineBorder(Color.blue, 1));
s3.setBorder(new LineBorder(Color.red, 1));
int n = s3.getComponentCount();
if (n > 0) {
Component[] components = s3.getComponents();
String compName = "";
for (int i = 0, l = components.length; i < l; i++) {
if (components[i] instanceof JButton) {
JButton button = (JButton) components[i];
if (button.hasFocus()) {
String btnMane = button.getName();
}
button.setBorder(new LineBorder(Color.red, 1));
System.out.println("JButton");
} else if (components[i] instanceof JComboBox) {
System.out.println("JComboBox");
} else if (components[i] instanceof JTextField) {
System.out.println("JTextField");
} else if (components[i] instanceof JFormattedTextField) {
System.out.println("JFormattedTextField");
} else if (components[i] instanceof JTable) {
System.out.println("JTable");
} else if (components[i] instanceof JScrollPane) {
System.out.println("JScrollPane");
} else if (components[i] instanceof JPanel) {
JPanel panel = (JPanel) components[i];
panel.setBackground(Color.red);
panel.setBorder(null);
System.out.println("JPanel");
}
}
}
JPanel p = new JPanel();
p.setBackground(Color.black);
p.add(s0);
p.add(s1);
p.add(s2);
p.add(s3);
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
try {
//UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
for (UIManager.LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(laf.getName())) {
UIManager.setLookAndFeel(laf.getClassName());
}
}
} catch (Exception e) {
e.printStackTrace();
}
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new InactiveBackgroundTest().makeUI());
f.setPreferredSize(new Dimension(120, 140));
f.setLocationRelativeTo(null);
f.pack();
f.setVisible(true);
}
}
You can use the getTextField() method of JSpinner.DefaultEditor.

Categories