Resizing an image from a database using Scalr - resize

I am trying to resize an image from by db. Below is the webservlet where I get the blob from my database and try to resize it using UtilImage.
Problem: The image i tried to resize isn't shown in my browser and my console hasn't listed any stacktraces. After the UtilImage.resize() call, which returns a new BufferedImage, the imageType has changed from 5 to 1.
#WebServlet("/images")
public class BildService extends HttpServlet {
private static final long serialVersionUID = 1L;
#EJB
private LesenService lesenService;
private Veranstaltung veranstaltung;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Integer veranstaltungId = Integer.parseInt(request.getParameter("id"));
veranstaltung = lesenService.getVeranstaltungByVeranstaltungId(veranstaltungId);
if (veranstaltung == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
response.setContentType(veranstaltung.getFormat());
OutputStream os = response.getOutputStream();
byte[] img = UtilImage.resizeScalr(veranstaltung.getBild(), veranstaltung.getFormat());
os.write(img);
}
}
This is my UtilImage class:
public class UtilImage {
public static final byte[] resizeScalr(byte[] img, String type) {
if (img != null) {
BufferedImage bImage = getBufferedImage(img);
double scaleFactor = getScaleFactor(bImage.getWidth(), UtilKonstanten.PICTURE_WIDTH);
int targetWidth = (int) (scaleFactor * bImage.getWidth());
int targetHeight = (int) (scaleFactor * bImage.getHeight());
// return getByteArray(Scalr.resize(bImage, targetWidth,
// targetHeight), type);
return getByteArray(Scalr.resize(bImage, Scalr.Method.BALANCED, targetWidth, targetHeight), type);
}
return null;
}
private static final double getScaleFactor(int width, int wishwidth) {
return (double) wishwidth / width;
}
private static final BufferedImage getBufferedImage(byte[] array) {
InputStream is = new ByteArrayInputStream(array);
BufferedImage img;
try {
img = ImageIO.read(is);
return img;
} catch (IOException e) {
// TODO
e.printStackTrace();
}
return null;
}
private static final byte[] getByteArray(BufferedImage img, String type) {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(img, type, os);
byte[] byteArray = os.toByteArray();
os.close();
return byteArray;
} catch (IOException e) {
// TODO
e.printStackTrace();
}
return null;
}
}
Thanks a lot for your help!

Unfortunately I didn't post the answer to this question.
As far as I know it was something with the type, that wasn't saved correctly and in cause of that the browser wasn't able to resolve the type.
--> "img" instead of "application/img" or something like that.

Related

Sending and receiving data to serialport

