Simplify Switch with multiple variables in Java - java

I have this monster of code, because depending on the length of the list, it is the number of times that I have to add that result to the menu.
Does anyone know how to simplify these entries to the list? I cannot use the same variable since the method overwrites the last input...
//This list receives a list of values
List<LBUResumen> lbu = CargarTabla.cargarTablaLBUResumen();
//This for loop generates a menuitem for each value in the list lbu
for (int a = 0; a < lbu.size(); a++) {
MenuItem menu = null;
String supervisor = lbu.get(a).getSupervisor();
//This is a model of a table, we store a value that helps us
//make reference to another table in the database
modr.setIdArea(lbu.get(a).getIdArea());
//This list saves the results of the query
List<Puesto> lbuP = CargarTabla.cargarTablaPuesto(modr);
//Conditions according to the size of the query
switch (lbuP.size()) {
case 1: {
String puesto = lbuP.get(0).getNombre_Puesto();
int propuestoP = lbu.get(0).getPropuesto();
int propuestoS = lbu.get(a).getPropuesto();
MenuItem submenu1 = new MenuItem(puesto, propuestoP, null);
menu = new MenuItem(supervisor, propuestoS, null,
submenu1);
addMenu(menu);
break;
}
case 2: {
String puesto1 = lbuP.get(0).getNombre_Puesto();
String puesto2 = lbuP.get(1).getNombre_Puesto();
int propuestoP1 = lbu.get(0).getPropuesto();
int propuestoP2 = lbu.get(1).getPropuesto();
int propuestoS = lbu.get(a).getPropuesto();
int propuestoD = lbu.get(a).getDiferencia();
int propuestoP = lbu.get(a).getPlantilla();
int A = lbu.get(a).getTurnoA();
int B = lbu.get(a).getTurnoB();
int C = lbu.get(a).getTurnoC();
int D = lbu.get(a).getTurnoD();
int LV = lbu.get(a).getTurnoLV();
SubMenuItem submenu1 = new SubMenuItem(puesto1, 0, 0, 0,
0, 0, 0, 0, 0, null);
SubMenuItem submenu2 = new SubMenuItem(puesto2, 0, 0, 0,
0, 0, 0, 0, 0, null);
menu = new MenuItem(supervisor, propuestoS, propuestoD, propuestoP,
A, B, C, D, LV,
null, submenu1, submenu2);
addMenu(menu);
break;
}
case 3: {
String puesto1 = lbuP.get(0).getNombre_Puesto();
String puesto2 = lbuP.get(1).getNombre_Puesto();
String puesto3 = lbuP.get(2).getNombre_Puesto();
int propuestoP1 = lbu.get(0).getPropuesto();
int propuestoP2 = lbu.get(1).getPropuesto();
int propuestoP3 = lbu.get(2).getPropuesto();
int propuestoS = lbu.get(a).getPropuesto();
MenuItem submenu1 = new MenuItem(puesto1, propuestoP1, null);
MenuItem submenu2 = new MenuItem(puesto2, propuestoP2, null);
MenuItem submenu3 = new MenuItem(puesto3, propuestoP3, null);
menu = new MenuItem(supervisor, propuestoS, null,
submenu1, submenu2, submenu3);
addMenu(menu);
break;
}
So I wanted to know if it is possible in some way to simplify the statements so that I don't have so many lines of code in the switch,Thanks in advance <3
This is the method that receives the submenus, it makes an instance of itself
private void addMenu(MenuItem... menu) {
for (int i = 0; i < menu.length; i++) {
frm.jPanel1.add(menu[i]);
ArrayList<MenuItem> subMenu = menu[i].getSubMenu();
for (MenuItem m : subMenu) {
addMenu(m);
}
}
frm.jPanel1.revalidate();
}
This is the constructor class to MenuItem
public MenuItem(String menuName, int propuesto, ActionListener act, MenuItem... subMenu) {
initComponents();
lbName.setText(menuName);
lbPropuesto.setText(menuName);
if (act != null) {
this.act = act;
}
this.setSize(new Dimension(Integer.MAX_VALUE, 60));
this.setMaximumSize(new Dimension(Integer.MAX_VALUE, 60));
this.setMinimumSize(new Dimension(Integer.MAX_VALUE, 60));
for (int i = 0; i < subMenu.length; i++) {
this.subMenu.add(subMenu[i]);
subMenu[i].setVisible(false);
}
}

Related

SWT TableItem getText doesn't return what I expect

I want to swap two texts in TableItems. Firstly, I set the text, then I check which TableItems are selected, save them in 2 variables and overwrite them. But I get these strings instead of the message I wanted:
[Lorg.eclipse.swt.widgets.TableItem;#6fadae5d
The part after the # is always different, I guess it's an ID or something but I can't find a solution. Here's the code snippets. groupsList is a String array.
for (int i = 1; i <= logic.amountOfGroups; i++) {
Table table = new Table(shell, SWT.MULTI | SWT.BORDER);
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
for (int j = 0; j < logic.personsInGroup; j++) {
TableItem tableItem_1 = new TableItem(table, SWT.NONE);
tableItem_1.setText(logic.groupsList.get(i - 1)[j]);
}
tableList.add(table);
}
So I wrote the content into the TableItems, then I want to swap them:
swapButton = new Button(shell, SWT.NONE);
swapButton.setText("Swap");
swapButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseDown(MouseEvent e) {
int[] playerIndices = new int[2];
int[] groupIndices = new int[2];
int i = 0;
String toBeSwappedZero = "";
String toBeSwappedOne = "";
for (Table table : tableList) {
if (table.getSelectionCount() == 1) {
if (toBeSwappedZero == "") {
groupIndices[0] = i;
playerIndices[0] = table.getSelectionIndex();
toBeSwappedZero = table.getSelection().toString();
} else {
groupIndices[1] = i;
playerIndices[1] = table.getSelectionIndex();
toBeSwappedOne = table.getSelection().toString();
}
}
if (table.getSelectionCount() == 2) {
playerIndices = table.getSelectionIndices();
groupIndices[0] = i;
groupIndices[1] = i;
toBeSwappedZero = table.getItem(playerIndices[0]).getText();
toBeSwappedOne = table.getItem(playerIndices[1]).getText();
}
i++;
}
System.out.println(toBeSwappedOne);
tableList.get(groupIndices[0]).getItem(playerIndices[0]).setText(toBeSwappedOne);
tableList.get(groupIndices[1]).getItem(playerIndices[1]).setText(toBeSwappedZero);
}
});
Here's the GUI
Take a look these lines in your MouseAdapter:
if (table.getSelectionCount() == 1) {
if (toBeSwappedZero == "") {
// ...
toBeSwappedZero = table.getSelection().toString();
} else {
// ...
toBeSwappedOne = table.getSelection().toString();
}
}
Notice that Table.getSelection() returns an array of TableItem objects. As #greg-449 pointed out, you'll get [Lorg.eclipse.swt.widgets.TableItem;#XXXXXXXX if you call toString() on that array.
In each of those two cases you've already checked that there is only one TableItem selected, so you can safely do table.getSelection()[0] to access that TableItem (Alternatively, you could do table.getItem(table.getSelectionIndex()) after verifying that there is at least one and only one item selected).
In an unrelated if-statement later on, you're correctly getting the TableItem text:
table.getItem(playerIndices[0]).getText();
So instead of using the toString() method on those two lines at the start, you'll want to use getText() as you've done here.

How do I add up the loaded value from a textfile with the new inputed value in the Jtextfield

When I press the load button it displays the values from the reload.txt
public class VotingSystem extends javax.swing.JFrame {
private final JTextField[] textFields;
/**
* Creates new form VotingSystem
*/
public VotingSystem() {
initComponents();
textFields = new JTextField[12];
textFields[0] = koontf;
textFields[1] = baamtf;
textFields[2] = sachitf;
textFields[3] = fakertf;
textFields[4] = phonsekaltf;
textFields[5] = lauretf;
textFields[6] = yeontf;
textFields[7] = aguerotf;
textFields[8] = agnistf;
textFields[9] = lokitf;
textFields[10] = lawliettf;
textFields[11] = ryuzakitf;
} private void loadActionPerformed(java.awt.event.ActionEvent evt) {
int line = 0;
try(Scanner scanner = new Scanner(new File("reload.txt"))){
while(scanner.hasNextLine()){
textFields[line++].setText(scanner.nextLine());
if(line == textFields.length){
break;
}
}
}catch(FileNotFoundException ex){
Logger.getLogger(VotingSystem.class.getName()).log(Level.SEVERE, null, ex);
}
koontf.requestFocus(); // you can only call request focus on one element at a time (it does not make sense to call it on all textfields
}
private void baamtfActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
When I press vote It shoud add up but instead it returns to 1. Any way I can make it add up to the imported value???Below is the code for the Vote Jbutton.
int pick1 = 0, pick2 = 0,pick3 = 0, pick4 = 0,pick5 = 0, pick6 = 0, pick7 = 0, pick8 = 0, pick9 = 0, pick10 = 0, pick11 = 0, pick12 = 0;
private void voteActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if (koonchk.isSelected()){
pick1++;
koontf.setText(Integer.toString(pick1));
}
else if (baamchk.isSelected()){
pick2++;
baamtf.setText(Integer.toString(pick2));
}
if(sachichk.isSelected()){
pick3++;
sachitf.setText(Integer.toString(pick3));
}
else if (fakerchk.isSelected()){
pick4++;
fakertf.setText(Integer.toString(pick4));
}
if (phonsekalchk.isSelected()){
pick5++;
phonsekaltf.setText(Integer.toString(pick5));
}
else if (laurechk.isSelected()){
pick6++;
lauretf.setText(Integer.toString(pick6));
}
if (yeonchk.isSelected()){
pick7++;
yeontf.setText(Integer.toString(pick7));
}
else if (aguerochk.isSelected()){
pick8++;
aguerotf.setText(Integer.toString(pick8));
}
else if (agnischk.isSelected()){
pick9++;
agnistf.setText(Integer.toString(pick9));
}
if (lokichk.isSelected()){
pick10++;
lokitf.setText(Integer.toString(pick10));
}
else if (lawlietchk.isSelected()){
pick11++;
lawliettf.setText(Integer.toString(pick11));
}
else if (ryuzakichk.isSelected()){
pick12++;
ryuzakitf.setText(Integer.toString(pick12));
}
}
The problem lies in the fact that you are initialising all the variables as
int pick1 = 0, pick2 = 0,pick3 = 0, pick4 = 0,pick5 = 0, pick6 = 0, pick7 = 0, pick8 = 0, pick9 = 0, pick10 = 0, pick11 = 0, pick12 = 0;
So the previous values of text that you had loaded are lost. I would suggest that you initialise the variables as:
int pick1 = Integer.parseInt(textFields[1].getText());
int pick2 = Integer.parseInt(textFields[2].getText());
.
.
.
//And so on.
This will ensure that the previous number in the text field stays where it is.
A still better solution would be you could declare an Integer array of variables as pick with size of 12. Like:
int[] pick = new int[12];
Then declare a method that is going to update the text fields with the value of pick like:
public void updateTextFields(){
for(int i = 0; i < 12; i++){
textFields[i].setText(String.valueOf(pick[i])); //corrected the code
}
}
Now in your reading file method instead of
textFields[line++].setText(scanner.nextLine());
use
pick[i++] = Integer.parseInt(scanner.nextLine());
and at last line of the method simply call the previously declared updateTextFields().
Also in the method to vote, remove all the code for textField.setText(). and in the last line simply call the method upadateTextFields(). What I mean by this is:
private void voteActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if (koonchk.isSelected()){
pick1++; //Change to pick[1]++
// koontf.setText(Integer.toString(pick1)); remove
}
else if (baamchk.isSelected()){
pick2++; //change to pick[2]++
// baamtf.setText(Integer.toString(pick2)); remove
}
if(sachichk.isSelected()){
pick3++; //change to pick[3]++
// sachitf.setText(Integer.toString(pick3)); remove
}
else if (fakerchk.isSelected()){
pick4++; //Change to pick[4]++
// fakertf.setText(Integer.toString(pick4)); remove
}
if (phonsekalchk.isSelected()){
pick5++; //Change to pick[5]++
// phonsekaltf.setText(Integer.toString(pick5)); remove
}
else if (laurechk.isSelected()){
pick6++; //Change to pick[6]++
// lauretf.setText(Integer.toString(pick6)); remove
}
if (yeonchk.isSelected()){
pick7++; //Change to pick[7]++
// yeontf.setText(Integer.toString(pick7)); remove
}
else if (aguerochk.isSelected()){
pick8++; //Change to pick[8]++
// aguerotf.setText(Integer.toString(pick8)); remove
}
else if (agnischk.isSelected()){
pick9++; //Change to pick[9]++
//agnistf.setText(Integer.toString(pick9)); remove
}
if (lokichk.isSelected()){
pick10++; //Change to pick[10]++
//lokitf.setText(Integer.toString(pick10)); remove
}
else if (lawlietchk.isSelected()){
pick11++; //Change to pick[11]++
//lawliettf.setText(Integer.toString(pick11)); remove
}
else if (ryuzakichk.isSelected()){
pick12++; //Change to pick[12]++
//ryuzakitf.setText(Integer.toString(pick12)); remove
}
updateTextFields(); //Add this new line.
}

