Java Swing JComboBox/ Button edit parameters - java

I am quite new to working with GUI in Java. I was trying several things, for example, adding a new entry to a JComboBox or changing a JButtons caption using the following commands in the run method:
pwSelection.addItem("Name 1");
dec_btn.setText("Example");
protected JComboBox pwSelection = new JComboBox(contents);
Unfortunately, none of it shows any effect as soon as I start the program.
The layout was made with the IntelliJ GUI Form Creator.
It would be great if you could give me any tips or alternative approaches.
package PackMain;
import javax.swing.*;
public class Password {
String[] contents = {"Name 1", "Name 2"};
protected JTextField newAdress;
protected JPanel panel1;
protected JComboBox pwSelection = new JComboBox(contents); // ?
protected JLabel title;
protected JTextField pwOutput;
protected JButton enc_btn;
protected JButton dec_btn;
public JFrame run(){
JFrame mainFrame= new JFrame ("Password");
mainFrame.setContentPane(new Password().panel1);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setSize(400, 200);
mainFrame.setResizable(false);
mainFrame.setVisible(true);
pwSelection.addItem("Name 1");
dec_btn.setText("Example");
return mainFrame;
}
public static void main(String[] args){
new Password().run();
}
}

You're not adding any panel to the frame, also you didn't initialize any of the attributes...
package password;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.*;
public class Password extends JFrame{
String[] contents = {"Name 1", "Name 2"};
protected JTextField newAdress;
protected JPanel panel1, panel2; //2 panels for a more organized approach...
protected JComboBox pwSelection;// ?
protected JTextField pwOutput;
protected JButton enc_btn;
protected JButton dec_btn;
public Password(){ //Constructor of the class, initialize stuff here...
super("Shinny title");
//1. Initialize all your atributtes...
newAdress = new JTextField();
panel1 = new JPanel();
panel2 = new JPanel();
pwSelection = new JComboBox(contents);
pwOutput= new JTextField();
enc_btn = new JButton("First button");
dec_btn = new JButton("Second Button");
//Set layouts..
panel1.setLayout(new GridLayout(3,1));
panel2.setLayout(new FlowLayout());
//Add items to panel 1...
panel1.add(new JLabel("Adress:")); //A more simple aproach for creating a label...
panel1.add(newAdress);
panel1.add(pwSelection);
panel1.add(enc_btn);
panel1.add(dec_btn);
panel1.add(pwOutput);
//Add items of panel 1 to panel 2...
panel2.add(panel1);
add(panel2);
setSize(300,300);
setVisible(true);
//Proper way of stop the application at closing...
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
//This is not necessary as everything should be implemented in the constructor.
/*
public JFrame run(){
JFrame mainFrame= new JFrame ("Password");
mainFrame.setContentPane(new Password().panel1);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
mainFrame.setSize(400, 200);
mainFrame.setResizable(false);
mainFrame.setVisible(true);
pwSelection.addItem("Name 1");
dec_btn.setText("Example");
setVisible(true);
return mainFrame;
}
*/
public static void main(String[] args){
//Initialize the constructor...
Password ps = new Password();
}
}
This will give you an idea of how the GUI on java can be implemented.

panel1 is never defined as a new JPanel(), so it's null, and all of your other components -- pwSelection, title, etc. -- have never been added to panel1.

Related

add two JPanels to JFrame

I'm trying to add two JPanels to a Jframe, but it seems that they look like one. I'm trying tow stack them on top of each other like this image.
I thinking I may need to look at layout managers? I just need a little nudge in the right direction.
package projectTwo;
import javax.swing.*;
public class checkFrame
{
public static void main (String[] args)
{
JFrame frame = new JFrame("Compose Message");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
checkPanel bob = new checkPanel();
//frame.add(bob);
frame.getContentPane().add(bob);
frame.setResizable(false);
frame.setSize(750, 500);
frame.setVisible(true);
}
}
package projectTwo;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class checkPanel extends JPanel implements ActionListener
{
private JPanel entry, display;
private JLabel name, checkAmount, payOrderOf, numPrint, numWords;
private JTextField nameT, checkAmountT;
private JButton Submit;
public checkPanel()
{
entryComponents();
checkDisplay();
}
private void entryComponents(){
name = new JLabel("Name:");
checkAmount = new JLabel("Check Amount:");
nameT = new JTextField(20);
nameT.addActionListener(this);
checkAmountT = new JTextField(20);
checkAmountT.addActionListener(this);
Submit = new JButton("Submit");
Submit.addActionListener(this);
add(name);
add(nameT);
add(checkAmount);
add(checkAmountT);
add(Submit);
setPreferredSize(new Dimension(750, 75));
setBackground(new Color(200,200,200));
}
private void checkDisplay(){
payOrderOf = new JLabel("Pay to the Order of: ");
add(payOrderOf);
setBackground(new Color(220,255,225));
}
public void actionPerformed (ActionEvent event)
{
}
}
You should definitely take a look at layout managers. At the moment you are simply adding JPanels to each other without any specification on where they should be.
You have a few options in this case. You could use a GridLayout, but that leads to all the panels being the same size. If you just want two panels below each other, I would suggest using a BorderLayout. I've adjusted your code as follows:
public class checkPanel extends JPanel implements ActionListener
{
private JPanel entry, display;
private JLabel name, checkAmount, payOrderOf, numPrint, numWords;
private JTextField nameT, checkAmountT;
private JButton Submit;
public checkPanel()
{
this.setPreferredSize(new Dimension(750, 75));
entryComponents();
checkDisplay();
this.setLayout(new BorderLayout());
this.add(entry, BorderLayout.NORTH);
this.add(display, BorderLayout.CENTER);
}
private void entryComponents(){
entry = new JPanel();
// You should specify entry's layout as well FlowLayout are used by default
name = new JLabel("Name:");
checkAmount = new JLabel("Check Amount:");
nameT = new JTextField(20);
nameT.addActionListener(this);
checkAmountT = new JTextField(20);
checkAmountT.addActionListener(this);
Submit = new JButton("Submit");
Submit.addActionListener(this);
entry.add(name);
entry.add(nameT);
entry.add(checkAmount);
entry.add(checkAmountT);
entry.add(Submit);
entry.setBackground(new Color(200,200,200));
}
private void checkDisplay(){
display = new JPanel();
// You should specify display's layout as well FlowLayout are used by default
payOrderOf = new JLabel("Pay to the Order of: ");
display.add(payOrderOf);
display.setBackground(new Color(220,255,225));
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
It is in general a good idea to assign a layout to each JPanel you create. The choice of layout depends on how the panel should function.
using Gridbag Layout can help you a lot I would put a separator between panels as well

Java syntax for separating action listeners

Please help me out to separate these ActionListeners in a periodic table that I am attempting to complete. When I execute the program and click on 'H', it opens all the other elements and when the others are clicked, it does not work. So I need a way to separate these using any method...
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PeriodicTable
{
public static void main (String[] args)
{
JFrame frame = new JFrame("Elements");
frame.setVisible(true);
frame.setSize(1000,1500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JButton button1 = new JButton("H");
panel.add(button1);
button1.addActionListener (new Action1());
JButton button2 = new JButton("He");
panel.add(button2);
button2.addActionListener (new Action2());
JButton button3 = new JButton("Li");
panel.add(button3);
button3.addActionListener (new Action2());
}
static class Action1 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame2 = new JFrame("H");
frame2.setVisible(true);
frame2.setSize(1000,1500);
JLabel label = new JLabel("Hydrogen");
JPanel panel = new JPanel();
frame2.add(panel);
panel.add(label);
}
}
static class Action2 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame3 = new JFrame("He");
frame3.setVisible(true);
frame3.setSize(1000,1500);
JLabel label = new JLabel("Helium");
JPanel panel = new JPanel();
frame3.add(panel);
panel.add(label);
}
}
static class Action3 implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JFrame frame4 = new JFrame("Li");
frame4.setVisible(true);
frame4.setSize(1000,1500);
JLabel label = new JLabel("Lithium");
JPanel panel = new JPanel();
frame4.add(panel);
panel.add(label);
}
}
}
Thanks in advance.
(note: only the first 3 elements are coded for...)
When I execute the program and click on 'H', it opens all other elements
Only one frame opens for me.
and when the others are clicked, it does not work.
Each button opens a single frame for me.
However, button 3 opens the wrong frame because you add the wrong listener to the button:
//button3.addActionListener (new Action2());
button3.addActionListener (new Action3());
Other issues:
You should add the components to the frame BEFORE making the frame visible.
Don't hardcode screen sizes, you never know what size screen other users will be using
So the order of your code might be something like:
JLabel label = new JLabel("Helium");
JPanel panel = new JPanel();
panel.add(label);
JFrame frame3 = new JFrame("He");
frame3.add(panel);
frame3.pack();
frame3.setVisible(true);
And of course you really don't want to create dozens of separate ActionListeners. You want to make the listener more generic so it can be shared.
Something like:
static class Action implements ActionListener
{
public Action(String element, String description)
{
this.element = element;
this.description = description;
}
public void actionPerformed (ActionEvent e)
{
JLabel label = new JLabel(description);
JPanel panel = new JPanel();
panel.add(label);
JFrame frame3 = new JFrame(element);
frame3.add(panel);
frame3.pack();
frame3.setVisible(true);
}
}
Then when you create the listener you use:
button3.addActionListener (new Action("HE", "Helium"));

