How to disable JButton in the particular row in the JTable - swing

I'm struggling with a at the first sight simple problem (and probably it is so...) - I have to disable certain button in the JTable upon value in one of the cells within the same row.
Below is my inner class for button rendering and editing:
private class CellButton {
class ButtonsPanel extends JPanel {
public JButton jbutton = new JButton("Accept!!");
public ButtonsPanel() {
super();
setOpaque(true);
jbutton.setFocusable(false);
jbutton.setRolloverEnabled(false);
jbutton.setSize(122, 30);
jbutton.setFont(new java.awt.Font("Tahoma", 3, 12));
jbutton.setForeground(new java.awt.Color(0, 102, 102));
add(jbutton);
}
private class ButtonsRenderer extends ButtonsPanel implements TableCellRenderer {
ButtonsPanel bp;
public ButtonsRenderer() {
super();
}
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
this.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
Object o = table.getModel().getValueAt(row, 8);
bp = (ButtonsPanel) o;
if (jTable5.getValueAt(row, 3).equals("NORMALNA")) {
bp.jbutton.setEnabled(false);
}
return this;
}
}
private class ButtonsEditor extends ButtonsPanel implements TableCellEditor {
ButtonsPanel bp;
public ButtonsEditor(final JTable table, final String tableName) {
super();
//DEBUG: view button click -> control key down + edit button(same cell) press -> remain selection color
MouseListener ml = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
ButtonModel m = ((JButton) e.getSource()).getModel();
if (m.isPressed() && table.isRowSelected(table.getEditingRow()) && e.isControlDown()) {
setBackground(table.getBackground());
}
}
};
jbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int row = table.convertRowIndexToModel(table.getEditingRow());
Object o = table.getModel().getValueAt(row, 0);
fireEditingStopped();
//update info status
setDmlUpdateStatusPrejeteInfo();
jDialog2.requestFocus();
}
});
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
fireEditingStopped();
}
});
}
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
this.setBackground(table.getSelectionBackground());
Object o = table.getModel().getValueAt(row, 8);
bp = (ButtonsPanel) o;
if (jTable5.getValueAt(row, 3).equals("NORMALNA")) {
bp.jbutton.setEnabled(false);
}
return this;
}
#Override
public Object getCellEditorValue() {
return "";
}
transient protected ChangeEvent changeEvent = null;
#Override
public boolean isCellEditable(EventObject e) {
return true;
}
#Override
public boolean shouldSelectCell(EventObject anEvent) {
return true;
}
#Override
public boolean stopCellEditing() {
fireEditingStopped();
return true;
}
#Override
public void cancelCellEditing() {
fireEditingCanceled();
}
#Override
public void addCellEditorListener(CellEditorListener l) {
listenerList.add(CellEditorListener.class, l);
}
#Override
public void removeCellEditorListener(CellEditorListener l) {
listenerList.remove(CellEditorListener.class, l);
}
public CellEditorListener[] getCellEditorListeners() {
return listenerList.getListeners(CellEditorListener.class);
}
protected void fireEditingStopped() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == CellEditorListener.class) {
// Lazily create the event:
if (changeEvent == null) {
changeEvent = new ChangeEvent(this);
}
((CellEditorListener) listeners[i + 1]).editingStopped(changeEvent);
}
}
}
protected void fireEditingCanceled() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == CellEditorListener.class) {
// Lazily create the event:
if (changeEvent == null) {
changeEvent = new ChangeEvent(this);
}
((CellEditorListener) listeners[i + 1]).editingCanceled(changeEvent);
}
}
}
}
public ButtonsRenderer br() {
return new ButtonsRenderer();
}
public ButtonsEditor be(JTable jTable, String tableName) {
return new ButtonsEditor(jTable, tableName);
}
}

