By default GridLayout(5,3) would add the components in this way:
A B C
D E F
G H I
J K L
M N O
To have the components disposed in the following positions:
A F K
B G L
C H M
D I N
E J O
I have this code:
//imports...
public class GridLayoutProblem {
private static final int NUM_ROWS = 5, NUM_COLMS=3;
private JPanel mainPanel = new JPanel();
private JPanel buttonPannel = new JPanel(new GridLayout(NUM_ROWS, NUM_COLMS));
private JButton btnA = new JButton("A");
private JButton btnB = new JButton("B");
//same with C, D...
private JButton btnO = new JButton("O");
private JComponent[] buttons = {
btnA, btnB, btnC, btnD, btnE,
btnF, btnG, btnH, btnI, btnJ,
btnK, btnL, btnM, btnN, btnO
};
public GridLayoutProblem(){
int i=0;
for (JComponent button : buttons){
int index = i%NUM_ROWS*NUM_COLMS+i/NUM_ROWS;
buttonPannel.add(button,index);
i++;
}
mainPanel.add(buttonPannel);
}
//...
But it results in:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: illegal component position.
I did a quick test and it seems you cannot skip indexes and add elements to higher index.
So your option is to do something like this,
for (int i = 0; i < NUM_ROWS*NUM_COLMS; i++){
int index = i%NUM_COLMS*NUM_ROWS+i/NUM_COLMS; // Note the change in calculation. Just interchange rows and colms from your algo.
buttonPannel.add(button[index],i);
}
Change buttonPannel.add(button,index); to buttonPannel.add(buttons[index]);. (You don't need a foreach-loop) GridLayout always adds the components like you showed in the first example, but if you can make your calculation for index right (see other answer), so it adds it like "A,F,K,B...", you can achieve what you want.
Run the code below to see how the buttons are being added:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
//imports...
public class GridLayoutProblem {
private static final int NUM_ROWS = 5, NUM_COLMS=3;
private static JPanel mainPanel = new JPanel();
private JPanel buttonPannel = new JPanel(new GridLayout(NUM_ROWS, NUM_COLMS));
private JButton btnA = new JButton("A");
private JButton btnB = new JButton("B");
private JButton btnC = new JButton("C");
private JButton btnD = new JButton("D");
private JButton btnE = new JButton("E");
private JButton btnF = new JButton("F");
private JButton btnG = new JButton("G");
private JButton btnH = new JButton("H");
private JButton btnI = new JButton("I");
private JButton btnJ = new JButton("J");
private JButton btnK = new JButton("K");
private JButton btnL = new JButton("L");
private JButton btnM = new JButton("M");
private JButton btnN = new JButton("N");
private JButton btnO = new JButton("O");
private JComponent[] buttons = {
btnA, btnB, btnC, btnD, btnE,
btnF, btnG, btnH, btnI, btnJ,
btnK, btnL, btnM, btnN, btnO
};
public static void main(String[] args) {
new GridLayoutProblem();
}
public GridLayoutProblem(){
JFrame frame = new JFrame();
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < NUM_ROWS * NUM_COLMS; i++) {
int index = i%NUM_COLMS*NUM_ROWS+i/NUM_COLMS;
buttonPannel.add(buttons[index]);
frame.revalidate();
frame.repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
mainPanel.add(buttonPannel);
frame.getContentPane().add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setVisible(true);
}
}
Related
In the following code I am creating a JFrame with a JMenuBar and JPanel, the later having three JTextFields and three JLabels. However, all the components of the JPanel are gathering in the center. I've set the layout before adding components so I don't think its this issue (which I've had before). If anyone has anybody ideas how to sort this out I would be much obliged.
public class InterfaceWindow {
private static final Logger LOGGER = Logger.getLogger(DownloadWindow.class.getName());
private JButton helpJButton;
private JButton copyToClipBoardJButton;
private JButton enterJButton;
private JButton selectFileJButton;
private JLabel pathJLabel;
private JLabel jobNameJLabel;
private JLabel emailJLabel;
private JTextField pathJTextField;
private JTextField jobNameJTextField;
private JTextField emailJTextField;
private JTextArea transcriptionJTextArea;
private JMenu accountJMenu;
private JMenu jobsJMenu;
private JMenu helpJMenu;
private JMenuBar toolBarJMenuBar = new JMenuBar();
private JMenuItem uploadYouTubeJMenuItem;
private JMenuItem uploadFileJMenuItem;
private JMenuItem downloadJMenuItem;
private JMenuItem helpJMenuItem;
private GridBagConstraints panelGbc = new GridBagConstraints();
private GridBagConstraints frameGbc = new GridBagConstraints();
private JPanel interfaceJPanel = new JPanel();
private String emptyField = "default";
private String filePath = "default";
public JButton getHelpJButton() {
return helpJButton;
}
public JButton getCopyToClipBoardJButton() {
return copyToClipBoardJButton;
}
public JButton getEnterJButton() {
return enterJButton;
}
public JButton getSelectFileJButton() {
return selectFileJButton;
}
public JFrame setInterfaceWindow() {
JFrame interfaceJFrame = new JFrame();
frameGbc.fill = GridBagConstraints.HORIZONTAL;
interfaceJPanel = setInterfaceJPanel();
interfaceJFrame.getContentPane().setLayout(new GridBagLayout());
interfaceJFrame.setLayout(new GridBagLayout());
interfaceJFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
interfaceJFrame.setTitle("Audio Transcribe");
interfaceJFrame.setSize(800, 800);
interfaceJFrame.setLocationRelativeTo(null);
interfaceJFrame.setJMenuBar(setToolBar(toolBarJMenuBar));
interfaceJFrame.add(interfaceJPanel, frameGbc);
interfaceJFrame.setVisible(true);
return interfaceJFrame;
}
private JPanel setInterfaceJPanel() {
panelGbc.fill = GridBagConstraints.HORIZONTAL;
panelGbc.insets.bottom = 1;
panelGbc.insets.top = 2;
panelGbc.insets.right = 1;
panelGbc.insets.left = 1;
panelGbc.weightx = 1;
panelGbc.weighty = 1;
interfaceJPanel.setLayout(new GridBagLayout());
interfaceJPanel.setSize(800, 700);
setJobName(interfaceJPanel);
setPath(interfaceJPanel);
setEmail(interfaceJPanel);
setButtons(interfaceJPanel);
setTextArea(interfaceJPanel);
setAction();
return interfaceJPanel;
}
public JMenuBar setToolBar(JMenuBar toolBarJMenuBar) {
accountJMenu = new JMenu("Accounts");
jobsJMenu = new JMenu("Jobs");
helpJMenu = new JMenu("Help");
toolBarJMenuBar.add(accountJMenu);
toolBarJMenuBar.add(jobsJMenu);
toolBarJMenuBar.add(helpJMenu);
downloadJMenuItem = new JMenuItem("Download");
uploadFileJMenuItem = new JMenuItem("Upload file");
uploadYouTubeJMenuItem = new JMenuItem("Upload from YouTube");
helpJMenuItem = new JMenuItem("Help");
jobsJMenu.add(downloadJMenuItem);
jobsJMenu.addSeparator();
jobsJMenu.add(uploadFileJMenuItem);
jobsJMenu.addSeparator();
jobsJMenu.add(uploadYouTubeJMenuItem);
helpJMenu.add(helpJMenuItem);
return toolBarJMenuBar;
}
private void setEmail(JPanel interfaceJPanel) {
JLabel emailLabel = new JLabel("Email:");
panelGbc.gridx = 1;
panelGbc.gridy = 3;
panelGbc.gridwidth = 1;
panelGbc.gridheight = 1;
interfaceJPanel.add(emailLabel, panelGbc);
emailJTextField = new JTextField();
emailJTextField.setText(emptyField);
panelGbc.gridx = 2;
panelGbc.gridy = 3;
panelGbc.gridwidth = 3;
panelGbc.gridheight = 1;
interfaceJPanel.add(emailJTextField, panelGbc);
}
private void setPath(JPanel interfaceJPanel) {
JLabel filePathLabel = new JLabel("File path:");
panelGbc.gridx = 1;
panelGbc.gridy = 0;
panelGbc.gridwidth = 1;
panelGbc.gridheight = 1;
interfaceJPanel.add(filePathLabel, panelGbc);
pathJTextField = new JTextField();
pathJTextField.setText(filePath);
panelGbc.gridx = 2;
panelGbc.gridy = 0;
panelGbc.gridwidth = 2;
panelGbc.gridheight = 1;
interfaceJPanel.add(pathJTextField, panelGbc);
}
private void setJobName(JPanel interfaceJPanel) {
JLabel jobNameLabel = new JLabel("Job name:");
panelGbc.gridx = 1;
panelGbc.gridy = 2;
panelGbc.gridwidth = 1;
panelGbc.gridheight = 1;
interfaceJPanel.add(jobNameLabel, panelGbc);
jobNameJTextField = new JTextField();
jobNameJTextField.setText(emptyField);
panelGbc.gridx = 2;
panelGbc.gridy = 2;
panelGbc.gridwidth = 2;
panelGbc.gridheight = 1;
interfaceJPanel.add(jobNameJTextField, panelGbc);
}
private void setAction() {
}
private void setTextArea(JPanel interfaceJPanel) {
}
private void setButtons(JPanel interfaceJPanel) {
}
}
It's because you're nesting two JPanels with GridBagLayout, and when adding the inner JPanel to the outer panel your frameGbc constraint does not have weightx or weighty set, centering the inner JPanel. The inner JPanel will size to its preferredSize, meaning, size as small as allowed, and will be centered.
Best not to do this. Instead let the JFrame continue to use BorderLayout, and add the GridBagLayout using JPanel BorderLayout.CENTER, or don't nest JPanels unnecessarily and just give the contentPane a GridBagLayout.
Im trying to make a hangman game in java using JPanels and labels, but I am struggling to get all of my panels showing up. I have to make a drawing of the hangman in a panel below the text field, but when I run my code the text field takes up the entire GUI and doesn't show my drawing at all. If anyone can help that would be great. Heres my code.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class GameMaker extends JFrame {
private JLabel label;
private JButton button;
private JButton button1;
private JLabel wordLabel = new JLabel("Word to Guess");
private JTextField text = new JTextField(5);
private JPanel wordPanel = new JPanel();
private JPanel displayPanel = new JPanel();
private JPanel renameThisField;
private Random random = new Random();
private String[] guesses = {"Brendan", "Vaughn", "Josh"};
private char[] randomWordToGuess =
guesses[random.nextInt(guesses.length)].toCharArray();
private int amountOfGuesses = randomWordToGuess.length;
private char[] playerGuess = new char[amountOfGuesses];
private Graphics g;
public GameMaker(){
createComponents();
}
public void createComponents(){
boolean wordIsGuessed = false;
int tries = 0;
for (int i = 0; i<playerGuess.length; i++){
playerGuess[i] = ' ';
printArray(playerGuess);
}
JLabel wordToGuessLabelBlank = new JLabel("_ _ _ _ _ _ _");
button = new JButton("Submit Letter");
ActionListener listener = new SubmitLetter();
button.addActionListener(listener);
button1 = new JButton("adasdasd");
ActionListener listener1 = new SubmitLetter();
button1.addActionListener(listener1);
label = new JLabel();
JLabel wordLength = new JLabel("The word to Guess is " + playerGuess.toString() +
"letters long.");
JPanel panel = new JPanel();
final int FIELD_WIDTH = 1;
final JTextField rateField = new JTextField(FIELD_WIDTH);
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(wordLabel);
panel.add(wordToGuessLabelBlank);
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(wordLength);
panel.add(rateField);
JComponent component = new BodyComponent();
panel.add(component);
panel.add(button);
panel.add(label);
add(panel);
}
public void printArray(char[] array){
for(int i = 0; i < array.length; i++){
System.out.println(array[i] + " ");
}
}
public class SubmitLetter implements ActionListener
{
public void actionPerformed(ActionEvent event){
}
/*This is where the magic happens.
* increment the numClicks and display results
*/
}
}
I am creating a game similar to the star wars game sabacc. I am trying to create a Jtextfield that has three card suites already on the screen. The user will press a button and depending on the button they press the card suit will change to a different suit. If they get three of the same suites they win. I am having trouble getting text onto the screen though. As of right now I keep getting an error saying non static method can not be referenced by a static content.
Here is my code for the main application :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CardApp extends JFrame implements ActionListener {
private JButton oneButton,
twoButton,
threeButton;
private int width = 25;
private int height = 15;
public CardApp() {
//JPanel boardPanel = new JPanel(new GridLayout(height,width));
JPanel buttonPanel = new JPanel(new GridLayout(1, 3));
JTextField TextField = new JTextField(30);
Hand settingTheText = new Hand();
TextField.setText(settingTheText.ListOfCards());
oneButton = new JButton("1");
twoButton = new JButton("2");
threeButton = new JButton("3");
// Listen for events on each button
oneButton.addActionListener(this);
twoButton.addActionListener(this);
threeButton.addActionListener(this);
// Add each to the panel of buttons
buttonPanel.add(oneButton);
buttonPanel.add(twoButton);
buttonPanel.add(threeButton);
// Add everything to a main panel attached to the content pane
JPanel mainPanel = new JPanel(new BorderLayout());
getContentPane().add(mainPanel);
mainPanel.add(TextField, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
setTitle("Sabacc Example by Angela Rucci");
setSize(375, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
int pressed = 0;
if (e.getSource() == oneButton){
pressed = 1;}
if (e.getSource() == twoButton){
pressed = 2;}
if (e.getSource() == threeButton){
pressed = 3;}
Hand handObject = new Hand();
///This IS WHERE IM GETTING MY ERROR!//
String screenText = handObject.ListOfCards();
TextField.setText(screenText);
}
public static void main(String[] args) {
CardApp c = new CardApp();
}
}
This is the other file where i am getting my list of suits
package cardapp;
import java.util.Random;
import javax.swing.JOptionPane;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Hand {
String [] Suits = {"C", "H", "S", "D"};
String [] probability = {"C","H","R","D"};
Random randomInt = new Random ();
String RandomSuit;
String RandomShuffle;
String ThreeSuits;
String LeftSuit;
String MiddleSuit;
String RightSuit;
int pressed = 0;
public int Discards(int pressedNumber){
return pressed;
}
public void Randomizer (){
int RandomSuitNumber = randomInt.nextInt(4);//this is generator a random number
//------------------Decide what hand to randomize --------------------------//
if (pressed==1){
LeftSuit= Suits[RandomSuitNumber];
}
if (pressed==2){
MiddleSuit=Suits[RandomSuitNumber];
}
if (pressed==3){
RightSuit=Suits[RandomSuitNumber];
}
//----------------20% chance of new random set------------------------------------//
int ProabilityRandomNum = randomInt.nextInt(5);//this will create a random number for probability array
RandomShuffle= probability[ProabilityRandomNum];//this will pick a random letter in proability array
//------------If proability array equals R then change all of the suits----------//
if (RandomShuffle.equals("R")){
JOptionPane.showMessageDialog(null, "Randomized Hand!");
int leftNumber = randomInt.nextInt(4);
int middleNumber = randomInt.nextInt(4);
int rightNumber = randomInt.nextInt(4);
LeftSuit= Suits[leftNumber];
MiddleSuit= Suits[middleNumber];
RightSuit= Suits[rightNumber];}
ThreeSuits = (LeftSuit + MiddleSuit + RightSuit);
}
public String ListOfCards (){
return ThreeSuits;
}
public void GameOver(){
if (LeftSuit == MiddleSuit && MiddleSuit == RightSuit &&
RightSuit== LeftSuit){
JOptionPane.showMessageDialog(null, "WINNER!!");
}
}
}
The variables are local to the method. the JTextField TextField is visible to the CardApp() only. if you want it to be available to the whole class, put it as a private class member :
public class CardApp extends JFrame implements ActionListener {
private JButton oneButton,
twoButton,
threeButton;
private int width = 25;
private private int height = 15;
// available to all methods
// better naming convention was JTextfield tf = new JTextField(30);
// even stackoverflow thinks its a class name :)
// see the color highlighting
private JTextField TextField = new JTextField(30);
public CardApp() {
//JPanel boardPanel = new JPanel(new GridLayout(height,width));
JPanel buttonPanel = new JPanel(new GridLayout(1, 3));
//JTextField TextField = new JTextField(30);
Hand settingTheText = new Hand();
TextField.setText(settingTheText.ListOfCards());
}
//
// code continues here ...
//
}
Hey I could use help debugging this program. The code is not mine, it is from an answer to a question and I wanted to try it but I get a NullPointerException and can't figure out where the problem is. I think the problem may be image paths but I am not sure so I could use help.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
public class CircleImages {
private int score = 0;
private JTextField scoreField = new JTextField(10);
public CircleImages() {
scoreField.setEditable(false);
final ImageIcon[] icons = createImageIcons();
final JPanel iconPanel = createPanel(icons, 8);
JPanel bottomLeftPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
bottomLeftPanel.add(new JLabel("Score: "));
bottomLeftPanel.add(scoreField);
JPanel bottomRightPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
JButton newGame = new JButton("New Game");
bottomRightPanel.add(newGame);
JButton quit = new JButton("Quit");
bottomRightPanel.add(quit);
JPanel bottomPanel = new JPanel(new GridLayout(1, 2));
bottomPanel.add(bottomLeftPanel);
bottomPanel.add(bottomRightPanel);
newGame.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
reset(iconPanel, icons);
score = 0;
scoreField.setText(String.valueOf(score));
}
});
JFrame frame = new JFrame();
frame.add(iconPanel);
frame.add(bottomPanel, BorderLayout.PAGE_END);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void reset(JPanel panel, ImageIcon[] icons) {
Component[] comps = panel.getComponents();
Random random = new Random();
for(Component c : comps) {
if (c instanceof JLabel) {
JLabel button = (JLabel)c;
int index = random.nextInt(icons.length);
button.setIcon(icons[index]);
}
}
}
private JPanel createPanel(ImageIcon[] icons, int gridSize) {
Random random = new Random();
JPanel panel = new JPanel(new GridLayout(gridSize, gridSize));
for (int i = 0; i < gridSize * gridSize; i++) {
int index = random.nextInt(icons.length);
JLabel label = new JLabel(icons[index]);
label.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
score += 1;
scoreField.setText(String.valueOf(score));
}
});
label.setBorder(new LineBorder(Color.GRAY, 2));
panel.add(label);
}
return panel;
}
private ImageIcon[] createImageIcons() {
String[] files = {"DarkGrayButton.png",
"BlueButton.png",
"GreenButton.png",
"LightGrayButton.png",
"OrangeButton.png",
"RedButton.png",
"YellowButton.png"
};
ImageIcon[] icons = new ImageIcon[files.length];
for (int i = 0; i < files.length; i++) {
icons[i] = new ImageIcon(getClass().getResource("/circleimages/" + files[i]));
}
return icons;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CircleImages();
}
});
}
}
Your problem is here:
icons[i] = new ImageIcon(getClass().getResource("/circleimages/" + files[i]));
You don't have the required images in your project, so getClass().getResource() will return null and you will have a NullPointerException in the constructor of ImageIcon.
What you have to do is put the following files in your project:
/circleimages/DarkGrayButton.png
/circleimages/BlueButton.png
/circleimages/GreenButton.png
/circleimages/LightGrayButton.png
/circleimages/OrangeButton.png
/circleimages/RedButton.png
/circleimages/YellowButton.png
So I am working on this small program when I ran in to this problem.Its mostly about location set up with GridBagLayout it wont show me the text for the JLable.Another problem is that every ones in a will my progress that was working stops working and later comes back.Any idea what it is?I would also like some one too help me with the location problem I want to place the JTextField in the bottom left corner any help?I cant go around this problem and no info online to specifically help me.So maybe you can help me.Hers my code so far...
package Main;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class code extends JFrame{
public static JTextField consol;
public static String title = "Metal-Lock:The Start";
public static Dimension size = new Dimension(650, 550);
public static JPanel panel;
public static JButton enter;
public static JLabel output;
public static void main(String args[]) {
code frame = new code();
}
public code() {
setTitle(title);
setSize(size);
setResizable(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
// VISITOR LIST
CONSOL();
P1();
P2();
}
//******************************************************************************************************************************
public void CONSOL() {
consol = new JTextField(30);
consol.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
String input = consol.getText();
output.setText(input);
}});
final JButton enter = new JButton("Enter");
enter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
String input = consol.getText();
output.setText(input);
panel.add(consol);
add(panel);
panel.add(enter);
add(panel);
output = new JLabel();
panel.add(output);
add(panel);
}
});
}
//******************************************************************************************************************************
public void P1() {
}
//******************************************************************************************************************************
public static JLabel grid1;
public static JLabel grid2;
public static JLabel grid3;
public static JLabel grid4;
public static JLabel grid5;
public void P2() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints R = new GridBagConstraints();
JLabel grid1 = new JLabel ("Hello"); panel.add(grid1, R);
R.gridx = 0; R.gridy = 0;
JLabel grid2 = new JLabel ("Hello"); panel.add(grid2, R);
R.gridx = 0; R.gridy = 0;
JLabel grid3 = new JLabel ("Hello"); panel.add(grid3, R);
R.gridx = 0; R.gridy = 0;
JLabel grid4 = new JLabel ("Hello"); panel.add(grid4, R);
R.gridx = 0; R.gridy = 0;
JLabel grid5 = new JLabel ("Hello"); panel.add(grid5, R);
R.gridx = 0; R.gridy = 0;
}
}
Just went really quickly through your code.
Change these lines:
GridBagConstraints R = new GridBagConstraints();
R.gridx = 0; R.gridy = 0;
JLabel grid1 = new JLabel ("Hello");
//important to set these R values BEFORE you ad grid1.
panel.add(grid1, R);
Change this in all lines there...
You are adding 6 Labels all to the location gridx=0 and gridy=0, which is wrong. Imagine it like an excel tabel, you are inserting every label to field 1.
If you want to add fields do it like this
E.g.
x y
z
//a.gridx=0; a.gridy=0;
//y.gridx=1; y.gridy=0;
//z.gridx=0; z.gridy=1;
x coordinates are horizontal.
y are vertical starting from the top left corner.
Read this article, it's really good:
http://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html