separate two sets of code - java

How to separate the components from the sql method? I need to get this set of code separated from the rest. I am having difficulty because it linked.
Component droplabel = new DropTargetTextArea("test", "testing");
JLabel cellLabel = new JLabel(icon);
JPanel cellPanel = new JPanel(new BorderLayout());
cellPanel.add(cellLabel, BorderLayout.NORTH);
cellPanel.add(droplabel, BorderLayout.CENTER);
gridPanel.add(cellPanel);
////full code
connection = getConnection();
try {
statement = (PreparedStatement) connection
.prepareStatement("select image from image");
result = statement.executeQuery();
while (result.next()) {
byte[] image = null;
image = result.getBytes("image");
Image img = Toolkit.getDefaultToolkit().createImage(image);
ImageIcon icon = new ImageIcon(img);
Component droplabel = new DropTargetTextArea("test", "testing");
JLabel cellLabel = new JLabel(icon);
JPanel cellPanel = new JPanel(new BorderLayout());
cellPanel.add(cellLabel, BorderLayout.NORTH);
cellPanel.add(droplabel, BorderLayout.CENTER);
gridPanel.add(cellPanel);
}
}

Basically you have two tasks here:
Retrieve a set of images from the underlying database. I say set because you are using a while-loop for iterating over a ResultSet.
connection = getConnection();
try {
statement = (PreparedStatement) connection.prepareStatement("select image from image");
result = statement.executeQuery();
while (result.next()) {
byte[] image = null;
image = result.getBytes("image");
}
}
You could extract this code to a separate method and use an byte-array to store the retrieved information. This array would be the return-value of the method.
Creating ImageIcons and using them in JLabels
Image img = Toolkit.getDefaultToolkit().createImage(image);
ImageIcon icon = new ImageIcon(img);
Component droplabel = new DropTargetTextArea("test", "testing");
JLabel cellLabel = new JLabel(icon);
JPanel cellPanel = new JPanel(new BorderLayout());
cellPanel.add(cellLabel, BorderLayout.NORTH);
cellPanel.add(droplabel, BorderLayout.CENTER);
gridPanel.add(cellPanel);
This code could also be moved to a separate method. The method retrieves an array of images (or only one depending on your setup) and created the ImageIcon.

First a little Tip: you should read about JPA and MVC.
Now to your code: Make a new class and give her a name like "DatabaseHelper" and then put your whole JDBC-Code in a method like "getAllImages()" and make a container class (POJO) for the Image. For the first term this should help you but on the long term you should use JPA and MVC.

Related

RCaller, thread handling, and a Java GUI

