Java External class JComboBox missing selection - java

OK, so after rethinking my design of the payroll calculator, I am trying to modularize the program into reusable pieces. I am starting off by creating a JComboBox in one class, adding it to a JFrame that I am creating in another class and then calling the JFrame in my main.
When I tested my combo box alone, it worked. However, when I create it in a class and add it to the window class, I am loosing the String array that I added. Any ideas where I am going wrong?
My Main class:
import javax.swing.*;
import java.awt.*;
public class WindowTesting
{
public static void main(String[] args) {
CreateWindow gui = new CreateWindow();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CreateCombo deptBox = new CreateCombo();
}
}
My Window class
import javax.swing.*;
import java.awt.*;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author bsmith624
*/
public class CreateWindow extends JFrame {
public CreateWindow() {
JFrame frame1;
CreateCombo box1 = new CreateCombo();
frame1 = new JFrame("Department Combo Box");
frame1.setSize(400,200);
frame1.add(box1);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setVisible(true);
}
}
And finally my JComboBox class:
import javax.swing.*;
import java.awt.*;
public class CreateCombo extends JComboBox {
public static String [] deptList = {"Marketing","IT","Accounting","Development","Payroll","Facilities"};
/**Creates the combo box
* with department names
*/
public CreateCombo () {
JComboBox combo = new JComboBox (deptList);
combo.setVisible(true);
}
}

You are creating another JComboBox inside your CreateCombo , is not necesary cause your CreateCombo is a JComboBox
You have to set the model
public CreateCombo () {
super(); // this call JComboBox superConstructor is implicit if you don't put it
this.setModel(new DefaultComboBoxModel(depList));
this.setVisible(true);
}
Or may be a better design would be making this constructor
public CreateCombo(Object[] array ){
super(array);
}
Im not quite sure about your design ,i think you have to review it, you have a class CreateCombo that is a JComboBox may be you don't want this, may you only want a factory of JComboBox.

Related

I am making a java program and wanted to add a scrollpain in the main framework

I am making a java program and wanted to add a scrollpain in the main framework.
But I have no idea how to do it. If someone could pass me the code of how I would do it, I would appreciate it.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.JTextField;
public class GUIAE2 extends JFrame implements ActionListener{
private JTextField area;
private JLabel label2;
private JButton
buton1,buton2,buton3,buton4;buton5,buton6,buton7,buton8;buton9,buton10,buton11;
private JScrollPane sp1;
public GUIAE2(){
setLayout(null);
setTitle("ejercicios java");
getContentPane().setBackground(new Color(0,0,0));
buton1 = new JButton("Ejercicio 1 (Expresiones regulares)");
buton1.setBounds(350,40,700,60);
buton1.setBackground(new Color (0,0,224));
buton1.setFont(new Font("andale mono",1,14));
buton1.setForeground(new Color(0,0,0));
buton1.addActionListener(this);
add(buton1);
}
public void actionPerformed(ActionEvent e){
}
public static void main(String args[]){
GUIAE2 ventanabienvenida = new GUIAE2();
ventanabienvenida.setBounds(0,0,350,450);
ventanabienvenida.setVisible(true);
ventanabienvenida.setResizable(true);
ventanabienvenida.setLocationRelativeTo(null);
}
}
One possibility is:
private JScrollPane sp1;
public GUIAE2() {
setLayout(null);
setTitle("ejercicios java");
getContentPane().setBackground(new Color(0,0,0));
// first initialize the JScrollPane:
sp1 = new JScrollPane();
// now let's add the JScrollPane to the content pane:
getContentPane().add(sp1);
buton1 = new JButton("Ejercicio 1 (Expresiones regulares)");
...
buton1.addActionListener(this);
// we also add other elements to the scroll pane so it has content that
// can be scrolled:
sp1.add(buton1);
}
But instead of handling writing the UI code by yourself, I would highly recommend to use UI tools like the UI Builder that is integrated in NetBeans IDE. There you can build your GUI with drag and drop.
Basically the UI is made up like a tree where your JFrame is the root and you can add branches, i.e. more content to the branches.

Concat a Title "GetTitle().Concat(GetTitle()));"

today i try to do a example of a "Window" on Java. I try to Concat the Title but my "GetTitle()" don't work! Anyone can help me with this?
And why "public class MiVentana extends JFrame {" and "MiVentana Frame = new MiVentana("Titulo");" says warning?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MiVentana extends JFrame {
public MiVentana (String Titulo){
this.setTitle(Titulo);
this.setSize(300,400);
this.setLocation(160,80);
this.setLayout(new FlowLayout());
this.ConfigurarVentana();
this.setVisible(true);
}
public void ConfigurarVentana(){
JPanel panel = new JPanel();
JButton boton = new JButton ("OK");
boton.addActionListener(new EscuchadorBoton());
panel.add(boton);
this.add(panel);
}
class EscuchadorBoton implements ActionListener{
public void actionPerformed(ActionEvent a){
this.setTitle(this.getTitle().concat(this.getTitle()));
}
}
public static void main(String[] args) {
MiVentana Frame = new MiVentana("Titulo");
//frameTest.setVisible(true);
}
}
EDIT: I'm working on Ubuntu 14.04 IDE Eclipse 3.8
Using this inside the ActionListener refers to the EscuchadorBoton listener, not the instance of MiVentana - your JFrame.
Using MiVentana.this should refer to the window, not the listener and you'll be able to get and set the title with that.
This post describes what is happening a bit better - basically you want this from the enclosing class, not the enclosed class.
Basically instead of doing this:
this.setTitle(this.getTitle().concat(this.getTitle()));
You need to do this:
MiVentana.this.setTitle(MiVentana.this.getTitle().concat(MiVentana.this.getTitle()));

