Hey all I have one question I am new to GUI stuff so I need some help when I want to add an element to a window using some other method or if statement I don't get error but it doesn't show up hears a code I marked problem I am working in java by the way this is not whole program but only this is a problem
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Gui extends JFrame{
private JTextField usernameTF;
private JPasswordField passwordField;
private String username,password;
private JRadioButton A,B,C,D,F;
//private JComboBox box;
private JLabel logo,errorPic,promt;
private JButton logIn;
private boolean value;
private Apples function= new Apples();
public Gui(){
super ("Awsome Progrma");
setLayout(new FlowLayout());
Icon errorIcon = new ImageIcon(getClass().getResource("wrong.png"));
errorPic = new JLabel(errorIcon);
usernameTF = new JTextField(10);
usernameTF.setToolTipText("Enter your user name hear");
add(usernameTF);
passwordField = new JPasswordField(10);
passwordField.setToolTipText("Enter your password hear");
add(passwordField);
logIn = new JButton("Log IN");
add(logIn);
usernameTF.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
username = event.getActionCommand();
password = passwordField.getText();
value = function.chack(username,password);
if (value == true){add(errorPic);} // this is a problem JLabel dosn't show up in my window
}
}
);
passwordField.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
username = usernameTF.getText();;
password = event.getActionCommand();
value = function.chack(username,password);
if (value == true){add(errorPic);} // this is a problem JLabel dosn't show up in my window
}
}
);
logIn.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
username = usernameTF.getText();
password = passwordField.getText();
value = function.chack(username,password);
if (value == true){add(errorPic);} // this is a problem JLabel dosn't show up in my window
}
}
);
}
}
The only GUI element that won't show up is the Jlabel errorPic. This is because the container needs to be validated after the component has been added. You need to call:
revalidate();
repaint();
after adding the JLabel. A better approach would be to add a JLabel with no image when adding components to the JFrame and later simply call JLabel.setIcon to update the label.
Some side notes:
Don't extend JFrame. Instead create an instance of the window component directly.
JPassword.getText is deprecated. Safer to use JPassword.getPassword instead.
Consider using Initial Threads at application startup.
Related
This question already has answers here:
Access GUI components from another class
(5 answers)
Java/Swing: reference a component from another class
(2 answers)
Closed 4 years ago.
I'm trying populate a JComboBox, whenever a button is clicked in a different frame. In the other frame, there is a text field where a person enters a name for example and a submit button, that is all. Every time the submit button is clicked, I want to populate the JComboBox. Here is the code to demonstrate what I mean. The code works, with static variables, something I'm wanting to avoid if possible.
public class Frame1Panel extends JPanel{
private static MyComboBox comboBox;
private JButton addItemsButton, exitButton;
public Frame1Panel() {
comboBox = new MyComboBox();
exitButton = new JButton("exit");
addItemsButton = new JButton("Add Items");
Dimension dim = addItemsButton.getPreferredSize();
addItemsButton.setPreferredSize(dim);
setupLayout();
exitButton.setPreferredSize(dim);
addItemsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == addItemsButton) {
Frame2 frame2 = Frame2.getInstance();
frame2.setVisible(true);
}
}
});
//This is what I'm trying to avoid. This works of course
public static MyComboBox getComboBox() {
return comboBox;
}
}
}
If you notice, I just use Frame1Panel and call the getComboBox method and of course the addItem method and it works as expected. Again is there way where I can avoid using static?
public class Frame2Panel extends JPanel {
private JTextField nameTextField;
private JLabel nameLabel;
private JButton submitButton;
public Frame2Panel() {
setLayout(new GridBagLayout());
nameTextField = new JTextField(10);
nameLabel = new JLabel("Name: ");
submitButton = new JButton("Submit");
setupLayout();
submitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
String name = nameTextField.getText();
Frame1Panel.getComboBox().addItem(name);
}
});
}
}
If anyone is wondering as to why I have a separate MyComboBox class, that is because I incorporate the DefaultComboBoxModel so Eclipse doesn't yell at me, when I use the window design editor, it isn't necessary to the question to include it, You can assume MyComboBox doesn't exist and just think it is JComboBox instead.
When user push a button (I created), it makes the TextField editable.
First I use if condition in constructor as:
if(button.isSelected()) TextField.isEditable(true); else TextField.isEditable(false);
But, this gives me an error. Then I use the same statement (to give permission to user weather he want to make text editable or not) in a method with parameter ActionEvent in which is another method_implemented by ActionListener. But this also gives error. Code and output before applying action on button is given:
Code is given below
Output
package Radio_Button;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Radio_Buttons extends JPanel{
private JRadioButton bold;
private JRadioButton italic;
private JRadioButton both;
private JRadioButton plain;
private ButtonGroup group;
private JTextField TextField;
private JButton button;
public Radio_Buttons(){
//Declare all radio buttons
plain = new JRadioButton("Plain",false);
bold = new JRadioButton("Bold", false);
italic = new JRadioButton("Italic", false);
both = new JRadioButton("Bold+Italic", false);
//Declare Text Field
TextField = new JTextField("The quick brown fox jumps over the lazy dog.",40);
TextField.setFont(new Font("Chiller", Font.PLAIN, 30));
//For button
button = new JButton("Push to edit");
//Add in panel
add(bold);
add(italic);
add(both);
add(plain);
add(TextField);
add(button);
//Make a family of radiobuttons so they can understand each others.
group = new ButtonGroup();
group.add(bold);
group.add(italic);
group.add(both);
group.add(plain);
RadioListener listener = new RadioListener();
bold.addActionListener(listener);
italic.addActionListener(listener);
plain.addActionListener(listener);
both.addActionListener(listener);
setBackground(Color.yellow);
setPreferredSize(new Dimension(800,500));
}
private class RadioListener implements ActionListener{
public void actionPerformed(ActionEvent event){
int source = 0;
if (bold.isSelected()) {source =Font.BOLD; }
else if (italic.isSelected()) {source = Font.ITALIC; }
else if (both.isSelected()){source = Font.BOLD+Font.ITALIC; }
else {source = Font.PLAIN; }
TextField.setFont(new Font("Chiller", source, 30));
}
}
public static void main (String [] args){
JFrame frame = new JFrame("Quote Options");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Radio_Buttons panel = new Radio_Buttons();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
First thing first. Spend some time to understand having meaningful "variable" names and Naming Convention. e.g variable name like TextField is a no no.
In your example, TextField is enabled by default itself. Initialize it with "editable" as false like below:
TextField.setEditable(false);
Add listener to your button and change editable of Textflied like below
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
TextField.setEditable(true);
}
});
hello i am confused in reading values from JComboBox. I want a program that if user click and select any item from JComboBox. It will appear as output. example i choose apple it will appear apple the main problem of this is i have no button of my program so i really need it to click then output here is my code so far .
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class imagebut extends JFrame
{
ImageIcon we = new ImageIcon(getClass().getResource("ban.png"));
ImageIcon wer = new ImageIcon(getClass().getResource("ba.png"));
public static void main(String args [])
{
imagebut w = new imagebut();
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
w.setSize(300,300);
w.setVisible(true);
}
String []kwe = {"Convertion","Adv.Calculator","Looping","Remarks","Average","MagicSquare","Calendar","Multiplication"};
JComboBox box = new JComboBox(kwe);
public imagebut()
{
/* JButton converter = new JButton("Convertion");
JButton advancecalc = new JButton("Adv.Calculator");
JButton calc = new JButton("Calculator");
JButton Multiplication = new JButton("Multiplication");
JButton Looping = new JButton("Looping");
JButton Calendar = new JButton("Calendar");
JButton Remarks = new JButton("Remarks");
JButton Average = new JButton("Average");
JButton Magicsq = new JButton("Magic Square");*/
JLabel background = new JLabel(new ImageIcon(getClass().getResource("gif.gif")));
JPanel pan = new JPanel();
box.setBounds(10,10,150,25);
getContentPane().add(background);
background.add(box);
/* background.add(converter);
background.add(calc);
background.add(advancecalc);
background.add(Magicsq);
background.add(Remarks);
background.add(Calendar);
background.add(Average);
background.add(Looping);
background.add(Multiplication);*/
}
}
this is my update so example if i click convertion it will make an Frame for Convertion if Average another frame .
Add ActionListener to your JComboBox component and to like:
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println(jComboBox1.getSelectedItem().toString());
}
this will get the selected item from your combo box, it will triggers every item you select from combobox
Seems you need to use ItemListener, for example:
JComboBox box = new JComboBox(kwe);
box.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED){
System.out.println(((JComboBox)e.getSource()).getSelectedItem());
// other actions
}
}
});
I'm learning Java and GUI. I have some questions, and the first is if there are any major difference between creating a subclass of JFrame and an instance of JFrame. It seems like like a subclass is more powerful? I also wonder if it's necessary to use this code when creating a GUI:
Container contentPane = getContentPane();
contentPane.setLayot(new Flowlayout());
I add my GUI class, it's a simple test so far, to a task that I have to hand in. When a user has entered some text in the textfield and press the button to continue to the next step, how do I do to clear the frame and show a new content or is there a special way to do this is in Java? I guess there must be better to use the same window instead of creating a new!? Help id preciated! Thanks
// Gui class
import java.awt.FlowLayout; // layout
import java.awt.event.ActionListener; // listener
import java.awt.event.ActionEvent; // event
import javax.swing.JFrame; // windows properties
import javax.swing.JLabel; // row of text
import javax.swing.JTextField; // enter text
import javax.swing.JOptionPane; // pop up dialog
import javax.swing.JButton; // buttons
// import.javax.swing.*;
public class Gui extends JFrame {
private JLabel text1;
private JTextField textInput1;
private JTextField textInput2;
private JButton nextButton;
// constructor creates the window and it's components
public Gui() {
super("Bank"); // title
setLayout(new FlowLayout()); // set default layout
text1 = new JLabel("New customer");
add(text1);
textInput1 = new JTextField(10);
add(textInput1);
nextButton = new JButton("Continue");
add(nextButton);
// create object to handle the components (action listener object)
frameHandler handler = new frameHandler();
textInput1.addActionListener(handler);
nextButton.addActionListener(handler);
}
// handle the events (class inside another class inherits contents from class outside)
private class frameHandler implements ActionListener {
public void actionPerformed(ActionEvent event){
String input1 = "";
// check if someone hits enter at first textfield
if(event.getSource() == textInput1){
input1 = String.format(event.getActionCommand());
JOptionPane.showMessageDialog(null, input1);
}
else if(event.getSource() == nextButton){
// ??
}
}
}
}
This small code might help you explain things :
import java.awt.event.*;
import javax.swing.*;
public class FrameDisplayTest implements ActionListener
{
/*
* Creating an object of JFrame instead of extending it
* has no side effects.
*/
private JFrame frame;
private JPanel panel, panel1;
private JTextField tfield;
private JButton nextButton, backButton;
public FrameDisplayTest()
{
frame = new JFrame("Frame Display Test");
// If you running your program from cmd, this line lets it comes
// out of cmd when you click the top-right RED Button.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel1 = new JPanel();
tfield = new JTextField(10);
nextButton = new JButton("NEXT");
backButton = new JButton("BACK");
nextButton.addActionListener(this);
backButton.addActionListener(this);
panel.add(tfield);
panel.add(nextButton);
panel1.add(backButton);
frame.setContentPane(panel);
frame.setSize(220, 220);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
JButton button = (JButton) ae.getSource();
if (tfield.getText().length() > 0)
{
if (button == nextButton)
{
/*
* this will remove the first panel
* and add the new panel to the frame.
*/
frame.remove(panel);
frame.setContentPane(panel1);
}
else if (button == backButton)
{
frame.remove(panel1);
frame.setContentPane(panel);
}
frame.validate();
frame.repaint(); // prefer to write this always.
}
}
public static void main(String[] args)
{
/*
* This is the most important part ofyour GUI app, never forget
* to schedule a job for your event dispatcher thread :
* by calling the function, method or constructor, responsible
* for creating and displaying your GUI.
*/
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new FrameDisplayTest();
}
});
}
}
if you want to switch (add then remove) JComponents, then you have to
1) add/remove JComponents and then call
revalidate();
repaint()// sometimes required
2) better and easiest choice would be implements CardLayout
If your requirement is to make a wizard, a panel with next and prev buttons, and on clicking next/prev button showing some component. You could try using CardLayout.
The CardLayout manages two or more components (usually JPanel instances) that share the same display space. CardLayout let the user choose between the components.
How to Use CardLayout
If your class extends JFrame, you can do:
getContentPane().removeAll();
I've created a frame (mainframe) for my program in the main class which I want to add and remove panels from in order switch between different screens of my program. The first screen of my program is the login panel which has a start button. When I press the start button I want to switch to the menu frame.
The removeAll method seems to work fine since the login panel disappears, but nothing appears in its place when I use the add, validate and repaint methods. I have tried to refer explicitly to the mainframe in the actionlistener (i.e. mainframe.add(menu)) but it does not recognise the object.
Thanks in advance!
public class Main {
public static JFrame mainframe = new JFrame();
public static void main(String[] args) {
// Create mainframe to add and remove panels from
LoginPanel lp = new LoginPanel();
System.out.println("mainframe created!");
// Set size of mainframe
mainframe.setBounds(0, 0, 500, 500);
mainframe.add(lp);
// Get the size of the screen
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
// Determine the new location of the mainframe
int w = mainframe.getSize().width;
int h = mainframe.getSize().height;
int x = (dim.width-w)/2;
int y = (dim.height-h)/2;
// Move the mainframe
mainframe.setLocation(x, y);
mainframe.setVisible(true);
}
}
This is my login panel class:
public class LoginPanel extends JPanel {
private JTextField usernameField;
private JPasswordField passwordField;
private final Action action = new SwingAction();
/**
* Create the panel.
*/
public LoginPanel() {
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();
String password = new String (passwordField.getPassword());
Login login = new Login();
boolean Correct = login.isCorrect(username, password);
**if (Correct == true){
removeAll();
Menu menu = new Menu();
add(menu);
validate();
repaint();
setBounds(0, 0, 500, 500);
System.out.println("Attempted to start menu!");
}**
}
});
btnLogin.setAction(action);
btnLogin.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
}});
}
I want to add and remove panels from in order switch between different screens of my program
Sounds like you should be using a Card Layout.
Define mainframe as a class field:
private JFrame mainframe;