Button and textfield don't show up in Java

For school I had to make a JFrame and within that One button and Two textfields. Whatever you put in Textfield one have to get into textfield two when the button is pressed. I got the code to the point I should see the textfields and the button when i run the program. For whatever reason it doesn't.
My come so far:
package helloworld;
import javax.swing.*;
import java.awt.event.*;
public class HelloWorld extends JFrame {
public static void main(String[] args) {
JFrame frame = new HelloWorld();
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Hello World Button App");
JPanel panel = new JPanel();
frame.setContentPane(panel);
fram.setVisible(true);
}
}
class panel extends JPanel {
public JButton btn1 = new JButton("Klick!");
public JTextField txt1 = new JTextField(10);
public JTextField txt2 = new JTextField(10);
public panel() {
add(btn1);
add(txt1);
add(txt2);
}
}
I am not yet allowed to post images but I will provide a link to the picture down here
I am sorry if this question allready exests but i couldnt's find a similar question.
I am new to programming so please dont yell at me when I forgot something or wrote something wrong in it!
Here i have modified your code a bit, but did in a similar way.
I won't extend JFrame until and unless i don't want to do something creative, but you always CAN.
You had already extended JFrame , so no worth of calling methods with frame.foo()
but simply foo() , and most important JFrame frame = new HelloWorld() , will make no sense, if you have already extended you class with JFrame:
import javax.swing.*;
public class HelloWorld extends JFrame{
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new HelloWorld().setVisible(true);
}
});
}
public HelloWorld()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Hello World Button App");
panel pan= new panel();
add(pan.panel);
pack();
setVisible(true);
}
}
class panel {
private JButton btn1 = new JButton("Klick!");
private JTextField txt1 = new JTextField(10);
private JTextField txt2 = new JTextField(10);
JPanel panel;
public panel() {
panel = new JPanel();
panel.add(btn1);
panel.add(txt1);
panel.add(txt2);
}
}
Also, you can also extend your panel class with JPanel :
public HelloWorld()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Hello World Button App");
panel pan= new panel();
add(pan);
pack();
setVisible(true);
}
}
class panel extends JPanel {
private JButton btn1 = new JButton("Klick!");
private JTextField txt1 = new JTextField(10);
private JTextField txt2 = new JTextField(10);
public panel() {
add(btn1);
add(txt1);
add(txt2);
}
}
That is because your class name is panel not JPanel
Modify this:
panel panel = new panel();
frame.setContentPane(panel);
frame.setVisible(true);
You should try to use names for your Class that are not so confusing, and try to declare them with uppercase.
Example:
Class Panel extends JPanel {}
Object:
Panel panel = new Panel()
Here you can clearly read which one is the class name and which is the object (instance of that class) of that class.
You declared a class called panel that you are not using anywhere. Please replace the line bwlow:
JPanel panel = new JPanel();
with:
SomePanel panel = new SomePanel();
Then, your class panel becomes SomePanel to follow correct class naming.
Some thoughts to help you:
Name your classes following the Java style
Don't use public fields
Set layouts on your panels. This time it worked for you as the default is FlowLayout.

