Java GUi Being inconsistent - java

Hi so I am trying to creat this menu for the game, and when I run the code it is very hit or miss. In the same computer with same screen same OS and everything the same, I might run the code ones and the menu is fine. and then I run it again and the pictures are missalighed or the just disappear and so on. I have tried changing the order of the contentPane.add but and I am out of ideas. What else could it be? Thanks
public static int type(){
// Create a "clickable" image icon
int i =0;
Color c = new Color (0,0,0);
ImageIcon icon = new ImageIcon("images/mike_main.png");
JLabel label = new JLabel(icon);
ImageIcon icon1 = new ImageIcon("images/igal_main.png");
JLabel label1 = new JLabel(icon1);
JPanel contentPane = new JPanel();
JLabel label3 = new JLabel("Choose your character!");
JLabel mike_l = new JLabel("Mike");
JLabel mike_info = new JLabel("<html>Speed: 10<br>Range: 7</html>");
JLabel igal_l = new JLabel("Igal");
JLabel igal_info = new JLabel("<html>Speed: 7<br>Range: 10</html>");
label3.setBounds(600,100,2000,100);
label3.setFont(new Font("Serif", Font.BOLD, 56));
label3.setForeground(Color.WHITE);
contentPane.setOpaque(true);
contentPane.setBackground(c);
contentPane.setLayout(null);
final JFrame frame = new JFrame("My Window");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(label);
frame.setTitle("The Ultimate Game");
frame.setExtendedState(frame.MAXIMIZED_BOTH);
frame.pack();
frame.setVisible(true);
label.setBounds(400,400,300,600);
mike_l.setBounds(500,330,1000,100);
mike_info.setBounds(750,500,1000,100);
//label.setLocation(50, 50);
label1.setBounds(1200,400,300,600);
igal_l.setBounds(1300,330,1000,100);
igal_info.setBounds(1550,500,1000,100);
//label1.setLocation(250, 250);
mike_l.setFont(new Font("Serif", Font.BOLD, 26));
mike_l.setForeground(Color.WHITE);
mike_info.setFont(new Font("Serif", Font.BOLD, 26));
mike_info.setForeground(Color.WHITE);
igal_l.setFont(new Font("Serif", Font.BOLD, 26));
igal_l.setForeground(Color.WHITE);
igal_info.setFont(new Font("Serif", Font.BOLD, 26));
igal_info.setForeground(Color.WHITE);
contentPane.add(label);
contentPane.add(label1);
contentPane.add(label3);
contentPane.add(mike_l);
contentPane.add(mike_info);
contentPane.add(igal_l);
contentPane.add(igal_info);
frame.setContentPane(contentPane);
label.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
System.out.println("CLICKED");
frame.setTitle("Mike");
}
});
label1.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
System.out.println("CLICKED");
frame.setTitle("Igal");
}
});
while (i==0){
//System.out.println("I am here");
String s = frame.getTitle();
System.out.println(s);
if (s.equals("Mike")){
i =1;
}
else if(s.equals("Igal")){
i = 2;
}
// Add it to a frame.
}
System.out.println("im out");
frame.setVisible(false);
return i;
}

I think the issue is that your are calling frame.setVisible(true) before you are done making changes to frame. If you move this (and maybe the pack() call) pass all your add()s and after you setContentFrame(), then your window will open more reliably.
As for the alignment, that is going to come down to all your setBounds() calls. If you don't need to use setBounds() you should probably look into Layout Managers and nest JPanels for modular sections of you're design (e.g. character info).

Related

Why does some of my components such as JLabel and JComboBox sometimes not appear after using a JButton?