GUI close issue?

I have a program which displays two buttons and changes the image of one of the buttons on roll over. I am getting an error on my
press.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
part, And it looks like this: The method setDefaultCloseOperation(int) is undefined for the type ButtonClass. Even with the exit on close commented out there are more errors, please help.
Main class (with error):
package Buttons;
import javax.swing.JFrame;
public class Main_buttons{
public static void main(String[] args) {
ButtonClass press = new ButtonClass();
press.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
press.setSize(300,200);
press.setVisible(true);
}
}
ButtonClass class:
package Buttons;
import java.awt.FlowLayout; //layout proper
import java.awt.event.ActionListener; //Waits for users action
import java.awt.event.ActionEvent; //Users action
import javax.swing.JFrame; //Window
import javax.swing.JButton; //BUTTON!!!
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane; //Standard dialogue box
public class ButtonClass extends JButton {
private JButton regular;
private JButton custom;
public ButtonClass() { // Constructor
super("The title"); // Title
setLayout(new FlowLayout()); // Default layout
regular = new JButton("Regular Button");
add(regular);
Icon b = new ImageIcon(getClass().getResource("img.png"));
Icon x = new ImageIcon(getClass().getResource("swag.png"));
custom = new JButton("Custom", b);
custom.setRolloverIcon(x); //When you roll over the button that says custom the image will change from b to x
add(custom);
Handlerclass handler = new Handlerclass();
regular.addActionListener(handler);
custom.addActionListener(handler);
}
private class Handlerclass implements ActionListener { // This class is inside the other class
public void actionPerformed(ActionEvent eventvar) { // This will happen
// when button is
// clicked
JOptionPane.showMessageDialog(null, String.format("%s", eventvar.getActionCommand()));//Opens a new window with the name of the button
}
}
}
I have searched everywhere for this problem and found nothing. Please tell me how to resolve this issue about exiting my window.
Thanks!
You're a little confused as you're creating a class that extends JButton, and calling setVisible(true) on it as if it were a top-level window such as a JFrame or JDialog, and that doesn't make sense. Since it isn't a top-level window it also makes sense to not have a default close operation or understand what that means.
I suggest that you call this method only on top-level windows such as on a JFrame or JDialog and the like. As a side recommendation, I usually avoid setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); and instead more often do setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); which gives it a little more flexibility.
Edit: actually, just change your class to extends JFrame not extends JButton.
Make sure your image path to your resources is correct. For example:
that method is defined for JFrame, not JButton. You're calling it on an instance of a class that extends JButton
The JFrame.Exit_on_close must be used in a JFrame, and you are extending from JButton.
To set a JButton to close a JFrame its something like this.
public class MyClass extends JFrame implements ActionListener{
private JButton button = new JButton("Button");
private JPanel panel = new JPanel();
public static void main(String args[]) {
new MyClass();
}
public MyClass() {
setSize(300, 300);
button.addActionListener(this);
panel.add(button);
add(panel);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
this.dispose();
}
}

Java Swing. Need to open 3 separate windows

Suppose to pull up 3 different windows with different Labels and Strings in the frames. Below is a picture of the projected output
I have three classes.
P1Panel that extends JPanel
P1Frame that extends JFrame
P1Driver used for main
----------------------------------------------------------P1Panel class below:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class P1Panel extends JPanel
{
private String s0;
public P1Panel(String s0){
{
add(new P1Panel(s0));
}
}
}
---------------------------------------------This is P1Frame class below:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class P1Frame extends JFrame
{
private String s1;
public P1Frame (String s1){
this.s1 = s1;
{
add(new P1Panel(s1));
}
P1Frame p1 = new P1Frame(s1);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p1.setSize(300,200);
p1.setVisible(true);
}
}
----------------------------------------This is P1Driver class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class P1Driver
{
public static void main(String [] args)
{
P1Frame p1 = new P1Frame("This is window 1");
//JFrame f2 = new JFrame("This is window 2");
//JFrame f3 = new JFrame("This is window 3");
p1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p1.setSize(300,200);
p1.setVisible(true);
}
}
I believe my P1Panel class is correct in that I called a constructor and added it to itself. The text in my label is passing the P1Panel constructor as a parameter
My P1Frame class I am having difficult with. In the constructor I am wanting to make a P1Panel object and add it to the P1Frame. I think I need to pass a string into the P1Frame constructor as a parameter and then pass string to P1Panel?
I believe my Driver class is correct too as I am just putting main here and setting items size and visibility.
I believe my fix is a small one, but I am stuck and unsure in how to do so. When I run the program as is, it runs infinite with nothing popping up.
You have an infinitely recursive constructor in P1Panel class and that is why your program gets stuck. Just remove the line
add(new P1Panel(s0));
when you execute this line in the constructor you are essentially calling it again by doing
new P1Panel(s0)
so the constructor never returns and it keeps calling itself recursively. Plus why are you not adding any Swing components to your P1Panel? It will be empty without Swing components. If you want to display a String inside the panel, I suggest you do the below in the constructor.
setLayout(new BorderLayout());
JLabel label = new JLabel(s0);
add(label, BorderLayout.CENTER);