I am making a Java GUI to go with my colleague's custom made R package, IntramiRExploreR, which includes a function made to create an interactive graphic via igraph and IntramiRExploreR's Visualisation function, using the following parameters:
Visualisation(miR,mRNA_type=c('GeneSymbol'),method,thresh,platform=Platform,visualisation = 'igraph',layout = 'interactive')
where miR is a vector made via selected JCheckboxes, and method, thresh, and platform are populated from JRadioButtons. I've no doubt the function itself and how the variables are filled in is correct, as I have run the function in R and run the function using a text output format and both run correctly.
The code first fills out a JTable correctly with the results from
Visualisation(miR,mRNA_type=c('GeneSymbol'),method,thresh,platform=Platform)
which outputs text accessible using
caller.getParser().getAsStringArray(//one of seven parameters)
then provides a JButton to use the same parameters and objects to call the aforementioned igraph function in R. However, when the JButton is clicked, the igraph is created but then its frame is disposed as soon as the graphic is fully made. The second time the button is clicked, calling the function again, the provided error is:
Exception in thread "AWT-EventQueue-0" com.github.rcaller.exception.ExecutionException: Can not run C:\Program Files\R\R-3.3.0\bin\x64\Rscript.exe. Reason: java.lang.IllegalThreadStateException
Should I create new thread to handle the igraph visualisation, or is there some method in RCaller I am missing that can handle this? Is Java emptying its memory of my objects after I call a second RCaller and RCode block?
Here's what of my code I can show without violating my agreement to confidentiality:
public void actionPerformed(ActionEvent e){//if goButton is clicked
if(e.getSource() == goButton){
JFrame resultFrame = new JFrame("Results: For full readout, use export button below.");//creates entire resultFrame
resultFrame.setLayout(new BorderLayout());
resultFrame.setSize(new Dimension(950,750));
JPanel resultBack = new JPanel();
resultBack.setLayout(new BorderLayout());//creates the resultBack to be placed into JScrollPane
//RESULTS (from user query; calls R commands to fill out JTable)
//create int checkCnt to keep track of how much info is needed
int checkCnt = 0;
for(int t = 0;t<155;t++){
if(selected[0][t]==true){//if targets for one miR with index t is queried
checkCnt++;
}}
//create JTable
//create column names
String[] colNames = {"miRNA", "tar_GS", "tar_FB", "tar_CG", "Score", "Function", "Experiment", "Method"};
//determine threshold
int threshold=0;
if(checkCnt==1){threshold=100;}
if(checkCnt==2){threshold=50;}
if(checkCnt==3){threshold=33;}
if(checkCnt==4){threshold=25;}
if(checkCnt>=5){threshold=20;}
/*create RCaller and wire query to buttons;
code handles table filling,
///code1 handles graphic display*/
RCaller caller = RCaller.create();
RCaller caller1 = RCaller.create();
RCode code = RCode.create();
RCode code1 = RCode.create();
code.R_require("IntramiRExploreR");
code.R_require("futile.logger");
code.R_require("devtools");
code.R_require("Runiversal");
code1.R_require("IntramiRExploreR");
code1.R_require("futile.logger");
code1.R_require("devtools");
//create array of selected miRs to input to R code
String[] chosen = new String[checkCnt];
for(int kk=0;kk<checkCnt;kk++){
chosen[kk] = litmiR(selected)[kk];
}
code.addStringArray("miR", chosen);
code.addInt("thresh", threshold);
code1.addStringArray("miR", chosen);
code1.addInt("thresh", threshold);
String method =new String();
if(Pears.isSelected()){
method="Pearson";
code.addString("method", method);
code1.addString("method", method);
}
else if(Dist.isSelected()){
method="Distance";
code.addString("method", method);
code1.addString("method", method);
}
else{
method="Both";
code.addString("method", method);
code1.addString("method", method);
}
if(Affy1.isSelected()){
String Platform="Affy1";
code.addString("Platform", Platform);
code1.addString("Platform", Platform);
}
else{
String Platform="Affy2";
code.addString("Platform", Platform);
code1.addString("Platform", Platform);
}
code.addRCode("yy <-Visualisation(miR,mRNA_type=c('GeneSymbol'),method,thresh,platform=Platform)");
String [] aa= caller.getParser().getAsStringArray("miRNA");
String [] aa1= caller.getParser().getAsStringArray("Target_GeneSymbol");
String [] aa2= caller.getParser().getAsStringArray("Targets_FBID");
String [] aa3= caller.getParser().getAsStringArray("Targets_CGID");
double [] aa4= caller.getParser().getAsDoubleArray("Score");
//convert double array to string array
String [] sa4= new String[aa4.length];
for(int ss=0;ss<aa4.length;ss++){
sa4[ss]= Double.toString(aa4[ss]);
}
String [] aa5 = caller.getParser().getAsStringArray("GeneFunction");
String [] aa6 = caller.getParser().getAsStringArray("Experiments");
//create JTable objects
String[][] results = new String[checkCnt*threshold][8];
int w = 0;
int x = 0;
for(int n=0;n<checkCnt;n++){
for(int jj=0;jj<threshold;jj++){//first miR
results[jj+w][0]=aa[jj+x*threshold];//the first miR, then the next one after n loops once
results[jj+w][1]=aa1[jj+x*threshold];//tar_GS
results[jj+w][2]=aa2[jj+x*threshold];//tar_FB
results[jj+w][3]=aa3[jj+x*threshold];//tar_CG
results[jj+w][4]= sa4[jj+x*threshold];//Score
results[jj+w][5]=aa5[jj+x*threshold];//Function
results[jj+w][6]=aa6[jj+x*threshold];//Experiment
}
w=w+threshold;
x++;
}
System.out.println(checkCnt);
//make JTable
JTable resultTable = new JTable(results, colNames);
//create scroll pane to embed results JTable in; allow for vertical scrolling
JScrollPane scrollTable = new JScrollPane(resultTable);
resultTable.setFillsViewportHeight(true);
scrollTable.setPreferredSize(new Dimension(resultBack.getWidth(),(resultFrame.getHeight()-150)));
scrollTable.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollTable.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollTable.getVerticalScrollBar().setUnitIncrement(12);
//create bottom buttonPanel to allow for visualization, exportation, and ontological research
JPanel buttonPanel = new JPanel();
buttonPanel.setPreferredSize(new Dimension(200, 150));
buttonPanel.setBackground(Color.LIGHT_GRAY);
buttonPanel.setLayout(null);
//create buttons
JButton gOnt = new JButton("Gene Ontology");
gOnt.setFont(new Font("Arial", Font.PLAIN, 18));
gOnt.setBorder(BorderFactory.createLineBorder(Color.BLACK));
gOnt.setBounds(50,50,250,100);
buttonPanel.add(gOnt);
JButton vis = new JButton("Visualization");
vis.setFont(new Font("Arial", Font.PLAIN, 18));
vis.setBorder(BorderFactory.createLineBorder(Color.BLACK));
vis.setBounds(650,50,250,100);
buttonPanel.add(vis);
vis.addActionListener(new ActionListener(){
**public void actionPerformed(ActionEvent v){
if(v.getSource() == vis){
code1.addRCode("yy1<-Visualisation(miR,mRNA_type=c('GeneSymbol'),method,thresh,platform=Platform,visualisation = 'igraph',layout = 'interactive')");
caller1.setRCode(code1);
caller1.runAndReturnResult("yy1");
}
}
});**
JButton exp = new JButton("Export as .txt file");
exp.setFont(new Font("Arial", Font.PLAIN, 18));
exp.setBorder(BorderFactory.createLineBorder(Color.BLACK));
exp.setBounds(350, 50, 250, 100);
buttonPanel.add(exp);
resultFrame.setLocation(470,150);//add in the panels and display the resultFrame
resultFrame.add(buttonPanel, BorderLayout.PAGE_END);
resultFrame.add(scrollTable, BorderLayout.PAGE_START);
resultFrame.setVisible(true);
}}});
The area of concern is the ActionListener for my JButton vis. I am absolutely certain that all else is well, but the igraph is unresponsive at first after populating and then a second call provides the IllegalThreadException error.
This is what I would check first:
The GUI can NOT be modified from a NON gui thread.
Make sure you have a background thread that passes the info to the GUI. Otherwise the GUI will become unresponsive until it finishes the processing (this is in the scenario of no background thread)
You can always put a gui runnable around the actionPerformed code.
In your case
SwingUtilities.invokeLater(new Runnable() {...});

