Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to make a nice gui for downloading some stuff and I'm trying to add some text explaining how to use the gui. The only problem is the text isn't appearing. Here is all relevant code.
public static class Dissplay extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawString("Please enter you plugin folder location and what you want to install.", 30, 20);
}
}
static JTextField input;
static JCheckBox villagesBox;
static JCheckBox slabsBox;
static JFrame window;
static boolean clicked;
public static void main(String[] args) {
clicked = false;
input = new JTextField("Enter plugin folder location here");
input.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if(clicked){
} else {
input.setText("");
clicked = true;
}
}
});
JPanel content1 = new JPanel();
JPanel content2 = new JPanel();
JPanel content3 = new JPanel();
content3.setLayout(new BorderLayout());
content1.setLayout(new BorderLayout());
content2.setLayout(new GridLayout(0,2));
content3.add(input, BorderLayout.SOUTH);
content3.add(new Dissplay(), BorderLayout.CENTER);
villagesBox = new JCheckBox("Villages");
content1.add(content3, BorderLayout.NORTH);
villagesBox.setSelected(false);
slabsBox = new JCheckBox("Slabs");
slabsBox.setSelected(false);
content2.add(villagesBox);
content2.add(slabsBox);
JButton button = new JButton("Go");
ActionListener buttonLisener = new Button();
button.addActionListener(buttonLisener);
content1.add(button, BorderLayout.SOUTH);
window = new JFrame();
window.setContentPane(content1);
window.add(content2, 0);
window.setSize(200, 150);
window.setLocation(100, 100);
window.setVisible(true);
}
No clue what's wrong.
Found the solution to your woes. You need to call the setPreferredSize method on your JPanel object. It quite bizarrely defaults to a 10x10 Dimension initially. Once you up that, you'll be able to see your drawn text.
public static class Dissplay extends JPanel{
/**
*
*/
private static final long serialVersionUID = 1L;
public Dissplay() {
super();
this.setPreferredSize(new java.awt.Dimension(600, 100));
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawString("Please enter you plugin folder location and what you want to install.", 30, 20);
}
}
You may try to set font, color, etc. Something like this :
g.setFont(new Font("TimesRoman", Font.PLAIN, fontSize));
g.setColor(Color.red);
g.drawString("some string", 40, 40);
Related
I'm trying to add a small tornado graphic (upside down pyramid) to my Frame. I can get the tornado by adding it to the frame in the main method but when I do that all I see is the tornado graphic and not the GUI underneath it.
So, I'm now trying to add the Tornado graphic to the frame when its created in the createComponents method but it now doesn't appear at all. Instead all I can see it the GUI in the frame.
I' probably missing something easy but I can't seem to figure it out. I'm not sure what I need to to in order to get the GUI and the tornado graphic both to appear.
public class EFScaleViewer {
public static void main(String[] args) {
// TODO Auto-generated method stub
TornadoFrame frame = new TornadoFrame();
frame.setTitle("EF Scale");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Here is where I create the frame and am trying to add the tornado:
public class TornadoFrame extends JFrame{
private JButton submit;
private JLabel label;
static JLabel errorLabel;
static JTextField textBox;
JPanel tornado = new TornadoComponent();
private static final int FRAME_WIDTH = 400;
private static final int FRAME_HEIGHT = 300;
//Constructor for the frame
public TornadoFrame() {
super();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
createComponents();
}
private void createComponents()
{
textBox = new JTextField(" ");
submit = new JButton("Submit");
label = new JLabel("Please enter a windspeed:");
errorLabel = new JLabel("Error Message " );
JPanel panel = new JPanel();
panel.add(label);
panel.add(textBox);
panel.add(submit);
panel.add(errorLabel);
panel.add(tornado);
add(panel);
}
}
I know this is working but I may be missing something so here is where I create the tornado:
public class TornadoComponent extends JPanel {
public void paintComponent(Graphics g) {
int[] xPoints = {100,200,0};
int[] yPoints = {0,200,200};
int nPoints = 3;
g.drawPolygon(xPoints, yPoints, nPoints);
}
}
You have to set the JPanels size for it to be able to display Graphics.
static class TornadoComponent extends JPanel {
public TornadoComponent() {
setPreferredSize(new Dimension(500, 500));
}
#Override
public void paintComponent(Graphics g) {
//Whatever
}
}
And in order to trigger paintComponent(Graphics g) you have to add tornado.repaint(); at the end of your createComponents() function.
private void createComponents() {
//All your components
panel.add(tornado);
add(panel);
tornado.repaint();
}
Now the Polygon is shown but not at the right place (slightly off the image)
Therefore we have to arrange your JPanels a bit:
private void createComponents() {
textBox = new JTextField(" ");
submit = new JButton("Submit");
label = new JLabel("Please enter a windspeed:");
errorLabel = new JLabel("Error Message " );
JPanel upper = new JPanel();
upper.setLayout(new BoxLayout(upper,BoxLayout.X_AXIS));
upper.add(label);
upper.add(textBox);
upper.add(submit);
upper.add(errorLabel);
JPanel lower = new JPanel();
lower.setLayout(new BoxLayout(lower,BoxLayout.X_AXIS));
lower.add(tornado);
JPanel over = new JPanel();
over.setLayout(new BoxLayout(over,BoxLayout.Y_AXIS));
over.add(upper);
over.add(lower);
add(over);
tornado.repaint();
}
Basically I make some boxes...
Over
Upper
... your stuff with text
Lower
Our tornado
Now our tornado is the wrong way round...
int[] xPoints = {100,200,150};
int[] yPoints = {0,0,150};
And voilĂ :
We just created a very basic tornado that is not aiming at anything :)
If you want to change the tornados position later you just have to recall tornado.repaint(); and you are all set.
I am trying to create a board class that extends JPanel for a backgammon game and a JLayeredPane to create a dragging area for my checkers but i cant even print a simple rectangle to the panel. It does print the image but not the JLabel.
Here is my JPanel class
public class BoardPanel extends JPanel{
private JLayeredPane lp;
private BufferedImage imageBoard;
private final int WIDTH = 1000;
private final int HEIGHT = 800;
private ArrayList<Slot> slotSet1;
private ArrayList<Slot> slotSet2;
private ArrayList<Slot> slotSet3;
private ArrayList<Slot> slotSet4;
private CheckerSet ch1;
public Checker chc;
public BoardPanel(){
initComponents();
}
private void initComponents(){
lp = new JLayeredPane();
setPreferredSize(new java.awt.Dimension(1500, 1000));
//lp.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
lp.setBorder(javax.swing.BorderFactory.createTitledBorder("asdadsaddadsadasdadsa"));
lp.setMaximumSize(new java.awt.Dimension(1124, 904));
lp.setMinimumSize(new java.awt.Dimension(1124, 904));
try {
imageBoard = ImageIO.read(getClass().getResource("/images/board.jpg"));
} catch (IOException e) {
System.out.println("file error");
}
JLabel label = new JLabel();
label.setVerticalAlignment(JLabel.TOP);
label.setHorizontalAlignment(JLabel.CENTER);
label.setOpaque(true);
label.setBackground(Color.BLACK);
label.setForeground(Color.black);
label.setBorder(BorderFactory.createLineBorder(Color.black));
label.setBounds(0, 0, 50, 50);
lp.add(label,JLayeredPane.DEFAULT_LAYER);
}
public void paintComponent(Graphics g){
//g.drawImage(imageBoard,0,0,null);
}
}
And there is the main
public static void main(String[] args){
JFrame f = new JFrame();
//GamePanel gp = new GamePanel();
BoardPanel gp = new BoardPanel();
f.add(gp);
//f.getContentPane().add(gamePanel);
f.setSize(new Dimension(1500, 1000));
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
How can i resolve it? Thanks guys
You will have to add a Layout to your JLayeredPane, like a GridLayout for example. Try this:
GridLayout gl = new GridLayout(20, 21);
lp.setLayout(gl);
after initializing lp. Then you can add all components that you Need to the GridLayout, for instance lp:
gl.add(lp)
The Layout will manage how the things will be displayed; in this case, it will fill the grid from the GridLayout, first the first row (of which 20 exist), then the second one and so on (I don't think you actually Need 20 rows, it is just like that in my example code)
so I remember about 2 years ago I had an issue with displaying an icon on a label on a mac.
I've tried to do it again this year whilst working on a project and still have the same issue. Could anyone check my code works on a different computer? Either mac or windows just so I know the code works and also if anyone has any idea why it doesn't work on mine let me know!
All that happens is the frame appears with the text and buttons but no background image.
public class MemoryRoom extends JPanel {
/** Background image of the menu screen */
private Image bg = new ImageIcon("memoryRoom.jpg").getImage();
/** JFrame used in the entire game */
protected JFrame app;
public MemoryRoom(JFrame app) {
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
app.setVisible(true);
app.setSize(1150, 680);
this.app = app;
initialize();
app.repaint();
}
protected void initialize() {
//final JPanel menuScreenPanel = new JPanel();
setVisible(true);
setSize(1150, 680);
setLayout(null);
JLabel lblSelectGame = new JLabel("Please select the game you wish to play:");
lblSelectGame.setBounds(320, 180, 600, 50);
add(lblSelectGame);
lblSelectGame.setFont(new Font("Dialog", Font.BOLD, 24));
lblSelectGame.setForeground(Color.WHITE);
JButton btnSnakesAndLadders = new JButton("Snakes and Ladders");
btnSnakesAndLadders.setBounds(370, 250, 200, 45);
add(btnSnakesAndLadders);
JButton btnDansCrazyTic = new JButton("Dan's Crazy Tic Tac Toe");
btnDansCrazyTic.setBounds(590, 250, 200, 45);
add(btnDansCrazyTic);
btnDansCrazyTic.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent TicTacToeEvent) {
setVisible(false);
}
});
btnSnakesAndLadders.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent SnakesAndLaddersEvent) {
setVisible(false);
}
});
app.getContentPane().add(this);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bg, 0, 0, 1150, 680, this);
}
public static void main (String args []){
new MemoryRoom(new JFrame());
}
}
I trying to draw a rectangle in JPanel but the rectangle not showing. What did I missed ?
Here is what I have tried so far.
public class selectSeat extends JFrame {
JPanel panel = new JPanel();
public static void main(String[] args) {
selectSeat frameTabel = new selectSeat("","","");
}
public selectSeat(String title, String day, String time)
{
super("Select Seat");
setSize(350,350);
setLocation(500,280);
panel.setLayout(null);
RectDraw rect= new RectDraw();
panel.add(rect);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private static class RectDraw extends JPanel
{
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawRect(230,80,10,10);
g.setColor(Color.RED);
g.fillRect(230,80,10,10);
}
public Dimension getPreferredSize() {
return new Dimension(50, 20); // appropriate constants
}
}
}
You're drawing the rectangle, but it's located at 280, 80, which is way outside the confines of your visible JPanel. Understand that the drawing location is relative to the coordinates within the JPanel itself.
Noticed that you are using Absolute layout (null layout). Component.setbounds are needed in order to position the object in place.
public Test(String title, String day, String time)
{
super("Select Seat");
setSize(350,350);
setLocation(500,280);
panel.setLayout(null);
RectDraw rect= new RectDraw();
rect.setBounds(0, 0, 100, 100);
panel.add(rect);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
Check out the details:
https://docs.oracle.com/javase/tutorial/uiswing/layout/problems.html
Note: Try Ctrl+Shift+F1 to get debug message from AWT as well.
Code is underneath. Basically what I'm trying to do is I have display going on in my JPanel of a JTextPane. I have a button that edits the value of the string that's supposed to be displayed in the JTextPane. I can't figure out how to update the JTextPane however. I've tried revalidate(), validate(), repaint(), none of those seemed to work.
The code is complete, it should be able to run.
import java.awt.Canvas;
public class windowBuild extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private int health = 20;
private int energy = 4;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
windowBuild frame = new windowBuild();
frame.setVisible(true);
}
});
}
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String which = e.getActionCommand();
if (which.equals("Claw")){
energy = energy-1;
System.out.println("Player one's dragon clawed the opponent. Dragon's energy is now at: "+ energy);}
else if (which.equals("Wait")){
System.out.println("Turn succesfully skipped");}
System.out.println(getEnergy());
}
}
public windowBuild() {
ButtonHandler bh;
System.out.println("Starting frame...");
bh = new ButtonHandler();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
contentPane.setBorder(new TitledBorder(null, "Dragon Duel",
TitledBorder.CENTER, TitledBorder.TOP, null, Color.CYAN));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnClaw = new JButton("Claw");
btnClaw.setBounds(288, 511, 109, 39);
contentPane.add(btnClaw);
btnClaw.addActionListener(bh);
if (energy == 0)
btnClaw.setEnabled(false);
JButton btnWait = new JButton("Wait");
btnWait.setBounds(645, 511, 109, 39);
contentPane.add(btnWait);
btnWait.addActionListener(bh);
StringBuilder sb = new StringBuilder();
String strB = Integer.toString(health);
sb.append("H: ").append(strB).append("/20");
String healthString = sb.toString();
JTextPane txtpnH_1 = new JTextPane();
txtpnH_1.setEditable(false);
txtpnH_1.setFont(new Font("Impact", Font.PLAIN, 30));
txtpnH_1.setText(healthString);
txtpnH_1.setBounds(134, 511, 109, 39);
contentPane.add(txtpnH_1);
String strR = Integer.toString(energy);
String energyString = "E: ";
energyString += strR;
energyString += "/4";
JTextPane txtpnH = new JTextPane();
txtpnH.setEditable(false);
txtpnH.setText(energyString);
txtpnH.setFont(new Font("Impact", Font.PLAIN, 30));
txtpnH.setBounds(39, 511, 85, 39);
contentPane.add(txtpnH);
}
}
Thanks so much!!
Take the time to read through the Code Conventions for the Java Programming Language
Make use of appropriate layout managers, see A Visual Guide to Layout Managers and Using Layout Managers for more details
For what it's worth, use JTextField instead JTextPane, you're gaining little to no benefit by using JTextPane for what you seem to be trying to achieve. In fact, you might actually be better of us just using JLabel, seen as you don't want them to be editable
Avoid overriding top level containers, like JFrame, instead start with something like JPanel, build your UI on it and then deploy it to what ever top level container you want.
The problem you have is a reference issue. In the constructor of your windowBuild, you are defining all your UI components. This means that there is no way you can reference them anywhere else from with your program. Instead, make those components you need to reference else where instance fields.
public class WindowBuild extends JFrame {
//...//
private JTextPane txtpnH_1;
private JTextPane txtpnH;
//...//
public WindowBuild() {
//...//
txtpnH_1 = new JTextPane();
//...//
txtpnH = new JTextPane();
//...//
}
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String which = e.getActionCommand();
// Now you can use txtpnH_1.setText and txtpnH.setText
}
}