I have googled on this and there is nothing on the internet similar to what I'm trying to do. I'm actually now thinking if I'm tackling this issue in the right way as I have spent so much of time to resolve it.
Here is what I'm trying to do. I have a JFrame on which I have a JTabbedMenu assigned to the left of the frame. When I click on the menu item it displays the relevant JPanel on the right.
To create the tabs on the left hand menu, I loop through a HashMap like this:
for (Entry<String, AbstractBasePanelView> menu : menuItems.entrySet()) {
addTab(menu.getKey(), menu.getValue());
}
the menuItems HashMap is constructed like this:
for (Menu menu : Menu.values()) {
menuItems.put(menu.getName(), Menu.lookup(menu.getName()).getInstance());
}
where Menu is an Enum class and the getInstance() method returns a new instance of the class extending the AbstractBasePanelView. The AbstractBasePanelView class extends JPanel.
Now my question is how can I add JScrollPane to each panel on the right. So that it displays a vertical scrollbar only for the JPanel where elements of that Panel stretch beyond the dimension of the JFrame.
I thought I could do something like this when I create my tabs:
JScrollPane[] scrollPane = new JScrollPane[menuItems.size()];
int i = 0;
for (Entry<String, AbstractBasePanelView> menu : menuItems.entrySet()) {
scrollPane[i].getViewport().add(menu.getValue());
addTab(menu.getKey(), scrollPane[i]);
++i;
}
But I get a runtime exception as soon as I run my application:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
The exception is thrown on the line when I add the JPanel: scrollPane[i].getViewport().add(menu.getValue());
when I don't use an array of JScrollPane, I don't get any NullPointerException.
The below works fine but doesn't solve my purpose because the left menu appears fine but the JPanels are all empty.
for (Entry<String, AbstractBasePanelView> menu : menuItems.entrySet()) {
JScrollPane scrollPane = new JScrollPane();
scrollPane.getViewport().add(menu.getValue());
addTab(menu.getKey(), scrollPane);
}
Any idea what I'm doing wrong here and how I can resolve it? A code snippet would be highly appreciated.
Related
Example:
I made a table, and I want a search box for each column. I hid the column titles with this code:
table.setTableHeader(null);
And put a textField and Button to each top of columns. Now I can search for each different column, but I can't sort the items.
I want to sort the column items when I click the top button. I tried some thing but it is so complex for a beginner as me.
Is there any way to do it? Or all the thing i tried useless and there is much easy way to do it? I hope explained it right.
Note :
I have found this code.I dont even know if it does what i need. I did try it but getting error.
/** Default sort behaviour, plus every third click removes the sort. */
private final class CustomSorter extends MouseAdapter {
#Override public void mouseClicked(MouseEvent aEvent) {
int columnIdx = fTable.getColumnModel().getColumnIndexAtX(aEvent.getX());
//build a list of sort keys for this column, and pass it to the sorter
//you can build the list to fit your needs here
//for example, you can sort on multiple columns, not just one
List<RowSorter.SortKey> sortKeys = new ArrayList<>();
//cycle through all orders; sort is removed every 3rd click
SortOrder order = SortOrder.values()[fCountClicks % 3];
sortKeys.add(new RowSorter.SortKey(columnIdx, order));
fSorter.setSortKeys(sortKeys);
++fCountClicks;
}
private int fCountClicks;
}
}
And did try this and getting same error.
btnNewButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
table.getRowSorter().toggleSortOrder(1);
}
});
Error:Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
This is the code: Code
This is the what program looks like : Picture
In the ActionListener of your JButton you can try sorting the column with code like:
table.getRowSorter().toggleSortOrder(columnIndex);
This should allow you to click the button to reverse the sort order each time it is clicked.
Edit:
As I said in my comment you need to learn how to solve a NullPointerException.
The stack trace when I run the code states:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at frame1$2.actionPerformed(frame1.java:83)
Line 83 is:
table.getRowSorter().toggleSortOrder(0);
So you have two variables at that statement:
table
table.getRowSorter()
It is up to you to determine which variable is null
So you add debug code before that statement:
System.out.println( table );
System.out.println( table.getRowSorter() );
If you do you will see that table.getRowSorter() returns null.
So now you can ask a proper question like:
"Why does table.getRowSorter() return null?"
The answer is simple you didn't set the properties of the table to do sorting.
This is easily done by adding:
table.setModel(model);
table.setAutoCreateRowSorter(true); // added
In the future do some basic debugging BEFORE asking a question. You can't code if you don't know the basics of debugging code.
My original answered assumed you new how to sort columns in a table when using the table header and you just wanted to know how to use a separate button. That is why a "MRE" should be posted with EVERY question so we don't have to guess what your code is really doing.
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.
So I have this project,
the source code is here.
When you run the project and goto Processing, there is a jcombobox there that is suppose to have an addActionListener.
p_customer_list = new JComboBox<>(customers_name);
pp_customer_list.setPreferredSize(new Dimension(360, 35));
panel_processing_header.add(pp_customer_list);
//pp_customer_list.addActionListener(this);
pp_customer_list.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
JComboBox tmpBox = (JComboBox) e.getSource();
int selected = tmpBox.getSelectedIndex();
pp_refresh_data(selected);
}
});
This is what I have so far, its suppose to find the selected index when the value of the combobox changes and pass it to pp_refresh_data() but for some reason it does not run (I tried putting a JOptionPane to see when the code is executed, and its only executed once when the program runs.)
Hard to tell from just a partial code snippet, but do you have 2 combos, one named "p_customer_list" and another named "pp_customer_list"?
This could be your problem. You may be adding the listener to the wrong combo, or you may be adding the wrong combo to your panel, or maybe you don't need two, or maybe...
Again, it's hard to tell from just a snippet.
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!
I have a JCheckBox defined as:
JCheckBox NewCB = new JCheckbox();
NewCB.setSelected(false);
NewCB.setMnemonic(KeyEvent.VK_C);
NewCB.addItemListener(this);
This Check Box is using an ItemLisener:
public void itemStateChanged(ItemEvent e) {
Object source = e.getItemSelectable();
if(source == NewCB) {TEST = "SELECTED"; System.out.println(TEST);}
}
I launch a JFrame when the program starts. If I add this CheckBox to the frame, it works fine. If I open a second JFrame, and add this Check Box to the 2nd frame, and the Object Source no longer works. Is there some other definition I need to make to get the Object source to read the check box name for any open frames?
First of all, you can't add a component to more than one parent; I'm not sure that's your problem though.
The thing you're calling the "name" of the checkbox isn't a property of the checkbox, but rather a property of a variable that points to the checkbox. The difference is important, because there could be many such variables. The checkbox doesn't know anything about the variables that point to it.
Given that, how do we solve the problem? You can set the "action command" of the checkbox, and then check that:
NewCB.setActionCommand("Fred");
// ...
if ("Fred".equals(((JCheckBox) source).getActionCommand())))
// ...