I have a Magellan scanner/scale. It is connected to my pc through rs232. When i send the command "S11" on ComTestSerial programm, i receive the weight. However, with my vb.net code i cannot receive a response. As a result i get a TimeoutException.
The file that sends the command:
Dim yy() As Byte = System.Text.Encoding.ASCII.GetBytes("S11" & vbLf)
Me.Port.Send(yy)
Dim input = Me.Port.Receive
Return Me.ExtractMeasurement(input)
The file that writes and reads from serialport:
public void Send(byte b)
{
byte[] bytes = new byte[1] { b };
this.Send(bytes);
}
public void Send(byte[] bytes)
{
this.Send(bytes, 0, bytes.Length);
}
public void Send(byte[] bytes, int offset, int count)
{
this._port.Write(bytes, offset, count);
}
public byte[] Receive()
{
int attempts = 1;
Boolean dataReceived;
try
{
while (!this.DataReceived && this._port.BytesToRead == 0 && attempts < 15)
{
System.Threading.Thread.Sleep(100);
attempts++;
}
}
finally
{
dataReceived = this.DataReceived;
this.DataReceived = false;
}
if (!dataReceived && this._port.BytesToRead == 0) throw new TimeoutException();
byte[] bytes = new byte[this._port.BytesToRead];
this._port.Read(bytes, 0, bytes.Length);
return bytes;
}
I can't understand why BytesToRead and BytesToWrite stays 0 after this._port.Write(bytes, offset, count);
Here is the serialportconfig.xml file
<PortName>COM3:</PortName>
<BaudRate>Baud_9600</BaudRate>
<DataBits>Eight</DataBits>
<Parity>None</Parity>
<StopBits>One</StopBits>
<FlowCtrl>CtsRts</FlowCtrl>
Update: i figure out that if i send vbCr instead of vbLf i sometimes get the right response back. But the problem is SOMETIMES. I sometimes get a TimeoutException and sometimes get the response. I am using an adaptor from RS232 to usb. Could this be the problem?
Here is all the code related to the serial:
public class SerialPortAdapter
{
#region Private Members
private System.IO.Ports.SerialPort _port;
private Object _dataReceivedLock = new Object();
private Boolean _dataReceived;
#endregion
#region Constructor/Destructor
public SerialPortAdapter(SerialCnfg config)
{
if (string.IsNullOrEmpty(config.PortName))
{
this._port = new System.IO.Ports.SerialPort();
}
else
{
string portName = config.PortName.TrimEnd(':');
this._port = new System.IO.Ports.SerialPort(portName);
}
this._port.WriteTimeout = 2000;
this._port.ReadTimeout = 2000;
this._port.SetBaudRate(config.BaudRate);
this._port.SetDataBits(config.DataBits);
this._port.SetStopBits(config.StopBits);
this._port.SetHandshake(config.FlowCtrl);
this._port.SetParity(config.Parity);
}
~SerialPortAdapter()
{
this.Close();
this._port = null;
}
#endregion
#region Public Properties
public Boolean IsOpen
{
get { return this._port.IsOpen; }
}
public System.Text.Encoding Encoding
{
get { return this._port.Encoding; }
set { this._port.Encoding = value; }
}
#endregion
#region Public Methods
public void Open()
{
if (this.IsOpen) return;
this.DataReceived = false;
this.AttachPortHandlers();
this._port.Open();
}
public void Close()
{
if (!this.IsOpen) return;
this._port.Close();
this.DetachPortHandlers();
this.DataReceived = false;
}
public void Send(byte b)
{
byte[] bytes = new byte[1] { b };
this.Send(bytes);
}
public void Send(byte[] bytes)
{
this.Send(bytes, 0, bytes.Length);
}
public void Send(byte[] bytes, int offset, int count)
{
this._port.Write(bytes, offset, count);
}
public byte[] Receive()
{
int attempts = 1;
Boolean dataReceived;
try
{
while (!this.DataReceived && this._port.BytesToRead == 0 && attempts < 15)
{
System.Threading.Thread.Sleep(100);
attempts++;
}
}
finally
{
dataReceived = this.DataReceived;
this.DataReceived = false;
}
if (!dataReceived && this._port.BytesToRead == 0) throw new TimeoutException();
byte[] bytes = new byte[this._port.BytesToRead];
this._port.Read(bytes, 0, bytes.Length);
return bytes;
}
#endregion
#region Private Properties
private Boolean DataReceived
{
get
{
lock (this._dataReceivedLock)
{
return this._dataReceived;
}
}
set
{
lock (this._dataReceivedLock)
{
this._dataReceived = value;
}
}
}
#endregion
#region Initialization/Finalization
private void AttachPortHandlers()
{
this._port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.OnDataReceived);
}
private void DetachPortHandlers()
{
this._port.DataReceived -= new System.IO.Ports.SerialDataReceivedEventHandler(this.OnDataReceived);
}
#endregion
#region Event Handlers
private void OnDataReceived(Object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
this.DataReceived = true;
}
#endregion
}
Based on the code you posted, you are attempting to handle your own timeout exception. SerialPort class has its own built in timeout (ie, ReadTimeout, WriteTimeout) which you set in the constructor. Therefore you do not need the other methods to handle the timeout as it would be redundant. Moreover, stay away from the System.Threading.Sleep method as it can be a huge waste of resources Why is Thread.Sleep so harmful.
I suggest that you refactor your code a bit to get rid of the self imposed Throw TimeoutException.
Here is just a suggestion:
public byte[] Receive()
{
try
{
byte[] bytes = new byte[]{};
while(_port.BytesToRead > 0)
{
bytes = new byte[this._port.BytesToRead];
this._port.Read(bytes, 0, bytes.Length);
}
}
catch (TimeoutException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
this.DataReceived = false;
}
return bytes;
}
It appears that Magellan can work if you resend the command to request the weight(S11). So the solution for me was whenever i have _port.bytesToRead=0 after this._port.Write(bytes, offset, count) , then i resend the command S11. Eventually, it will response the right result.

