I'm working on creating a 3 man's morris board, but nothing is being displayed on the frame. It's empty despite having added my JPanel. Everything is fine if I used board = new JPanel(new GridLayout()); and do the following, but I wouldn't be able to draw the lines that would draw the board. I've looked over it a few times but can't seem to find a problem.
public class Project5 extends JFrame {
public final static int FRAME_WIDTH = 600;
public final static int FRAME_HEIGHT = 600;
private JButton jb[] = new JButton[9];
private Board board = new Board();
Project5(){
for(int i = 0; i<9; i++){
jb[i] = new JButton();
board.add(jb[i]);
}
add(board);
}
public static void main(String[] args) {
JFrame frame = new Project5();
frame.setTitle("Three Man's Morris");
frame.setSize(Project5.FRAME_WIDTH,Project5.FRAME_HEIGHT);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class Board extends JPanel{
public Board(){
super();
setLayout(new GridLayout(3,0,Project5.FRAME_WIDTH,Project5.FRAME_HEIGHT));
}
#Override
public void paintComponents(Graphics g){
super.paintComponents(g);
g.drawLine(0, Project5.FRAME_WIDTH, 0, Project5.FRAME_HEIGHT);
g.drawLine(0, 0, 0, Project5.FRAME_HEIGHT);
g.drawLine(0,Project5.FRAME_WIDTH,0,0);
g.drawLine(0, Project5.FRAME_HEIGHT, Project5.FRAME_WIDTH, Project5.FRAME_HEIGHT);
g.drawLine(Project5.FRAME_WIDTH, 0, 0, Project5.FRAME_HEIGHT);
g.drawLine(Project5.FRAME_WIDTH,0,Project5.FRAME_WIDTH,Project5.FRAME_HEIGHT);
}
}
The problem is in your GridLayout() parameters :
GridLayout(rows,cols,horizontal_gap,vertical_gap)
in your case, both gaps are 600 (FRAME_WIDTH, FRAME_HEIGHT) !
The buttons are displayed, but they are outside the panel, try to lower the gap,
i.e. : setLayout(new GridLayout(3,0,0,0));
You should see the buttons.
Related
I have tried this code by setting setComponentZOrder() but it also did not worked please give me some suggestion how can i achieve this goal to make an image slideshow and put a button on it in jframe
import java.awt.Image;
import java.awt.*;
import java.awt.event.ActionListener;
import javafx.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.*;
public class slidemain extends JFrame {
JLabel jl;
JButton b;
Timer tm;
int x = 0;
int w;
int h;
String[] list = {
"C:\\Users\\HARITI\\Desktop\\sat.jpg",
"C:\\Users\\HARITI\\Desktop\\mtab.jpg",
"C:\\Users\\HARITI\\Desktop\\abc.jpg"
};
public slidemain()
{
super("java slide show");
// w = super.getWidth();
// h = super.getHeight();
jl = new JLabel();
b = new JButton();
//b.setVisible(true);
super.setComponentZOrder(jl, 0);
super.setComponentZOrder(b, 1);
jl.setBounds(0, 100, 1350, 650);
setImageSize(2);
tm = new Timer(1500, new ActionListener(){
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
setImageSize(x);
x += 1;
if (x >= list.length)
{
x = 0;
}
}
});
add(jl);
tm.start();
setLayout(null);
getContentPane().setBackground(Color.decode("#bdb67b"));
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void setImageSize(int i) {
ImageIcon icon = new ImageIcon(list[i]);
Image img = icon.getImage();
Image newimg = img.getScaledInstance(jl.getWidth(), jl.getHeight(), Image.SCALE_SMOOTH);
ImageIcon newimc = new ImageIcon(newimg);
jl.setIcon(newimc);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
new slidemain();
}
}
This...
super.setComponentZOrder(jl, 0);
super.setComponentZOrder(b, 1);
is going to have no affect if neither of the components have been added to the container yet.
Which brings us to your next problem, you never actually add the button to anything
And event if you did, it wouldn't be displayed, because you're using a null layout
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify.
Maybe have a look at Why is it frowned upon to use a null layout in SWING? for some more details
I have a specific problem I'm stuck on. My job is to have this pop up:
Here's the program I have so far:
import javax.swing.*;
import java.awt.event.*;
public class Assignment5 implements ActionListener
{
JFrame frame;
JPanel panel;
JLabel label1, label2, label3, label4;
JButton button;
JTextField text1, text2, text3;
public Assignment5()
{
frame = new JFrame();
frame.setVisible(true);
frame.setSize(400,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label1 = new JLabel("No. of Years: ");
text1 = new JTextField(20);
label2 = new JLabel("Rate of Interest: ");
text2 = new JTextField(20);
label3 = new JLabel("Principal Amount: ");
text3 = new JTextField(20);
button = new JButton("Calculate Simple Interest");
panel = new JPanel();
panel.add(label1);
panel.add(label2);
panel.add(label3);
panel.add(text1);
panel.add(text2);
panel.add(text3);
panel.add(button);
frame.add(panel);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
int years = Integer.parseInt(text1.getText());
double rate = Double.parseDouble(text2.getText());
double amount = Double.parseDouble(text3.getText());
double simple = years*rate*amount;
label4 = new JLabel("Your Payable Amount Is: "+simple);
panel.add(label4);
}
public static void main(String[] args)
{
Assignment5 obj = new Assignment5();
}
}
Everything works so far, but my final label containing the actual result won't show up. I've tried a couple different things, each of which doesn't work, so I'm hoping you guys will be able to tell me a better way of doing this. Thanks.
Do you have any red errors showing up in any line of your code? I am not sure if it is the output code that is wrong. Try this:
label4.setText("Your payable amount is "+simple);
Try this:
JOptionPane.showMessageDialog(null,"Your payable amount is “+simple);
That will pop your message.
Ok basically my problem is I don't know how to get my buttons and my labels to appear in the frame that I just created. I tried using frame.add(new JButton("VOTE1")); but that doesn't work and it says it's missing an identifier. Here is my code so far, your help is much appreciated.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class VotingMachine extends JFrame implements ActionListener {
public static void main(String[] args) {
JFrame frame = new JFrame("Voting Machine");
frame.setSize(400, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private JLabel Candidate1 = new JLabel("My Name");
private JLabel Candidate2 = new JLabel("Jennifer Lawrence");
private JLabel Candidate3 = new JLabel("Cristiano Ronaldo");
private JButton VOTE1 = new JButton("VOTE FOR Bishoy Morcos");
private JButton VOTE2 = new JButton("VOTE FOR Jennifer Lawrence");
private JButton VOTE3 = new JButton("VOTE FOR Cristiano Ronaldo");
int countcandidate1;
int countcandidate2;
int countcandidate3;
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if(o == VOTE1)
countcandidate1++;
else if(o == VOTE2)
countcandidate2++;
else if(o == VOTE3)
countcandidate3++;
}
}
First you need to create a JPanel
JPanel welcomePanel = new JPanel();
Then add the buttons and labels to that panel
welcomePanel.add(Candidate1);
welcomePanel.add(VOTE1);
ETC.... for all of your buttons and labels
Lastly, add that JPanel to your JFrame
frame.add(welcomePanel);
If this answers your question, please mark it as answered so other viewers will be informed.
I'm pretty new to this whole JavaFX thing, as you can probably tell. This is an issue I ran into recently while playing around with the Canvas node. I've got a BorderPane as my root node, and I'd like to have a Canvas occupy all available space within the center of it. However, I'm having some trouble implementing that exact behavior. Here's the just of what I've been trying:
public void start(Stage stage){
BorderPane root=new BorderPane();
Canvas canvas=new Canvas(250,250);
//canvas.widthProperty().bind(root.widthProperty());
//canvas.heightProperty().bind(root.heightProperty());
GraphicsContext gc=canvas.getGraphicsContext2D();
new AnimationTimer(){
#Override
public void handle(long l){
double width=canvas.getWidth(),height=canvas.getHeight();
gc.clearRect(0,0,width,height);
gc.strokeRect(0,0,width,height);
gc.strokeLine(0,0,width,height);
gc.strokeLine(0,height,width,0);
}
}.start();
root.setCenter(canvas);
root.setBottom(new Button("Placeholder"));
root.setTop(new Button("Placeholder"));
stage.setScene(new Scene(root));
stage.show();
}
Instead of expanding as the Pane does, my Canvas just stays centered within it, retaining its original size. If the two commented lines near the top are re-added, the Canvas grows and shrinks as the Pane does, but without regarding the dimensions of its center (as expected). Is there a way to apply this sort of binding behavior to just the center of the BorderPane, or perhaps another way to do this entirely that I'm unaware of?
EDIT: Just found a much nicer solution today (19.05.2014):
http://fxexperience.com/2014/05/resizable-grid-using-canvas/
So much easier and shorter than mine -.-
Now my original approach:
I had the same problem as you do.
I found a really ugly workaround you can use, but maybe there is another method doing this...
My Workaround:
class MyCanvas {
private Canvas cv;
private StackPane box;
public MyCanvas(Stage stg) {
cv = new Canvas(500, 500);
box = new StackPane();
box.getChildren().add(cv);
//When the Stage size changes, the canvas size becomes resetted
//but the Hbox expandes automatically to fit the with again
//and so the canvas become resized to fit the HBox
stg.widthProperty().addListener(new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> arg0, Number arg1, Number arg2) {
resize();
}
});
stg.heightProperty().addListener(new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> arg0, Number arg1, Number arg2) {
resize();
}
});
box.widthProperty().addListener(new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> arg0, Number arg1, Number arg2) {
adapt();
}
});
box.heightProperty().addListener(new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> arg0, Number arg1, Number arg2) {
adapt();
}
});
paint();
}
private void paint(){
//Paint something ....
GraphicsContext ctx = cv.getGraphicsContext2D();
double w = cv.getWidth();
double h = cv.getHeight();
ctx.clearRect(0, 0, w, h);
ctx.setFill(Color.BLUE);
ctx.fillRect(0, 0, w, h);
}
//Add this HBox to your content pane
public StackPane getBox() {
return box;
}
public void resize(){
cv.setWidth(50);
cv.setHeight(50);
}
private void adapt(){
cv.setHeight(box.getHeight());
cv.setWidth(box.getWidth());
paint();
}
}
And in your Main:
public class Root extends Application{
public static void main(String[] args){ launch(args); }
public void start(Stage stg){
MyCanvas cv = new MyCanvas(stg);
BorderPane pane = new BorderPane();
pane.setCenter(pane.getBox());
stg.setScene(new Scene(pane));
stg.show();
}
}
Hope this helps you solving your problem.
nZeloT
So i am trying to add an image to my program after a button is pressed with a certain value entered into a text field. I want the image to be blank until the button is pressed with the correct value. The only issue i seem to be having is making the photo appear, i know the output should be working. here is the code i have for adding the label.
photo = new JLabel();
photo.setBounds(425, 170, 400, 360);
contentPane.add(photo);
ImageIcon icon = new ImageIcon("AwsomeSauce.jpg");
here is the code for when the value is entered correctly
if (error) {
photo.setIcon(image);
}
now im still pretty new at this so go easy on me.
Here is simple example for you:
public class Frame extends JFrame {
private JLabel label;
public Frame() {
getContentPane().add(label = new JLabel(),BorderLayout.SOUTH);
JButton b = new JButton("show Icon");
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
URL resource = getClass().getResource("/res/3_disc.png");
ImageIcon ico = new ImageIcon(resource);
label.setIcon(ico);
}
});
getContentPane().add(b,BorderLayout.NORTH);
}
public static void main(String[] args) {
Frame frame = new Frame();
frame.setTitle("This is a test");
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
"/res/3_disc.png" - is my icon which is placed in my project in res folder.