Error when I try to put an ImageIcon in Java

I tried to put a simple icon in a JPanel formatted with the BoxLayout.
JPanel panel_4 = new JPanel();
contentPane.add(panel_4, BorderLayout.CENTER);
panel_4.setLayout(new BoxLayout(panel_4, BoxLayout.X_AXIS));
ImageIcon seven= new ImageIcon("‪C:\\Users\\alewe\\workspace\\SlotMachine\\Lucky_Seven-128.png");
JLabel lblNewLabel_1 = new JLabel(seven);
panel_4.add(lblNewLabel_1);
When I ran the code it gave me the error "Some characters cannot be mapped using "Cp1252" character encoding", I saved by UTF-8, now it starts but I can't see the icon.
Maybe if you use setIcon will help you:
ImageIcon seven= new ImageIcon("‪C:\\Users\\alewe\\workspace\\SlotMachine\\Lucky_Seven-128.png");
JLabel lblNewLabel_1 = new JLabel();
//Set your icon to your label
lblNewLabel_1.setIcon(seven);
panel_4.add(lblNewLabel_1);
You can read more about icons here
you will need a inputstream to read the picture. use it like this:
File f = new File("filepath");
InputStream in=new FileInputStream(f);
if (in != null) {
ImageIcon imageIcon = new ImageIcon(ImageIO.read(in));
label.setIcon(imageIcon);
} else {
LOG.debug("No icon found...");
}

Grid Layout does not display correctly

I'm trying to build simple calculator gui with display and 9 buttons
public void init()
{
setSize(60,80);
inf = new InfoButton(this);
zero = new CalcButton(this,"0");
one = new CalcButton(this,"1");
add = new CalcButton(this,"+");
sub = new CalcButton(this,"-");
div = new CalcButton(this,"/");
mlt = new CalcButton(this,"*");
modu = new CalcButton(this,"%");
blank = new JButton("");
wys = new Wyswietlacz(); // its JTextPane
wys.setSize(60,20);
przyciski = new JPanel();
przyciski.setSize(60,60);
przyciski.setLayout(new GridLayout(3,3));
przyciski.add(zero);
przyciski.add(one);
przyciski.add(add);
przyciski.add(sub);
przyciski.add(mlt);
przyciski.add(div);
przyciski.add(modu);
przyciski.add(inf);
przyciski.add(blank);
calosc = new JPanel();
calosc.setLayout(new BoxLayout(calosc,BoxLayout.Y_AXIS));
calosc.add(wys);
calosc.add(przyciski);
calosc.setSize(60,80);
add(calosc);
}
and in main i make frame with size (60,80) but when i make it visible all i can see is display and one row of buttons. What am i doing wrong?
Call setPreferredSize(..) instead of setSize() on wys and przyciski. Then use JFrame's pack() instead of specifying a size for it.

