I have the following class ReviewPanel in which i have created a JList and trying to populate it with Vector passed to it. the vector already has its values filled but when i add it to JList it doesn't shows anything.
following is my class
public class ReviewPanel extends JPanel
{
private Vector bookList;
private JList jl;
private JRadioButton poor,fair,avg,good,exlnt;
private JButton jb;
public ReviewPanel(Vector bookList)
{
this.bookList = bookList;
jl = new JList<String>(this.bookList);
String tmp=null;
for(int i=0;i<bookList.size();i++){
tmp = tmp + bookList.get(i) + "\n";
System.out.println(tmp); //here it is showing the values in booklist vector
}
add(jl);
ButtonGroup bg =new ButtonGroup();
poor = new JRadioButton("1 Poor");
fair = new JRadioButton("2 Fair");
avg = new JRadioButton("3 Average");
good = new JRadioButton("4 Good");
exlnt = new JRadioButton("5 Excellent");
bg.add(poor);
bg.add(fair);
bg.add(avg);
bg.add(good);
bg.add(exlnt);
add(poor);
add(fair);
add(avg);
add(good);
add(exlnt);
jb = new JButton("Submit Review");
add(jb);
}
//more code
}
below is the pic for what it looks like. even though i have added the Jlist already. it doesn't show anything
not savvy to jlist and vectors, any help appreciated.
In the past I have had simular issues with the FlowLayout, which is the default layout for a JPanel.
It sometimes does not show one of the items added (in my case it was often the last).
You can test if the use of your layout manager is your problem by starting you function with setLayoutManager(null). This turns is off, which will place the elements on their default locations and sizes. If the JList does show this is your problem.
A very good example for your program is the Button Demo. This also shows the use of SwingUtils to make sure you create your program on the 'Event Dispatch Thread', which is required for all interaction with Swing objects.
Related
I have these two methods:
private void bcsButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
DefaultListModel model = new DefaultListModel<>();
for (Subject s : cCores) {
coreSubjectsList.setModel(model);
model.addElement(bcs.displayCores(s));
}
record1 = new Record(bcs.getCourseName());
ArrayList cores = new ArrayList<>(Arrays.asList(cCores));
record1.enrolCores(cores);
DefaultListModel model2 = new DefaultListModel<>();
for (Major m : BCSMajors) {
majorsList.setModel(model2);
model2.addElement(bcs.displayMajors(m));
}
DefaultListModel model3 = new DefaultListModel<>();
for (Subject s : cEles) {
this.electivesList.setModel(model3);
model3.addElement(bcs.displayElectives(s));
}
}
private void enrolButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String text = this.studNumberField.getText();
int studentNumber = Integer.parseInt(text);
String selection = group.getSelection().getActionCommand();
Student stud1 = new UnderGraduate(this.studentNameTextField.getText(), studentNumber, selection, this.dobField.getText(), "");
if (stud1 instanceof UnderGraduate) {
((UnderGraduate) stud1).writeFileUnderGrad();
record1.setStatus(Record.Status.ACTIVE);
record1.writeRecordFile();
}
}
For the enrol button, I want to make a case that if the bcsButton is chosen, and I click enrol, it will execute what is inside the enrol method. Because later on I want to make another button called mcsButton, and make two cases, that if mcsButton is chosen it will perform "the enrol code for mcs", and if bcsButton is chosen, it will perform "the enrol code for bcs". Is there any particular way I can do this? Thank you.I've tried using something like:
if(evt.getSource() == bcsButton){
//put my code here
}
It doesn't run anything though.
and make two cases, that if mcsButton is chosen it will perform "the enrol code for mcs", and if bcsButton is chosen, it will perform "the enrol code for bcs".
You would generally use a JRadioButton for this. The user can only select one of two buttons that has been added to the ButtonGroup.
Then in your "Enroll" button you check to see which button has been selected and execute the appropriate logic. The ActionListener code would be something like:
if (mcsButton.isSelected())
processMCSEnrol();
else if (bcsButton.isSelected())
processBCSEnrol();
Read the section from the Swing tutorial on How to Use Radio Buttons for more information and working examples.
Edit:
You need a variable lets say, mcsSelected.
In the ActionListener for the "mcsButton" you add:
mcsSelected = true;
In the ActionListener for the "bcsButton" you add:
mcsSelected = false;
In the "Enrol" ActionListener you add:
if (mcsSeleced)
processMCS();
else
processBCS();
this code below creates a checkbox which I want to turn synchronized scrolling on my two panels on/off. Initially when the program runs the scrollbars are independent. When the checkbox is checked and the "if" statement is reached, scroller2's scrollbar is set to the model of scroller1's scrollbar and they are connected, i.e. they move together.
However the problem is when the checkbox is unchecked, meaning I want the scrollbars to be independent again. Nothing I put in the else statement seems to work.
JCheckBox check = new JCheckBox("Global");
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
AbstractButton abstractButton = (AbstractButton) actionEvent.getSource();
boolean selected = abstractButton.getModel().isSelected();
System.out.println(selected);
if (selected){
scroller2.getHorizontalScrollBar().setModel(scroller.getHorizontalScrollBar().getModel());
} else {
scroller = new JScrollPane(plotPanel);
scroller2 = new JScrollPane(plotPanel2);
}
}
};
check.addActionListener(actionListener);
This:
scroller = new JScrollPane(plotPanel);
scroller2 = new JScrollPane(plotPanel2);
creates two new JScrollPanes but you do nothing with them. Understand that changing the object a variable refers to, here the scroller and scroller2 vairables will have no effect on the object that is displayed, and this issue gets to the core distinction of the difference between a reference variable and a reference or object. If you wanted to change the displayed JScrollPane you'd have to remove the old one, and add the new one to the GUI.
But you don't want to do this. Simply give one of the horizontal JScrollBars a new model, specifically a new DefaultBoundedRangeModel. I would use the constructor that takes 4 ints, and would scrape the value, extent, min, max parameters from the current model.
e.g., something like:
else {
JScrollBar horizBar = scroller2.getHorizontalScrollBar();
DefaultBoundedRangeModel currentModel = (DefaultBoundedRangeModel) horizBar.getModel();
int extent = currentModel.getExtent();
int min = currentModel.getMin();
int max = currentModel.getMax();
int value = currentModel.getValue();
DefaultBoundedRangeModel newModel = new DefaultBoundedRangeModel(value, extent, min, max);
horizBar.setModel(newModel);
}
Note code not tested
I'm having difficulty changing unselected options in a JList table to set them to setEnable(false). The method that is receiving the values is an ActionListener button method that, once pressed, receives the selected values from the JList. Here is the method and the buildEnemySelectionPanel() method is creating the JList with the appropriate JPanel for later placement:
private String[] enemies = {"Goblin", "Skeleton"};
private void buildEnemySelectionPanel()
{
enemyPanel = new JPanel();
enemyListPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
enemyListPanel.setPreferredSize(new Dimension(180, 85));
enemyListPanel.setBackground(Color.WHITE);
enemyPanel.setLayout(new BoxLayout(enemyPanel, BoxLayout.Y_AXIS));
enemyList = new JList(enemies);
enemyList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
enemyList.addListSelectionListener(new EnemyListListener());
enemyListPanel.add(enemyList);
enemyPanel.add(enemyListPanel);
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Select Enemy"))
{
indexEnemy = enemyList.getSelectedIndex();
indexEnemyWeapon = weaponList.getSelectedIndex();
/*
here is where I'm having problems
*/
}
}
So far I've tried to take all of the items from the JList and, matching them with the references from the original String[] list items that I sent to the JList, parsed the indexes and if they didn't match set to false. Unfortunately as you are all probably well aware, compilation errors came up as result due to the fact that the JList is not actually a list. Here is a sample of my for loop that I tried to use in my method above:
for(int x = 1; x < enemyList.length(); x++)
{
if (!(enemies[x] == indexEnemy))
{
enemyList[x].setEnable(false);
}
}
I've read the http://docs.oracle.com/javase/8/docs/api/ , (tried to link 'setEnable') among some examples but don't seem to be making the connection.
Ideally, what I wish to happen is that when the ActionEvent of my button is triggered, all non-selected options in my JList will be disabled. I understand that the end-user will still be able to change his/her mind and make a different selection. But I'd like to still receive some help on how I can set the non-selected items in my JList to false if they are not the indexEnemy from my method above.
I'm trying to setup a GUI to display an array of classes, but can't figure out how to add the array to the GUI. I'm fairly new to Java, so I could use all the help possible.
Book[] bk = new Book{10]
JFrame frame = new JFrame("Bookstore");
frame.setSize(600, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.NORTH);
frame.getContentPane().add(panel);
frame.setVisible(true);
class Book implements Comparable<Book> {
//rest of code }
How would I display Book in the GUI?
You're question's a bit unclear, but if you want to present the names of the books in a GUI, first you need to give each Book a name, aka a string representation. Add a name attribute to Book with a getName() method.
Then create a String array containing the names of the books. You can do that by:
String names = new String[books.length];
for(int i=0; i<names.length; i++){
names[i] = books[i].getName();
}
Then you can input all the names into a JTextArea, or possibly a JComboBox if you want users to be able to choose a book.
With a JComboBox:
JComboBox combo = new JComboBox(names);
panel.add(combo);
With a JTextArea:
JTextArea textArea = new JTextArea(10,names.length);
textArea.setEditable(false);
for(int i=0; i<names.size; i++){
textArea.append("Book " + i + "#: " + names[i] + "\n");
}
panel.add(textArea);
Hope this helps.
When you need to display the attributes of a collection or array of objects of a class, you have several options available to you including:
The simplest would be to use a JTextArea, give it a monospaced font, and display the String representation of each object, with each object on one line, and using a formatted String, such as can be obtained via String.format(...), to display the contents.
Better would be to put your collection of objects into a TableModel of some sort and then display the data in a JTable. Easiest would be to use a DefaultTableModel, but this will require that you convert the attributes of each Book object into an array or Vector of Object. More flexible would be to create your own class that extends AbstractTableModel, but this will require more work on your part to create the appropriate methods of the TableModel, and making sure to fire the correct AbstractTableModel notification methods when any of these methods change the data nucleus (usually a collection of Book object) in any significant way.
If you want to display one object's attributes at time, you could populate your GUI with several JTextFields, each one corresponding to an attribute of your Book object, and then use Next and Previous JButtons to move through your collection of Books, displaying the attributes of the selected book on button press. Say when the next button is pressed, an int index variable that is used to select a Book from the collection is incremented, and the Book corresponding to that index is selected. Then all of the attributes from that selected Book are displayed in their corresponding text field.
The details will depend on which route you go.
I am implementing a program for a Component Design course and am currently struggling with what should be simple use of a Jlist. The program draws shapes and should display them in a JList in a ScrollPane in the BorderLayout.West of the frame.
The current program shows the ScrollPane but will not display objects I add to the shapeListModel like it should. I am wondering it I am missing something or if something is flat out wrong with my code. Currently this is all the code that partains to the JList creation, assigning, and updating.
//Class Variable Declaration
protected ArrayList<Shape> shapes = new ArrayList<Shape>();
private JScrollPane shapeScrollPane = new JScrollPane();
private JList<String> shapeList;
protected DefaultListModel<String> shapeListModel;
//Creation of JList objects and what not
shapeListModel = new DefaultListModel<String>();
//This element is added aimply to try and get one to show up on my JList,
shapeListModel.addElement("SERIOUSLY FRUSTRATED");
//It does not just so you know
shapeList = new JList<String>(shapeListModel);
shapeList.setModel(shapeListModel);
//Adding JList to ScrollPane and setting size
shapeScrollPane.add(shapeList);
shapeScrollPane.setPreferredSize(new Dimension(250,600));
//Clarifying JList actions
shapeList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
shapeList.setLayoutOrientation(JList.HORIZONTAL_WRAP);
shapeList.setVisibleRowCount(-1);
shapeList.addListSelectionListener(this);**
//This is called everytime a new shape is created and adds it to the Arraylist
//shapes and the DefaultListModel shapeListModel
shapes.add(newShape);
shapeListModel.addElement(newShape.toString());
I apologize for my poorly formatted question a few moments ago. I have been stuck on this for approximately 4 hours, the last two hours spent searching for answers online. I am now resulting to asking anyone if they see an issue within the code I have.
You don't "add" components a scroll pane. You need to set it's view ports view instead.
Don't do this...
shapeScrollPane.add(shapeList);
Do this...
shapeScrollPane.setViewportView(shapeList);
Check out
How to use Scroll Panes
JScrollPane#setViewportView
Also, this shapeList.setVisibleRowCount(-1) scares me to no end.
Updated
You also don't need to this...
shapeList = new JList<String>(shapeListModel);
shapeList.setModel(shapeListModel);
This is more then sufficient...
shapeList = new JList<String>(shapeListModel);
Updated
Also, if this is the same code that was used in a previously closed question...
This canvas.getGraphics() terrifies me!! If your instructor gave you this code, then they shouldn't be teaching you!