I'm trying to transition from the home screen to the option menu through a JButton by adding a JPanel (menu) to the frame and hiding the currently visible panel (background). I'm using an Action Listener to activate the transition. Sometimes when running the code (more like most of the time), some parts of the menu won't appear such as the JComboBox and two of the JLabels. I'm not having an issue with the JSlider though, but I haven't been able to identify the problem for the other components. I tried implementing menu.revalidate() and menu.setVisible(true) at the end of my code, but to no prevail. I also tried doing frame.revalidate() and frame.setVisible(true). Another attempt at fixing this was by moving around the menu.add([insert JLabel/JComboBox]).
The code that I used is as provided
Window.java
JFrame frame;
JPanel background;
JPanel menu;
JSlider difficulty;
JLabel difficultyLabel;
JComboBox exerciseChoice;
JPanel dropDownPanel;
JLabel exerciseChoiceLabel;
JPanel difficultyPanel;
public ActionListener startButtonPressed() throws IOException {
ActionListener temp =
new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
background.setVisible(false);
menu = new JPanel();
menu.setLayout(new BoxLayout (menu, BoxLayout.Y_AXIS));
menu.setBounds(menu.getLocation().x+50, 50, 700, 100);
menu.setBackground(Color.WHITE);
startButton.setEnabled(false);
createDifficultySlider();
createWorkoutDropDown();
frame.add(menu);
frame.setVisible(true);
} catch (IOException r) {}
}
};
return temp;
}
public void createWorkoutDropDown() throws IOException {
dropDownPanel = new JPanel();
dropDownPanel.setLayout(new FlowLayout(FlowLayout.LEADING));
dropDownPanel.setBackground(Color.WHITE);
String[] choices = {"Abs", "Cardio", "Full Body", "Upper Body", "Stretches", "Lower Body"};
exerciseChoice = new JComboBox(choices);
exerciseChoice.setFont(new Font("Verdana", Font.PLAIN, 20));
exerciseChoiceLabel = new JLabel("Workout Options");
exerciseChoiceLabel.setFont(new Font("Verdana", Font.PLAIN, 20));
dropDownPanel.add(exerciseChoiceLabel);
dropDownPanel.add(exerciseChoice);
menu.add(dropDownPanel);
}
public void createDifficultySlider() throws IOException {
difficultyPanel = new JPanel();
difficultyPanel.setLayout(new FlowLayout(FlowLayout.LEADING));
difficultyPanel.setBackground(Color.WHITE);
difficulty = new JSlider(JSlider.HORIZONTAL, 1, 10, 5);
difficulty.setPreferredSize(new Dimension(difficulty.getPreferredSize().width + 60, difficulty.getPreferredSize().height + 5));
difficultyLabel = new JLabel("Difficulty Level (Easy 1- Hard 10)");
difficultyLabel.setFont(new Font("Verdana", Font.PLAIN, 20));
difficulty.setFont(new Font("Verdana", Font.PLAIN, 10));
difficulty.setMajorTickSpacing(1);
difficulty.setPaintLabels(true);
difficulty.setPaintTicks(true);
difficulty.setSnapToTicks(true);
difficultyPanel.add(difficultyLabel, BorderLayout.PAGE_START);
difficultyPanel.add(difficulty, BorderLayout.LINE_START);
menu.add(difficultyPanel);
}
EDIT: I had to throw IOExceptions because I was importing fonts from my drive.

JPanel not displaying JLabel

I am trying to make an application, which displays a JLabel and a button, which if clicked switches to another jPanel. For some reason my JLabel is not displaying at all in either case. I would appreciate an expert eye to look over my code and see what I am doing wrong. Thanks in advance.
HomeScreenUI(){
//frame
JFrame frame = new JFrame("Opisa");
//panels, one before button click and one after
JPanel panel = new JPanel();
JPanel panelAfterButtonClick = new JPanel();
panel.setLayout(null);
panelAfterButtonClick.setLayout(null);
//jlabel that isnt displaying + dimensions
JLabel label = new JLabel("Opisa");
Dimension size = label.getPreferredSize();
label.setBounds(100, 100, size.width, size.height);
label.setFont(new Font("Helvetica", Font.PLAIN, 70));
//second jlabel that isn't displaying
JLabel label2 = new JLabel("Opisa");
Dimension size4 = label2.getPreferredSize();
label2.setBounds(100, 100, size4.width, size4.height);
label2.setFont(new Font("Helvetica", Font.PLAIN, 70));
//adding the labels to the panels
panel.add(label);
panelAfterButtonClick.add(label2);
//button that is displaying both before and after
JButton button = new JButton("Click Me..");
JButton buttonAfterClick = new JButton("Clicked Me..");
//dimensions
Dimension size2 = button.getPreferredSize();
button.setBounds(100, 100, size2.width, size2.height);
Dimension size3 = button.getPreferredSize();
buttonAfterClick.setBounds(100, 100, size3.width, size3.height);
//adding the buttons to the jpanel
panel.add(button);
panelAfterButtonClick.add(buttonAfterClick);
//function that changes the panel after the button is clicked
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
frame.setContentPane(panelAfterButtonClick);
frame.invalidate();
frame.validate();
}
});
//adding the panel to the frame and setting the size
frame.add(panel);
frame.setSize(1000,800);
frame.setVisible(true);
}
Check the label bounds, more specifically its size... try setting some fixed values (great enough to show its content like setBounds(100, 100, 250, 80)).
The preferred size is being retrieved before changing the font size, so it is not big enough to show that big characters. Try changing the font first.

How to add JLabels to JFrame?