a) it's better not to call a Jbutton in the name Jbutton, it's just confusing
b) there are many way to disable a jbutton (make it disappear, remove it, resize it...) but the best one is probably this:
Jbutton.setEnabled(false);
c) I think you can use this very useful guide: http://www.macs.hw.ac.uk/guidebook/?name=JButton&page=1

Related

how to add ( admob ) Interstitial ads to libgdx game and what activity to use?

I followed google guide:
updated build.gradle dependencies
updated AndroidManifest.xml
updated the AndroidLauncher and tried banner ads first
from libgdx wiki https://libgdx.com/wiki/third-party/admob-in-libgdx
#Override public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the layout
RelativeLayout layout = new RelativeLayout(this);
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Create the libGDX View
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
View gameView = initializeForView(new mygame(), config);
// Create and setup the AdMob view
AdView adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111"); // Put in your secret key here
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
// Add the libGDX view
layout.addView(gameView);
// Add the AdMob view
RelativeLayout.LayoutParams adParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
adParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layout.addView(adView, adParams);
// Hook it all up
setContentView(layout);
}}
but I cant figure out how to do the same for Interstitial ads
i tried adding adscontroller interface
public interface AdsController {
public void loadInterstitialAd();
public void showInterstitialAd();
}
and updating AndroidLauncher
public class AndroidLauncher extends AndroidApplication implements AdsController {
InterstitialAd mInterstitialAd;
private static final String TAG = "Androidlauncher";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// // Create the layout
RelativeLayout layout = new RelativeLayout(this);
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Create the libGDX View
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
View gameView = initializeForView(new mygame(this), config);
layout.addView(gameView);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {}
});
AdRequest adRequest = null;
InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
Log.i(TAG, "onAdLoaded");
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
Log.d(TAG, loadAdError.toString());
mInterstitialAd = null;
}
});
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
#Override
public void onAdClicked() {
// Called when a click is recorded for an ad.
Log.d(TAG, "Ad was clicked.");
}
#Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
// Set the ad reference to null so you don't show the ad a second time.
Log.d(TAG, "Ad dismissed fullscreen content.");
mInterstitialAd = null;
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when ad fails to show.
Log.e(TAG, "Ad failed to show fullscreen content.");
mInterstitialAd = null;
}
#Override
public void onAdImpression() {
// Called when an impression is recorded for an ad.
Log.d(TAG, "Ad recorded an impression.");
}
#Override
public void onAdShowedFullScreenContent() {
// Called when ad is shown.
Log.d(TAG, "Ad showed fullscreen content.");
}
});
loadInterstitialAd();
}
#Override
public void loadInterstitialAd() {
AdRequest adRequest = new AdRequest.Builder().build();
}
#Override
public void showInterstitialAd() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(mInterstitialAd!=null) {
mInterstitialAd.show();
}
else loadInterstitialAd();
}
});
}
}
InterstitialAd.show(MyActivity.this); require activity but libgdx doesn't work like that(I think?)
every code I found is no longer useful because google updated Admob
AndroidApplication extends Activity, so for interstitials you can just pass in a reference to the application, eg InterstitialAd.show(this);
I did something very similar to get interstitials working in my project. I use Ironsource but the process should be very similar. First, I defined an AdManager interface:
public interface AdManager {
/**
* Show a rewarded video ad
*/
void showRewardedVideo();
/**
* Called on app pause
*/
void onPause();
/**
* Called on app resume
*/
void onResume();
/**
* Attempts to show an interstitial ad
*
* #param onSuccess
* #param onFailed
*/
void showInterstitial(Listener onSuccess, Listener onFailed);
/**
* Called every frame, for any extra work that might need to be done
*
* #param deltaTime
*/
void update(float deltaTime);
}
Following that, you can implement your platform's ad provider:
public class AndroidAdManager implements AdManager, RewardedVideoListener, InterstitialListener, OfferwallListener {
private OnlineRPG game;
private boolean videoAvailable;
private Listener onInterstitialSuccess;
private Listener onInterstitialFailed;
private float timeSinceAd;
public AndroidAdManager(Activity activity, Gamegame) {
this.game = game;
this.activity = activity;
IronSource.setRewardedVideoListener(this);
IronSource.setInterstitialListener(this);
IronSource.setOfferwallListener(this);
IronSource.init(activity, "whatever");
IronSource.shouldTrackNetworkState(activity, true);
IronSource.loadInterstitial();
IntegrationHelper.validateIntegration(activity);
}
#Override
public void showRewardedVideo() {
if (IronSource.isRewardedVideoPlacementCapped(REWARDED_VIDEO_PLACEMENT_NAME)) {
Log.i(TAG, "Rewarded video placement is capped");
return;
}
IronSource.showRewardedVideo(REWARDED_VIDEO_PLACEMENT_NAME);
}
#Override
public void onPause() {
IronSource.onPause(activity);
}
#Override
public void onResume() {
IronSource.onResume(activity);
}
#Override
public void showInterstitial(Listener onSuccess, Listener onFailed) {
if (timeSinceAd < INTERSTITIAL_MIN_PERIOD || true) {
onFailed.invoke();
return;
}
this.onInterstitialSuccess = onSuccess;
this.onInterstitialFailed = onFailed;
IronSource.showInterstitial(INTERSTITIAL_PLACEMENT_NAME);
}
#Override
public void update(float deltaTime) {
timeSinceAd += deltaTime;
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoAdClosed() {
}
#Override
public void onRewardedVideoAvailabilityChanged(boolean b) {
Log.i(TAG, "onRewardedVideoAvailabilityChanged: " + b);
videoAvailable = b;
}
#Override
public void onRewardedVideoAdStarted() {
}
#Override
public void onRewardedVideoAdEnded() {
}
#Override
public void onRewardedVideoAdRewarded(Placement placement) {
}
#Override
public void onRewardedVideoAdShowFailed(IronSourceError ironSourceError) {
}
#Override
public void onRewardedVideoAdClicked(Placement placement) {
}
#Override
public void onInterstitialAdReady() {
}
#Override
public void onInterstitialAdLoadFailed(IronSourceError ironSourceError) {
if (onInterstitialFailed != null) {
Gdx.app.postRunnable(new Runnable() {
#Override
public void run() {
onInterstitialFailed.invoke();
onInterstitialFailed = null;
}
});
}
}
#Override
public void onInterstitialAdOpened() {
Log.i(TAG, "Interstitial Ad Opened");
}
#Override
public void onInterstitialAdClosed() {
Log.i(TAG, "Interstitial Ad Closed");
if (onInterstitialSuccess != null) {
Gdx.app.postRunnable(new Runnable() {
#Override
public void run() {
timeSinceAd = 0;
onInterstitialSuccess.invoke();
onInterstitialSuccess = null;
}
});
}
IronSource.loadInterstitial();
}
#Override
public void onInterstitialAdShowSucceeded() {
}
#Override
public void onInterstitialAdShowFailed(IronSourceError ironSourceError) {
Log.e(TAG, ironSourceError.getErrorMessage());
if (onInterstitialFailed != null) {
Gdx.app.postRunnable(new Runnable() {
#Override
public void run() {
onInterstitialFailed.invoke();
onInterstitialFailed = null;
}
});
}
}
#Override
public void onInterstitialAdClicked() {
}
#Override
public void onOfferwallAvailable(boolean b) {
}
#Override
public void onOfferwallOpened() {
}
#Override
public void onOfferwallShowFailed(IronSourceError ironSourceError) {
}
#Override
public boolean onOfferwallAdCredited(int i, int i1, boolean b) {
return false;
}
#Override
public void onGetOfferwallCreditsFailed(IronSourceError ironSourceError) {
}
#Override
public void onOfferwallClosed() {
}
}
Lastly, in your AndroidLauncher you can create your AndroidAdManager, giving it a reference to your game/activity.
public class AndroidLauncher extends AndroidApplication {
private Game game;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
game = new Game();
game.setAdManager(new AndroidAdManager(this, game));
game.setPermissionManager(new AndroidPermissionManager(this, game));
initialize(game, config);
}
#Override
protected void onPause() {
super.onPause();
game.getAds().onPause();
}
#Override
protected void onResume() {
super.onResume();
game.getAds().onResume();
}
}
I hope this helps in your project!

