How to write File name to a label - file

I would like to have the name of the chosen file from JFileChooser from the JMenuItem and show it in a JLabel when a JCheckBoxMenuItem is checked. I am able to choose the file but can't have its name. The important bits of the code is shown below,
private JFileChooser fc;
private JLabel currentDocPanel;
public JCheckBoxMenuItem viewOpt;
public String getFileName() {
String str = fc.getSelectedFile().getName();
return str;
}
private class ActionEventHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == viewOpt) {
if (currentDocPanel.isVisible()) {
currentDocPanel = new JLabel(getFileName());
currentDocPanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
add(currentDocPanel, BorderLayout.SOUTH);
}
}
}

Thank you for your reply..I tried the code you provided but did not see the file name on the label. I changed my code a bit and I am able to see the text within the label, but the problem is that I can only see it when I hold the window and expand it with mouse. I call this function in the actionPerformed when JCheckBoxMenuItem is clicked. This is what I did;
public void getFileName() throws Exception {
System.out.println("getFileName");
try {
File getfile = fc.getSelectedFile();
boolean check = getfile.exists();
if (check) {
System.out.println("File Name: " + getfile.getName()); //to check
String nameToLabel = "File Name: " + getfile.getName();
currentDocPanel = new JLabel(nameToLabel);
//currentDocPanel.setText(String.valueOf(fc.getSelectedFile()));
currentDocPanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
add(currentDocPanel, BorderLayout.SOUTH);
}
} catch (Exception e) {
}
}

Fairly simple:
currentDocPanel.setText(String.valueOf(Your_JFileChooser.getSelectedFile()));
Should work. Here, I just get the selectedFile of the JFC and transform the output as String.

Related

The codeScanner doesn't work when it's used with my application

I have a problem with the code scanner, I use this lib https://github.com/codenameone/cn1-codescan in my application to scan the barcode. I work on an android application and I try to scan code_128 code format.
public class ScanQr extends Form {
final Container cnt = this;
public ScanQr(Form parent){
this.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
ButtonGroup bg = new ButtonGroup();
final RadioButton qr = new RadioButton("QR Code");
final RadioButton bar = new RadioButton("Bar Code");
bg.add(qr);
bg.add(bar);
this.addComponent(new Label("Code Type"));
this.addComponent(qr);
this.addComponent(bar);
Button scanBtn = new Button("Scan Code");
scanBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(qr.isSelected()){
CodeScanner.getInstance().scanQRCode(new ScanResult() {
public void scanCompleted(String contents, String formatName, byte[] rawBytes) {
//barCode.setText("Bar: " + contents);
cnt.addComponent(new Label(contents));
cnt.revalidate();
}
public void scanCanceled() {
cnt.addComponent(new Label("cancelled"));
}
public void scanError(int errorCode, String message) {
cnt.addComponent(new Label("err " + message));
}
});
}else{
CodeScanner.getInstance().scanBarCode(new ScanResult() {
public void scanCompleted(String contents, String formatName, byte[] rawBytes) {
//barCode.setText("Bar: " + contents);
cnt.addComponent(new Label(contents));
cnt.revalidate();
}
public void scanCanceled() {
cnt.addComponent(new Label("cancelled"));
}
public void scanError(int errorCode, String message) {
cnt.addComponent(new Label("err " + message));
}
});
}
}
});
if (CodeScanner.isSupported()) {
this.addComponent(scanBtn);
} else {
this.addComponent(new SpanLabel("Sorry. Codescanner not supported on this platform"));
}
}
}
First it installs Barcode Scanner+ Simple if it's not installed then when this app is used with my application, it takes a lot of time to find and display the information scanned on the barcode or it doesn't find anything but when I just use Barcode Scanner+ Simple alone, it works very well, I don't have any problem with it.
I don't understand where's the problem since I use the same codescanner application but in 2 differents contexts, when it's launched alone and when it's launched with my application.
You need to try narrowing the types that are scanned to get a better result e.g. do this some time before invoking the scan:
Display.getInstance().setProperty("android.scanTypes", "CODE_128");