Extract images of signatures contained in a pdf file with iText7

I am wondering how we can use ITEXT7 to extract image info associated to digital signatures. I know there have been similar questions asked in the past, but they were mostly around ITEXT5, which is quite different from the ITEXT7 after all the updates and modifications to the software.
You can extract the image from a signature appearance using low-level API.
Complete Java code:
private void saveImageFromSignature(PdfDocument document, String fieldName) throws IOException {
PdfAcroForm acroForm = PdfAcroForm.getAcroForm(document, false);
PdfDictionary xObject = acroForm.getField(name)
.getWidgets()
.get(0)
.getNormalAppearanceObject()
.getAsDictionary(PdfName.Resources)
.getAsDictionary(PdfName.XObject)
.getAsStream(new PdfName("FRM"))
.getAsDictionary(PdfName.Resources)
.getAsDictionary(PdfName.XObject);
PdfStream stream = xObject.getAsStream(new PdfName("Im1"));
PdfImageXObject image = new PdfImageXObject(stream);
BufferedImage result = createImageFromBytes(image.getImageBytes());
//pdf allows using masked image in the signature appearance
PdfStream maskStream = (PdfStream) stream.getAsStream(PdfName.SMask);
if (maskStream != null) {
PdfImageXObject maskImage = new PdfImageXObject(maskStream);
BufferedImage maskBimage = createImageFromBytes(maskImage.getImageBytes());
String fileMask = String.format(getOutputFolder() + "/file_mask_%d.%s",
image.getPdfObject().getIndirectReference().getObjNumber(),
image.identifyImageFileExtension());
ImageIO.write(maskBimage,
image.identifyImageFileExtension(),
new File(fileMask));
//the mask defines an alfa channel
Image transpImg = transformToTransperency(maskBimage);
result = applyTransperency(result, transpImg);
}
String filenameComp = String.format(getOutputFolder() + "/file_comp_%d.%s",
image.getPdfObject().getIndirectReference().getObjNumber(),
image.identifyImageFileExtension());
ImageIO.write(result,
image.identifyImageFileExtension(),
new File(filenameComp));
document.close();
}
private Image transformToTransperency(BufferedImage bi) {
ImageFilter filter = new RGBImageFilter() {
#Override
public int filterRGB(int x, int y, int rgb) {
return (rgb << 8) & 0xFF000000;
}
};
ImageProducer ip = new FilteredImageSource(bi.getSource(), filter);
return Toolkit.getDefaultToolkit().createImage(ip);
}
private BufferedImage applyTransperency(BufferedImage bi, Image mask) {
BufferedImage dest = new BufferedImage(
bi.getWidth(), bi.getHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = dest.createGraphics();
g2.drawImage(bi, 0, 0, null);
AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.DST_IN, 1.0F);
g2.setComposite(ac);
g2.drawImage(mask, 0, 0, null);
g2.dispose();
return dest;
}
Upd: This works for a very limited number of cases. Thanks for #mkl.
First of all, thank you for the proposals which personally guided me.
After several tries, here is the code that worked for me:
public void extract(String inputFilename, String fieldName) throws IOException {
try (PdfDocument document = new PdfDocument(new PdfReader(inputFilename))){
PdfAcroForm acroForm = PdfAcroForm.getAcroForm(document, false);
final PdfFormField signatorySignature1 = acroForm.getField(fieldName);
final PdfDictionary appearanceDic = signatorySignature1.getPdfObject().getAsDictionary(PdfName.AP);
final PdfStream normalAppearance = appearanceDic.getAsStream(PdfName.N);
final PdfDictionary ressourceDic = normalAppearance.getAsDictionary(PdfName.Resources);
PdfResources resources = new PdfResources(ressourceDic);
final ImageRenderInfo imageRenderInfo = extractImageRenderInfo(normalAppearance.getBytes(), resources);
Files.write(
Path.of(inputFilename + "_" + fieldName + "_" + System.currentTimeMillis() + ".png"),
imageRenderInfo.getImage().getImageBytes());
} catch (Exception e) {
e.printStackTrace();
}
}
public ImageRenderInfo extractImageRenderInfo(byte[] contentBytes, PdfResources pdfResource) {
MyLocationExtractionStrategy strategy = new MyLocationExtractionStrategy();
PdfCanvasProcessor parser = new PdfCanvasProcessor(strategy, new HashMap<>());
parser.processContent(contentBytes, pdfResource);
return strategy.getImageRenderInfo();
}
class MyLocationExtractionStrategy implements ILocationExtractionStrategy {
private ImageRenderInfo imageRenderInfo;
#Override public Collection<IPdfTextLocation> getResultantLocations() {
return null;
}
#Override public void eventOccurred(IEventData iEventData, EventType eventType) {
if (eventType.equals(EventType.RENDER_IMAGE)) {
imageRenderInfo = (ImageRenderInfo)iEventData;
}
}
#Override public Set<EventType> getSupportedEvents() {
return null;
}
public ImageRenderInfo getImageRenderInfo() {
return this.imageRenderInfo;
}
}

