public class WASD extends JFrame{
Ellipse2D.Double ball;
int ballx = 100;
int bally = 100;
static JTextField typingArea;
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI(){
WASD frame = new WASD("frame");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.addComponentsToPane();
frame.pack();
frame.setVisible(true);
}
private void addComponentsToPane(){
typingArea = new JTextField(20);
//typingArea.addKeyListener(this);
}
public WASD(String name){
super(name);
}
}
When I run the program all I get is an empty window. The JTextField doesn't show up. Thanks!
(Apparently my post has too much code, so I'm adding this to make it let me submit. Ignore this sentence and the previous one.)
The JTextField needs to also be added to the frame after it is created.
private void addComponentsToPane(){
typingArea = new JTextField(20);
frame.add(typingArea);
}
Related
I don't understand why the RackBuilder object I added to the frame does not get displayed.
The code runs and the frame gets generated. I expect to see a panel with 42 rows, each row containing a JLabel "test". Is there something incorrect/missing from my constructor?
public class RackBuilderTool extends JPanel{
public RackBuilderTool() {
super(new GridLayout(42, 0));
for (int i = 0; i < 42; i++) {
add(new JLabel("test"));
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Rack Builder Tool");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
RackBuilderTool rackBuilder = new RackBuilderTool();
rackBuilder.setOpaque(true);
frame.setContentPane(rackBuilder);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Thanks!
import javax.swing.*;
import java.awt.*;
public class RackBuilderTool extends JPanel{
public RackBuilderTool() {
super(new GridLayout(42, 0));
for (int i = 0; i < 42; i++) {
add(new JLabel("test"));
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Rack Builder Tool");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
RackBuilderTool rackBuilder = new RackBuilderTool();
rackBuilder.setOpaque(true);
frame.setContentPane(rackBuilder);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
now it will show you 42 rows of your label.
Realized that the "run" button on Netbeans IDE is to run the entire project. As a result it was running another java file under the same project.
Once I right clicked on the java file I wanted to compile and clicked run it worked.
Thanks everyone for the help.
I'm building a program that requires swapping out the current, visible JPanel with another. Unfortunately there seems to be multiple to go about this and all of my attempts have ended in failure. I can successfully get the first JPanel to appear in my JFrame, but swapping JPanels results in a blank JFrame.
My Main JFrame:
public class ShellFrame {
static CardLayout cl = new CardLayout(); //handles panel switching
static JFrame frame; //init swing on EDT
static MainMenu mm;
static Panel2 p2;
static Panel3 p3;
public static void main(String[] args) {
initFrame();
}
public static void initFrame() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame = new JFrame();
frame.setDefaultCloseOperation(3);
frame.setLayout(cl);
mm = new MainMenu();
pp = new PlacementPanel();
//first panel added to frame will always show first
frame.add(mm, "MainMenu");
frame.pack(); //sizes frame to fit the panel being shown
frame.setVisible(true);
}
});
}
public static void switchPanel(String name) {
cl.show(frame.getContentPane(), name);
frame.pack();
}
public static void updatePanel2(/* args */) {
frame.removeAll();
p2 = new Panel2(/* args */);
frame.add(pp, "PlacementPanel");
frame.pack();
frame.validate();
frame.repaint();
}
I'm trying to use updatePanel2 to swap out the existing panel with a new Panel2 but It doesn't seem to be working. Panel2 works fine on it's own but trying to use it in conjunction with my program simply yields a blank window. Any help would be greatly appreciated!
that requires swapping out the current, visible JPanel with another
Have a look at CardLayout for a complete example of how to do it properly.
I have a Swing app which 'swaps' Panels when the user press the 'SPACE' key, showing a live plot of a running simulation. What i did goes like this:
public class MainPanel extends JPanel implements Runnable {
// Called when the JPanel is added to the JFrame
public void addNotify() {
super.addNotify();
animator = new ScheduledThreadPoolExecutor(1);
animator.scheduleAtFixedRate(this, 0, 1000L/60L, TimeUnit.MILLISECONDS);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (spacePressed)
plot.render(g);
else
simulation.render(g);
}
public void run() {
simulation.update();
repaint();
}
}
public class PlotView {
public void render(Graphics g) {
//draw the plot here
}
}
public class SimulationView {
public void render(Graphics g) {
//draw simulation here
}
}
This works very well for my 'show live plot' problem. And there's also the CardLayout approach, which you may turn into a new separate question if you having trouble. Good luck!
You should do .setVisible(false); to the panel which you want to be replaced.
Here is a working example, it switches the panels when you press "ENTER";
If you copy this in an IDE, automatically get the imports (shift+o in Eclipse);
public class MyFrame extends JFrame implements KeyListener {
private JButton button = new JButton("Change Panels");
private JPanel panelOnFrame = new JPanel();
private JPanel panel1 = new JPanel();
public MyFrame() {
// adding labels to panels, to distinguish them
panelOnFrame.add(new JLabel("panel on frame"));
panel1.add(new JLabel("panel 1"));
setSize(new Dimension(250,250));
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(button);
add(panelOnFrame);
setVisible(true);
addKeyListener(this);
addKeyListener(this);
setFocusable(true);
}
public static void main(String[] args) {
MyFrame frame = new MyFrame();
}
#Override
public void keyPressed(KeyEvent k) {
if(k.getKeyCode() == KeyEvent.VK_ENTER){
//+-------------here is the replacement:
panelOnFrame.setVisible(false);
this.add(panel1);
}
}
#Override
public void keyReleased(KeyEvent arg0) {
}
#Override
public void keyTyped(KeyEvent arg0) {
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I intended for this to paint a square on my JPanel, however, it does not show up.
What am I doing wrong?
class GUI extends JPanel {
private static Game game = new Game();
...
public GUI () {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setAttributes();
makeMenu();
}
});
}
...
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.white);
g.drawRect(20, 20, 100, 100);
}
}
Edit: the code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class GUI extends JPanel {
private static Game game = new Game();
private static JPanel panel = new JPanel();
private static JFrame frame = new JFrame();
final private static int FRAME_HEIGHT = 500;
final private static int FRAME_WIDTH = 500;
//Board size 25x25px
final private static int PIXEL_SIZE = 20;
public GUI () {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
setAttributes();
makeMenu();
}
});
}
public static void setAttributes() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("");
frame.setBackground(Color.black);
frame.setVisible(true);
}
private static void makeMenu() {
JButton start = new JButton("Start");
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
game.startGame();
}
});
panel.add(start);
frame.add(panel);
frame.pack();
}
public void setGameFrame() {
panel.removeAll();
frame.setTitle("Snake v0.1");
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.white);
g.drawRect(20, 20, 100, 100);
}
public void paintGraphics() {
int[][] pixels = Game.getGraphics();
}
}
I looked at your code. Where do you ever add GUI to anything? Answer: you don't, and if you don't, nothing will be painted. Solution: add it to the gui, and read the tutorials as there is much to fix in your code.
Other suggestions:
Get rid of all static variables except for the contants.
Call your invokeLater in your main method, not in a JPanel's constructor
Again, add your painting GUI to your actual gui so that it gets added to something that will display it.
Don't call getGraphics() on any component as that will get you a non-persisting Graphics object.
e.g.,
import javax.swing.*;
import java.awt.*;
class GUI extends JPanel {
private static final int PREF_W = 200;
private static final int PREF_H = PREF_W;
private static final int RECT_X = 20;
private static final int RECT_Y = RECT_X;
private static final int RECT_WIDTH = 100;
public GUI() {
setBackground(Color.darkGray);
}
// use #Override to be sure that your method is a true override
// Note that paintComponent should be protected, not public
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.white);
// avoiding "magic" numbers here.
g.fillRect(RECT_X, RECT_Y, RECT_WIDTH, RECT_WIDTH);
g.setColor(Color.red);
g.drawRect(RECT_X, RECT_Y, RECT_WIDTH, RECT_WIDTH);
}
// so that the layout managers know how big I want this JPanel to be.
// this is a dumb method implementation. Yours will hopefully be smarter
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
GUI mainPanel = new GUI();
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_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();
}
});
}
}
When using JTextFields i like to set a default text.
Then i run the program and this default text will automatically be selected (at least when you have only one field). In other words, if I type a letter right away, the default text will be deleted and replaced by the new one.
My question is how I can change the default settings in a way that allows me to type a letter without deleting the default text? I would like the letter to just be added at the end of the default text.
Here's my code:
public class ButtonsNText extends JPanel implements ActionListener, KeyListener {
private JTextField TextLine;
private JToggleButton UpperCaseButton;
private JToggleButton LowerCaseButton;
private JCheckBox ContinuousButton;
private ButtonGroup myButtonGroup;
public ButtonsNText(){
TextLine = new JTextField(10);
add(TextLine); TextLine.setName("TextLine");
TextLine.setText("default text");
TextLine.setCaretPosition(TextLine.getText().length());
TextLine.addKeyListener(this);
myButtonGroup = new ButtonGroup();
UpperCaseButton = new JToggleButton("Upper case");
add(UpperCaseButton);UpperCaseButton.setName("UpperCaseButton");
LowerCaseButton = new JToggleButton("Lower case");
add(LowerCaseButton); LowerCaseButton.setName("LowerCaseButton");
ContinuousButton = new JCheckBox("Continuous?");
add(ContinuousButton); ContinuousButton.setName("ContinuousButton");
myButtonGroup.add(UpperCaseButton); myButtonGroup.add(LowerCaseButton);
UpperCaseButton.addActionListener(this);
LowerCaseButton.addActionListener(this);
ContinuousButton.addActionListener(this);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Hello world example");
frame.add(new ButtonsNText());
frame.pack();
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == UpperCaseButton){
TextLine.setText(TextLine.getText().toUpperCase());
}
else if(e.getSource() == LowerCaseButton){
TextLine.setText(TextLine.getText().toLowerCase());
}
}
#Override
public void keyReleased(KeyEvent k) {
if(ContinuousButton.isSelected()){
if(UpperCaseButton.isSelected()){
int pos = TextLine.getCaretPosition();
TextLine.setText(TextLine.getText().toUpperCase());
TextLine.setCaretPosition(pos);
}
else if(LowerCaseButton.isSelected()){
int pos = TextLine.getCaretPosition();
TextLine.setText(TextLine.getText().toLowerCase());
TextLine.setCaretPosition(pos);
}
}
int key = k.getKeyCode();
if(key == KeyEvent.VK_ENTER){
if(UpperCaseButton.isSelected()){
TextLine.setText(TextLine.getText().toUpperCase());
}
else if(LowerCaseButton.isSelected()){
TextLine.setText(TextLine.getText().toLowerCase());
}
}
}
}
I have tried things like isFocusable(), setFocusable(), setCaterPosition() and other similar methods, but here I think I need a different approach.
Just add one FocusListener for focus Gained, that will do for you along with tfield2.setCaretPosition(tfield2.getDocument().getLength());
Here see the code for your help :
import java.awt.event.*;
import javax.swing.*;
public class TextFieldExample extends JFrame
{
public TextFieldExample()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JPanel contentPane = new JPanel();
JTextField tfield = new JTextField(10);
final JTextField tfield2 = new JTextField(10);
tfield2.setText("default text");
tfield2.addFocusListener(new FocusListener()
{
public void focusGained(FocusEvent fe)
{
tfield2.setCaretPosition(tfield2.getDocument().getLength());
}
public void focusLost(FocusEvent fe)
{
}
});
contentPane.add(tfield);
contentPane.add(tfield2);
setContentPane(contentPane);
pack();
setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TextFieldExample();
}
});
}
}
for #Pete and will be deleted
import java.awt.*;
import javax.swing.*;
import javax.swing.text.DefaultCaret;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
public class TestTextComponents extends JFrame {
private static final long serialVersionUID = 1L;
private JTextField jTextField1;
private JTextField jTextField2;
public TestTextComponents() {
initComponents();
}
private void initComponents() {
jTextField1 = new JTextField();
jTextField2 = new JTextField();
getContentPane().setLayout(new FlowLayout());
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setTitle("Text component persistent selection");
setResizable(false);
getContentPane().add(new JLabel(
"Please skip between text fields and watch persistent selection: "));
jTextField1.setText("jTextField1");
getContentPane().add(jTextField1);
jTextField2.setText("jTextField2");
getContentPane().add(jTextField2);
jTextField1.setCaret(new HighlightCaret());
jTextField2.setCaret(new HighlightCaret());
//Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
// setBounds((screenSize.width - 600) / 2, (screenSize.height - 70) / 2, 600, 70);
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestTextComponents().setVisible(true);
}
});
}
}
class HighlightCaret extends DefaultCaret {
private static final Highlighter.HighlightPainter unfocusedPainter =
new DefaultHighlighter.DefaultHighlightPainter(new Color(230, 230, 210));
private static final long serialVersionUID = 1L;
private boolean isFocused;
#Override
protected Highlighter.HighlightPainter getSelectionPainter() {
return isFocused ? super.getSelectionPainter() : unfocusedPainter;
}
#Override
public void setSelectionVisible(boolean hasFocus) {
if (hasFocus != isFocused) {
isFocused = hasFocus;
super.setSelectionVisible(false);
super.setSelectionVisible(true);
}
}
}
How about if you moved the caret to the end?
txt.setCaretPosition(txt.getText().length());
--EDIT--
I have got a welcome window consisting of two JLabels. It has a link to a timer counting from 3 to 0. After that time, a new window, "UsedBefore", containing JLabel and radio buttons should automatically appear in the place of the previous one. When I run the "Launcher", the first window shows up with counter displaying 3,2,1,0 and then nothing happens.
I think the problem lies in poor referencing, but I'm not sure. I've got "Launcher" class:
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
Welcome window = new Welcome();
window.setVisible(true);
}
});
} // end main
Where I launch the "Welcome" window:
public Welcome() {
init();
}
public void init() {
// here I'm adding stuff to the window and then I have:
setLayout(cardLayout);
add(big, "1welcome");
// UsedBefore.MakeUsedBeforeWindow(); // ???
new MyTimer(this).start();
} // end init
this goes to MyTimer which does the countdown and:
welcome.showNextWindow(); // private Welcome welcome;
we go back to the "Welcome" class:
public void showNextWindow() {
cardLayout.next(this);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("My Frame");
frame.getContentPane().add(new Welcome());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(550, 450);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
and finally the "UsedBefore" class:
public UsedBefore() {
super(new BorderLayout());
init();
}
public void MakeUsedBeforeWindow() {
String q = "Have you used GUI before?";
JPanel area = new JPanel(new BorderLayout());
add(area, "2usedBefore?");
area.setBackground(Color.white);
JLabel textLabel = new JLabel("<html><div style=\"text-align: center;\">"
+ q + "</html>", SwingConstants.CENTER);
textLabel.setForeground(Color.green);
Font font = new Font("SansSerif", Font.PLAIN, 30);
textLabel.setFont(font);
textLabel.setBorder(new EmptyBorder(0, 0, 250, 0)); //top, left, bottom, right
area.add(textLabel, SwingConstants.CENTER);
add(area, "2usedBefore?");
}
with its main:
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("RadioButtons");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane - not sure how to do it
// JComponent newContentPane = new UsedBefore();
// newContentPane.setOpaque(true); //content panes must be opaque
// frame.setContentPane(newContentPane);
// frame.getContentPane().add(new UsedBefore());
//Display the window.
frame.setSize(550, 450);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
That's quite a journey. Sorry for a lot of code, I hope the path is clear. Once I've got 1->2->3 links right, I should be able to do the rest of them, so any help is appreciated. Thank you.
I suggest a slightly different approach. Why not building JPanel instead of Windows and adding/removing these JPanel at the desire time.
Ex (here welcome panel is shown first with its decreasing counter and when the counter reach 0, other panel is shown):
public class T extends JFrame {
private int couterValue = 3;
private JPanel welcome;
private JLabel counter;
private JPanel other;
private Timer timer;
public T() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
buildWelcomePanel();
buildOtherPanel();
add(welcome);
setSize(550, 450);
setLocationRelativeTo(null);
setVisible(true);
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
if (couterValue == 0) {
timer.cancel();
// Switch the panels as the counter reached 0
remove(welcome);
add(other);
validate();
} else {
counter.setText(couterValue + ""); // Update the UI counter
couterValue--;
}
}
}, 0, 1000);
}
private void buildWelcomePanel() {
welcome = new JPanel();
counter = new JLabel();
welcome.add(counter);
}
private void buildOtherPanel() {
other = new JPanel();
JLabel otherStuff = new JLabel("Anything else ...");
other.add(otherStuff);
}
public static void main(String[] args) {
new T();
}
}