I'm pretty sure I have to make a container and add the labels to the container in the win() and lose() methods. But how should I do this? Also, if you have any other tips to make the code more readable and coherent.
P.S. This is my first time using Java Swing to program graphics, so I know the code is very messy. I mostly just care if the program works the way I want it to...
P.P.S There were a few class variables, but StackOverflow wouldn't let me post them
public class TwoDBettingGame extends JFrame {
/** Constructor to setup the UI components */
public TwoDBettingGame() {
Container cp = this.getContentPane();
cp.setLayout(new FlowLayout(FlowLayout.CENTER));
if (money == 0) {
money = 1000;
}
// Define the UI components
JLabel label1 = new JLabel("Your money: $"+String.valueOf(money));
JLabel label2 = new JLabel("How much would you like to bet?");
JLabel label3 = new JLabel("$");
JTextArea textarea1 = new JTextArea(1, 3);
Icon heads = new ImageIcon(getClass().getResource("heads.png"));
Icon tails = new ImageIcon(getClass().getResource("tails.png"));
JButton buttonheads = new JButton(" Heads", heads);
JButton buttontails = new JButton(" Tails", tails);
// Define preferred characteristics
label1.setFont(new Font("Times New Roman", 1, 50));
label2.setFont(new Font("Times New Roman", 1, 33));
label3.setFont(new Font("Times New Roman", 1, 70));
textarea1.setEditable(true);
textarea1.setFont(new Font("Times New Roman", 1, 60));
buttonheads.setPreferredSize(new Dimension(200, 75));
buttontails.setPreferredSize(new Dimension(200, 75));
buttonheads.setFont(new Font("Times New Roman", 1, 30));
buttontails.setFont(new Font("Times New Roman", 1, 30));
// Create new panel with buttons 1 and 2
JPanel panel2 = new JPanel();
panel2.add(buttonheads);
((FlowLayout)panel2.getLayout()).setHgap(40);
panel2.add(buttontails);
// Add all UI components
cp.add(label1);
cp.add(label2);
cp.add(label3);
cp.add(textarea1);
cp.add(panel2);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit when close button clicked
setTitle("Betting Game"); // "this" JFrame sets title
setSize(WINDOW_WIDTH, WINDOW_HEIGHT); // or pack() the components
setResizable(false); // window can't be resized
setLocationRelativeTo(null); // puts window in center of screen
setVisible(true); // show it
// Add action listeners to buttons
buttonheads.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sideBetOn = "heads";
// Get TextArea text
String betString = textarea1.getText();
try{
bet = Integer.parseInt(betString);
} catch (NumberFormatException n) {
bet = 0;
}
buttonClicked();
}
});
buttontails.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sideBetOn = "tails";
// Get TextArea text
String betString = textarea1.getText();
try{
bet = Integer.parseInt(betString);
} catch (NumberFormatException n) {
bet = 0;
}
buttonClicked();
}
});
}
public void buttonClicked() {
if (bet > 0 && bet <= money) {
int x = rand.nextInt(2);
if (x == 0) {
coinOutcome = "heads";
} else {
coinOutcome = "tails";
} if (coinOutcome.equals(sideBetOn)) {
money = money + bet;
dispose();
win();
Wait();
} else {
money = money - bet;
dispose();
lose();
Wait();
if (money <= 0) {
System.exit(0);
} else {
dispose();
main(null);
}
}
}
}
public void Wait() {
try {
Thread.sleep((long) (secs*1000)); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
public void win() {
JFrame frame = new JFrame();
frame.setLayout(new FlowLayout(FlowLayout.CENTER));
// Define the UI components
JLabel label4 = new JLabel("The coin flip was " + coinOutcome + ".");
JLabel label5 = new JLabel("You won $" + bet + "!");
// Define preferred characteristics
label4.setFont(new Font("Times New Roman", 1, 20));
label5.setFont(new Font("Times New Roman", 1, 20));
// Add all UI components
frame.add(label4);
frame.add(label5);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit when close button clicked
setTitle("You Win!!!"); // "this" JFrame sets title
setSize(WINDOW_WIDTH2, WINDOW_HEIGHT2); // or pack() the components
setResizable(false); // window can't be resized
setLocationRelativeTo(null); // puts window in center of screen
setVisible(true); // show it
}
public void lose() {
JFrame frame = new JFrame();
frame.setLayout(new FlowLayout(FlowLayout.CENTER));
// Define the UI components
JLabel label4 = new JLabel("The coin flip was " + coinOutcome + ".");
JLabel label5 = new JLabel("You lost $" + bet + "!");
// Define preferred characteristics
label4.setFont(new Font("Times New Roman", 1, 20));
label5.setFont(new Font("Times New Roman", 1, 20));
// Add all UI components
frame.add(label4);
frame.add(label5);
if (money <= 0) {
JLabel label6 = new JLabel("I'm sorry, you lost. Better luck next time...");
label6.setFont(new Font("Times New Roman", 1, 12));
frame.add(label6);
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit when close button clicked
setTitle("You Lose :("); // "this" JFrame sets title
setSize(WINDOW_WIDTH2, WINDOW_HEIGHT2); // or pack() the components
setResizable(false); // window can't be resized
setLocationRelativeTo(null); // puts window in center of screen
setVisible(true); // show it
}
/** The entry main() method */
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TwoDBettingGame(); // Let the constructor do the job
}});
}
}
How to add JLabels to JFrame?
I'm pretty sure I have to make a container and add the labels to the container in the win() and lose() methods..
I wouldn't use that approach. A label without text or icon is invisible (unless it has a visible border). So create and add the label at start-up with no text. When a win or loss is achieved, set some text.
If the layout refuses to add space for the label without any text (e.g. in the PAGE_START of a BorderLayout it would have no height), add some text to it before pack() is called, and set it to no text afterwards.