When merging PDF files using itext the result pdf show 0 bytes in android studio

My code is here; I was selecting PDF files from a SD card or internal phone memory using the showFileChooser() method then from onActivityResult(), the files go to mergePdfFiles(View view) method, and from there the files go to createPdf(String[] srcs).
Here is the complete code of my activity:
//Below is onCreate();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mergedpdf);
adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, locations);
// public void fileSelected(File file ) {
// locations.add(file.toString());
// adapter.notifyDataSetChanged();
// }
NewText = (TextView)findViewById(R.id.textView);
AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
listView = (ListView)findViewById(R.id.list_items);
btn = (ImageView) findViewById(R.id.imageView8);
btnconvert = (ImageView) findViewById(R.id.imageView11);
btnconvert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// btTag=((Button)v).getTag().toString();
try {
createPdf( locations);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Toast.makeText(Mergedpdf.this, "button clicked", Toast.LENGTH_SHORT).show();
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// btTag=((Button)v).getTag().toString();
showFileChooser();
NewText.setText("Below Files are Selected");
}
});
}
//this is mergedfiles();
public void mergePdfFiles(View view){
Toast.makeText(Mergedpdf.this, "merge function", Toast.LENGTH_SHORT).show();
try {String[] srcs= new String[locations.size()];
for(int i = 0;i<locations.size();i++) {
srcs[i] = locations.get(i);
}
// String[] srcs = {txt1.getText().toString(), txt2.getText().toString()};
createPdf(srcs);
}catch (Exception e){e.printStackTrace();}
}
//This method create merged pdf file
public void createPdf (String[] srcs) {
try {
// Create document object
File docsFolder = new File(Environment.getExternalStorageDirectory() + "/Merged-PDFFiles");
if (!docsFolder.exists()) {
docsFolder.mkdir();
Log.i(TAG, "Created a new directory for PDF");
}
Date date = new Date();
#SuppressLint("SimpleDateFormat") final String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date);
Document document = new Document();
// pdfCopy = new File(docsFolder.getAbsolutePath(),pdf+"Images.pdf");
// Document document = new Document();
//PdfWriter.getInstance(document, output);
// Create pdf copy object to copy current document to the output mergedresult file
PdfCopy copy = new PdfCopy(document, new FileOutputStream(docsFolder + "/" + timeStamp +"combine.pdf"));
Toast.makeText(Mergedpdf.this, "merged pdf saved", Toast.LENGTH_SHORT).show();
// Open the document
document.open();
PdfReader pr;
int n;
for (int i = 0; i < srcs.length; i++) {
// Create pdf reader object to read each input pdf file
pr = new PdfReader(srcs[i].toString());
// Get the number of pages of the pdf file
n = pr.getNumberOfPages();
for (int page = 1; page <= n; page++) {
// Import all pages from the file to PdfCopy
copy.addPage(copy.getImportedPage(pr, page));
}
}
document.close(); // close the document
} catch (Exception e) {
e.printStackTrace();
}
}
//below is showfilechooser(); method
private void showFileChooser () {
Log.e("AA", "bttag=" + btTag);
String folderPath = Environment.getExternalStorageDirectory() + "/";
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
Uri myUri = Uri.parse(folderPath);
intent.setDataAndType(myUri, "application/pdf");
Intent intentChooser = Intent.createChooser(intent, "Select a file");
startActivityForResult(intentChooser,PICKFILE_RESULT_CODE);
}
//below is onActivityResult(); method
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
if (requestCode == PICKFILE_RESULT_CODE) {
if (resultCode == RESULT_OK) {
String FilePath = data.getData().getPath();
locations.add(FilePath);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.listview,locations);
listView.setAdapter(adapter);
}
}
}
}
//And my declared variables before oncreate().
public com.itextpdf.text.Document Document;
public PdfCopy Copy;
public ByteArrayOutputStream ms;
TextView NewText;
private TextView txt1;
private Button bt1, bt2,bt3;
private Handler handler;
ListView listView;
ArrayList<String> locations = new ArrayList<>();
ArrayAdapter<String> adapter;
ImageView btn, btnconvert, btn3;
private static final String TAG = "PdfCreator";
private final int PICKFILE_RESULT_CODE=10;
private String btTag = "";

