Grid Layout does not display correctly - java

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.

Related

Swing components not moving to desired cell in GridBagLayout

I'm trying to create a simple UI for a program that can read a file, write to a file and search for text within a file. I have most of my Components created, the problem is that they're all being "drawn" in the same (center) cell. I've tried applying weights, widths, etc. all to no avail.
Here's my base code for the UI:
public void GUI(){
//Create main window for Program
JFrame mainWindow = new JFrame("Simple Data Base"); //Init frame
mainWindow.setSize(500, 400); //Set frame size
mainWindow.setVisible(true); //Make frame visible
//Create panel for the main window of the GUI
JPanel simpleGUI = new JPanel( new GridBagLayout());
GridBagConstraints gbCons = new GridBagConstraints();
simpleGUI.setBackground(Color.cyan);
//Create button linking to read function
JButton readButton = new JButton("Read"); //Init button, and give text
gbCons.fill = GridBagConstraints.BOTH;
gbCons.gridx = 0;
gbCons.gridy = 1;
//Create button linking to the search function
JButton searchButton = new JButton("Search");
gbCons.fill = GridBagConstraints.BOTH;
gbCons.gridx = 1;
gbCons.gridy = 1;
//Create label prompting user to specify desired function
JLabel promptText = new JLabel("Click 'Read' to read a file, 'Search' to search within a file, 'Write' to write to a file:");
gbCons.fill = GridBagConstraints.BOTH;
gbCons.gridx = 0;
gbCons.gridy = 0;
//Add components to Main window
mainWindow.getContentPane().add(simpleGUI);
simpleGUI.add(promptText, gbCons);
simpleGUI.add(readButton, gbCons);
simpleGUI.add(searchButton, gbCons);
}
the problem is that they're all being "drawn" in the same (center) cell.
simpleGUI.add(promptText, gbCons);
simpleGUI.add(readButton, gbCons);
simpleGUI.add(searchButton, gbCons);
You are using the same GridBagConstraints for each component so the contraints are identical for each component.
You neeed to:
set the constraints
add the component to the panel using the constraints
repeat steps 1 and 2.
For example:
JButton readButton = new JButton("Read");
gbCons.fill = GridBagConstraints.BOTH;
gbCons.gridx = 0;
gbCons.gridy = 1;
simpleGUI.add(readButton, gbCons);
JButton searchButton = new JButton("Search");
gbCons.fill = GridBagConstraints.BOTH;
gbCons.gridx = 1;
gbCons.gridy = 1;
simpleGUI.add(searchButton, gbCons);
I suggest you read the section from the Swing tutorial on How to Use GridBagLayout for more information and examples.
Download the demo code and use that example as your starting code. The demo code will show you how to better structure your class by:
NOT extending JFrame
Creating the GUI on the Event Dispatch Thread
Use the pack() method, NOT the setSize(...) method
Make the frame visible AFTER all components have been added to the frame

separate two sets of code

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.

define multiple labels in javafx at once

I would like to declare multiple labels in javafx all at once, is this possible?
at the moment this is what i type, and i have line 20 to 30 labels!!
fajr_Label_ar = new Label();
fajr_Label_eng = new Label();
zuhr_Label_ar = new Label();
zuhr_Label_eng = new Label();
asr_Label_ar = new Label();
asr_Label_eng = new Label();
maghrib_Label_ar = new Label();
maghrib_Label_eng = new Label();
isha_Label_ar = new Label();
isha_Label_eng = new Label();
hadith_Label = new Label();
fajr_hourLeft = new Label();
Can I declare something along the line of;
label1, label2, label3.... = new Label();
This is not about JavaFX. This question is about Java in general ..
I see some localizations there : en,ar ... so I would suggest this pattern:
Label lbs[];
lbs=new Label[7];
String strings_en[]=new String[]{
"fajr",
"zuhr",
"asr",
"maghrib",
"isha",
"hadith",
"fajr_lefthour"
};
String strings_ar[]=new String[]{
"فجر",
"ظهر",
"عصر",
"مغرب",
"عشاء",
"حديث",
"فجر ساعة لاحقة"
};
String strings[];
//assing lan list
strings=strings_ar; // or strings=strings_en;
for (int i = 0; i < lbs.length; i++) {
lbs[i]=new Label(strings[i]);//initializing labels
//doing what you want here with labels
//...
}
It would be better to isolate data from design as you can see we have labels as Label array and data as String array.. and it would be better and better to define the lang set before retrieving data as we have done when assign object array strings to object array Ar or en .. that would help you to extend/scale/debug your program easily and healthy by adding more labels or languages ..

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.)

Text area doesn't seem to be working

I am try to create a text area that will display a list of scores. For some reason though, the text area only expands when someone types in it, and the user should not even be allowed to type in it. I thought i wrote in the code for it properly but for some reason it doesn't seem to work. The "hello" phrase I appended isn't even displaying in the text area. Can anyone provide some advice:
public HighScores() throws FileNotFoundException, IOException{
frame.setVisible(true);
frame.setSize(400,200);
frame.add(main);
GridBagConstraints g = new GridBagConstraints();
g.insets = new Insets(10,10,10,10);
g.gridx = 0;
g.gridy = 0;
main.add(highscorespanel, g);
highscorespanel.add(highscores);
g.gridx = 0;
g.gridy = 1;
main.add(textareapanel, g);
Color c = textareapanel.getBackground();
textareapanel.setBackground(c);
textareapanel.add(ta);
ta = new JTextArea ();
ta.setVisible(true);
ta.setEnabled(true);
ta.setEditable(false);
ta.append("hello");
JScrollPane sp = new JScrollPane(ta);
BufferedReader br = new BufferedReader(new FileReader("src/BattleShip/scores.txt"));
String namescore = br.readLine();
while(namescore!=null){
ta.append("\t"+namescore);
}
Im almost sure you don't need the answer anymore but you need to move your line "textareapanel.add(ta);" to some point after you initialize ta.
ta = new JTextArea();
textareapanel.add(ta);
ta.setVisible(true);
ta.setEnabled(true);
ta.setEditable(false);
EDIT:
At a second look you want a JScrollPane for your JTextArea so you code should be like this:
JTextArea ta = new JTextArea();
ta.setVisible(true);
ta.setEnabled(true);
ta.setEditable(false);
JScrollPane sp = new JScrollPane(ta);
textareapanel.add(sp);

Categories

Resources