Add Jpanel to Jframe NetBeans

Hi all, I was in a development of my college mini project. It was a Library Management system , which i should do in Java swing using Net-beans IDE. First I was doing manual coding. It takes time.
In manual coding I create single JFrame with Menu bar and and items, on all action performed I wrote codes for all Jpanels. It made the file and code huge. and confusing too.
Now I need your help.
I have created a Main JFrame with Menu
A JPanel - ADD Book
another Jpanel - On add book success (demo! , for Actions happening in ADD Book )
I had made action listener
addBook addbk = new addBook();
this.getContentPane().add(addbk);
wrote this code.
I doesn't make sense.
Friends, As a new to java, What i need to study is
1.) How cal and Show an external Jpanel an action performed
2.) How to show another JPanel to same root JFrame if any event has occurred in external JPanel.
In sort, something like Iframe in HTML
Thank you all.
http://compilr.com/abelkbil/openlib/OpenLibMainGUI.java
http://compilr.com/abelkbil/openlib/addBook.java
http://compilr.com/abelkbil/openlib/bookAdded.java
CardLayout, is exactly what you need for this situation. And do learn Java Naming Conventions and stick to them, as you are a beginner, so to be on the right track from the start is always GOOD.
Here is one example, that you can look at :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample
{
private JPanel contentPane;
private MyPanel panel1;
private MyPanel panel2;
private MyPanel panel3;
private JComboBox choiceBox;
private String[] choices = {
"Panel 1",
"Panel 2",
"Panel 3"
};
private void displayGUI()
{
JFrame frame = new JFrame("Card Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new CardLayout());
choiceBox = new JComboBox(choices);
panel1 = new MyPanel(contentPane
, Color.RED.darker().darker(), this);
panel2 = new MyPanel(contentPane
, Color.GREEN.darker().darker(), this);
panel3 = new MyPanel(contentPane
, Color.DARK_GRAY, this);
contentPane.add(panel1, "Panel 1");
contentPane.add(panel2, "Panel 2");
contentPane.add(panel3, "Panel 3");
frame.getContentPane().add(choiceBox, BorderLayout.PAGE_START);
frame.getContentPane().add(contentPane, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public JComboBox getChoiceBox()
{
return choiceBox;
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new CardLayoutExample().displayGUI();
}
});
}
}
class MyPanel extends JPanel
{
private JButton jcomp1;
private JPanel contentPane;
private Color backgroundColour;
private JComboBox choiceBox;
public MyPanel(JPanel panel, Color c, CardLayoutExample cle)
{
contentPane = panel;
backgroundColour = c;
choiceBox = cle.getChoiceBox();
setOpaque(true);
setBackground(backgroundColour);
//construct components
jcomp1 = new JButton ("Show New Panel");
jcomp1.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String changeToPanel = (String) choiceBox.getSelectedItem();
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.show(contentPane, changeToPanel);
}
});
add(jcomp1);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(500, 500));
}
}
Else you can have a look at this example also.