D/Volley: [1] 5.onErrorResponse: Product

How do I insert data from MySQL into Gridview on Fragments? I've tried it with a coding method used for Activity. I've changed a lot but it's still wrong. This is my coding:
/**
* A simple {#link Fragment} subclass.
*/
public class Product extends Fragment implements
SwipeRefreshLayout.OnRefreshListener {
GridView grid_product;
SwipeRefreshLayout swipe;
List<ProductData> newsList = new ArrayList<ProductData>();
private static final String TAG = Product.class.getSimpleName();
private static String url_list = Server.URL + "news.php?offset=";
private int offSet = 0;
int no;
ProductAdapter adapter;
public static final String TAG_NO = "no";
public static final String TAG_ID = "id";
public static final String TAG_JUDUL = "judul";
public static final String TAG_TGL = "tgl";
public static final String TAG_ISI = "isi";
public static final String TAG_GAMBAR = "gambar";
Handler handler;
Runnable runnable;
public Product() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_product, container, false);
swipe = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_layout);
grid_product = (GridView) view.findViewById(R.id.grid_product);
setProduct();
return view;
}
private void setProduct(){
adapter = new ProductAdapter(getActivity(), newsList);
grid_product.setAdapter(adapter);
grid_product.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//pindah activity
startActivity(new Intent(
getActivity(), DetailActivity.class
));
}
});
I don't know where the mistake is:
swipe.setOnRefreshListener(this);
swipe.post(new Runnable() {
#Override
public void run() {
swipe.setRefreshing(true);
newsList.clear();
adapter.notifyDataSetChanged();
callNews(0);
}
}
);
grid_product.setOnScrollListener(new AbsListView.OnScrollListener() {
private int currentVisibleItemCount;
private int currentScrollState;
private int currentFirstVisibleItem;
private int totalItem;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
this.currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
this.totalItem = totalItemCount;
}
private void isScrollCompleted() {
if (totalItem - currentFirstVisibleItem == currentVisibleItemCount
&& this.currentScrollState == SCROLL_STATE_IDLE) {
swipe.setRefreshing(true);
handler = new Handler();
runnable = new Runnable() {
public void run() {
callNews(offSet);
}
};
handler.postDelayed(runnable, 3000);
}
}
});
}
#Override
public void onRefresh() {
newsList.clear();
adapter.notifyDataSetChanged();
callNews(0);
}
I don't know where the mistake is:
private void callNews(int page){
swipe.setRefreshing(true);
// Creating volley request obj
JsonArrayRequest arrReq = new JsonArrayRequest(url_list + page,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
ProductData news = new ProductData();
no = obj.getInt(TAG_NO);
news.addId(obj.getString(TAG_ID));
news.addJudul(obj.getString(TAG_JUDUL));
if (obj.getString(TAG_GAMBAR) != "") {
news.addGambar(obj.getString(TAG_GAMBAR));
}
news.addDatetime(obj.getString(TAG_TGL));
news.addIsi(obj.getString(TAG_ISI));
// adding news to news array
newsList.add(news);
if (no > offSet)
offSet = no;
Log.d(TAG, "offSet " + offSet);
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}
swipe.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
swipe.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(arrReq);
}
}

