I have an issue where when I include the JPanel in my JFrame, it covers the entire screen. My code reads
import java.awt.*;
import javax.swing.*;
public class TestFrameExample extends JPanel {
static String TheQuestion;
static String QN1 = "Question 1: ";
static String Q1 = "What is Lead's chemical symbol?";
static String brk = "___________________";
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(new Color(135, 206, 250));
g.setFont(new Font("Tahoma", Font.BOLD, 48));
g.setColor(Color.WHITE);
g.drawString(QN1, 80, 100);
g.setFont(new Font("Tahoma", Font.BOLD, 48));
g.setColor(Color.WHITE);
g.drawString(brk, 60, 130);
g.setFont(new Font("Tahoma", Font.PLAIN, 36));
g.setColor(Color.WHITE);
g.drawString(Q1, 80, 200);
}
public static void main(String[] args) {
TestFrameExample graphics = new TestFrameExample();
JFrame ThisFrame = new JFrame();
TheQuestion = QN1;
JTextField txt = new JTextField(10);
JPanel Panel = new JPanel();
ThisFrame.setTitle("Question 1");
ThisFrame.setSize(720, 480);
ThisFrame.setLocationRelativeTo(null);
ThisFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ThisFrame.setVisible(true);
ThisFrame.add(graphics);
Panel.setBackground(new Color(135, 206, 250));
Panel.setSize(null);
Panel.setLocation(null);
Panel.add(txt);
ThisFrame.add(Panel);
}
}
However, when I change
Panel.setLocation(null)
to
Panel.setLocation(80, 250)
It covers the entire screen.
Could someone please help me put it in the right spot on the screen?
UPDATE
I made the modifications as I said in my comment, with the code reading
import java.awt.*;
import javax.swing.*;
public class TestFrameExample extends JPanel {
static String TheQuestion;
static String QN1 = "Question 1: ";
static String Q1 = "What is Lead's chemical symbol?";
static String brk = "___________________";
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(new Color(135, 206, 250));
g.setFont(new Font("Tahoma", Font.BOLD, 48));
g.setColor(Color.WHITE);
g.drawString(QN1, 80, 100);
g.setFont(new Font("Tahoma", Font.BOLD, 48));
g.setColor(Color.WHITE);
g.drawString(brk, 60, 130);
g.setFont(new Font("Tahoma", Font.PLAIN, 36));
g.setColor(Color.WHITE);
g.drawString(Q1, 80, 200);
}
public static void main(String[] args) {
TestFrameExample graphics = new TestFrameExample();
JFrame ThisFrame = new JFrame();
TheQuestion = QN1;
JTextField txt = new JTextField(20);
JPanel panel = new JPanel();
ThisFrame.setTitle("Question 1");
ThisFrame.setSize(720, 480);
ThisFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ThisFrame.add(graphics);
panel.setBackground(new Color(135, 206, 250));
panel.add(txt);
ThisFrame.add(panel);
ThisFrame.add(panel, BorderLayout.PAGE_END);
ThisFrame.setLocationRelativeTo(null);
ThisFrame.setVisible(true);
}
}
It places the input txt at the bottom of the screen, but the rest of the screen remains grey.
But I simply don't understand the second set of code that you posted; it's far beyond my skill set (I've only been learning Java for the last 6 weeks). All I'm looking for at this stage is make the panel not blank out the rest of the screen.
Is this possible just by modifying the current set of code, or would I have to completely rewrite the code?
A JFrame's contentPane uses BorderLayout by default, and you can use that to your advantage:
Add your TestFrameExample object BorderLayout.CENTER to your JFrame
Add your other JPanel, or perhaps just a JTextField to the JFrame in the BorderLayout.PAGE_END position. This will add the component to the bottom of the GUI.
Don't call setLocation(...) on your components as that's inviting use of null layouts, a layout that leads to rigid GUI's that are hard to debug and upgrade.
For more details, read up on the BorderLayout in the tutorials.
e.g.,
public static void main(String[] args) {
TestFrameExample graphics = new TestFrameExample();
JFrame thisFrame = new JFrame();
TheQuestion = QN1;
JTextField txt = new JTextField(10);
JPanel panel = new JPanel();
thisFrame.setTitle("Question 1");
thisFrame.setSize(720, 480); // better to not do this, but to pack instead
// thisFrame.setLocationRelativeTo(null);
thisFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// thisFrame.setVisible(true); // *** not yet ***
thisFrame.add(graphics, BorderLayout.CENTER);
panel.setBackground(new Color(135, 206, 250));
// panel.setSize(null); // *** don't do this ***
// panel.setLocation(null); // *** don't do this ***
panel.add(txt);
thisFrame.add(panel, BorderLayout.PAGE_END);
thisFrame.setLocationRelativeTo(null);
thisFrame.setVisible(true); // *** HERE ***
}
Note that myself, I'd avoid direct painting if possible and instead would use components and layout managers. This should make it easier to display different kinds of questions. For example, run the following program and by pressing the <enter> key repeatedly, scroll the questions to see just what I mean:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class TestQuestion2 extends JPanel {
private static final Color BACKGROUND = new Color(135, 206, 250);
private static final Color LABEL_FOREGROUND = Color.white;
private static final int EB_GAP = 60;
private static final int PREF_W = 720;
private static final int PREF_H = 480;
private static final Font TITLE_FONT = new Font("Tahoma", Font.BOLD, 48);
private static final Font Q_FONT = TITLE_FONT.deriveFont(Font.PLAIN, 36f);
private JLabel questionTitleLabel = new JLabel();
private JTextArea questionArea = new JTextArea(4, 10);
private JTextField answerField = new JTextField(20);
private Question question;
private List<Question> questionList;
private int questionListIndex = 0;
public TestQuestion2(List<Question> questionList) {
this.questionList = questionList;
questionTitleLabel.setFont(TITLE_FONT);
questionTitleLabel.setForeground(LABEL_FOREGROUND);
JSeparator separator = new JSeparator();
separator.setForeground(LABEL_FOREGROUND);
questionArea.setFont(Q_FONT);
questionArea.setForeground(LABEL_FOREGROUND);
questionArea.setWrapStyleWord(true);
questionArea.setLineWrap(true);
questionArea.setBorder(null);
questionArea.setOpaque(false);
questionArea.setFocusable(false);
JScrollPane scrollPane = new JScrollPane(questionArea);
scrollPane.setBorder(null);
scrollPane.setOpaque(false);
scrollPane.getViewport().setOpaque(false);
JPanel answerPanel = new JPanel();
answerPanel.add(answerField);
answerPanel.setOpaque(false);
setBackground(BACKGROUND);
setBorder(BorderFactory.createEmptyBorder(EB_GAP, EB_GAP, EB_GAP, EB_GAP));
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
add(questionTitleLabel);
add(Box.createHorizontalStrut(10));
add(separator);
add(Box.createHorizontalStrut(5));
add(scrollPane);
add(Box.createHorizontalGlue());
add(answerPanel);
setQuestion(questionList.get(questionListIndex));
answerField.addActionListener(new AnswerListener());
}
public void setQuestion(Question question) {
this.question = question;
questionTitleLabel.setText("Question " + question.getNumber() + ":");
questionArea.setText(question.getQuestion());
}
#Override
public Dimension getPreferredSize() {
Dimension superSz = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSz;
}
int prefW = Math.max(superSz.width, PREF_W);
int prefH = Math.max(superSz.height, PREF_H);
return new Dimension(prefW, prefH);
}
private class AnswerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
questionListIndex++;
questionListIndex %= questionList.size();
setQuestion(questionList.get(questionListIndex));
}
}
private static void createAndShowGui() {
List<Question> questionList = new ArrayList<>();
questionList.add(new Question(1, "What is Lead's chemical symbol?"));
questionList.add(new Question(2, "Who is buried in Grant's tomb?"));
questionList.add(new Question(3, "What ..... is your quest?"));
questionList.add(new Question(4, "What ..... is your favorite color?"));
questionList.add(new Question(5, "What is the capital of Assyria?"));
questionList.add(new Question(6, "What is the airspeed velocity of the unladen laden swallow?"));
questionList.add(new Question(7, "This will be a very long question, one that shows the display "
+ "of multiple lines, and a JTextArea that looks like a JLabel. "
+ "What do you think of it?"));
TestQuestion2 testQuestion2Panel = new TestQuestion2(questionList);
JFrame frame = new JFrame("Question");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(testQuestion2Panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class Question {
private int number;
private String question;
private List<String> possibleAnswers;
public Question(int number, String question) {
this.number = number;
this.question = question;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
}
Related
I created FlashScreen.java as loading screen consist of JProgressBar.
I want that after progressbar percentage is completed current window should be closed and new window should be open.
I made it but after closing first window in next window there is no component in window. Empty window is opening.
Here is code:
FlashScreen.java
package crimeManagement;
import javax.swing.*;
import java.awt.Rectangle;
import java.awt.Font;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class FlashScreen extends JFrame{
JProgressBar jb;
JLabel lblStat;
int i=0,num=0;
FlashScreen(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setBounds(new Rectangle(400, 200, 0, 0));
jb=new JProgressBar(0,2000);
jb.setBounds(100,219,579,22);
jb.setValue(0);
jb.setStringPainted(true);
getContentPane().add(jb);
setSize(804,405);
getContentPane().setLayout(null);
lblStat = new JLabel("");
lblStat.setForeground(Color.CYAN);
lblStat.setHorizontalAlignment(SwingConstants.CENTER);
lblStat.setHorizontalTextPosition(SwingConstants.CENTER);
lblStat.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 18));
lblStat.setBounds(229, 252, 329, 14);
getContentPane().add(lblStat);
JLabel lblBackGround = new JLabel("");
lblBackGround.setHorizontalTextPosition(SwingConstants.CENTER);
lblBackGround.setHorizontalAlignment(SwingConstants.CENTER);
lblBackGround.setIcon(new ImageIcon(FlashScreen.class.getResource("/Images/FlashImage.jpg")));
lblBackGround.setBounds(0, 0, 798, 376);
getContentPane().add(lblBackGround);
}
public void iterate(){
while(i<=2000){
jb.setValue(i);
i=i+20;
try{
Thread.sleep(50);
if(i==20)
{
lblStat.setText("Loading...");
}
if(i==500)
{
lblStat.setText("Please Wait...");
}
if(i==1000)
{
Thread.sleep(100);
lblStat.setText("Loading Police Station Management System...");
}
if(i==1200)
{
lblStat.setText("Please Wait...");
}
if(i==1600)
{
lblStat.setText("Almost Done...");
}
if(i==1980)
{
lblStat.setText("Done");
}
if(i==2000)
{
this.dispose();
LoginPage lp=new LoginPage();
lp.setVisible(true);
}
}
catch(Exception e){}
}
}
public static void main(String[] args) {
FlashScreen fs=new FlashScreen();
fs.setVisible(true);
fs.iterate();
}
}
**LoginPage.java**
package crimeManagement;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.border.*;
public class LoginPage extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JFrame frame;
private JTextField txtUserName;
private JPasswordField txtPass;
public static void main(String[] args) {
LoginPage window = new LoginPage();
window.frame.setVisible(true);
}
public LoginPage() {
frame = new JFrame();
frame.setResizable(false);
frame.getContentPane().setBackground(SystemColor.inactiveCaption);
frame.getContentPane().setFont(new Font("Tahoma", Font.PLAIN, 16));
frame.setBounds(100, 100, 554, 410);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblLoginType = new JLabel("Login Type");
lblLoginType.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblLoginType.setBounds(97, 53, 99, 20);
frame.getContentPane().add(lblLoginType);
JLabel lblUsename = new JLabel("User Name");
lblUsename.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblUsename.setBounds(97, 177, 99, 26);
frame.getContentPane().add(lblUsename);
JLabel lblPaaword = new JLabel("Password");
lblPaaword.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblPaaword.setBounds(97, 223, 99, 26);
frame.getContentPane().add(lblPaaword);
JPanel panel = new JPanel();
FlowLayout flowLayout = (FlowLayout) panel.getLayout();
panel.setBackground(SystemColor.inactiveCaptionBorder);
panel.setBounds(210, 47, 143, 93);
frame.getContentPane().add(panel);
TitledBorder tb=new TitledBorder( "Login");
tb.setTitleJustification(TitledBorder.CENTER);
tb.setTitlePosition(TitledBorder.CENTER);
panel.setBorder(BorderFactory.createTitledBorder(tb));
JRadioButton rdbAdmin = new JRadioButton("Admin");
rdbAdmin.setBackground(SystemColor.inactiveCaption);
rdbAdmin.setFont(new Font("Tahoma", Font.PLAIN, 13));
rdbAdmin.setSelected(true);
panel.add(rdbAdmin);
JRadioButton rdbOthers = new JRadioButton("Others");
rdbOthers.setBackground(SystemColor.inactiveCaption);
rdbOthers.setFont(new Font("Tahoma", Font.PLAIN, 13));
panel.add(rdbOthers);
txtUserName = new JTextField();
txtUserName.setBackground(UIManager.getColor("TextField.background"));
txtUserName.setBounds(210, 177, 158, 26);
frame.getContentPane().add(txtUserName);
txtUserName.setColumns(30);
JButton btnLogin = new JButton("Login");
btnLogin.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnLogin.setBounds(210, 286, 71, 23);
frame.getContentPane().add(btnLogin);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
btnExit.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnExit.setBounds(297, 286, 71, 23);
frame.getContentPane().add(btnExit);
txtPass = new JPasswordField();
txtPass.setBounds(210, 226, 158, 26);
frame.getContentPane().add(txtPass);
}
}
You're displaying the wrong JFrame. Yes the LoginPage extends JFrame, and yes you display it, but you add no components to it, and instead add all components to a private JFrame field of the class named, frame.
A quick solution is to change your LoginPage class so that it doesn't extend JFrame and then give this class a public getFrame() method:
public JFrame getFrame() {
return frame;
}
and when wanting to show it, call
this.dispose();
LoginPage lp = new LoginPage();
// lp.setVisible(true);
lp.getFrame().setVisible(true);
but having said this, there are still some serious threading issues with your code that you'll eventually want to fix, including trying to avoid calling Thread.sleep() in code that risks being called on the Swing event thread.
Also please check out The Use of Multiple JFrames: Good or Bad Practice? to see why it is often a bad practice to display a bunch of JFrames in your app, and ways around this.
Other issues include use of null layouts. Yes they may seem like an easy way to create complex GUI's quickly -- until you try to show the GUI on another platform and find that they don't look so nice, or have to enhance, debug or change it, and find it very tricky and easy to mess up. Much better to use layout managers.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class FlashScreenTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame mainFrame = new JFrame("Main App");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.add(new MainAppPanel());
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
FlashScreenPanel dialogPanel = new FlashScreenPanel();
JDialog dialog = new JDialog(mainFrame, "Flash Screen", ModalityType.APPLICATION_MODAL);
dialog.add(dialogPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialogPanel.startProgress();
dialog.setVisible(true);
mainFrame.setVisible(true);
});
}
}
class FlashScreenPanel extends JPanel {
public static final String LOADING = "Loading...";
public static final String PLEASE_WAIT = "Please Wait...";
public static final String LOADING_POLICE_STATION = "Loading Police Station...";
public static final String ALMOST_DONE = "Almost Done...";
public static final String DONE = "Done";
private static final int TIMER_DELAY = 50;
private JProgressBar jb = new JProgressBar(0, 2000);
private JLabel statusLabel = new JLabel("", SwingConstants.CENTER);
public FlashScreenPanel() {
setPreferredSize(new Dimension(800, 400));
statusLabel.setForeground(Color.CYAN);
statusLabel.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 18));
jb.setStringPainted(true);
JPanel bottomPanel = new JPanel(new BorderLayout(20, 20));
bottomPanel.add(jb, BorderLayout.PAGE_START);
bottomPanel.add(statusLabel, BorderLayout.CENTER);
int eb = 40;
setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
setLayout(new GridLayout(0, 1));
add(new JLabel()); // dummy component to move prog bar lower
add(bottomPanel);
}
public void startProgress() {
statusLabel.setText(LOADING);
new Timer(TIMER_DELAY, new ActionListener() {
private int i = 0;
#Override
public void actionPerformed(ActionEvent e) {
i += 20;
jb.setValue(i);
if (i == 500) {
statusLabel.setText(PLEASE_WAIT);
} else
if (i == 1000) {
statusLabel.setText(LOADING_POLICE_STATION);
} else
if (i == 1200) {
statusLabel.setText(PLEASE_WAIT);
} else
if (i == 1600) {
statusLabel.setText(ALMOST_DONE);
} else
if (i == 1980) {
statusLabel.setText(DONE);
} else
if (i == 2000) {
((Timer) e.getSource()).stop();
Window win = SwingUtilities.getWindowAncestor(FlashScreenPanel.this);
win.dispose();
}
}
}).start();
}
}
class MainAppPanel extends JPanel {
public MainAppPanel() {
setPreferredSize(new Dimension(600, 400));
}
}
Im developing an little "clicker" but, if i press the button, and i should get 1+ Score, it dont work! Is there any way to reload or anything else?
Heres my code: (ClickEvent)
public class event implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("PRESS");
game.timesClicked.add(1);
points.setText(game.seePoints);
}
}
And there is my JFrame:
public class game extends JFrame
{
public static JButton buttonStart;
JButton buttonCredits;
JButton buttonBack;
JButton buttonLeave;
public static JFrame panel = new game();
public static ArrayList<Integer> timesClicked = new ArrayList<Integer>();
public static JLabel label1;
public static JLabel points;
public static String seePoints = "Deine Knöpfe: " + timesClicked.size();
public game()
{
setLayout(null);
label1 = new JLabel("ButtonClicker");
points = new JLabel(seePoints);
points.setFont(new Font("Tahoma", Font.BOLD, 15));
points.setBounds(0, 0, 200, 200);
label1.setFont(new Font("Tahoma", Font.BOLD, 50));
label1.setBounds(315, 50, 500, 200);
event e1 = new event();
JButton b = new JButton("KNOPF");
b.setBackground(new Color(96, 140, 247));
b.setForeground(Color.WHITE);
b.setFocusPainted(false);
b.setFont(new Font("Tahoma", Font.BOLD, 15));
b.setBounds( 402, 380, 180, 50 );
b.addActionListener(e1);
add(b);
add(label1);
add(points);
}
}
(Sorry For My Bad English)
public static String seePoints = "Deine Knöpfe: " + timesClicked.size();
This is only being called once at the start of your program. When you add to timesClicked, it does not recalculate seePoints.
You will need to set this variable to the correct value every time you click.
I am trying to get some Java skills back because i worked for a long time in webdevelopment. Now I am just create a main Jframe where are a little Menu and a Class createSchueler extends JPanel.
So what I want to do if you go into the Menu click Neu > Schueler
A new Jpanel should be created and added to the Window
Main Class
public class MainWindow {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 807, 541);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel createSchueler = new createSchueler();
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu mnNewMenu = new JMenu("Neu");
mnNewMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
createSchueler.setVisible(true);
frame.getContentPane().add(createSchueler);
}
});
menuBar.add(mnNewMenu);
JMenuItem mntmSchler = new JMenuItem("Sch\u00FCler");
mnNewMenu.add(mntmSchler);
JMenu mnBearbeiten = new JMenu("Bearbeiten");
menuBar.add(mnBearbeiten);
JMenuItem mntmSchler_1 = new JMenuItem("Sch\u00FCler");
mnBearbeiten.add(mntmSchler_1);
}
}
The createSchueler Class extends JPanel that i want to add to the frame
public class createSchueler extends JPanel {
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
/**
* Create the panel.
*/
public createSchueler() {
setLayout(null);
JLabel lblNeuenSchuelerErstellen = new JLabel("Neuen Schueler erstellen");
lblNeuenSchuelerErstellen.setFont(new Font("Tahoma", Font.PLAIN, 22));
lblNeuenSchuelerErstellen.setBounds(29, 27, 268, 27);
add(lblNeuenSchuelerErstellen);
JLabel lblVorname = new JLabel("Vorname");
lblVorname.setBounds(29, 102, 46, 14);
add(lblVorname);
textField = new JTextField();
textField.setBounds(97, 99, 172, 20);
add(textField);
textField.setColumns(10);
JLabel lblNachname = new JLabel("Nachname");
lblNachname.setBounds(29, 133, 69, 14);
add(lblNachname);
textField_1 = new JTextField();
textField_1.setBounds(97, 130, 172, 20);
add(textField_1);
textField_1.setColumns(10);
JLabel lblGeburtstag = new JLabel("Geburtstag");
lblGeburtstag.setBounds(29, 169, 69, 14);
add(lblGeburtstag);
textField_2 = new JTextField();
textField_2.setBounds(97, 166, 172, 20);
add(textField_2);
textField_2.setColumns(10);
ButtonGroup bg = new ButtonGroup();
JRadioButton rdbtnMnnlich = new JRadioButton("M\u00E4nnlich");
rdbtnMnnlich.setBounds(29, 206, 69, 23);
bg.add(rdbtnMnnlich);
JRadioButton rdbtnWeiblich = new JRadioButton("Weiblich");
rdbtnWeiblich.setBounds(97, 206, 109, 23);
bg.add(rdbtnWeiblich);
}
}
Everything is important hopefully :D
Use a CardLayout to swap JPanels rather than adding them by hand. If you must add them by hand, be sure that the receiving container's layout manager is up to the task and handles the addition well. For example BorderLayout would take it fine, but GroupLayout won't. If you do add or remove by hand, call revalidate(); and repaint() on the container after these changes.
Also you're using null layout in your added JPanel and contentPane which will completely ruin it's preferredSize calculation. Never use this layout. Learn to use and then use the layout managers. This is your main mistake.
For more on this, please read: Why is it frowned upon to use a null layout in Swing?
For example:
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class MainGui {
public static final String SCHUELER_PANEL = "Schueler Panel";
public static final String EMPTY = "Empty Panel";
private JPanel mainPanel = new JPanel();
private JMenuBar menuBar = new JMenuBar();
private CardLayout cardLayout = new CardLayout();
private SchuelerPanel schuelerPanel = new SchuelerPanel();
public MainGui() {
mainPanel.setLayout(cardLayout);
mainPanel.add(new JLabel(), EMPTY); // empty label
mainPanel.add(schuelerPanel, SCHUELER_PANEL);
JMenu menu = new JMenu("Panel");
menu.add(new JMenuItem(new SwapPanelAction(EMPTY)));
menu.add(new JMenuItem(new SwapPanelAction(SCHUELER_PANEL)));
menuBar.add(menu);
}
public JPanel getMainPanel() {
return mainPanel;
}
public JMenuBar getMenuBar() {
return menuBar;
}
#SuppressWarnings("serial")
private class SwapPanelAction extends AbstractAction {
public SwapPanelAction(String title) {
super(title);
int mnemonic = (int) title.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.show(mainPanel, (String) getValue(NAME));
}
}
private static void createAndShowGui() {
MainGui mainGui = new MainGui();
JFrame frame = new JFrame("Main Gui");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainGui.getMainPanel());
frame.setJMenuBar(mainGui.getMenuBar());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
and
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
#SuppressWarnings("serial")
public class SchuelerPanel extends JPanel {
private static final String TITLE_TEXT = "Lorem Ipsum Dolor Sit Amet";
public static final String[] LABEL_STRINGS = {"Monday", "Tuesday", "Wednesday"};
private Map<String, JTextField> labelFieldMap = new HashMap<>();
public SchuelerPanel() {
JLabel titleLabel = new JLabel(TITLE_TEXT, JLabel.CENTER);
titleLabel.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 20));
JPanel labelFieldPanel = new JPanel(new GridBagLayout());
for (int i = 0; i < LABEL_STRINGS.length; i++) {
addToPanel(labelFieldPanel, LABEL_STRINGS[i], i);
}
// Don't do what I'm doing here: avoid "magic" numbers!
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setLayout(new BorderLayout(10, 10));
add(titleLabel, BorderLayout.PAGE_START);
add(labelFieldPanel, BorderLayout.CENTER);
}
// get the text from the JTextField based on the JLabel associated with it
public String getText(String labelText) {
JTextField textField = labelFieldMap.get(labelText);
if (textField == null) {
throw new IllegalArgumentException("For labelText: " + labelText);
}
return textField.getText();
}
private void addToPanel(JPanel gblUsingPanel, String labelString, int row) {
JLabel label = new JLabel(labelString);
label.setFont(label.getFont().deriveFont(Font.BOLD));
JTextField textField = new JTextField(10);
labelFieldMap.put(labelString, textField);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = row;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.insets = new Insets(5, 5, 5, 5);
gblUsingPanel.add(label, gbc);
gbc.gridx = 1;
gbc.anchor = GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gblUsingPanel.add(textField, gbc);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("SchuelerPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new SchuelerPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
I'm trying to build a program and I am having trouble getting my ArrayList from another class to show up in a JComboBox. My program will look something like this but before where "Melissa" is written, I want to have a JComboBox that has a list of users and be able to select from it to get the results:
UPDATE Here is my error:
----jGRASP exec: javac -g UserHistory.java
UserHistory.java:20: error: cannot find symbol
String[] userListItems = users.toArray(new String[0]);
^
symbol: variable users
location: class UserHistory
Note: UserHistory.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
Here is my incomplete code which gives me an error because it cannot locate my arrayList:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.ArrayList;
public class UserHistory extends JPanel {
private JLabel jcomp1;
private JComboBox userList;
private JLabel jcomp3;
private JTextField selectedUser;
private JLabel jcomp5;
private JTextField pointsEarned;
private JLabel jcomp7;
private JList choresCompleted;
public UserHistory() {
//construct preComponents
String[] userListItems = users.toArray(new String[0]);
String[] choresCompletedItems = {"Item 1", "Item 2", "Item 3"};
//construct components
jcomp1 = new JLabel ("User History");
userList = new JComboBox(userListItems);
jcomp3 = new JLabel ("Below are the results of : ");
selectedUser = new JTextField (5);
jcomp5 = new JLabel ("Total points earned: ");
pointsEarned = new JTextField (5);
jcomp7 = new JLabel ("List of chores completed: ");
choresCompleted = new JList (choresCompletedItems);
//set components properties
userList.setToolTipText ("Select a user");
//adjust size and set layout
setPreferredSize (new Dimension (465, 343));
setLayout (null);
//add components
add (jcomp1);
add (userList);
add (jcomp3);
add (selectedUser);
add (jcomp5);
add (pointsEarned);
add (jcomp7);
add (choresCompleted);
//set component bounds (only needed by Absolute Positioning)
jcomp1.setBounds (120, 20, 70, 25);
userList.setBounds (210, 20, 100, 25);
jcomp3.setBounds (95, 70, 155, 25);
selectedUser.setBounds (245, 70, 100, 25);
jcomp5.setBounds (125, 105, 140, 25);
pointsEarned.setBounds (245, 105, 100, 25);
jcomp7.setBounds (95, 140, 160, 25);
choresCompleted.setBounds (245, 145, 100, 75);
}
public static void main (String[] args) {
JFrame frame = new JFrame ("UserHistory");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new UserHistory());
frame.pack();
frame.setVisible (true);
}
}
Here's my code for another panel that contains the ArrayList:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.JCheckBox;
public class ManageUsersGUI extends JPanel {
public ArrayList<User> users = new ArrayList<>();
private JLabel addNewUserLabel;
private JTextField addNewUserTextField;
private JLabel deleteUsersLabel;
private JButton addButton;
private JButton deleteButton;
private JPanel namePanel;
public ManageUsersGUI() {
//construct components
addNewUserLabel = new JLabel ("Add new User here:");
addNewUserTextField = new JTextField (0);
deleteUsersLabel = new JLabel ("Select which User(s) you would like to delete:");
addButton = new JButton ("Add");
deleteButton = new JButton ("Delete");
namePanel = new JPanel();
namePanel.setLayout(new BoxLayout(namePanel, BoxLayout.Y_AXIS));
//set components properties
addNewUserTextField.setToolTipText ("Enter name and click on Add button.");
addButton.setToolTipText ("Click here to Add new user.");
deleteButton.setToolTipText ("Click here to delete User(s) selected.");
//adjust size and set layout
setPreferredSize (new Dimension (580, 485));
setLayout (null);
//add components
add (addNewUserLabel);
add (addNewUserTextField);
add (deleteUsersLabel);
add (namePanel);
add (addButton);
add (deleteButton);
//set component bounds (only needed by Absolute Positioning)
addNewUserLabel.setBounds (85, 130, 120, 25);
addNewUserTextField.setBounds (235, 130, 125, 25);
deleteUsersLabel.setBounds (135, 225, 281, 25);
addButton.setBounds (385, 130, 100, 25);
namePanel.setBounds(225, 270, 140, 0);
deleteButton.setBounds (230, 335, 100, 25);
addButton.addActionListener(new AddButtonListener());
deleteButton.addActionListener(new DeleteButtonListener());
}
public ArrayList<User> getUser() {
return users;
}
private class AddButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = addNewUserTextField.getText();
users.add(new User(text));
// Display the changes.
JOptionPane.showMessageDialog(null, text + " has been added.");
JCheckBox nameCheckBox = new JCheckBox();
nameCheckBox.setText(addNewUserTextField.getText());
namePanel.add(nameCheckBox);
namePanel.setBounds(225, 270, 140, namePanel.getHeight() + 25);
deleteButton.setBounds(230, deleteButton.getY() + 25, 100, 25);
JFrame frame = (JFrame) getRootPane().getParent();
frame.setSize(frame.getWidth(), frame.getHeight() + 25);
frame.pack();
}
}
private class DeleteButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
for(Component component : namePanel.getComponents()) {
if(component instanceof JCheckBox) {
if(((JCheckBox)component).isSelected())
namePanel.remove(component);
}
}
namePanel.revalidate();
namePanel.repaint();
}
}
public static void main (String[] args) {
JFrame frame = new JFrame ("AddUsersPanel1");
frame.setTitle("Manage Users");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new ManageUsersGUI());
frame.pack();
frame.setVisible (true);
}
}
Here's my User class that was used to make the ArrayList:
public class User {
private String userName;
private int points = 0;
public User(String userName) {
this.userName = userName;
}
public User() {
userName = "";
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void addPoints(int chorePoints) {
points += chorePoints;
}
// public String toString() {
// return userName + "\n";
// }
}
First of all you would better call user manager module from history main like
JFrame frame = new JFrame ("UserHistory");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new UserHistory());
frame.pack();
frame.setVisible (true);
manageUsers();
Which will start both JPanels so you can manage users and watch history at the same time.
Additionally,
// in ManageUsersGUI
public static void manageUsers() {
JFrame frame = new JFrame ("AddUsersPanel1");
frame.setTitle("Manage Users");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new ManageUsersGUI());
frame.pack();
frame.setVisible (true);
}
And one more thing, as soon as you initialize userlist you need to attach a listener like below:
userList = new JComboBox(userListItems);
userList.addPopupMenuListener(new PopupMenuListener() {
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
userList.removeAllItems();
for (User user: users) {
userList.addItem(user.getUserName());
}
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
#Override
public void popupMenuCanceled(PopupMenuEvent e) {
}
});
These two corrections would you make be able to list user names on the combo box and the dynamic change of user list would be reflected to the listing in the box.
Cheers.
Let me upload the whole source code here
User.java -- Source code just follows (I don't know why they came out of box.)
package userchorelist;
public class User {
private String userName;
private int points = 0;
public User(String userName) {
this.userName = userName;
}
public User() {
userName = "";
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void addPoints(int chorePoints) {
points += chorePoints;
}
}
ManageUsersGUI.java -- Source code just follows (I don't know why they came out of box, again.)
package userchorelist;
import javax.swing.;
import java.awt.;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.JCheckBox;
public class ManageUsersGUI extends JPanel {
public static ArrayList users = new ArrayList<>();
private JLabel addNewUserLabel;
private JTextField addNewUserTextField;
private JLabel deleteUsersLabel;
private JButton addButton;
private JButton deleteButton;
private JPanel namePanel;
public ManageUsersGUI() {
//construct components
addNewUserLabel = new JLabel ("Add new User here:");
addNewUserTextField = new JTextField (0);
deleteUsersLabel = new JLabel ("Select which User(s) you would like to delete:");
addButton = new JButton ("Add");
deleteButton = new JButton ("Delete");
namePanel = new JPanel();
namePanel.setLayout(new BoxLayout(namePanel, BoxLayout.Y_AXIS));
//set components properties
addNewUserTextField.setToolTipText ("Enter name and click on Add button.");
addButton.setToolTipText ("Click here to Add new user.");
deleteButton.setToolTipText ("Click here to delete User(s) selected.");
//adjust size and set layout
setPreferredSize (new Dimension (580, 485));
setLayout (null);
//add components
add (addNewUserLabel);
add (addNewUserTextField);
add (deleteUsersLabel);
add (namePanel);
add (addButton);
add (deleteButton);
//set component bounds (only needed by Absolute Positioning)
addNewUserLabel.setBounds (85, 130, 120, 25);
addNewUserTextField.setBounds (235, 130, 125, 25);
deleteUsersLabel.setBounds (135, 225, 281, 25);
addButton.setBounds (385, 130, 100, 25);
namePanel.setBounds(225, 270, 140, 0);
deleteButton.setBounds (230, 335, 100, 25);
addButton.addActionListener(new AddButtonListener());
deleteButton.addActionListener(new DeleteButtonListener());
}
public ArrayList<User> getUser() {
return users;
}
private class AddButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String text = addNewUserTextField.getText();
users.add(new User(text));
// Display the changes.
JOptionPane.showMessageDialog(null, text + " has been added.");
JCheckBox nameCheckBox = new JCheckBox();
nameCheckBox.setText(addNewUserTextField.getText());
namePanel.add(nameCheckBox);
namePanel.setBounds(225, 270, 140, namePanel.getHeight() + 25);
deleteButton.setBounds(230, deleteButton.getY() + 25, 100, 25);
JFrame frame = (JFrame) getRootPane().getParent();
frame.setSize(frame.getWidth(), frame.getHeight() + 25);
frame.pack();
}
}
private class DeleteButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
for(Component component : namePanel.getComponents()) {
if(component instanceof JCheckBox) {
if(((JCheckBox)component).isSelected())
namePanel.remove(component);
}
}
namePanel.revalidate();
namePanel.repaint();
}
}
public static void main (String[] args) {
JFrame frame = new JFrame ("AddUsersPanel1");
frame.setTitle("Manage Users");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new ManageUsersGUI());
frame.pack();
frame.setVisible (true);
}
// in ManageUsersGUI
public static void manageUsers() {
JFrame frame = new JFrame ("AddUsersPanel1");
frame.setTitle("Manage Users");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new ManageUsersGUI());
frame.pack();
frame.setVisible (true);
}
}
UserHistory.java -- Source code just follows (I don't know why they came out of box, third and final time.)
import java.awt.;
import javax.swing.;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import userchorelist.ManageUsersGUI;
import static userchorelist.ManageUsersGUI.manageUsers;
import static userchorelist.ManageUsersGUI.users;
import userchorelist.User;
public class UserHistory extends JPanel {
private JLabel jcomp1;
private JComboBox userList;
private JLabel jcomp3;
private JTextField selectedUser;
private JLabel jcomp5;
private JTextField pointsEarned;
private JLabel jcomp7;
private JList choresCompleted;
public UserHistory() {
//construct preComponents
String[] userListItems = new String[users.size()];
String[] choresCompletedItems = {"Item 1", "Item 2", "Item 3"};
//construct components
jcomp1 = new JLabel ("User History");
userList = new JComboBox(userListItems);
userList.addPopupMenuListener(new PopupMenuListener() {
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
userList.removeAllItems();
for (User user: users) {
userList.addItem(user.getUserName());
}
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
#Override
public void popupMenuCanceled(PopupMenuEvent e) {
}
});
jcomp3 = new JLabel ("Below are the results of : ");
selectedUser = new JTextField (5);
jcomp5 = new JLabel ("Total points earned: ");
pointsEarned = new JTextField (5);
jcomp7 = new JLabel ("List of chores completed: ");
choresCompleted = new JList (choresCompletedItems);
//set components properties
userList.setToolTipText ("Select a user");
//adjust size and set layout
setPreferredSize (new Dimension (465, 343));
setLayout (null);
//add components
add (jcomp1);
add (userList);
add (jcomp3);
add (selectedUser);
add (jcomp5);
add (pointsEarned);
add (jcomp7);
add (choresCompleted);
//set component bounds (only needed by Absolute Positioning)
jcomp1.setBounds (120, 20, 70, 25);
userList.setBounds (210, 20, 100, 25);
jcomp3.setBounds (95, 70, 155, 25);
selectedUser.setBounds (245, 70, 100, 25);
jcomp5.setBounds (125, 105, 140, 25);
pointsEarned.setBounds (245, 105, 100, 25);
jcomp7.setBounds (95, 140, 160, 25);
choresCompleted.setBounds (245, 145, 100, 75);
}
public static void main (String[] args) {
JFrame frame = new JFrame ("UserHistory");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new UserHistory());
frame.pack();
frame.setVisible (true);
manageUsers();
}
}
I suggest you add receive the list of users as an explicit parameter in both classes UserHistory and ManageUsersGUI:
class UserHistory
{
private final List<User> users;
public UserHistory(List<User> users)
{
super();
this.users=users;
...
}
}
class ManageUsersGUI
{
private final List<User> users;
public UserHistory(List<User> users)
{
super();
this.users=users;
...
}
}
Then, you can create a unique list of users as an external class, let's say UserManagement, and make it a singleton:
public class UserManagement
{
private static final UserManagement INSTANCE=new UserManagement();
private final List<User> list=new ArrayList<User>();
public static UserManagement getInstance()
{
return INSTANCE;
}
private UserManagement()
{
}
public List<User> getUsers()
{
return users;
}
}
Then, you must provide the list of users when instatiating both classes in the main methods (and further, future instatiations you may have):
public static void main (String[] args) {
...
UserManagement.getInstance().getUsers().add("winkum");
UserManagement.getInstance().getUsers().add("blinkum");
UserManagement.getInstance().getUsers().add("nod");
frame.getContentPane().add (new UserHistory(UserManagement.getInstance().getUsers()));
...
}
public class FrameTest extends JFrame {
private JPanel contentPane;
private JPanel spielPane;
private JPanel infoPane;
private JButton btnStart;
private JLabel lblRunde;
private Monster monster1;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FrameTest frame = new FrameTest();
frame.setVisible(true);
Monster m = new Monster();
frame.repaintSpielPanel();
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
public FrameTest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
spielPane = new JPanel();
spielPane.setBounds(6, 6, 566, 566);
spielPane.setLayout(null);
spielPane.setBackground(Color.yellow);
contentPane.add(spielPane);
infoPane = new JPanel();
infoPane.setBounds(578, 6, 216, 566);
infoPane.setLayout(null);
infoPane.setBackground(Color.yellow);
contentPane.add(infoPane);
btnStart = new JButton("Start");
btnStart.setBounds(44, 6, 117, 29);
infoPane.add(btnStart);
lblRunde = new JLabel("Runde");
lblRunde.setBounds(77, 47, 61, 16);
infoPane.add(lblRunde);
monster1 = new Monster();
monster1.setVisible(true);
spielPane.add(monster1);
}
private class Monser extends JLabel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(0, 0, 10, 10);
}
}
public void repaintSpielPanel() {
spielPane.repaint();
}
}
I tried to put a Rectangle into my frame, but it isn't there. I'm just starting to program, so probably I just don't know how to get it onto the screen. Pls help!
Don't paint in a JLabel which isn't opaque. Instead do so in a JPanel.
Don't use null layouts and setBounds(...). While null layouts and setBounds() might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
Most important, you never add an instance of your drawing component, here Monser, to anything. To see that this is true, search your code for any calls to new Monser(). If a constructor isn't being called, an instance isn't going to be created.
Also note that you're creating a Monster instance, and this is a class that you've not shown us.
You're adding it to a null layout using JPanel, and so since it has no size, it won't show at all. Again, don't use null layouts.
For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class MyTest extends JPanel {
private static final Color BG = Color.yellow;
private static final int GAP = 8;
private JButton btnStart = new JButton("Start");
private JLabel lblRunde = new JLabel("Runde", SwingConstants.CENTER);
private MonsterPanel monsterPanel = new MonsterPanel(600, 600, BG);
public MyTest() {
JPanel buttonPanel = createButtonPanel();
buttonPanel.setBackground(BG);
setLayout(new BorderLayout(GAP, GAP));
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
add(monsterPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.LINE_END);
}
private JPanel createButtonPanel() {
JPanel btnPanel = new JPanel();
btnPanel.setBackground(BG);
JPanel gridPanel = new JPanel(new GridLayout(0, 1, 0, 5));
gridPanel.setOpaque(false);
gridPanel.add(btnStart);
gridPanel.add(lblRunde);
btnPanel.add(gridPanel);
return btnPanel;
}
private static void createAndShowGui() {
MyTest mainPanel = new MyTest();
JFrame frame = new JFrame("MyFrameTest");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class MonsterPanel extends JPanel {
public static final int MONST_WIDTH = 10;
public static final Color MONST_COLOR = Color.red;
private int prefW;
private int prefH;
private int monstX = 0;
private int monstY = 0;
public MonsterPanel(int prefW, int prefH, Color bkgrnd) {
this.prefW = prefW;
this.prefH = prefH;
setBackground(bkgrnd);
}
public void setMonstXY(int x, int y) {
this.monstX = x;
this.monstY = y;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(MONST_COLOR);
g.fillRect(monstX, monstY, MONST_WIDTH, MONST_WIDTH);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(prefW, prefH);
}
}