How to close second JFrame without terminating program

How do I dispose my second frame while retaining my MainFrame?
I have a JFrame( CCurrencyConverterFrame) that I call from the Main Frame.
JMenuItem mntmCurrencyConverter = new JMenuItem("Currency Converter");
mntmCurrencyConverter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CCurrencyConverterFrame frame = new CCurrencyConverterFrame();
myFrame = frame;
JPanel contentPane = new CCurrencyConverter(myFrame);
frame.setContentPane(contentPane);
frame.setVisible(true);
}
});
In CCurrencyConverterFrame.java,
public CCurrencyConverterFrame() {
setFont(new Font("Dialog", Font.BOLD, 12));
getContentPane().setFont(new Font("Tahoma", Font.BOLD, 16));
setTitle("Currency Converter ");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 469, 470);
//Center
setLocationRelativeTo(null) ;
}
I have tried using JFrame.HIDE_ON_CLOSE but it still terminates my application. What can I do to resolve this?

Calling a JPanel inside a split panel Java

Hi I'm having trouble in my code. I can't call or display my JPanel(TruthTable) inside my splitpane in the Minimize class when I click the button and Keypressed(Enter).The problem is in the class Minimize
*UPDATE: I'have solved my problem regarding to diplaying the panel my next problem is when I call the constructor the text in the panel should be updated.I also change the setText to append 'coz they say that JPanel doesnt support setText.I've already used,validate,repaint method but no luck in updating the textArea.
Heres my code for class Minimize:
package splashdemo;
public class Minimize extends JPanel implements ClipboardOwner
{
simButton.addActionListener(new ActionListener()
{ public void actionPerformed(ActionEvent ae)
{
LogicGates lg= new LogicGates();
lg.geth();
sim s=new sim();
s.InputExp(lg.g,lg.g1);
s.menu();
s.setSize(700,700);
s.setVisible(false);
Frame f = new Frame();
Panel panel = new Panel();
f.add(BorderLayout.SOUTH, panel);
f.add(BorderLayout.CENTER, new sim());
f.add(BorderLayout.SOUTH, panel);
f.setSize(580, 500);
panel.add(s.button);
f.show();
f.setVisible(false);
JOptionPane.showMessageDialog(null, b);
ex=b;
cAppend();
JOptionPane.showMessageDialog(null, ex1);
InToPost(ex1);
foutput= doTrans();
JOptionPane.showMessageDialog(null, foutput);
TruthTable_1 kl = new TruthTable_1(foutput);
Minimize mi = new Minimize();
s.InputExp(lg.g,lg.g1);
s.menu();
lg.gatessplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, mi, lg.p1);
//here's the splitpane where I should display the TruthTable_1 panel but it doesn't diplay
lg.p1.add(lg.gatessplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, s,kl));
lg.gatessplit.setOneTouchExpandable(true);
lg.gatessplit.setDividerLocation(250);
lg.gatessplit.setPreferredSize(new Dimension(900, 500));
lg.createAndShowGUI();
}});
}
Heres my code the TruthTable_1:constructors
public TruthTable_1() {
super();
tableArea.append("This is a Test");
//setBackground(Color.black);
createg();
setVisible(true);
}
public void createg(){
setLayout(new BorderLayout());
line= 0;
truth= 'T';
fallacy= 'F';
final JPanel top= new JPanel();
input= new TextField(35);
TFCheck= new Checkbox("Select for \"1/0\" (default\"T/F\")");
check= new JButton("Check");
check.addActionListener(this);
top.add(input);
top.add(TFCheck);
top.add(check);
top.setVisible(false);
tableArea= new JTextArea(16, 40);
tableArea.setEditable(false);
tableArea.setFont(new Font("Lucida Console", Font.PLAIN, 14));
// all letters are the same width in this font
go= new JButton("Do it to it!");
go.addActionListener(this);
input.addActionListener(this);
go.setVisible(false);
add(top, BorderLayout.NORTH);
scrolls= new JScrollPane(tableArea);// add scroll buttons to the area
add(scrolls, BorderLayout.CENTER);
add(go, BorderLayout.SOUTH);
setSize(535, 500);
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(100, 100);
}
public TruthTable_1(String f){
createg();
tableArea.append(run(f));
}

Categories

Resources