How to detect the end of input in Jsch?

I'm using Jsch in my program.
I'd like to display a directory that an user currently working on.
So, instead of displaying uid, I would like to show a directory such as, "[/home/user/abc] <user command input>".
My idea on this is sending pwd after every command from an user and parsing the output. But the problem is that I don't know how to parse it from inputstream. How to determine the input boundary between pwd and a user command?
public class TextFieldStreamer extends InputStream implements ActionListener
{
private JTextField tf;
private String str = null;
private int pos = 0;
private boolean finish = false;
public TextFieldStreamer(JTextField jtf)
{
tf = jtf;
}
public void close()
{
finish = true;
try
{
super.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
// gets triggered everytime that "Enter" is pressed on the textfield
public void actionPerformed(ActionEvent e)
{
enterAction();
}
public void enterAction()
{
str = tf.getText();
str += "\n";
pos = 0;
}
#Override
public int read()
{
// test if the available input has reached its end
// and the EOS should be returned
if (str != null && pos == str.length())
{
str = null;
// this is supposed to return -1 on "end of stream"
// but I'm having a hard time locating the constant
return java.io.StreamTokenizer.TT_EOF;
}
while (!finish && (str == null || pos >= str.length()))
{
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
return str.charAt(pos++);
}
}
 
public class TextAreaOutputStream extends OutputStream
{
JTextArea textArea;
public TextAreaOutputStream(JTextArea textArea)
{
this.textArea = textArea;
}
public void write(int b) throws IOException
{
write(new byte[] { (byte) b }, 0, 1);
}
public void write(byte[] b, int off, int len) throws IOException
{
final String text = new String(b, off, len, "UTF-8");
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
textArea.append(text);
}
});
}
}