search textfield in tableLayout

I ran out of ideas on how to perform search in table layout using textfield. I just want to match the text of textfield with 1st column text, if it exist, show the entire row containing that text.I have done it in list and table component but in table layout everything i do is just not working. Any help is appreciated.
TableLayout tl1 = new TableLayout(1, 2);
Container containerTableData = new Container(tl1);
for (int i = 1; i < 3; i++) {
Container tableNameDataContainer = new Container(new FlowLayout(Component.CENTER, Component.CENTER));
tableNameData = new TextArea("Table Name " + i);
tableNameDataContainer.add(tableNameData);
Container inaugurationDateDataContainer = new Container(new FlowLayout(Component.CENTER, Component.CENTER));
inaugurationDateData = new TextArea("Inauguration Date 1");
inaugurationDateDataContainer.add(inaugurationDateData);
containerTableData.add(tl1.createConstraint().widthPercentage(50), tableNameDataContainer);
containerTableData.add(tl1.createConstraint().widthPercentage(50), inaugurationDateDataContainer);
containerTableData.revalidate();
}
TextField searchTextField = new TextField();
searchTextField.addDataChangeListener(new DataChangedListener() {
#Override
public void dataChanged(int type, int index) {
String getTextAreaData = tableNameData.getText();
String getTextField = searchTextField.getText();
if (getTextAreaData.startsWith(getTextField)) {
}
}
}
Update 1:
To add black and white strips design to the table as in fig below:
Mycode so far:
for (int i = 1; i < 3; i++) {
Container tableNameDataContainer = new Container(new FlowLayout(Component.CENTER, Component.CENTER));
tableNameData = new TextArea("Table Name " + i);
tableData(tableNameData, i, tableNameDataContainer);
tableNameDataContainer.add(tableNameData);
Container inaugurationDateDataContainer = new Container(new FlowLayout(Component.CENTER, Component.CENTER));
inaugurationDateData = new TextArea("Inauguration Date 1");
tableData(inaugurationDateData, i, inaugurationDateDataContainer);
inaugurationDateDataContainer.add(inaugurationDateData);
containerTableData.add(tl1.createConstraint().widthPercentage(50), tableNameDataContainer);
containerTableData.add(tl1.createConstraint().widthPercentage(50), inaugurationDateDataContainer);
}
method to add desired style
public void tableData(TextArea textAreaName, int i, Container c) {
textAreaName.setName(textAreaName.getText());
c.setName("c" + i);
zeroPaddingMargin(textAreaName);
zeroPaddingMargin(c);
textAreaName.setUIID(textAreaName.getText());
textAreaName.getAllStyles().setFont(Font.createSystemFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_SMALL));
textAreaName.setEditable(false);
textAreaName.setGrowByContent(true);
textAreaName.setGrowLimit(2);
textAreaName.getAllStyles().setBgTransparency(0);
c.getAllStyles().setBgTransparency(255);
textAreaName.getAllStyles().setFgColor(0x000000);
if (i % 2 == 0) {
c.getAllStyles().setBgColor(0xcccccc);
} else {
c.getAllStyles().setBgColor(0xffffff);
}
textAreaName.getAllStyles().setPadding(0, 0, 0, 0);
textAreaName.getAllStyles().setMargin(0, 0, 0, 0);
textAreaName.getAllStyles().setAlignment(Component.CENTER);
}
public void zeroPaddingMargin(Component a) {
a.setUIID("Uiid" + a.getName());
a.getAllStyles().setPadding(0, 0, 0, 0);
a.getAllStyles().setMargin(0, 0, 0, 0);
}
The black and white strip style in table rows appears as abov img at first but all the styles disappears as soon as i search in the textfield. I managed to achieve those styles somehow though i think it is not the standard way to do that. Is there any standard way to achieve that?
Didn't try it but I'm guessing this should work. It will require making containerTableData final:
searchTextField.addDataChangeListener(new DataChangedListener() {
#Override
public void dataChanged(int type, int index) {
String getTextField = searchTextField.getText().toLowerCase();
int counter = 0;
boolean show = false;
for(Component c : containerTableData) {
if(counter % 2 == 0) {
Container cnt = (Container)c;
TextArea ta = (TextArea)cnt.getComponentAt(0);
show = ta.getText().toLowerCase().indexOf(getTextField) > -1);
}
counter++;
c.setHidden(!show);
c.setVisible(show);
}
containerTableData.animateLayout(200);
}
}
Edited the answer to hide/show the entire row. It relies on searching only in the first column and on there being two columns but that should be easily adaptable.