React-Native can't use jni library correctly

I'm using nanohttpd in my native java code. When I use it normally everything looks good, but when I use jni library methods it does not work.
my app uses nanohttpd to make stream for mediaPlayer.
native methods:
public native String LH();
public native int P();
public native String EngineGS(Context context);
public native byte[] OGB(byte[] inputBuff);
variables :
private MediaPlayer mp;
private HTTPServer encryptServer;
nanohttpd class:
public class HTTPServer extends NanoHTTPD {
public HTTPServer(int port) throws IOException {
super(port);
start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
}
#Override
public Response serve(IHTTPSession session) {
Response response = null;
try {
InputStream inputStream = new FileInputStream("/sdcard/Download/" + "encrypted.mp3");
byte[] encryptedInputByteArray = IOUtils.toByteArray(inputStream);
byte[] decryptedByteArray = OGB(encryptedInputByteArray);
inputStream = new ByteArrayInputStream(decryptedByteArray);
int totalLength = inputStream.available();
String requestRange = session.getHeaders().get("range");
if (requestRange == null) {
response = NanoHTTPD.newFixedLengthResponse(Response.Status.OK, "audio/mpeg", inputStream, totalLength);
} else {
Matcher matcher = Pattern.compile("bytes=(\\d+)-(\\d*)").matcher(requestRange);
matcher.find();
long start = 0;
try {
start = Long.parseLong(matcher.group(1));
} catch (Exception e) {
e.printStackTrace();
}
inputStream.skip(start);
long restLength = totalLength - start;
response = NanoHTTPD.newFixedLengthResponse(Response.Status.PARTIAL_CONTENT, "audio/mpeg", inputStream, restLength);
String contentRange = String.format("bytes %d-%d/%d", start, totalLength, totalLength);
response.addHeader("Content-Range", contentRange);
}
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
play method:
#ReactMethod
public void play() {
mp.getCurrentPosition();
try {
if (encryptServer == null) {
encryptServer = new HTTPServer(P());
}
Uri uri = Uri.parse(LH() + ":" + encryptServer.getListeningPort());
mp.reset();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(getReactApplicationContext(), uri);
mp.prepare();
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
I do not know where the problem is.
Errors:
I think the problem comes from here:
No Content Provider: http://localhost:8080

Java initialization question

JPanel p2 = new JPanel(new GridLayout(6,1));
ButtonGroup tubtype = new ButtonGroup();
JRadioButton roundrButton = new JRadioButton("Round", true);
tubtype.add(roundrButton);
JRadioButton ovalrButton = new JRadioButton("Oval", false);
tubtype.add(ovalrButton);
calcButton = new JButton("Calculate Volume");
exitButton = new JButton("Exit");
hlength = new JTextField(5);
hwidth = new JTextField(5);
hdepth = new JTextField(5);
hvolume = new JTextField(5);
lengthLabel = new JLabel("Enter the tub's length (ft):");
widthLabel = new JLabel("Enter the tub's width (ft):");
depthLabel = new JLabel("Enter the tub's depth (ft):");
volumeLabel = new JLabel("The tub's volume (ft^3):");
p2.add(roundrButton);
p2.add(ovalrButton);
p2.add(lengthLabel);
p2.add(hlength);
p2.add(widthLabel);
p2.add(hwidth);
p2.add(depthLabel);
p2.add(hdepth);
p2.add(volumeLabel);
p2.add(hvolume);
p2.add(calcButton);
p2.add(exitButton);
tab.addTab( "Hot Tubs", null, p2, " Panel #1" );
calcButtonHandler2 ihandler =new calcButtonHandler2();
calcButton.addActionListener(ihandler);
exitButtonHandler ghandler =new exitButtonHandler();
exitButton.addActionListener(ghandler);
FocusHandler hhandler =new FocusHandler();
hlength.addFocusListener(hhandler);
hwidth.addFocusListener(hhandler);
hdepth.addFocusListener(hhandler);
hvolume.addFocusListener(hhandler);
// add JTabbedPane to container
getContentPane().add( tab );
setSize( 550, 500 );
setVisible( true );
}
public class calcButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
DecimalFormat num =new DecimalFormat(",###.##");
double sLength, sWidth, sdepth, Total;
sLength = Double.valueOf(plength.getText());
sWidth =Double.valueOf(pwidth.getText());
sdepth =Double.valueOf(pdepth.getText());
if(e.getSource() == pcalcButton) {
Total = sLength * sWidth * sdepth;
pvolume.setText(num.format(Total));
try{
String value=pvolume.getText();
File file = new File("output.txt");
FileWriter fstream = new FileWriter(file,true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("Length= "+sLength+", Width= "+sWidth+", Depth= "+sdepth+" so the volume of Swimming Pool is "+value);
out.newLine();
out.close();
}
catch(Exception ex){}
}
}
}
public class calcButtonHandler2 implements ActionListener {
public void actionPerformed(ActionEvent g) {
DecimalFormat num =new DecimalFormat(",###.##");
double cLength, cWidth, cdepth, Total;
cLength = Double.valueOf(hlength.getText());
cWidth = Double.valueOf(hwidth.getText());
cdepth = Double.valueOf(hdepth.getText());
try
{
AbstractButton roundrButton;
if(roundrButton.isSelected())
{
Total = Math.PI * Math.pow(cLength / 2.0, 2) * cdepth;
}
else
{
Total = Math.PI * Math.pow(cLength * cWidth, 2) * cdepth;
}
hvolume.setText(""+num.format(Total));
}
catch(Exception ex){}
}
}
}
class exitButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent g){
System.exit(0);
}
}
class FocusHandler implements FocusListener {
public void focusGained(FocusEvent e) {
}
public void focusLost(FocusEvent e) {
}
public static void main( String args[] )
{
Final tabs = new Final();
tabs.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
I am getting an error that says my roundrButton may not have been initialized. Please help.
The problem is these lines here:
try
{
AbstractButton roundrButton;
if(roundrButton.isSelected())
{
You're declaring a variable called roundrButton, and then attempting to call .isSelected() on it. You never assign anything to roundButton, though, so it is going to be null.
It seems like you might want to be referring to the roundrButton that you declared earlier. Have you considered making it a field of your class?
The error happens here:
try {
AbstractButton roundrButton;
if (roundrButton.isSelected()) {
You declared a variable called roundrButton but did not assign any object to it.
Then you called a method on, well, who knows? There is no object on which to call the method, because the variable roundrButton never received a value.
I guess your problem is in method actionPerformed of class calcButtonHandler2 :
try {
AbstractButton roundrButton;
if(roundrButton.isSelected())
roundrButton is indeed not initialized and it will lead to a NullPointerException at runtime.