Java fixed element's position

I need to build BlackJack game as an study project.
I want build it with SWING GUI. What I need it just divide the screen in 2 parts, and then to be able insert elements (in my case it's extended JButton with signed ImageIcon) using absolute (x, y) position relative to specified part.
Something like that:
I came from developing under Android, where you can work with elements in very simple way, and I feel lost in SWING. There aren't AbsoluteLayout or something like that?
Here is one example of my several attempts to this:
public void run() {
// TODO Auto-generated method stub
JFrame jFrame = new JFrame("Blackjack");
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = jFrame.getContentPane();
Insets insets = pane.getInsets();
URL url = ClassLoader.getSystemClassLoader().getResource("10_of_clubs.png");
BufferedImage bi = null;
try {
bi = ImageIO.read(url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Image resizedImage = bi.getScaledInstance(128, 186, 0);
ImageIcon icon = new ImageIcon(resizedImage);
ImageButton imgButton = new ImageButton(icon);
imgButton.setPreferredSize(new Dimension(128, 186));
ImageButton imgButton2 = new ImageButton(icon);
imgButton.setPreferredSize(new Dimension(128, 186));
pane.setLayout(new GridBagLayout());
JPanel headPanel = new JPanel();
JPanel headPanel2 = new JPanel();
GridBagConstraints cns = new GridBagConstraints();
cns.gridx = 0;
cns.gridy = 0;
cns.weightx = 0.5;
cns.weighty = 0.2;
cns.anchor = GridBagConstraints.FIRST_LINE_START;
cns.fill = GridBagConstraints.BOTH;
headPanel.setBackground(Color.RED);
headPanel.add(imgButton, cns);
GridBagConstraints cns2 = new GridBagConstraints();
cns2.gridx = 0;
cns2.gridy = 0;
cns2.weightx = 0.5;
cns2.weighty = 0.2;
cns2.anchor = GridBagConstraints.FIRST_LINE_START;
cns2.fill = GridBagConstraints.CENTER;
headPanel2.setBackground(Color.BLUE);
headPanel2.add(imgButton2, cns2);
pane.add(headPanel);
pane.add(headPanel2);
jFrame.setSize(800, 600);
jFrame.setVisible(true);
jFrame.setLocationRelativeTo(null);
}
That what I get:
Tnx.
if you want absolute layout, please take a look at: http://docs.oracle.com/javase/tutorial/uiswing/layout/none.html
in general to read about layouts in java you can take a look at:
http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
here is all java swing components: visual guide:
http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
I think you can use JSplitPane (http://algo.math.ntua.gr/~symvonis/other-material/java_material/JavaTutorial/uiswing/components/splitpane.html) to create vertical separation
Since you have overlapping elements you can:
Use your existing JButtons with images inside a JLayeredPane. Put your cards on different layers for a clean rendering. Set the position of your Cards absolute with 'setBounds()'
Draw your cards with absolute position yourself using a Canvas. If you take this approach, you will also have to do your Click handling yourself (check if a click is inside a card.)

Displaying jpg image on JPanel

How can I display jpg image which I stored in arraylist in JPanel?
Im not able to display the jpg files in the JPanel.
String[] pictureFile = {"A.jpg","B.jpg","C.jpg"};
List<String> picList1 = Arrays.asList(pictureFile);
Collections.shuffle(picList1);
ImageIcon icon = new ImageIcon("picList1.get(0)");
JLabel label1 = new JLabel();
label1.setIcon(icon);
JPanel panel = newJPanel;
panel.add(label);
You should not put the call to the array in quotes.
Instead, you should try the following:
ImageIcon icon = new ImageIcon(picList1.get(0));
The problem is in the line
ImageIcon icon = new ImageIcon("picList1.get(0)");
It's interpreting the string as a file name. You should just need to unquote the picList1.get(0) bit.

Categories

Resources