How to call to a list of established objects? (JAVA)

I have this code (and excuse the language) that my friend made for a game we are working on. The code is meant to create a list of possible weapons to pick up throughout the game, however it always returns a null value. So I made a method arms.printAllGuns(), which printed ever gun and then "null" at the very bottom without giving my a null point error(since it was only returning the name). So it seems to successfully establish every object as intended, but it creates an extra null Gun object, and can't properly return any object in the array.
This is giving the null
import java.util.*;
public class Soldier
{
//BASE
private ArrayList <Gun> gunsCarried;
private GunsAvalible arms = new GunsAvalible();
private Armor armor;
private int size;
private int bodyTempature;//1-10
private int health = 100;
private int numberOfSpecials;
public Soldier(int s, int g)
{
Gun temp = arms.get(g);
temp.getGunName();
final int size = s;
}
public void takeDamage(int damage)
{
health -= damage;
}
}
And then here is the List of guns
public class GunsAvalible
{
Gun [] gunsArray = new Gun [40];
public GunsAvalible()
{
//(Name, ClipSize, Power)
gunsArray[0] = new Gun("Hucker", 13, 10);//PISTOL
gunsArray[1] = new Gun("Rafile", 10, 15);//RIFLE
gunsArray[2] = new Gun("Slumper", 14, 14);//PISTOL
gunsArray[3] = new Gun("Normality", 3, 40);//SHOTGUN
gunsArray[4] = new Gun("Feminest Friendly", 1, 1);//TAZER
gunsArray[5] = new Gun("China Man", 32, 5);//MACHINEGUN
gunsArray[6] = new Gun("Bax", 6, 25);//SNIPER
gunsArray[7] = new Gun("Regicidal Tyranus", 7, 20);//SPECIAL
gunsArray[8] = new Gun("Blaking", 12, 15);//RIFLE
gunsArray[9] = new Gun("Olive Branch", 4, 50);//SNIPER
gunsArray[10] = new Gun("DYL-SCHO", 0,0);//SNIPER
gunsArray[11] = new Gun("Forrest Burrner",0,0 );//FLAMETHROWER
gunsArray[12] = new Gun("Sahaka",0,0);//Hose
gunsArray[13] = new Gun("Chirper", 16, 7);//PISTOL
gunsArray[14] = new Gun("Gourd", 1, 100);
gunsArray[15] = new Gun("Fohell", 0, 0);
gunsArray[16] = new Gun("Candle Stick", 0, 0);
gunsArray[17] = new Gun("Rock Wing",0 ,0);
gunsArray[18] = new Gun("Busting Pain", 0 ,0);
gunsArray[19] = new Gun("Wosham's Anahe",0,0);
gunsArray[20] = new Gun("Fucker", 13, 10);//PISTOL
gunsArray[21] = new Gun("Rafiphile", 10, 15);//RIFLE
gunsArray[22] = new Gun("Humper", 14, 14);//PISTOL
gunsArray[23] = new Gun("Reality", 3, 40);//SHOTGUN
gunsArray[24] = new Gun("Dick Frier", 1, 1);//TAZER
gunsArray[25] = new Gun("Yellow River", 32, 5);//MACHINEGUN
gunsArray[26] = new Gun("Bax-Stabber", 6, 25);//SNIPER
gunsArray[27] = new Gun("Regicidal Tyranus II", 7, 20);//SPECIAL
gunsArray[28] = new Gun("Faking", 12, 15);//RIFLE
gunsArray[29] = new Gun("Broken Branch", 4, 50);//SNIPER
gunsArray[30] = new Gun("DYL-DO", 0,0);//SNIPER
gunsArray[31] = new Gun("Worrld Burrner",0,0 );//FLAMETHROWER
gunsArray[32] = new Gun("Water Will",0,0);//Hose
gunsArray[33] = new Gun("Chirper", 16, 7);//PISTOL
gunsArray[34] = new Gun("Budai", 1, 100);//RPG
gunsArray[35] = new Gun("Fovaehan",0,0);
gunsArray[36] = new Gun("Candle Stick",0,0);
gunsArray[37] = new Gun("Rock Wing",0,0);
gunsArray[38] = new Gun("Riding Vain",0,0);
gunsArray[39] = new Gun("IF-EA",0,0);
}
public Gun get(int gunNumber)
{
return gunsArray[gunNumber];
}
}
and lastly the gun class
public class Gun
{
private String name = ("");
private int ammo = 0;
private int clipSize = 0;
private int clip = 0;
private int power = 0;
private Gun [] gunsArray = new Gun [20];
private Gun [] gunsRankIIArray = new Gun [20];
public Gun(String n, int cs, int p)
{
final int clipSize = cs;
clip = 1 + (int)(3.14 * 5 * Math.random());
power = p;
name = n;
if(clip > clipSize)
clip = clipSize;
}
public void ammoPickup(int a)
{
ammo += a;
}
public int fire()
{
if(clip == 0)
{
reload();
return 0;
}
clip--;
int damage = 0;
double critical = Math.random();
if(critical < .5)
{
damage = (int)(power * (1+critical));
}
else
{
damage = power * 2;
}
return damage;
}
public boolean reload()
{
if(ammo > 0)
{
ammo -= clipSize;
clip += clipSize;
return true;
}
else
{
return false;
}
}
public String getGunName()
{
return name;
}
}
I appreciate any help or tips, because I'm sorta at a stand still
I think you're missing
gunsCarried = new ArrayList<>();
gunsCarried.add(temp);
in your Soldier constructor.