TableModelListener of JTable doesn't fire an event while editing a cell

I have added the following JTable.
public final class EmployeeApp extends JPanel implements ActionListener, TableModelListener
{
private static JTable myTable;
private static JButton btnDelete;
public EmployeeApp()
{
CountryDAO countryDAO=new CountryDAO();
myTable = new JTable(new CountryAbstractTableModel(countryDAO.getList()));
JScrollPane myPane = new JScrollPane(myTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
add(myPane);
myTable.setPreferredScrollableViewportSize(new Dimension(1000, 200));
((CountryAbstractTableModel)myTable.getModel()).addTableModelListener(this);//<---
//Added TableModelListener.
}
#Override
public void tableChanged(TableModelEvent e)
{
int row = e.getFirstRow();
int column = e.getColumn();
CountryAbstractTableModel model = (CountryAbstractTableModel)e.getSource();
Object data = model.getValueAt(row, column);
System.out.println("The tableChanged() method called."); // This is never be seen on the console.
}
}
When a cell is edited, the tableChanged() method should be invoked but it never gets called.
I have extended AbstractTableModel as follows.
package admin.model;
import entity.Country;
import java.util.Iterator;
import java.util.List;
import javax.swing.table.AbstractTableModel;
public final class CountryAbstractTableModel extends AbstractTableModel
{
private List<Country> countries;
public CountryAbstractTableModel(List<Country> countries)
{
this.countries = countries;
}
#Override
public void setValueAt(Object value, int rowIndex, int columnIndex)
{
if(value instanceof Country)
{
Country newCountry=(Country) value;
Country oldCountry = countries.get(rowIndex);
switch (columnIndex)
{
case 2:
oldCountry.setCountryName(newCountry.getCountryName());
break;
case 3:
oldCountry.setCountryCode(newCountry.getCountryCode());
//break;
}
fireTableCellUpdated(rowIndex, columnIndex);
}
}
#Override
public Object getValueAt(int rowIndex, int columnIndex)
{
Country country = countries.get(rowIndex);
switch (columnIndex)
{
case 0:
return rowIndex+1;
case 1:
return country.getCountryId();
case 2:
return country.getCountryName();
case 3:
return country.getCountryCode();
}
return "";
}
#Override
public int getRowCount()
{
return countries.size();
}
#Override
public int getColumnCount()
{
return 4;
}
public void add(Country country)
{
int size = countries.size();
countries.add(country);
fireTableRowsInserted(size, size);
}
public void remove(List<Long>list)
{
Iterator<Country> iterator = countries.iterator();
while(iterator.hasNext())
{
Country country = iterator.next();
Iterator<Long> it = list.iterator();
while(it.hasNext())
{
if(country.getCountryId().equals(it.next()))
{
iterator.remove();
int index = countries.indexOf(country);
fireTableRowsDeleted(index, index);
break;
}
}
}
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex)
{
return columnIndex>1?true:false;
}
}
In which the setValueAt() method is called when the return key is pressed after editing a cell. Therefore, the tableChanged() method should be called after fireTableCellUpdated() gets called.
Since the first two columns are not editable, there is no need to set the values for them.
Why isn't the tableChanged() method invoked?
Unless you have specifically set a dedicated Country editor for that column, your test value instanceof Country is likely to be false. Most likely value is actually a String. Your setValueAt method should rather look like this:
#Override
public void setValueAt(Object value, int rowIndex, int columnIndex)
{
if(value instanceof String)
{
Country country = countries.get(rowIndex);
String newValue = (String) value;
switch (columnIndex)
{
case 2:
country.setCountryName(newValue); break;
case 3:
country.setCountryCode(newValue); break;
}
fireTableCellUpdated(rowIndex, columnIndex);
}
}
Of course, if the type of countryName and countryCode is not String, you should return appropriate values for the method TableModel.getColumnClass and test for appropriate types in setValueAt

Change Background color of leaf of Tree

Want to change color of only leaf of tree on one particular condition.
if (l_sel_node_object.getIsEnabled().trim().equalsIgnoreCase("N"))
defaultTreeCellRenderer.setBackgroundSelectionColor(Color.red);
but it is changing background of each selected node.Can anyone please help me out.
Only tested on Metal Look and Feel:
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
public class MainPanel {
public JPanel makeUI() {
JTree tree = new JTree();
tree.setCellRenderer(new RedTreeCellRenderer());
JPanel p = new JPanel(new BorderLayout(5, 5));
p.add(new JScrollPane(tree));
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new MainPanel().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
//*
class RedTreeCellRenderer extends DefaultTreeCellRenderer {
#Override public Component getTreeCellRendererComponent(
JTree tree, Object value, boolean isSelected,
boolean expanded, boolean leaf, int row, boolean hasFocus) {
JComponent c = (JComponent)super.getTreeCellRendererComponent(
tree, value, isSelected, expanded, leaf, row, hasFocus);
if(isSelected) {
c.setForeground(getTextSelectionColor());
if (leaf && value.toString().equalsIgnoreCase("red")) {
//<strong>
c.setOpaque(true);
//</strong>
c.setBackground(Color.RED);
} else {
c.setOpaque(false);
c.setBackground(getBackgroundSelectionColor());
}
} else {
c.setOpaque(false);
c.setForeground(getTextNonSelectionColor());
c.setBackground(getBackgroundNonSelectionColor());
}
return c;
}
}
/*/
class RedTreeCellRenderer2 extends DefaultTreeCellRenderer {
#Override public Component getTreeCellRendererComponent(
JTree tree, Object value, boolean isSelected,
boolean expanded, boolean leaf, int row, boolean hasFocus) {
JComponent c = (JComponent)super.getTreeCellRendererComponent(
tree, value, isSelected, expanded, leaf, row, hasFocus);
if(isSelected) {
if(leaf) {
setParticularCondition(value.toString());
}
c.setForeground(getTextSelectionColor());
c.setBackground(getBackgroundSelectionColor());
} else {
c.setForeground(getTextNonSelectionColor());
c.setBackground(getBackgroundNonSelectionColor());
}
return c;
}
boolean particularCondition = false;
private void setParticularCondition(String str) {
particularCondition = str.equalsIgnoreCase("red");
}
#Override public Color getBackgroundSelectionColor() {
if(particularCondition) return Color.RED;
else return super.getBackgroundSelectionColor();
}
}
//*/