How can I raise a GUI event in WCF?

Suppose, I want to add a button in a WinForms WCF client such that, whenever a user pushes the button, a specific client on the other side would see a MessageBox saying Hello [user].
I have modified this program to have a DataGridView instead of the big TextBox. I also tried to raise the event up on double click of a DataGridView row.
I have done something like the following:
[ServiceContract(SessionMode = SessionMode.Allowed)]
public interface ICallableForm
{
[OperationContract]
void ShowMessage();
}
[DataContract]
public class ChatUser
{
//...
[DataMember]
public ICallableForm WinForm { get; set; }
public override string ToString()
{
return this.Username;
}
}
class MainForm : Form, ICallableForm
{
// ...
public void ShowMessage()
{
MessageBox.Show("Hello " + ___clientUser.Username);
}
// ...
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
int rowIndex = e.RowIndex;
ChatMessage message = dataGridView1.Rows[rowIndex+1].Tag as ChatMessage;
ChatUser user = message.User;
ICallableForm form = user.WinForm;
form.ShowMessage();
string str = string.Empty;
}
And, getting the following error:

How to generate report (Extent Report) in Specflow Project

Currently I am working designing my project in Specflow. I want to implement some reporting to my project. Currently I have created one separate .cs file and kept all my report setting. But these steps are getting unreachable. Can anyone please guide me how i can design my flow and how i can integrate with the feature file?
Please find the below BaseReport.cs file and my Step definition file.
namespace Verivox.CommonLib
{
public class BaseReport
{
public static ExtentReports extent;
public static ExtentTest test;
[BeforeFeature()]
public static void BasicSetUp()
{
//string pth = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
string pth = System.IO.Directory.GetCurrentDirectory();
string actualPath = pth.Substring(0, pth.LastIndexOf("bin"));
string projectPath = new Uri(actualPath).LocalPath;
string reportPath = projectPath + "Reports\\" + FeatureContext.Current.FeatureInfo.Title + ".html";
extent = new ExtentReports(reportPath, true);
extent.LoadConfig(projectPath + "CommonLib\\Extent-config.xml");
}
[BeforeScenario()]
public static void BeforeScenarioSetUp()
{
test = extent.StartTest("Running Scenario -->" + ScenarioContext.Current.ScenarioInfo.Title);
}
[AfterScenario()]
public static void AfterScnario()
{
if (ScenarioContext.Current.TestError != null)
{
var error = ScenarioContext.Current.TestError;
var errormessage = "<pre>" + error.Message + "</pre>";
//Add capture screen shot line here
extent.EndTest(test);
}
}
[AfterFeature()]
public static void EndReport()
{
extent.Flush();
// extent.Close();
}
}
}
Steps
namespace Verivox.Steps
{
[Binding]
class CalculationVerificationSteps
{
[Given(#"I have navigate to Home Page")]
public void GivenIHaveNavigateToHomePage()
{
Browser.Current.Navigate().GoToUrl(ConfigurationManager.AppSettings["seleniumBaseUrl"]);
PropertyCollection.currentPage = new HomePage();
Browser.Current.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
}
[Given(#"Navigate to Mobile Calculator under All Comparison Section")]
public void GivenNavigateToMobileCalculatorUnderAllComparisonSection()
{
PropertyCollection.currentPage.As<HomePage>().MainCompItemClick("Telekommunikation");
PropertyCollection.currentPage.As<HomePage>().SubCompItemClick("Mobilfunk");
PropertyCollection.currentPage.As<HomePage>().CalculatorLinkClick("Mobiles Internet");
}
[Then(#"Mobile Calculator should appear")]
public void ThenMobileCalculatorShouldAppear()
{
Assert.IsTrue(PropertyCollection.currentPage.As<HomePage>().IsMobileInternetCalcExistance());
}
[Then(#"(.*) option and (.*) option is selected by default\.")]
public void ThenMonatsflatrateOptionAndSIMOptionIsSelectedByDefault_(string defaultTarif, string hardware)
{
try
{
Assert.IsTrue(PropertyCollection.currentPage.As<HomePage>().VerifyMobiIntSelectedItem(defaultTarif));
string colorCode = PropertyCollection.currentPage.As<HomePage>().VerifySelectedHardWare();
Assert.AreEqual(0, string.Compare("rgba(253, 138, 2, 1)", colorCode, StringComparison.OrdinalIgnoreCase));
}
catch (Exception)
{
BaseReport.test.Log(LogStatus.Fail, "Default selections are incorrect.");
}
}
You are missing the Binding- attribute on the BaseReport class. Without that, the hooks defined there are not called.

Set ComboBoxCell in TableView JavaFX

i followed the instructions from this question to set a ComboBoxCell in the TableView of my application. (How to put ComboBoxTableCell in a TableView?)
The declaration of the Cell works fine, but the comboBox doesn't appear in the table. I think it's like this, because only col1 and col2 are in my model. col3 is not written in my table-entry after the database connection.
I don't know how to takte the ComboBox in the TableView and need your help.
Here is my code:
controller:
package controller;
imports
public class main_controller implements Initializable {
private ObservableList<model> tableData = FXCollections.observableArrayList();
private ObservableList<String> cbValues = FXCollections.observableArrayList("1", "2", "3");
#FXML
private TableView<model> ComboTable;
#FXML
private TableColumn<model, String> col1;
#FXML
private TableColumn<model, String> col2;
#FXML
private TableColumn<model, String> col3;
public main_controller() {
}
#Override
public void initialize(URL location, ResourceBundle resources) {
tableData.clear();
col1.setCellValueFactory(new PropertyValueFactory<model, String>("rCol1"));
col2.setCellValueFactory(new PropertyValueFactory<model, String>("rCol2"));
col3.setCellFactory(ComboBoxTableCell.forTableColumn(new DefaultStringConverter(), cbValues));
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("*** Loaded Oracle-Driver ***");
} catch (ClassNotFoundException e1) {
System.out.println("Driver-Loading failed.");
e1.printStackTrace();
}
try {
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:lukas/1234#10.140.79.56:1521:OTTO");
Statement statement = conn.createStatement();
ResultSet resultset = statement.executeQuery("SELECT NUMMER, DATEN1, DATEN2 FROM LUKAS order by NUMMER");
String Daten1 = "empty";
String Daten2 = "empty";
// Zum einfügen kann man später auf diese Variable zurückgreifen.
int columnIndex;
System.out.println("*** Connected with Database ***");
while (resultset.next()) {
columnIndex = resultset.getInt("NUMMER");
System.out.println("Tabellenindex der Zeile:\t" + columnIndex);
Daten1 = resultset.getString("DATEN1");
Daten2 = resultset.getString("DATEN2");
System.out.println("Daten1:\t " + Daten1 + "\t\t\tDaten2: " + Daten2);
**model entry = new model(Daten1, Daten2);
tableData.add(entry);**
}
System.out.println("*** Database data saved to Observable List named 'data' ***");
ComboTable.setItems(tableData);
System.out.println("*** Table Items setted ***");
statement.close();
} catch (SQLException e) {
System.out.println("Login fehlgeschlagen.");
e.printStackTrace();
}
}
}
model:
package model;
import javafx.beans.property.SimpleStringProperty;
public class model {
private final SimpleStringProperty rCol1;
private final SimpleStringProperty rCol2;
public model(String sCol1, String sCol2) {
this.rCol1 = new SimpleStringProperty(sCol1);
this.rCol2 = new SimpleStringProperty(sCol2);
}
public String getRCol1() {
return rCol1.get();
}
public void setRCol1(String set) {
rCol1.set(set);
}
public String getRCol2() {
return rCol2.get();
}
public void setRCol2(String set) {
rCol2.set(set);
}
}
The application looks like this right now:
Picture
Hope you can help me!
The declaration of the Cell works fine, but the comboBox doesn't
appear in the table.
The combobox of ComboBoxTableCell will be appeared when this cell is in edit mode. To do that you need to set the tableview to editable and then double click the over mentioned cell.
The quote from the ComboBoxTableCell javadoc:
By default, the ComboBoxTableCell is rendered as a Label when not
being edited, and as a ComboBox when in editing mode. The ComboBox
will, by default, stretch to fill the entire table cell.

How to delete item/file from a listView and external SD?

I'm new to Java and coding all together so I have hit a wall with my code. I've read nearly every post on this subject and still can't grasp it. Can somebody help?
Here is my code and permissions are already set in the manifest. Basically when I try to delete an item/file from a listview using onLongClick a file deletes, just not the one I want. The item first on the list deletes every attempt. I'm not sure how to solve this. I know that the code is half right considering the file does delete from the directory on the SD and from the listview. Getting the right file to delete is the problem. Any help would be appreciated.
public class ReadNoteMenu extends ActionBarActivity {
public static final String EXTRA_MESSAGE = "com.m4tchb0x87.rhinote.MESSAGE";
Context context;
public ReadNoteMenu() {
this.context = this;
}
ArrayAdapter mArrayAdapter;
ListView listView;
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
this.setContentView(R.layout.activity_read_note_menu);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
listView = (ListView) this.findViewById(R.id.readListView);
String fileNames[] = new File(String.valueOf(Environment.getExternalStorageDirectory().getAbsolutePath()) + "/Rhinote").list();
mArrayAdapter = new ArrayAdapter<>(this, R.layout.list_item_1, fileNames);
listView.setAdapter(mArrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView adapterView, View view, int i, long l) {
String string = (String) listView.getItemAtPosition(i);
Intent intent = new Intent(ReadNoteMenu.this, (Class) ReadNote.class);
intent.putExtra(EXTRA_MESSAGE, string);
ReadNoteMenu.this.startActivity(intent);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView adapterView, final View view, int position, long l) {
ContextThemeWrapper CTW = new ContextThemeWrapper( context, R.style.ADM_theme);
MaterialDialogCompat.Builder MDM1 = new MaterialDialogCompat.Builder(CTW);
MDM1.setMessage("Edit or delete file?");
MDM1.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int i) {
ContextThemeWrapper CTW = new ContextThemeWrapper( context, R.style.ADM_theme);
MaterialDialogCompat.Builder MDM2 = new MaterialDialogCompat.Builder(CTW);
MDM2.setMessage("Confirm delete file?");
MDM2.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int i) {
String str = (String) listView.getItemAtPosition(position);
Log.d(str,"Deleted" );
new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/RhiNote" + "/" + str).delete();
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_deleted,
(ViewGroup) findViewById(R.id.toast_layout_root_deleted));
TextView text = (TextView) layout.findViewById(R.id.text_deleted);
text.setText("Note deleted!");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.TOP, 250, 25);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
ReadNoteMenu.this.finish();
ReadNoteMenu.this.startActivity(ReadNoteMenu.this.getIntent());
}
});
MDM2.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int which) {
ReadNoteMenu.this.startActivity(ReadNoteMenu.this.getIntent());
}
});
MDM2.show();
}
});
MDM1.setNegativeButton("Edit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int which) {
ReadNoteMenu.this.startActivity(ReadNoteMenu.this.getIntent());
}
});
MDM1.show();
return true;
}
});
}
}
I figured out where I went wrong after a little debugging. It seems that the problem was that I hadn't declared the onItemLongClick int position final.
public boolean onItemLongClick(AdapterView adapterView, final View view, final int position, long l)

Resources