How to make TableSorter keep a row in a fixed position?

I have a table and and I use the DefaultTableModel. I implemenmted a TableListener to make sure that there are no empty values in the first column and remove duplicates. Additionally I add an empty row as the last line in the table, so when a user enters a non-existing value there it will be added to the row.
Now I wanted to keep the columns sorted and added a TableRowSorter to my model. But now the problem is that the empty row gets sorted as well. I implemented a Comparator because I thought I could override this by checking for the empty column, but that doesn't work, because I don't know in which direction the sorter currently orders.
Is there a way to do this (Have an empty row as last line always)? Can I get the sorting order somehow? Or do I have to implement a complete model just for this?
I found a solution. Here is the complete class for reference.
public class EnvironmentPanel
extends JPanel
implements Comparator<String>
{
private static final long serialVersionUID = 1L;
private static final String[] mHeader =
{
"Name",
"Value",
};
private JTable mEnvironmentTable = null;
private DefaultTableModel mTableModel = null;
private int mSortOrder = 1;
public EnvironmentPanel()
{
initialize();
}
private void initialize()
{
GridBagLayout gridBagLayout = new GridBagLayout();
setLayout(gridBagLayout);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.insets = new Insets(3, 3, 3, 3);
gbc_scrollPane.weighty = 1.0;
gbc_scrollPane.weightx = 1.0;
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.anchor = GridBagConstraints.NORTHWEST;
gbc_scrollPane.gridx = 0;
gbc_scrollPane.gridy = 0;
add(scrollPane, gbc_scrollPane);
scrollPane.setViewportView(getMEnvironmentTable());
}
private JTable getMEnvironmentTable()
{
if(mEnvironmentTable == null)
{
mEnvironmentTable = new JTable();
mEnvironmentTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
mTableModel = new DefaultTableModel();
mEnvironmentTable.setModel(mTableModel);
for(int i = 0; i < mHeader.length; i++)
mTableModel.addColumn(mHeader[i]);
Object[] row = new Object[mHeader.length];
row[0] = "";
mTableModel.addRow(row);
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>();
mEnvironmentTable.setRowSorter(sorter);
sorter.setModel(mTableModel);
sorter.setComparator(0, this);
sorter.setSortsOnUpdates(true);
sorter.addRowSorterListener(new RowSorterListener()
{
#Override
public void sorterChanged(RowSorterEvent oEvent)
{
if(oEvent.getType().equals(Type.SORT_ORDER_CHANGED))
mSortOrder *= (-1);
}
});
mTableModel.addTableModelListener(new TableModelListener()
{
public void tableChanged(TableModelEvent oEvent)
{
onTableChanged(oEvent);
}
});
}
return mEnvironmentTable;
}
/**
* The table will always have an empty line at the end. If a new name is entered
* the value is taken and a new line will be added.
* Entries with an empty name column will be removed.
*
* The name must be unique.
*
* #param oEvent
*/
private void onTableChanged(TableModelEvent oEvent)
{
String s = null;
Map<String, Integer>nmap = new HashMap<String, Integer>();
for(int i = mTableModel.getRowCount()-2; i >= 0; i--)
{
s = (String)mTableModel.getValueAt(i, 0);
if(s == null || s.equals(""))
{
mTableModel.removeRow(i);
continue;
}
// If we found an entry with the same name, we remove the one
// that is later in the list.
if(nmap.containsKey(s))
{
int pos = nmap.get(s);
mTableModel.removeRow(pos);
}
// Add the latest row to the map.
nmap.put(s, i);
}
int n = mTableModel.getRowCount();
if(n > 0)
{
s = (String)mTableModel.getValueAt(n-1, 0);
if(s != null && s.equals("") == false)
{
Object[] row = new Object[mHeader.length];
row[0] = "";
mTableModel.addRow(row);
}
else
{
s = (String)mTableModel.getValueAt(n-1, 1);
if(s != null && s.equals("") == false)
mTableModel.setValueAt(null, n-1, 1);
}
}
}
#Override
public int compare(String oLeft, String oRight)
{
if(oLeft.equals(""))
return -1*mSortOrder;
if(oRight.equals(""))
return 1*mSortOrder;
return oLeft.compareTo(oRight);
}
}

Categories

Resources