I have following two classes whose basical purpose to create an array of objects...
class MovieInfo
{ private String movieTitle;
private String movieRating;
private String movieImg;
private String movieShowTimes;
private static double adultPrice;
private static double childPrice;
MovieInfo(String title, String rating, String img, String showTimes)
{
movieTitle = title;
movieRating = rating;
movieImg = img;
movieShowTimes = showTimes;
}
/*....sets gets methods.... */
}
///////////////////////////////
class MovieList
{
MovieInfo[] mList;
public void createList()
{
mList = new MovieInfo[22];
mList[0] = new MovieInfo("A United Kingdom","PG","A_United_Kingdom.jpg","yyyn");
mList[1] = new MovieInfo("Amitiville The Awakening","18A","AmitivilleAwakening.jpg","yyyn");
mList[2] = new MovieInfo("Arrival","14A","arrival.jpg","yyyy");
mList[3] = new MovieInfo("Baywatch","14A","baywatch.jpg","yyyy");
mList[4] = new MovieInfo("Beauty and the Beast","PG","Beauty_and_the_Beast.jpg","yyyn");
}
}
I also have JList which is attached to JPanel and radio buttons..
And my problem is that I can not get how to display name of the movie from mList[0] on this JList when I click 1st rbutton, name of the movie from mList[1] when I click 2nd rbutton and etc....
Yes I know that I need to register listener for my rbuttons and group them and add ItemStateChange (just did not want to add too much code here)... I am asking here about logic after the lines of
if(e.getSource() instanceof JRadioButton)
{
Please help! Any ideas will be highly appreciated!
You could write a custom CellRenderer, as shown in the docs.
For example, having a Movie bean and a MoviesListCellRenderer which extends DefaultListCellRenderer you could end up with something like this:
public class JListCards {
private JFrame frame;
private JPanel radiosPane;
private JRadioButton[] radios;
private String[] radiosNames = {"Movie", "Classification", "Price"};
private JList <Movie> moviesList;
private ButtonGroup group;
private Movie[] movies = new Movie[] {
new Movie("Happy Feet", "AA", 10),
new Movie("Star Wars", "B12", 15),
new Movie("Logan", "C", 20)
};
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new JListCards().createAndShowGui());
}
public void createAndShowGui() {
frame = new JFrame(getClass().getSimpleName());
radiosPane = new JPanel(new GridLayout(1, 3));
radios = new JRadioButton[3];
group = new ButtonGroup();
for (int i = 0; i < radios.length; i++) {
radios[i] = new JRadioButton(radiosNames[i]);
radios[i].addActionListener(listener);
radiosPane.add(radios[i]);
group.add(radios[i]);
}
radios[0].setSelected(true);
moviesList = new JList<Movie>(movies);
moviesList.setCellRenderer(new MoviesListCellRenderer(0));
frame.add(moviesList);
frame.add(radiosPane, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < radios.length; i++) {
if (e.getSource().equals(radios[i])) {
moviesList.setCellRenderer(new MoviesListCellRenderer(i));
break;
}
}
}
};
class MoviesListCellRenderer extends DefaultListCellRenderer {
private int attribute;
public MoviesListCellRenderer(int attribute) {
this.attribute = attribute;
}
#Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value instanceof Movie) {
Movie movie = (Movie) value;
switch (attribute) {
case 0:
setText(movie.getMovieName());
break;
case 1:
setText(movie.getClassification());
break;
default:
setText(String.valueOf(movie.getPrice()));
break;
}
}
return this;
}
}
class Movie {
private String movieName;
private String classification;
private double price;
public Movie(String movieName, String classification, double price) {
super();
this.movieName = movieName;
this.classification = classification;
this.price = price;
}
public String getMovieName() {
return movieName;
}
public void setMovieName(String movieName) {
this.movieName = movieName;
}
public String getClassification() {
return classification;
}
public void setClassification(String classification) {
this.classification = classification;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
}
Which as you can see, changes the cell renderer based on the radio selected, this code can still be improved but should give you an idea:
Related
I have a student class and I've implemented all my methods correctly. However, I do not know how to get the information out of the object to display them into the GUI, such as the image file and also the texts to be shown.
So, in the GUI Frame I have their name, title, group and demowhat as labels and then the imageFile to actually show the image from the link.
class PersonInfo
{
protected String name;
protected String title;
protected String imageFile;
public PersonInfo(String name, String title, String imageFile)
{
this.name = name;
this.title = title;
this.imageFile = imageFile;
}
public PersonInfo(PersonInfo pi)
{
this(pi.name, pi.title, pi.imageFile);
}
public String getName()
{ return name; }
public String getTitle()
{ return title; }
public String getImageFile()
{ return imageFile; }
public void SetInfo(String name, String title, String imageFile)
{
this.name = name;
this.title = title;
this.imageFile = imageFile;
}
#Override public String toString()
{
return String.format("name: %s%ntitle: %s%nimageFile:%s%n", name, title, imageFile);
}
}
class Student extends PersonInfo
{
private String group;
private String demoWhat;
public Student(String name, String title, String imageFile, String group, String demoWhat)
{
super(name, title, imageFile);
this.group = group;
this.demoWhat = demoWhat;
}
public Student(Student s)
{
super(s);
}
public String getGroup()
{
return group;
}
public String getDemoWhat()
{
return demoWhat;
}
public void SetInfo(String name, String title, String imageFile, String group, String demoWhat)
{
super.SetInfo(name, title, imageFile);
this.group = group;
this.demoWhat = demoWhat;
}
#Override
public String toString()
{
return String.format ("%s" + "group: %s%n" + "demoWhat: %s%n", super.toString (), group, demoWhat);
}
}
class GUI2 extends JFrame
{
private JLabel label1;
private final JLabel image2;
public GUI2()
{
super("Welcome to 121 Demo System");
setLayout( new FlowLayout());
JButton plainJButton = new JButton("Refresh button to get the next student");
add(plainJButton);
ImageIcon image = new ImageIcon(getClass().getResource("images/xx.png"));
Image imageSIM = image.getImage();
Image imageSIMResized = imageSIM.getScaledInstance(260, 180, DO_NOTHING_ON_CLOSE);
image = new ImageIcon(imageSIMResized);
image2 = new JLabel(image);
add(image2);
ButtonHandler handler1 = new ButtonHandler();
plainJButton.addActionListener(handler1);
}
class ButtonHandler implements ActionListener //call student here
{
#Override
public void actionPerformed(ActionEvent event)
{
GUI3 gui3 = new GUI3();
setLayout( new FlowLayout());
gui3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui3.setSize(450,400);
gui3.setVisible(true);
**//I WANT THE GUI TO POP UP WITH THE NAME, TITLE, IMAGEFILE, GROUP AND DEMOWHAT**
Student student1 = new Student("name", "full time student","images/xxx.JPG", "I am from group 12", "I wish to demo A1");
add(label1);
}
}
}
class GUI3 extends JFrame //firststudent
{
private final JLabel image3;
public GUI3()
{
super("Let us welcome xxx");
JButton plainJButton = new JButton("OK");
add(plainJButton);
//ImageIcon image = new ImageIcon(getClass().getResource("images/xxx.JPG"));
//Image imagexxx= image.getImage();
//Image xxxResized = imagexxx.getScaledInstance(210, 280, DO_NOTHING_ON_CLOSE);
//image = new ImageIcon(xxxResized);
//image3 = new JLabel(image);
//add(image3);
ButtonHandler handler2 = new ButtonHandler();
plainJButton.addActionListener(handler2);
}
}
I tried making the student object in the ButtonHandler class, but then I don't know what to do from here.
Create a JPanel that renders your student. Here is a small example, based on your student class:
class StudentPanel extends JPanel {
JTextField tfGroup;
public StudentPanel() {
add(new JLabel("Group"));
tfGroup = new JTextField();
add(tfGroup);
}
public void setStudent(Student student) {
tfGroup.setText(student.getGroup());
}
}
You will want to add more fields and look at the sizing and arrangement of fields and labels. Maybe your application needs more than one way to render a student (short, full, list).
Once you have such a view, use it like so:
public static void main(String[] args) {
Student student = ... // populate the data you want to show somehow
JFrame f = new JFrame();
StudentPanel panel = new StudentPanel();
panel.setStudent(student);
f.add(panel);
f.pack();
f.setVisible(true);
}
So I think I need to split my scroll pane list because it's over 100 items I want to display. I was thinking I could have a scroll pane with tabs with each of the tabs having different parts of the list. Kind of like a tabbed pane, but just for the scroll pane like it's just one component. The problem is I don't know how to do this or if it is possible.
Here is an example which displays the MIDI instruments for all banks in a JTable. Above it offers three combo boxes (JComboBox) and a JTextField.
The text field can search (case insensitive) for any string the user enters.
The combos can be used to filter for:
Categories of instruments.
Types of instruments.
Common strings in instrument names.
Oh, and I threw in a JList of the categories. It does nothing, but if I was doing this over, I'd start with, and only have, the list in the LINE_START position.
import java.awt.*;
import java.awt.event.*;
import javax.sound.midi.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.border.EmptyBorder;
public class MidiInstrumentSearch {
private JComponent ui = null;
Instrument[] instruments;
JLabel messageLabel = new JLabel("Message Label");
JTable table;
MidiInstrumentTableModel tm;
TableRowSorter sorter;
InstrumentCategory[] instrumentCategories = {
new InstrumentCategory("All", 1, 10000),
new InstrumentCategory("Piano", 1, 8),
new InstrumentCategory("Chromatic Percussion", 9, 16),
new InstrumentCategory("Organ", 17, 24),
new InstrumentCategory("Guitar", 25, 32),
new InstrumentCategory("Bass", 33, 40),
new InstrumentCategory("Strings", 41, 48),
new InstrumentCategory("Ensemble", 49, 56),
new InstrumentCategory("Brass", 57, 64),
new InstrumentCategory("Reed", 65, 72),
new InstrumentCategory("Pipe", 73, 80),
new InstrumentCategory("Synth Lead", 81, 88),
new InstrumentCategory("Synth Pad", 89, 96),
new InstrumentCategory("Synth Effects", 97, 104),
new InstrumentCategory("Ethnic", 105, 112),
new InstrumentCategory("Percussive", 113, 120),
new InstrumentCategory("Sound Effects", 121, 128)
};
MidiInstrumentSearch() {
try {
initUI();
} catch (MidiUnavailableException ex) {
ex.printStackTrace();
}
}
public final void initUI() throws MidiUnavailableException {
if (ui != null) {
return;
}
ui = new JPanel(new BorderLayout(4, 4));
ui.setBorder(new EmptyBorder(4, 4, 4, 4));
ui.add(messageLabel, BorderLayout.PAGE_END);
ui.add(new JScrollPane(new JList(instrumentCategories)),
BorderLayout.LINE_START);
Synthesizer synthesizer = MidiSystem.getSynthesizer();
synthesizer.open();
instruments = synthesizer.getAvailableInstruments();
InstrumentPOJO[] inst = new InstrumentPOJO[instruments.length];
for (int ii = 0; ii < inst.length; ii++) {
inst[ii] = new InstrumentPOJO(instruments[ii]);
}
tm = new MidiInstrumentTableModel(inst);
sorter = new TableRowSorter<>(tm);
table = new JTable(tm);
table.setRowSorter(sorter);
ui.add(new JScrollPane(table));
JToolBar toolBar = new JToolBar();
toolBar.setLayout(new FlowLayout());
ui.add(toolBar, BorderLayout.PAGE_START);
final JComboBox categoryBox = new JComboBox<>(instrumentCategories);
ActionListener categoryListener = (ActionEvent e) -> {
InstrumentCategory ic = (InstrumentCategory) categoryBox.getSelectedItem();
CategoryFilter categoryFilter = new CategoryFilter(ic);
sorter.setRowFilter(categoryFilter);
setNumber();
};
categoryBox.addActionListener(categoryListener);
toolBar.add(new JLabel("Category"));
toolBar.add(categoryBox);
toolBar.add(new JLabel("Type"));
String[] types = {"", "Instrument", "Drumkit"};
final JComboBox typeBox = new JComboBox<>(types);
toolBar.add(typeBox);
ActionListener typeSearchListener = (ActionEvent e) -> {
String s = typeBox.getSelectedItem().toString();
SearchFilter sf = new SearchFilter(0, s);
sorter.setRowFilter(sf);
setNumber();
};
typeBox.addActionListener(typeSearchListener);
String[] nameCommon = {
"", "bass", "bell", "brass", "bs",
"drum", "flute", "gt", "harp", "horn",
"org", "orch", "pad", "piano",
"sax", "str", "syn", "vox", "wave"
};
final JComboBox nameBox = new JComboBox(nameCommon);
ActionListener nameListener = (ActionEvent e) -> {
SearchFilter sf = new SearchFilter(1, nameBox.getSelectedItem().toString());
sorter.setRowFilter(sf);
setNumber();
};
nameBox.addActionListener(nameListener);
toolBar.add(new JLabel("Name"));
toolBar.add(nameBox);
JTextField searchField = new JTextField("Enter to Search", 12);
toolBar.add(searchField);
ActionListener textSearchListener = (ActionEvent e) -> {
SearchFilter sf = new SearchFilter(1, e.getActionCommand());
sorter.setRowFilter(sf);
setNumber();
};
searchField.addActionListener(textSearchListener);
}
private void setNumber() {
int i = table.getRowCount();
setNumber(i);
}
private void setNumber(int n) {
messageLabel.setText(n + " presets");
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = () -> {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
MidiInstrumentSearch o = new MidiInstrumentSearch();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
};
SwingUtilities.invokeLater(r);
}
}
class InstrumentPOJO {
private final Instrument instrument;
private final String category;
private final String name;
private final int bank;
private final int preset;
InstrumentPOJO(Instrument instrument) {
this.instrument = instrument;
String s = instrument.toString();
category = getTextBetween(s, "", ":");
name = getTextBetween(s, ":", "bank");
bank = Integer.parseInt(getTextBetween(s, "bank #", " preset"));
String pre = "preset #";
int index = s.indexOf(pre);
s = s.substring(index + pre.length());
preset = Integer.parseInt(s);
}
private String getTextBetween(String s, String s1, String s2) {
int i1 = s.indexOf(s1);
int c1 = i1 + s1.length();
int i2 = s.indexOf(s2);
return s.substring(c1, i2).trim();
}
#Override
public String toString() {
return getCategory() + " \t"
+ getName() + " \t"
+ getBank() + " \t"
+ getPreset() + " \t";
}
public Instrument getInstrument() {
return instrument;
}
public String getCategory() {
return category;
}
public String getName() {
return name;
}
public int getBank() {
return bank;
}
public int getPreset() {
return preset;
}
}
class MidiInstrumentTableModel extends AbstractTableModel {
final static String[] colNames = {"Category", "Name", "Bank", "Preset"};
InstrumentPOJO[] orchestra;
MidiInstrumentTableModel(InstrumentPOJO[] orchestra) {
this.orchestra = orchestra;
}
#Override
public int getRowCount() {
return orchestra.length;
}
#Override
public int getColumnCount() {
return 4;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
final InstrumentPOJO ip = orchestra[rowIndex];
switch (columnIndex) {
case 0:
return ip.getCategory();
case 1:
return ip.getName();
case 2:
return ip.getBank();
case 3:
return ip.getPreset();
default:
return null;
}
}
#Override
public String getColumnName(int columnIndex) {
return colNames[columnIndex];
}
#Override
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return Integer.class;
case 3:
return Integer.class;
default:
return Integer.class;
}
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
}
class SearchFilter extends RowFilter {
int col;
String target;
SearchFilter(int col, String target) {
this.col = col;
this.target = target;
}
#Override
public boolean include(Entry entry) {
String s = entry.getValue(col).toString();
return s.toLowerCase().contains(target.toLowerCase());
}
}
class CategoryFilter extends RowFilter {
InstrumentCategory cat;
CategoryFilter(InstrumentCategory cat) {
this.cat = cat;
}
#Override
public boolean include(Entry entry) {
int i = (Integer) entry.getValue(3) + 1;
return (i >= cat.getFirst() && i <= cat.getLast());
}
}
class InstrumentCategory {
private final String name;
private final int first;
private final int last;
public InstrumentCategory(String name, int first, int last) {
this.name = name;
this.first = first;
this.last = last;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #return the first
*/
public int getFirst() {
return first;
}
/**
* #return the last
*/
public int getLast() {
return last;
}
#Override
public String toString() {
return name;
}
}
I have 3 instances of a class being created in another class.
Customer kyle = new Customer(true,false,false,"Kyle",1000.00);
Customer andrew = new Customer(false,true,false,"Andrew",0.00);
Customer connor = new Customer(false,false,true,"Connor",5000.00);
Here is the constructor if you need to see it.
public Customer(boolean regular, boolean payAhead, boolean loyal, String userName, double amountOfStorage) {
this.regular = regular;
this.payAhead = payAhead;
this.loyal = loyal;
this.userName = userName;
this.amtOfStore = amountOfStorage;
}
The user will input one of the three usernames through a jTextField. How do I take there input and have it choose what instance of the class will run? currently I have:
if (usernameInputField.getText().equals(kyle.getUserName())
|| usernameInputField.getText().equals(andrew.getUserName())
|| usernameInputField.getText().equals(connor.getUserName())){
}
But I don't know what should go into the if statement.
The user will input one of the three usernames through a jTextField.
How do I take there input and have it choose what instance of the
class will run?
You can store all the Customer objects into a Map (Customer Name as Key and Customer object as Value) and then upon receiving the user input, retrive the respective Customer object from the Map:
Map<String, Customer> map = new HashMap<>();
map.add("Kyle", new Customer(true,false,false,"Kyle",1000.00));
map.add("Andrew", new Customer(false,true,false,"Andrew",0.00));
map.add("Connor", new Customer(false,false,true,"Connor",5000.00));
Now, get the user input and retrieve the Customer object using the key (customer name by entered by user):
String userInput = usernameInputField.getText();
Customer customer = map.get(userInput);
Don't use a Map, an ArrayList or a JTextField, but instead put the Customers into a JComboBox, and have the user select the available Customers directly. This is what I'd do since it would be more idiot proof -- because by using this, it is impossible for the user to make an invalid selection.
DefaultComboBoxModel<Customer> custComboModel = new DefaultComboBoxModel<>();
custComboModel.addElement(new Customer(true,false,false,"Kyle",1000.00));
custComboModel.addElement(new Customer(false,true,false,"Andrew",0.00));
custComboModel.addElement(new Customer(false,false,true,"Connor",5000.00));
JComboBox<Customer> custCombo = new JComboBox<>(custComboModel);
Note that for this to work well, you'd have to either override Customer's toString method and have it return the name field or else give your JComboBox a custom renderer so that it renders the name correctly. The tutorials will help you with this.
e.g.,
import javax.swing.*;
#SuppressWarnings("serial")
public class SelectCustomer extends JPanel {
private DefaultComboBoxModel<SimpleCustomer> custComboModel = new DefaultComboBoxModel<>();
private JComboBox<SimpleCustomer> custCombo = new JComboBox<>(custComboModel);
private JTextField nameField = new JTextField(10);
private JTextField loyalField = new JTextField(10);
private JTextField storageField = new JTextField(10);
public SelectCustomer() {
custComboModel.addElement(new SimpleCustomer("Kyle", true, 1000.00));
custComboModel.addElement(new SimpleCustomer("Andrew", false, 0.00));
custComboModel.addElement(new SimpleCustomer("Connor", false, 5000.00));
custCombo.setSelectedIndex(-1);
custCombo.addActionListener(e -> {
SimpleCustomer cust = (SimpleCustomer) custCombo.getSelectedItem();
nameField.setText(cust.getUserName());
loyalField.setText("" + cust.isLoyal());
storageField.setText(String.format("%.2f", cust.getAmtOfStore()));
});
add(custCombo);
add(new JLabel("Name:"));
add(nameField);
add(new JLabel("Loyal:"));
add(loyalField);
add(new JLabel("Storage:"));
add(storageField);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("SelectCustomer");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new SelectCustomer());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
public class SimpleCustomer {
private String userName;
private boolean loyal;
private double amtOfStore;
public SimpleCustomer(String userName, boolean loyal, double amtOfStore) {
this.userName = userName;
this.loyal = loyal;
this.amtOfStore = amtOfStore;
}
public String getUserName() {
return userName;
}
public boolean isLoyal() {
return loyal;
}
public double getAmtOfStore() {
return amtOfStore;
}
#Override
public String toString() {
return userName;
}
}
You can create a lookup map for all the customers. You can even extend this to add and remove customers.
String username = textField.getText().toLowerCase();
if (customerMap.containsKey(username)) {
output.setText(customerMap.get(username).toString());
} else {
output.setText("Not found!");
}
Example
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class App implements Runnable {
private static class Customer {
private String userName;
private boolean regular;
private boolean payAhead;
private boolean loyal;
private double amountOfStorage;
public Customer(String userName, boolean regular, boolean payAhead, boolean loyal, double amountOfStorage) {
this.userName = userName;
this.regular = regular;
this.payAhead = payAhead;
this.loyal = loyal;
this.amountOfStorage = amountOfStorage;
}
#Override
public String toString() {
return String.format("{ userName: %s, regular: %s, payAhead: %s, loyal: %s, amountOfStorage: %s }",
userName, regular, payAhead, loyal, amountOfStorage);
}
}
private static class MainPanel extends JPanel {
private static final long serialVersionUID = -1911007418116659180L;
private static Map<String, Customer> customerMap;
static {
customerMap = new HashMap<String, Customer>();
customerMap.put("kyle", new Customer("Kyle", true, false, false, 1000.00));
customerMap.put("andrew", new Customer("Andrew", false, true, false, 0.00));
customerMap.put("connor", new Customer("Connor", false, false, true, 5000.00));
}
public MainPanel() {
super(new GridBagLayout());
JTextField textField = new JTextField("", 16);
JButton button = new JButton("Check");
JTextArea output = new JTextArea(5, 16);
button.addActionListener(new AbstractAction() {
private static final long serialVersionUID = -2374104066752886240L;
#Override
public void actionPerformed(ActionEvent e) {
String username = textField.getText().toLowerCase();
if (customerMap.containsKey(username)) {
output.setText(customerMap.get(username).toString());
} else {
output.setText("Not found!");
}
}
});
output.setLineWrap(true);
addComponent(this, textField, 0, 0, 1, 1);
addComponent(this, button, 1, 0, 1, 1);
addComponent(this, output, 0, 1, 1, 2);
}
}
protected static void addComponent(Container container, JComponent component, int x, int y, int cols, int rows) {
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = x;
constraints.gridy = y;
constraints.gridwidth = cols;
constraints.gridwidth = rows;
container.add(component, constraints);
}
#Override
public void run() {
JFrame frame = new JFrame();
MainPanel panel = new MainPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new App());
}
}
The JDialog isn't showing the JPanel after closing of the dialog and then if the user immediately repeats the action it isn't showing a panel at all but a dialog that is solid black with a small white box in the top left corner. I have tried creating a SSCCE but couldn't develop one. If I remove the window adapter in MainControl class it will just keep adding another panel to the dialog after closing and repeating the opening of the dialog. Below is the code of the SSCCE that I tried creating but it still behaves the same. The code below is the minimal amount needed to run the dialog.
public class CreateAndShowUI {
public static void createUI() {
JFrame frame = new JFrame();
MainPanel mainPanel = new MainPanel();
Dialog dialog = new Dialog();
MainControl mainControl = new MainControl(frame, mainPanel,
dialog);
frame.getContentPane().add(mainPanel.getMainPanel());
frame.setUndecorated(true);
frame.setPreferredSize(new Dimension(1100, 550));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
createUI();
}
}
public class MainControl {
private JFrame frame;
private MainPanel mainPanel;
private Dialog dialog;
public MainControl(JFrame frame, MainPanel panel, Dialog dialog) {
this.frame = frame;
this.mainPanel = panel;
this.dialog = dialog;
mainPanel.getTable().addMouseListener(new MouseListener());
dialog.getDialog().addWindowListener(new DialogWindowListener());
}
public class MouseListener extends MouseAdapter {
#Override
public void mousePressed(MouseEvent evt) {
if (evt.getButton() == MouseEvent.BUTTON3) {
dialog.showDialog(new KeywordPanel().getKeywordPanel(),
evt.getXOnScreen(), evt.getYOnScreen());
}
}
}
public class DialogWindowListener extends WindowAdapter {
#Override
public void windowClosing(final WindowEvent event) {
dialog.getDialog().dispose();
dialog.getDialog().removeAll();
}
}
}
public class MainPanel {
private JPanel mainPanel;
private JScrollPane listScrollPane;
private JTable table;
public MainPanel() {
mainPanel = new JPanel(new MigLayout("", "", "[]13[]"));
table = new JTable(new ProductTableModel());
listScrollPane = new JScrollPane(table,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
listScrollPane.setPreferredSize(new Dimension(850, 990));
mainPanel.add(listScrollPane, "cell 0 1");
}
public JPanel getMainPanel() {
return mainPanel;
}
public JTable getTable() {
return table;
}
}
public class KeywordPanel {
private JPanel keywordPanel;
private JLabel searchLbl;
public KeywordPanel() {
searchLbl = new JLabel("KeyWords");
keywordPanel = new JPanel();
keywordPanel.add(searchLbl);
}
public JPanel getKeywordPanel() {
return keywordPanel;
}
}
public class Dialog {
private JDialog dialog = new JDialog();
public Dialog() {
dialog.setLayout(new MigLayout());
}
public void showDialog(JPanel panel, int x, int y) {
dialog.add(panel);
dialog.pack();
dialog.setVisible(true);
}
public JDialog getDialog() {
return dialog;
}
}
public class ProductTableModel extends AbstractTableModel {
private ArrayList<Object> list = new ArrayList<Object>();
private String[] columnNames = { "ID", "Description", "Inventory",
"Minimum Quantity", "Cost", "Order Quantity" };
public ProductTableModel() {
list.add(new Product("Sup", "Sup", "Sup", 10, 20, "null"));
}
#Override
public int getColumnCount() {
return columnNames.length;
}
#Override
public String getColumnName(int column) {
switch (column) {
case 0:
return "<html>ID<br></html>";
case 1:
return "<html>Description<br></html>";
case 2:
return "<html>Inventory<br></html>";
case 3:
return "<html>Minimum<br>Quantity</html>";
case 4:
return "<html>Cost<br></html>";
case 5:
return "<html>Order<br>Quantity</html>";
default:
return null;
}
}
#Override
public int getRowCount() {
return list.size();
}
#Override
public boolean isCellEditable(int row, int column) {
return true;
}
#Override
public Object getValueAt(int row, int column) {
if (list.get(row) instanceof Product) {
Product product = (Product) list.get(row);
switch (column) {
case 0:
return product.getId();
case 1:
return product.getProductDescription();
case 2:
return product.getQtyOnHand();
case 3:
return product.getMinQty();
case 4:
return product.getCost();
case 5:
return product.getOrderQty();
default:
throw new IndexOutOfBoundsException();
}
} else {
return null;
}
}
}
public class Product {
private int minQty;
private double cost;
private String productDescription, id, category, qtyOnHand, orderQty;
public Product(String id, String productDescription, String qtyOnHand,
int minQty, double cost, String orderQty) {
this.setQtyOnHand(qtyOnHand);
this.setOrderQty(orderQty);
this.setId(id);
this.setMinQty(minQty);
this.setCost(cost);
this.setProductDescription(productDescription);
}
public String getQtyOnHand() {
return qtyOnHand;
}
public void setQtyOnHand(String qtyOnHand) {
this.qtyOnHand = qtyOnHand;
}
public String getOrderQty() {
return orderQty;
}
public void setOrderQty(String orderQty) {
this.orderQty = orderQty;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public double getCost() {
return cost;
}
public void setCost(double cost) {
this.cost = cost;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public int getMinQty() {
return minQty;
}
public void setMinQty(int minQty) {
this.minQty = minQty;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
You should use
dialog.getContentPane().add(panel);
and
dialog.getDialog().getContentPane().removeAll();
And you also must NOT dispose the dialog,
I have a ComboBox holding a String[]'s values. I have several other String[]'s holding numbers. I want the user to be able to select a item from the ComboBox(holding my String[] names) and according to which one they pick, I want that index associated with one of my other arrays to be printed out in a JLabel for display. Here's what I have so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class NewBuild extends JFrame
{
private static final int WIDTH = 900;
private static final int HEIGHT = 350;
//Create array constants
private static final String[] WARRIOR = {"7","6","6","5","15","11","5","5","5"};
private static final String[] KNIGHT = {"12","6","7","4","11","8","9","3","6"};
private static final String[] SWORDSMAN = {"4","8","4","6","9","16","6","7","5"};
private static final String[] BANDIT = {"9","7","11","2","9","14","3","1","8"};
private static final String[] CLERIC = {"10","3","8","10","11","5","4","4","12"};
private static final String[] SORCERER = {"5","6","5","12","3","7","8","14","4"};
private static final String[] EXPLORER = {"7","6","9","7","6","6","12","5","5"};
private static final String[] DEPRIVED = {"6","6","6","6","6","6","6","6","6"};
private static final String[] CLASS_NAMES = {" ", "Warrior", "Knight", "SwordsMan", "Bandit", "Cleric", "Sorcerer", "Explorer", "Deprived"};
private int num;
private int count = 0;
private String classes;
Container newBuildWindow = getContentPane();
private JLabel lblBuildName, lblStartingClass, lblDisplayStartingStats;
private JTextField txtBuildName;
private JComboBox cStartingClasses;
public NewBuild()
{
GUI();
}//End of Constructor
public void GUI()
{
this.setSize(WIDTH, HEIGHT);
newBuildWindow.setBackground(Color.DARK_GRAY);
setTitle("New Build");
setLayout(new GridLayout(5,2));
setVisible(true);
// setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
JPanel panel1 = new JPanel(new GridLayout());
JPanel panel2 = new JPanel(new GridLayout(2,3));
lblBuildName = new JLabel("Build Name");
lblBuildName.setForeground(Color.YELLOW);
panel1.setBackground(Color.DARK_GRAY);
panel1.add(lblBuildName);
txtBuildName = new JTextField(15);
txtBuildName.setBackground(Color.LIGHT_GRAY);
panel1.add(txtBuildName);
lblStartingClass = new JLabel("Pick a starting class:");
lblStartingClass.setForeground(Color.YELLOW);
lblDisplayStartingStats = new JLabel("Default");
lblDisplayStartingStats.setForeground(Color.YELLOW);
cStartingClasses = new JComboBox(CLASS_NAMES);
cStartingClasses.addItemListener(new itemChangeListener());
panel2.setBackground(Color.DARK_GRAY);
panel2.add(lblStartingClass);
panel2.add(cStartingClasses);
panel2.add(lblDisplayStartingStats);
//add panels to pane
newBuildWindow.add(panel1);
newBuildWindow.add(panel2);
// pack();
}//End of GUI method
class itemChangeListener implements ItemListener
{
#Override
public void itemStateChanged(ItemEvent e)
{
if(e.getStateChange() == ItemEvent.SELECTED)
{
}
}
}
}//End of class NewBuild
Any help would be very much appreciated...Please don't just post a solution, I want to understand the code not copy it.
First, create a "wrapper" class which can bind the String values to a particular name (before anyone rushes at me says you can use a Map of some kind, you could, but this "carries" the associated information within a neat package)
public class ClassType {
private String description;
private String[] values;
public ClassType(String description, String[] values) {
this.description = description;
this.values = values;
}
public String[] getValues() {
return values;
}
#Override
public String toString() {
return description;
}
}
Build an array of these ClassTypes and give this to the JComboBox
ClassType[] types = new ClassType[]{
new ClassType("Warrior", WARRIOR),
new ClassType("Knight", KNIGHT),
new ClassType("Swordsman", SWORDSMAN),
new ClassType("Bandit", BANDIT),
new ClassType("Cleric", CLERIC),
new ClassType("Socerer", SORCERER),
new ClassType("Explorer", EXPLORER),
new ClassType("Deprived", DEPRIVED)
};
cStartingClasses = new JComboBox(types);
And when the ItemListener is notified, extract the values from the selected item...
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
ClassType classType = (ClassType) ((JComboBox)e.getSource()).getSelectedItem();
if (classType != null) {
String values[] = classType.getValues();
}
}
}
You can get the index and item as:
public void itemStateChanged(ItemEvent e)
{
if(e.getStateChange() == ItemEvent.SELECTED)
{
int index = cStartingClasses.getSelectedIndex();
String item = String.valueOf(cStartingClasses.getSelectedItem());
}
}
Here cStartingClasses is JcomboBox.