So I'm working an an assignment and I seemed to be stuck on a bug I can't seem to overcome. Essentially when trying to create a 10x10 grid, it isn't appearing while everything else (eg. title and menu) is when I'm running the application. Here's the essential part of what I've done so far
public class minesweeperGUI extends JFrame{
private JFrame gameGUI;
private JPanel board;
private JButton[][] boardButtons = new JButton [10][10];
public minesweeperGUI(){
gameGUI = new JFrame("Enhanced Minesweeper"); //Title of the Window
gameGUI.setVisible(true); //We want (true) to set it visible
gameGUI.setSize(400,550); //400 550
gameGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //This will close the frame when you press X. IMPORTANT
gameGUI.getContentPane().setBackground(Color.CYAN);
gameGUI.setLayout(null);
//Panel for minesweeper board
board = new JPanel();
GridLayout experimentLayout = new GridLayout(10, 10);
board.setLayout(experimentLayout);
board.setSize(400,550);
for(int x=0;x<boardButtons.length;x++){
for(int y=0;y<boardButtons[x].length;y++){
boardButtons[x][y] = new JButton();
board.add(boardButtons[x][y]);
}
}
gameGUI.add(board);
}
public static void main(String[] args) {
minesweeperGUI mainInterface = new minesweeperGUI();
}
}
Any type of help would be greatly appreciated :)
gameGUI.setVisible(true); //We want (true) to set it visible
yes but its should be last code line in minesweeperGUI(), otherwise you added JComponents to the already visible Swing Gui (missing notifier for automatical refresh, repaint)
minesweeperGUI mainInterface = new minesweeperGUI();
should be wrapped into invokeLater, more in Oracle trail Initial Thread
class name should be MinesweeperGUI, search for Java Namings Convention
gameGUI.setLayout(null); and board.setSize(400,550);
missing there setBounds for board.setSize(400,550); (placing JPanel to JFrame, because JPanel has zero Dimension)
there no reason to use null layout, remove gameGUI.setLayout(null);
override getPreferredSize for private JPanel board;
remove code lines gameGUI.setLayout(null); and board.setSize(400,550);
add code line pack() before setVisible(true), for proper sizing for JFrame (based on getPreferredSize for private JPanel board;)
Remove the gameGUI.setLayout(null); call and move the next line to be after buttons adding
gameGUI.setSize(400,550); //400 550
gameGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //This will close the frame when you press X. IMPORTANT
gameGUI.getContentPane().setBackground(Color.CYAN);
gameGUI.setVisible(true); //We want (true) to set it visible
I think one Problem is that you mix up your instances...
public static void main(String[] args) {
minesweeperGUI mainInterface = new minesweeperGUI();
}
makes a new Instance of your minesweeperGUI wich extends JFrame - so this simply makes a new JFrame...
but in your construktor you create another JFrame instance private JFrame gameGUI; and gameGUI = new JFrame("Enhanced Minesweeper"); ...
i suggest you remove the private variable gameGUI (private JFrame gameGUI;) and use simply this for your layout...
//private JFrame gameGUI; //remove this one!
private JPanel board;
private JButton[][] boardButtons = new JButton [10][10];
public minesweeperGUI(){
super("Enhanced Minesweeper"); //construktor from superclass
this.setVisible(true); //use of this
this.setSize(400,550); //use of this
...
//Panel for minesweeper board
board = new JPanel();
GridLayout experimentLayout = new GridLayout(10, 10);
board.setLayout(experimentLayout);
board.setSize(400,550);
for(int x=0;x<boardButtons.length;x++){
for(int y=0;y<boardButtons[x].length;y++){
boardButtons[x][y] = new JButton();
board.add(boardButtons[x][y]);
}
}
this.add(board); //use of this
}
you don't HAVE to write this.setXXX() you can also simply write setVisible(true)for instance...
Related
I've started learning Java with Eclipse, and I altered the main function to pass two strings to the similarly altered GUI constructor (there was nothing passed before).
The GUI doesn't pop up on the screen now, but can be accessed from the task bar at the bottom of the screen. I was just wondering why this happened? I've pasted the shortened code below.
I've tried it multiple times, and tried to find the problem with keywords on the web.
public class MainButton
{
public static void main(String[] args)
{
String A = "title"; String B = "Button";
Agui a = new Agui(A,B);
//BEFORE Agui a = new Agui();
}
}
import javax.swing.*;
public class Agui extends JFrame
{
//BEFORE public Agui()
public Agui(String A, String B)
{
setTitle(A);
setSize(400, 400);
// Create JButton and JPanel
JButton button = new JButton(B);
JPanel panel = new JPanel();
// Add button to JPanel
panel.add(button);
// And JPanel needs to be added to the JFrame itself!
this.getContentPane().add(panel);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
It'd be great to get the pop up without going to the task bar at the bottom of the screen, and to understand the logic of why this problem occurs.
I have 2 classes,
My main class creates a frame and I want another class to add content to it. A bit of reading arroudn told me I should use components to do this however when I run my code the frame is empty.
public static void main(String[] args)
{
// create frame
JFrame frame = new JFrame();
final int FRAME_WIDTH = 800;
final int FRAME_HEIGHT = 600;
// set frame attributes
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setTitle("My Frame");
frame.setVisible(true);
Component1 Com = new Component1();
Component add = frame.add(Com);
}
My Component class creates a JLabel
public class Component1 extends JComponent {
public void paintComponent()
{
JLabel label = new JLabel("<html>Some Text</html>");
}
}
I don't get any compile errors, however I dont get any text in my JFrame.
Can anyone explain what I'm doing wrong?
Chris
You need to add the JLabel. Also better to extend JPanel instead of JComponent as it has a default layout manager and will make any added components appear without the need to set component sizes. paintComponent is used for custom painting BTW.
public class Component1 extends JPanel {
Component1() {
JLabel label = new JLabel("<html>Some Text</html>");
add(label);
}
}
No need to create a new Component. Just call frame.getContentPane().add(label). And initialize your label before this.
I am writing a tetris game. When the application starts Jlabel with button "Play" opens. How do I switch to a different label (Board) within the existing Jframe?
Like this it opens the game directly.. But first I would want to use the ButtonPage class to show some welcome screen with a button instead and then call the game.
public class Tetris extends JFrame {
public Tetris(){
// JFrame Properties
setSize(198, 409);
setResizable(false);
setTitle("Tetris");
setDefaultCloseOperation(EXIT_ON_CLOSE);
// ButtonPage buttons = new ButtonPage();
// add(buttons);
// buttons.setOpaque(true);
Board board = new Board(this);
add(board);
board.start();
} // end of constructor
public static void main(String[] args){
Tetris game = new Tetris();
game.setLocationRelativeTo(null);
game.setVisible(true);
game.setLayout(null);
} // end of main
} // end of class
Here is the ButtonPage class.
public class ButtonPage extends JPanel implements ActionListener{
JButton buttonPLAY = new JButton();
JLabel backgroundImage = new JLabel();
public ButtonPage(){
setLayout(null);
ImageIcon buttonIcon = new ImageIcon(getClass().getResource("PlayButton.png"));
ImageIcon buttonIconHover = new ImageIcon(getClass().getResource("PlayButtonHover.png"));
ImageIcon buttonIconClicked = new ImageIcon(getClass().getResource("PlayButtonClicked.png"));
int buttonHeight = buttonIcon.getIconHeight();
int buttonWidth = buttonIcon.getIconWidth();
buttonPLAY.addActionListener(this);
buttonPLAY.setActionCommand("Play");
buttonPLAY.setIcon(buttonIcon);
buttonPLAY.setRolloverIcon(buttonIconHover);
buttonPLAY.setPressedIcon(buttonIconClicked);
buttonPLAY.setBorderPainted(false);
add(buttonPLAY);
Dimension size2 = getSize();
Dimension size = buttonPLAY.getPreferredSize();
buttonPLAY.setBounds((192 - buttonWidth)/2, 100 ,buttonWidth, buttonHeight);
}// end of constructor
#Override
public void actionPerformed(ActionEvent e) {
if ("Play".equals(e.getActionCommand())) {
Tetris game = new Tetris();
// opens the window in the middle of the screen
game.setLocationRelativeTo(null);
// set the tetris window visible, unless its true - its invisible DUH!
game.setVisible(true);
game.setLayout(null);
}
} // end of actionPerformed
}// end of class
Using the actionPerformed method I can open the game in a new Frame, but I have no idea how to switch the Panels.
Thanks in advance for any tips!
Tetris is intanciated from main, the following line from actionPerformed():
Tetris game = new Tetris();
instanciates a second Tetris, it's really what's you want?
To add several panels to a frame, only one visible at a time, use CardLayout.
Have you tried a card layout?
http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html
I'm currently doing a Java assignment as a computer science fresher. As a part of that assignment I'm trying to bring up a secondary frame that the user can write UML code into which will then be passed into my main application and then into a class diagram.
The bit that I'm stuck with is that the JTextBox that I have put into this secondary frame is the size I want it to be, however the writing starts in the middle and does not change to a new line when it gets to the other size of the frame.
This is the image of what is currently happening:
Code
And this is the code that I currently have for this class if it's needed.
package classdesign;
import java.awt.*;
import javax.swing.*;
public class ClassCreation extends JFrame {
private JFrame frame;
private JLabel instructionlabel;
private JTextField inputUML;
private JButton upButton;
private String Message;
public void ClassCreation(){
frame = new JFrame();
frame.setSize(300, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Class Design");
JPanel CreationPanel = new JPanel();
CreationPanel.setLayout(new BorderLayout());
instructionlabel = new JLabel("Fill Class details in using UML");
CreationPanel.add(instructionlabel,BorderLayout.NORTH);
inputUML = new JTextField("",20);
CreationPanel.add(inputUML,BorderLayout.CENTER);
frame.add(CreationPanel);
}
public Frame getFrame() {
return frame;
}
}
So, to summarise what I was hoping somebody could tell me how to do is to get the text input from the user to start in the top left and change to the next line when it gets to the far right, like any normal text editor etc...
use JTextPane or JEditorPane. Sample can be found at
http://docs.oracle.com/javase/tutorial/uiswing/components/editorpane.html
JTextField is a lightweight component that allows the editing of a single line of text. (source)
As it is a single-line component, whatever its size is the cursor will always be centered and will never go to the next line.
I would suggest you use a JTextArea as it is a multi-line area and allow the user to enter input as you want him to.
An example of using a text area (with a few other tips thrown in free - check the comments).
import java.awt.*;
import javax.swing.*;
// Has an instance of frame, does not need to extend it.
public class ClassCreation { //extends JFrame {
private JFrame frame;
private JLabel instructionlabel;
// as mentioned by talnicolas
private JTextArea inputUML;
// Don't give a method the same name as a class!!
//public void ClassCreation(){
public void initGui(){
frame = new JFrame();
//frame.setSize(300, 400); //pack() instead!
//frame.setLocationRelativeTo(null); // do something better
frame.setLocationByPlatform(true); // better!
//frame.setVisible(true); // do later
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Class Design");
JPanel CreationPanel = new JPanel();
CreationPanel.setLayout(new BorderLayout());
instructionlabel = new JLabel("Fill Class details in using UML");
CreationPanel.add(instructionlabel,BorderLayout.NORTH);
inputUML = new JTextArea("",7,30);
// very important next 2 lines
inputUML.setLineWrap(true);
inputUML.setWrapStyleWord(true);
// add it to a scrollpane
CreationPanel.add(new JScrollPane(inputUML),BorderLayout.CENTER);
frame.add(CreationPanel);
frame.pack(); // assume the natural size!
frame.setVisible(true);
for (int ii=0; ii<150; ii++) {
inputUML.append(SENTENCE);
inputUML.setCaretPosition( inputUML.getText().length() );
}
}
public static void main(String[] args) {
// Swing GUIs should be created and altered on the EDT.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ClassCreation cc = new ClassCreation();
cc.initGui();
}
});
}
private static String SENTENCE = "The quick brown fox jumps over the lazy dog! ";
}
I am creating a JPanel form which will contain several other JPanels. I want to place this inside a JScrollPane. Then I want to place the JScrollPane into a JTabbedPane as one of the tabs. I'm having a problem though -- my JPanel form winds up expanding when placed in the scrollpane even though I have set size, preferredsize, maximumsize, etc.
public class test
{
private static JFrame frame = new JFrame();
private static JTabbedPane pane0 = new JTabbedPane();
private static JScrollPane pane1 = new JScrollPane();
private static JPanel pane2 = new JPanel();
//add the rest of your JPanels here
public static void main(String[] args)
{
frame.setSize(400,400);
//add all the other attributes here
frame.add(pane0);
pane0.add(pane1);
pane1.add(pane2);
//go ahead and add the rest of your panels here
frame.pack();//resizes the frame so that its subcomponents fit well inside.
}
}//this last bracket is for the class itself. Sorry i couldn't tab everything the right //way.
Is this what you're trying to do? That's what i understood from your question. By the way, if your JPanel is expanding, change the size of your frame as well.