processing text in jTextArea

I am trying to implement a Document Listener in my program. So far every time the user types in a new word, I am getting the whole text and saving it. What I want to do is to get only the new word/words typed in and process them. Can you give me suggestions how I can do that?
How about document at http://docs.oracle.com/javase/tutorial/uiswing/events/documentlistener.html ?
Basically, the parameter DocumentEvent from insertUpdate event contains the text. You will have to retrieve the texts from the object e.
My suggestion is to try out some code and we'll see how much you know about DocumentListener, ok?
Below is proposed code similar to yours above:
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
//public class DocumentListener { // Fix: not a good name for the class since it is part of JVM
public class DocumentEventDemo extends JFrame { // easier than extends JPanel
JPanel txtPanel, centerPanel;
GridLayout grid;
JTextField txtField;
JTextArea txtArea;
JFrame frame;
JComponent newContentPane;
FlowLayout flow;
public DocumentEventDemo() {
txtArea = new JTextArea();
txtArea.getDocument().addDocumentListener(new MyDocumentListener());
txtArea.getDocument().putProperty("txtArea", "MyDocumentListener");
// txtField = new JTextField(10); // 10 chars max
// txtField.setText("12345");
centerPanel = new JPanel();
grid = new GridLayout(2,1,1,1);
txtPanel = new JPanel();
flow = new FlowLayout(FlowLayout.CENTER);
txtPanel.setLayout(flow);
//Adding control GUI fields to the only panel
// txtPanel.add(txtArea);
// txtPanel.add(txtField);
// Forming the center view with GUI controls
centerPanel.setLayout(grid);
// centerPanel.add(txtPanel);
centerPanel.add(txtArea);
// Add Panels to the Frame
getContentPane().add(centerPanel,"Center");
this.setSize(500,200);
this.validate();
this.setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// newContentPane = getRootPane();
// newContentPane.setOpaque(true);
// frame.setContentPane(newContentPane);
}
//MyEditor editor = new MyEditor(); // what is MyEditor?
//javax.swing.event.DocumentListener mydocumentListener = new javax.swing.event.DocumentListener()
// Make a class to define the inherited abstract methods, which are also events.
class MyDocumentListener implements DocumentListener {
String[] word=new String[50];
String text;
int i=0;
int y;
int l;
int len;
public void changedUpdate(DocumentEvent documentEvent) {
System.out.println("The text has been changed.");
}
public void insertUpdate(DocumentEvent documentEvent) {
try {
GetWord(documentEvent);
} catch (BadLocationException ex) {
Logger.getLogger(DocumentListener.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void removeUpdate(DocumentEvent documentEvent) {
System.out.println("A character has been removed!");
}
private void GetWord(DocumentEvent documentEvent) throws BadLocationException {
//get the type of event
DocumentEvent.EventType type = documentEvent.getType();
//check what is the event, hence what is the user doing
if (type.equals(DocumentEvent.EventType.INSERT)) {
Document source = documentEvent.getDocument();
y=documentEvent.getOffset();
l=documentEvent.getLength();
len=source.getLength();
text = source.getText(y,l);
if(text.equals(" "))
{
for (int z=0;z<len;z++)
{
System.out.print(word[z]);
}
System.out.println("\n");
Arrays.fill(word,null);
i=0;
}
word[i]=text;
i++;
} else {
System.out.println("A character has been removed!");
}
}
}; // DocumentListener class instantiation
// editor. editArea.getDocument().addDocumentListener(mydocumentListener);
public static void main(String args[]){
new DocumentEventDemo();
}
} // TOP class
Notes:
My most outer class extends JFrame, which creates the window & listeners the easy way, I think.
DocumentEventDemo is a constructor that creates the UI controls and looks.
I created a class that implements DocumentListener. This way I can override the abstract events.
My main function is on the bottom inside the class DocumentEventDemo, like yours actually.
I do not see the code for class MyEditor. Therefore I replaced that with JTextArea, behaves like an editor.
Your code GetWord seems to be working well. Congratulations!
Your technique of using System.out.println is not working since the app is windows GUI application instead of console, which works well with System.out.
Obviously, you still have work to do with the Listener functions for changed and remove.
Have fun!
Tommy Kwee

Categories