BoxLayout program not working

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class File
{
private JFrame frame1;
private JPanel panel1;
private JPanel panel2;
private JLabel labelWeight;
private JLabel labelHeight;
File()
{
frame1 = new JFrame();
panel1 = new JPanel();
panel2 = new JPanel();
labelWeight = new JLabel("Weight :");
labelHeight = new JLabel("Height :");
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
panel1.setLayout(new FlowLayout());
panel1.add(labelWeight);
panel2.setLayout(new FlowLayout());
panel2.add(labelHeight);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
frame1.setLayout(new BoxLayout(frame1,BoxLayout.X_AXIS));
panel1.setAlignmentY(0);
panel2.setAlignmentY(0);
frame1.add(panel1);
frame1.add(panel2);
frame1.setSize(400, 200);
frame1.setDefaultCloseOperation(frame1.EXIT_ON_CLOSE);
frame1.setVisible(true);
}
public static void main (String args[])
{
new File();
}
}
It gives BoxLayout Sharing error at runtime
Generally, LayoutManagers are set on a JPanel. I guess JFrame implements this method to forward it to the content pane of the frame. I would suggest you try:
Container contentPane = frame1.getContentPane();
contentPane.setLayout(new BoxLayout(contentPane,BoxLayout.X_AXIS));
If you still have problems take a look at the Swing tutorial on How to Use Box Layout for working examples.
Swing components should be created in the Event Dispatch Thread. Try this in your main():
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new File();
}
});
But your problem may be the same as this question.

Categories

Resources